@outbuild-company/schedule-core 1.6.2 → 1.6.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +26 -0
- package/dist/cdn/schedule-core.global.js +1 -1
- package/dist/cdn/schedule-core.global.js.map +1 -1
- package/dist/index.cjs +48 -37
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +42 -15
- package/dist/index.d.ts +42 -15
- package/dist/index.js +47 -38
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var ScheduleCore=(()=>{var gn=Object.defineProperty;var Yd=Object.getOwnPropertyDescriptor;var Kd=Object.getOwnPropertyNames;var Gd=Object.prototype.hasOwnProperty;var $d=(e,t)=>{for(var r in t)gn(e,r,{get:t[r],enumerable:!0})},zd=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Kd(t))!Gd.call(e,i)&&i!==r&&gn(e,i,{get:()=>t[i],enumerable:!(n=Yd(t,i))||n.enumerable});return e};var qd=e=>zd(gn({},"__esModule",{value:!0}),e);var Ag={};$d(Ag,{ACTIVITY_TYPE:()=>ar,CALENDAR_UNIT:()=>ot,COLUMN:()=>R,CONSTRAINT_TYPE:()=>K,CONSTRAINT_TYPE_TO_LABEL:()=>Bd,CREATION_KIND:()=>Hd,DEFAULT_HOURS_PER_DAY:()=>Ud,DISPATCH_ACTION_KIND:()=>$,DISPATCH_ACTION_KINDS:()=>jd,DISPATCH_TRACK_EVENT:()=>At,LINK_CODE_TO_TYPE:()=>Jt,LINK_TYPE:()=>M,LINK_TYPE_CODE:()=>Ps,NEW_ACTIVITY_DEFAULTS:()=>jr,REJECTION_REASON:()=>T,ROOT_PARENT_ID:()=>F,ScheduleCore:()=>hn,WORK_TIME_DIRECTION:()=>X,checkNoUpdatedLinks:()=>Zl,computeExpectedProgress:()=>Yn,expectedProgressFromBaseline:()=>Ie,getActiveBaseline:()=>ut,getUnsavedActivities:()=>Wd,isRootParent:()=>L,normalizeParentKey:()=>Ft,parseFromBackend:()=>on,willRunCriticalPath:()=>Ol,yieldToBrowser:()=>Z});var ft=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 Qe=e=>String(e);function Qi(e){let{clickedId:t,isChecked:r,currentSelection:n,hierarchy:i,isFrozen:a,exists:s,autoCheckParents:o}=e,c=Qe(t),l=new Set([...n].map(String)),d=new Set(l),u=Jd(c,i).filter(s),f=u.filter(m=>!a(m)),p=r&&f.length<u.length;r&&!p?d.add(c):d.delete(c);for(let m of f)r?d.add(m):d.delete(m);return p||Xd({id:c,isChecked:r,autoCheckParents:o,hierarchy:i,isFrozen:a,exists:s,next:d}),{nextSelection:d,changed:Zd(l,d),parentBlocked:p}}function Jd(e,t){let r=[],n=new ft;n.enqueue(e);let i=new Set([e]);for(;!n.isEmpty();){let a=n.dequeue();for(let s of t.getChildrenIds(a)){let o=Qe(s);i.has(o)||(i.add(o),r.push(o),n.enqueue(o))}}return r}function Xd(e){let{id:t,isChecked:r,autoCheckParents:n,hierarchy:i,isFrozen:a,exists:s,next:o}=e,c=i.getParentId(t);for(;c!==null&&typeof c<"u";){let l=Qe(c);if(a(l))return;let d=i.getChildrenIds(l).map(Qe).filter(s),u=d.some(a),f=d.filter(I=>!a(I)),m=f.length>0&&f.every(I=>o.has(I))&&!u;if(r){if(!n||!m||o.has(l))return;o.add(l)}else{if(m||!o.has(l))return;o.delete(l)}c=i.getParentId(l)}}function Zd(e,t){let r=[],n=[];for(let i of t)e.has(i)||r.push(i);for(let i of e)t.has(i)||n.push(i);return{checked:r,unchecked:n}}function oe(e){return(e.pendingRequestIds?.length??0)>0}var T={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 ta=(e,t)=>{let r=e.getActivity(t);return r!=null&&oe(r)},ea=(e,t,r)=>{let n=[],i=(a,s)=>{let o=t.isChecked(a);t.setChecked(a,s)&&n.push({activityId:a,checked:{before:o,after:s}})};for(let a of r.checked)i(a,!0);for(let a of r.unchecked)i(a,!1);return{source:e,activities:[],links:[],calendars:[],trackingEvents:[],viewState:n}};function ra(e,t){let{adapter:r}=t,n=e.activityId;if(!r.getActivity(n))return{ok:!1,reason:T.ACTIVITY_NOT_FOUND};let i=e.frozenIds?new Set(e.frozenIds):null,a=i?o=>i.has(o):o=>ta(r,o),s=Qi({clickedId:n,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:ea(e,r,s.changed)}}function na(e,t){let{adapter:r}=t,n=new Set(e.activityIds.map(String).filter(s=>r.activityExists(s)).filter(s=>!ta(r,s))),i=new Set(r.checkedIds().map(String)),a={checked:[...n].filter(s=>!i.has(s)),unchecked:[...i].filter(s=>!n.has(s))};return{ok:!0,changes:ea(e,r,a)}}function $t(e,t,r=e.getAllIds()){let n=[];for(let i of r){let a=String(i),s=t.has(a),o=e.isVisible(a);o!==s&&(e.setVisible(a,s),n.push({activityId:a,visible:{before:o,after:s}}))}return n}function ia(e,t){let{adapter:r}=t,n=new Set(e.visibleIds.map(String)),i=$t(r,n);return{ok:!0,changes:{source:e,activities:[],links:[],calendars:[],trackingEvents:[],viewState:i}}}var Qd=["Waiting","Done","Doing","Overdue","Advancement"],tu=["mfo","mso","snlt","snet","alap","asap","fnet","fnlt"];function vn(e,t){return e===null||t<=0?null:e/t}function eu(e,t){let r=t.getTime()-e.getTime();return Math.floor(r/864e5)+1}var ru={name:{valueKind:"string",extract:e=>e.name},description:{valueKind:"string",extract:e=>e.description},customId:{valueKind:"string",extract:e=>e.customId},correlativeId:{valueKind:"number",extract:e=>e.correlativeId},uniqueCorrelativeId:{valueKind:"number",extract:e=>Number(e.uniqueCorrelativeId)},progress:{valueKind:"number",extract:e=>e.progress},durationDays:{valueKind:"number",extract:(e,t)=>vn(e.durationHours,t.hoursPerDay)},calendarDuration:{valueKind:"number",extract:e=>eu(e.startDate,e.endDate)},cost:{valueKind:"number",extract:e=>e.cost},usedCost:{valueKind:"number",extract:e=>e.usedCost},realCost:{valueKind:"number",extract:e=>e.realCost},workHours:{valueKind:"number",extract:e=>e.workHours},realWorkHours:{valueKind:"number",extract:e=>e.realWorkHours},ponderator:{valueKind:"number",extract:e=>e.ponderator},freeSlackDays:{valueKind:"number",extract:(e,t)=>vn(e.freeSlackHours,t.hoursPerDay)},totalSlackDays:{valueKind:"number",extract:(e,t)=>vn(e.criticalPath?.totalSlackHours??null,t.hoursPerDay)},expectedProgressBaseline:{valueKind:"number",extract:e=>e.expectedProgressBaseline},baselineDurationDays:{valueKind:"number",extract:e=>e.baselineSnapshot?.durationDays??null},baselineCost:{valueKind:"number",extract:e=>e.baselineSnapshot?.cost??null},baselineWorkHours:{valueKind:"number",extract:e=>e.baselineSnapshot?.workHours??null},startDate:{valueKind:"date",extract:e=>e.startDate},endDate:{valueKind:"date",extract:e=>e.endDate},constraintDate:{valueKind:"date",extract:e=>e.constraintDate},baselineStartDate:{valueKind:"date",extract:e=>e.baselineSnapshot?.startDate??null},baselineEndDate:{valueKind:"date",extract:e=>e.baselineSnapshot?.endDate??null},earlyStart:{valueKind:"date",extract:e=>e.criticalPath?.earlyStart??null},earlyFinish:{valueKind:"date",extract:e=>e.criticalPath?.earlyFinish??null},lateStart:{valueKind:"date",extract:e=>e.criticalPath?.lateStart??null},lateFinish:{valueKind:"date",extract:e=>e.criticalPath?.lateFinish??null},responsableIds:{valueKind:"id-array",extract:e=>e.responsableIds},tagIds:{valueKind:"id-array",extract:e=>e.tagIds},status:{valueKind:"enum",order:Qd,extract:e=>e.status},constraintType:{valueKind:"enum",order:tu,extract:e=>e.constraintType},calendarId:{valueKind:"reference",extract:e=>e.calendarId===null?null:String(e.calendarId)},subcontractId:{valueKind:"reference",extract:e=>e.subcontractId===null?null:String(e.subcontractId)},isCritical:{valueKind:"boolean",extract:e=>e.isCritical}};function xt(e){return ru[e]??null}function nu(e){return e instanceof Date?e:typeof e=="string"||typeof e=="number"?new Date(e):new Date(Number.NaN)}function iu(e,t,r){let n=e===null;return r==="includes"?!n&&String(e).toLowerCase().includes(t.toLowerCase()):r==="notIncludes"?n||!String(e).toLowerCase().includes(t.toLowerCase()):r==="is"?!n&&String(e)===t:r==="isNot"?n||String(e)!==t:!1}function au(e,t,r){return e===null||typeof e!="number"?r==="notEquals":r==="equals"?e===t:r==="notEquals"?e!==t:r==="greaterThan"?e>t:r==="lessThan"?e<t:r==="greaterOrEqual"?e>=t:r==="lessOrEqual"?e<=t:!1}function su(e,t,r){return e instanceof Date?r==="after"?e.getTime()>t.getTime():r==="before"?e.getTime()<t.getTime():!1:!1}function ou(e,t,r){let i=(Array.isArray(e)?e:[]).some(a=>t.has(String(a)));return r==="someOf"?i:r==="notSomeOf"?!i:!1}function cu(e,t,r){let n=e!==null&&t.has(String(e));return r==="someOf"?n:r==="notSomeOf"?!n:!1}function aa(e){let t=Array.isArray(e)?e:[e];return new Set(t.map(r=>String(r)))}function sa(e,t,r){let n=xt(t.field);if(n===null)return!1;let i=n.extract(e,r),{operator:a}=t;return n.valueKind==="string"?iu(i,String(t.value),a):n.valueKind==="number"?au(i,Number(t.value),a):n.valueKind==="date"?su(i,nu(t.value),a):n.valueKind==="id-array"?ou(i,aa(t.value),a):cu(i,aa(t.value),a)}function lu(e,t,r){return t.criteria.length===0?!0:t.logic==="or"?t.criteria.some(n=>sa(e,n,r)):t.criteria.every(n=>sa(e,n,r))}function du(e,t){let r=e.startDate.getTime(),n=e.endDate.getTime(),i=t.start.getTime(),a=t.end.getTime(),s=r>=i&&n<=a,o=r>=i&&r<=a,c=i>=r&&i<=n;return s||o||c}function An(e,t,r){let n=lu(e,t,r),i=t.dateRange,a=i===void 0||du(e,i);return n&&a}function uu(e,t,r){let n=t(e);for(;n!==null&&!r.has(String(n));)r.add(String(n)),n=t(n)}function oa(e){let{activities:t,parentOf:r,filter:n,context:i}=e,a=new Set,s=[];for(let o of t)An(o,n,i)&&(a.add(String(o.id)),s.push(o.id));for(let o of s)uu(o,r,a);return a}function fu(e){let{activities:t,parentOf:r,filter:n,context:i}=e,a=new Set,s=new Set,o=new Map,c=new Map,l=new Map;for(let d of t){let u=String(d.id),f=r(u);c.set(u,f),l.set(u,l.get(u)??0),f!==null&&l.set(f,(l.get(f)??0)+1);let p=An(d,n,i),m=e.pinnedVisibleIds?.has(u)===!0;o.set(u,(p?1:0)+(m?1:0)),p&&a.add(u),m&&s.add(u)}return{matchedIds:a,pinnedVisibleIds:s,visibleReferenceCounts:o,parentIds:c,remainingChildren:l}}function pu(e){let{visibleReferenceCounts:t,parentIds:r,remainingChildren:n}=e,i=[];for(let a of r.keys())n.get(a)===0&&i.push(a);for(;i.length>0;){let a=i.pop();if(a===void 0)break;let s=r.get(a);if(s==null)continue;let o=t.get(a)??0;t.set(s,(t.get(s)??0)+o);let c=(n.get(s)??1)-1;n.set(s,c),c===0&&i.push(s)}}function hu(e){let t=new Set;for(let[r,n]of e)n>0&&t.add(r);return t}function tr(e){let t=fu(e);pu(t);let r=hu(t.visibleReferenceCounts);return{filter:e.filter,context:e.context,matchedIds:t.matchedIds,pinnedVisibleIds:t.pinnedVisibleIds,visibleIds:r,visibleReferenceCounts:t.visibleReferenceCounts}}function ca(e,t,r){let n=new Set;for(let i of t){let a=String(i.id);n.add(a);let s=e.matchedIds.has(a),o=An(i,e.filter,e.context);if(s===o)continue;o?e.matchedIds.add(a):e.matchedIds.delete(a);let c=o?1:-1,l=a;for(;l!==null;){let d=e.visibleReferenceCounts.get(l)??0,u=d+c;e.visibleReferenceCounts.set(l,u);let f=d>0,p=u>0;f!==p&&(n.add(l),p?e.visibleIds.add(l):e.visibleIds.delete(l)),l=r(l)}}return n}function zt(e){return{hoursPerDay:e,locale:"en"}}var yu={string:new Set(["includes","notIncludes","is","isNot"]),number:new Set(["equals","notEquals","greaterThan","lessThan","greaterOrEqual","lessOrEqual"]),date:new Set(["after","before"]),"id-array":new Set(["someOf","notSomeOf"]),enum:new Set(["someOf","notSomeOf"]),boolean:new Set(["someOf","notSomeOf"]),reference:new Set(["someOf","notSomeOf"])};function la(e){let t=xt(e.field);return t===null?"unknown_field":yu[t.valueKind].has(e.operator)?mu(e,t.valueKind):"unknown_operator"}function mu(e,t){let{value:r}=e;return t==="id-array"||t==="enum"?Array.isArray(r)?null:"invalid_value":Array.isArray(r)?"invalid_value":t==="number"?Number.isFinite(Number(r))?null:"invalid_value":t==="date"?gu(r)?null:"invalid_value":null}function gu(e){return e instanceof Date?!0:typeof e=="string"||typeof e=="number"?!Number.isNaN(new Date(e).getTime()):!1}function da(e){return e.criteria.length===0&&e.dateRange===void 0}function vu(e,t,r){let n=e.getAllActivities();if(da(t))return{visibleIds:oa({activities:n,parentOf:a=>e.getParentId(a),filter:t,context:zt(r)}),projection:null};let i=tr({activities:n,parentOf:a=>e.getParentId(a),filter:t,context:zt(r)});return{visibleIds:i.visibleIds,projection:i}}function ua(e,t){let{adapter:r,hoursPerDay:n}=t;for(let l of e.criteria){let d=la(l);if(d!==null)return{ok:!1,reason:d}}let i=e.dateRange===void 0?{criteria:e.criteria,logic:e.logic}:{criteria:e.criteria,logic:e.logic,dateRange:e.dateRange};r.setActiveFilter(da(i)?null:i);let{visibleIds:a,projection:s}=vu(r,i,n);r.setFilterProjection(s);let o=$t(r,a);return{ok:!0,changes:{source:e,activities:[],links:[],calendars:[],trackingEvents:[],viewState:o}}}var F="0";function L(e){return e==null||e===0||e==="0"}function Ft(e){return L(e)?"0":String(e)}var Cn=Number.MAX_SAFE_INTEGER;function mt(e,t){let r=we(e,t),n=t.getOrderComparator?.()??null;return r.sort(n===null?er:(i,a)=>n(i,a)||er(i,a)),r.map(i=>String(i.id))}function pa(e){let t=[],r=i=>{t.push(i);let a=mt(String(i.id),e);for(let s of a){let o=e.getActivity(s);o&&r(o)}},n=mt("0",e);for(let i of n){let a=e.getActivity(i);a&&r(a)}return t}function ha(e,t,r){let n=r.getActivity(e);if(!n)return null;let i=ya(n),a=mt(i,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&&!Au(t,c))return c}return null}function In(e,t){let r=t.getActivity(e);if(!r)return-1;let n=ya(r);return mt(n,t).findIndex(a=>String(a)===String(e))}function we(e,t){let r=String(e)==="0"?t.getRootIds?.()??t.getChildren("0"):t.getChildren(e),n=[];for(let i of r){let a=t.getActivity(i);a&&n.push(a)}return n}function er(e,t){let r=fa(e),n=fa(t);return r!==n?r-n:String(e.id).localeCompare(String(t.id))}function fa(e){let t=e.correlativeId,r=typeof t=="number"?t:Number(t);return Number.isFinite(r)?r:Cn}function ya(e){let t=e.parentId;return t===null?"0":t}function Au(e,t){return e.has(t)?!0:e.has(String(t))}function Oe(e){let t=[],r=n=>{let i=mt(n,e);i.length>1&&t.push({parentId:n,childIds:i});for(let a of i)r(a)};return r("0"),t}function Sn(e,t){let r=[];for(let n of t){let i=mt(n,e);i.length>1&&r.push({parentId:n,childIds:i})}return r}function Cu(e){return xt(e.field)===null?"unknown_field":e.direction!=="asc"&&e.direction!=="desc"?"unknown_operator":null}function ma(e,t){let{adapter:r}=t;for(let a of e.rules){let s=Cu(a);if(s!==null)return{ok:!1,reason:s}}let n=e.rules.length===0?null:{rules:e.rules};return r.setActiveOrder(n),{ok:!0,changes:{source:e,activities:[],links:[],calendars:[],trackingEvents:[],order:Oe(r)}}}var ga="text";var va="description";var Aa="duration";var Ca="progress";var Ia="cost";var Sa="used_cost";var ka="hhWorkTime";var Da="start_date";var Ta="end_date";var _a="constraint_type";var Pa="constraint_date";var Ra="calendar_id";var Ea="custom_id";var ba="subcontractId";var La="responsables";var wa="tags";var Oa="custom_predecessors";var xa="custom_sucessors";var Fa="real_work";var Na="real_cost";var Ma="expected_progress";var Wa="expected_progress_base";var Ba="start_base";var Ua="end_base";var ja="duration_base";var Ha="cost_base";var Va="work_base";var Ya="calendarDuration";var Ka="is_critical",Ga="earlyStart",$a="earlyFinish",za="lateStart",qa="lateFinish",Ja="freeSlack",Xa="totalSlack";var Za="correlative_id";var Qa="unique_correlative_id";var ts="ponderator";var X={FUTURE:"future",PAST:"past"},ot={HOUR:"hour",DAY:"day"},Nt={DONE:"Done",OVERDUE:"Overdue",ADVANCEMENT:"Advancement",WAITING:"Waiting",DOING:"Doing"};var rr="status";var kn="Baseline";function nr(e){return e==="Actual"?"Actual":kn}var Iu={TEXT:ga,DESCRIPTION:va,DURATION:Aa,PROGRESS:Ca,COST:Ia,USED_COST:Sa,HH_WORK_TIME:ka,START_DATE:Da,END_DATE:Ta,CONSTRAINT_TYPE:_a,CONSTRAINT_DATE:Pa,CALENDAR_ID:Ra,CUSTOM_ID:Ea,SUBCONTRACT_ID:ba,RESPONSABLES:La,TAGS:wa,CUSTOM_PREDECESSORS:Oa,CUSTOM_SUCESSORS:xa},Su={REAL_WORK:Fa,REAL_COST:Na,EXPECTED_PROGRESS:Ma,EXPECTED_PROGRESS_BASE:Wa,START_BASE:Ba,END_BASE:Ua,DURATION_BASE:ja,COST_BASE:Ha,WORK_BASE:Va,CALENDAR_DURATION:Ya,IS_CRITICAL:Ka,EARLY_START:Ga,EARLY_FINISH:$a,LATE_START:za,LATE_FINISH:qa,FREE_SLACK:Ja,TOTAL_SLACK:Xa,CORRELATIVE_ID:Za,UNIQUE_CORRELATIVE_ID:Qa,PONDERATOR:ts,STATUS:rr},R={...Iu,...Su};function es(e,t){throw new Error(t)}function rs(e,t){return()=>t()===e}var K={ASAP:"asap",ALAP:"alap",SNET:"snet",SNLT:"snlt",FNET:"fnet",FNLT:"fnlt",MSO:"mso",MFO:"mfo"},ku={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 is(e,t,r){if(!t)return{violated:!1};let n=ku[e];return n?n(t,r)?{violated:!0,constraintType:e,constraintDate:t}:{violated:!1}:{violated:!1}}var Du=new Set(["mso","snet","snlt"]);function xe(e,t,r){return Du.has(e)?t:r}function as(e,t,r){return{type:"constraint",messageKey:"constraint_violation",data:{constraintType:e,constraintDate:t,...r?{projectedDate:r}:{}}}}var Tu={snet:{startOfDay:!0,direction:X.FUTURE},snlt:{startOfDay:!0,direction:X.PAST},fnet:{startOfDay:!1,direction:X.FUTURE},fnlt:{startOfDay:!1,direction:X.PAST},mso:{startOfDay:!0,direction:X.FUTURE},mfo:{startOfDay:!1,direction:X.PAST}},ir=e=>new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate())),ns=(e,t)=>new Date(e.getTime()+t*864e5),_u=(e,t)=>e.getUTCFullYear()===t.getUTCFullYear()&&e.getUTCMonth()===t.getUTCMonth()&&e.getUTCDate()===t.getUTCDate();function Dn(e,t){if(!e.constraintDate||!e.constraintType)return null;let r=Tu[e.constraintType];if(!r)return e.constraintDate;let n=e.constraintDate,i=t.getClosestWorkTime({date:ir(n),dir:X.FUTURE,task:e});if(_u(i,n))return n.getTime()!==ir(n).getTime()?n:r.startOfDay?i:t.getClosestWorkTime({date:ns(ir(n),1),dir:X.PAST,task:e});let a=ir(t.getClosestWorkTime({date:n,dir:r.direction,task:e}));return r.startOfDay?t.getClosestWorkTime({date:a,dir:X.FUTURE,task:e}):t.getClosestWorkTime({date:ns(a,1),dir:X.PAST,task:e})}function ss(e,t){let r={earliestStart:null,latestStart:null,earliestEnd:null,latestEnd:null},n=e.constraintType;if(!n||n==="asap"||n==="alap")return r;let i=Dn(e,t);if(!i)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(n){case"snet":return{earliestStart:i,latestStart:null,earliestEnd:a(i),latestEnd:null};case"snlt":return{earliestStart:null,latestStart:i,earliestEnd:null,latestEnd:a(i)};case"fnet":return{earliestStart:s(i),latestStart:null,earliestEnd:i,latestEnd:null};case"fnlt":return{earliestStart:null,latestStart:s(i),earliestEnd:null,latestEnd:i};case"mso":{let o=a(i);return{earliestStart:i,latestStart:i,earliestEnd:o,latestEnd:o}}case"mfo":{let o=s(i);return{earliestStart:o,latestStart:o,earliestEnd:i,latestEnd:i}}default:return r}}function os(e,t){return!(t.earliestStart&&e<t.earliestStart||t.latestStart&&e>t.latestStart)}function Tn(e,t){return t.latestStart&&e>t.latestStart?t.latestStart:t.earliestStart&&e<t.earliestStart?t.earliestStart:e}var M={FINISH_TO_START:"0",START_TO_START:"1",FINISH_TO_FINISH:"2",START_TO_FINISH:"3"};var ar={TASK:"task",PROJECT:"project",MILESTONE:"milestone"},cs={ALAP_DEBOUNCE_MS:1e3,CRITICAL_PATH_DEBOUNCE_MS:1e3,YIELD_SLICE_MS:8};var _n=typeof window>"u",Pu=!_n&&typeof MessageChannel<"u";function Z(){return Pu?new Promise(e=>{let t=new MessageChannel;t.port1.onmessage=()=>{t.port1.close(),t.port2.close(),e()},t.port2.postMessage(null)}):Promise.resolve()}async function sr(e,t){return performance.now()-e<cs.YIELD_SLICE_MS?{aborted:!1,newSliceStart:e}:(await Z(),t()?{aborted:!1,newSliceStart:performance.now()}:{aborted:!0,newSliceStart:performance.now()})}async function ce(e){return _n||await Z(),e()?{aborted:!1}:{aborted:!0}}function or(e,t){let{inDegree:r,successors:n}=Ru(e,t),i=Eu(r),a=bu(i,r,n),s=a.length<e.length,o=s?Lu(e,a):[],c=[...a].reverse();return{ordered:a,reversed:c,hasCycles:s,cycleNodes:o}}function Ru(e,t){let r=new Map,n=new Map;for(let i of e)r.set(i,0),n.set(i,[]);for(let i of t){let a=i.source,s=i.target;!r.has(a)||!r.has(s)||(n.get(a).push(s),r.set(s,(r.get(s)??0)+1))}return{inDegree:r,successors:n}}function Eu(e){let t=new ft;for(let[r,n]of e)n===0&&t.enqueue(r);return t}function bu(e,t,r){let n=[];for(;!e.isEmpty();){let i=e.dequeue();n.push(i);for(let a of r.get(i)??[]){let s=(t.get(a)??1)-1;t.set(a,s),s===0&&e.enqueue(a)}}return n}function Lu(e,t){let r=new Set(t);return e.filter(n=>!r.has(n))}var cr=class{cached=null;invalidate(){this.cached=null}get(t,r){return this.cached?this.cached:(this.cached=or(t,r),this.cached)}};function ls(e,t){let r=[];for(let n of e)t.has(n)&&r.push(n);return r}var Pn={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 Rn(e){return e==="project"||e==="task"||e==="milestone"}function Rt(e,t){return t||Rn(e)&&Pn[e].alwaysSummary}function qt(e){return e==="milestone"}function Mt(e){return Rn(e)&&Pn[e].promotesToProjectOnFirstChild}var En="project",le="task";function Fe(e,t){return t===0?"milestone":e===0&&t>0?"task":null}function ds(e,t){let r=t.getActivity(e);return r?Rt(r.type,t.getChildren(e).length>0):!1}function us(e,t,r){let n=String(t),i=r.getActivity(e);for(;i?.parentId&&String(i.parentId)!=="0";){if(String(i.parentId)===n)return!0;i=r.getActivity(i.parentId)}return!1}function hs(e,t){let r=[],n=[e];for(;n.length>0;){let i=n.pop(),a=t.getChildren(i);if(a.length===0){String(i)!==String(e)&&r.push(i);continue}for(let s of a)n.push(s)}return r}function wu(e){let t=new Map;for(let r of e)fs(t,String(r.source),r),fs(t,String(r.target),r);return t}function fs(e,t,r){let n=e.get(t);if(n){n.push(r);return}e.set(t,[r])}function Ou(e,t,r,n){if(e.length<=1)return e;let i=new Set(e.map(String)),a=[];for(let s of e)xu(s,i,t,r,n)||a.push(s);return a.length>0?a:e}function xu(e,t,r,n,i){let a=String(e),s=r.getActivity(e);if(!s||s.autoScheduling===!1)return!1;let o=n.get(a)??[];for(let c of o)if(Fu(c,a,s,t,r,i))return!0;return!1}function Fu(e,t,r,n,i,a){if(Nu(e)||!(a?String(e.source)===t:String(e.target)===t))return!1;let o=Mu(e,t);if(!n.has(String(o)))return!1;let c=i.getActivity(o);return!!(c?.autoScheduling!==!1&&c&&Wu(e,r,c))}function Nu(e){return e.source===e.target}function Mu(e,t){return String(e.source)===t?e.target:e.source}function Wu(e,t,r){let n=e.lag??0,i=Math.abs(n);return String(e.target)===String(r.id)&&i<=r.durationHours||String(e.target)===String(t.id)&&i<=t.durationHours}function ys(e,t){let r=[],n=wu(e),i=0;for(let a of e){let s=ds(a.source,t),o=ds(a.target,t);if(Bu(a,s,o,t))continue;if(!s&&!o){r.push(a);continue}let c=ps(a.source,s,t,n,!0),l=ps(a.target,o,t,n,!1);i=Gu(r,c,l,a,t,i,n)}return r}function Bu(e,t,r,n){return r&&us(e.source,e.target,n)||t&&us(e.target,e.source,n)}function ps(e,t,r,n,i){return t?Ou(hs(e,r),r,n,i):[e]}function Uu(e,t,r){let n=hs(e,t);if(n.length===0)return null;let i=null,a=null;for(let s of n){let o=r(s);if(!o)continue;(i===null||o.startDate<i)&&(i=o.startDate),(a===null||o.endDate>a)&&(a=o.endDate)}return i===null||a===null?null:{startDate:i,endDate:a}}function lr(e,t){return Uu(e,t,r=>{let n=t.getActivity(r);return n?{startDate:n.startDate,endDate:n.endDate}:null})}function ju(e,t,r){return e?t?r.calculateDuration({startDate:t.startDate,endDate:t.endDate,task:e}):e.durationHours:0}function Hu(e,t,r,n){if(!t)return 0;let i=n.getActivity(e);return!r||!i?-t.durationHours:-n.calculateDuration({startDate:r.startDate,endDate:i.endDate,task:t})}function Vu(e,t){let r=String(e);return(t.get(r)??[]).some(i=>String(i.target)===r)}function Yu(e,t,r,n,i){if(Vu(e,i))return 0;let a=n.getActivity(e);return!t||!a||!r?0:n.calculateDuration({startDate:t,endDate:a.startDate,task:r})}function Ku(e,t){let r=t.getActivity(e.source),n=t.getActivity(e.target),i=lr(e.source,t),a=lr(e.target,t),s=e.type===M.START_TO_START||e.type===M.START_TO_FINISH,o=e.type===M.FINISH_TO_FINISH||e.type===M.START_TO_FINISH;return{source:r,sourceBounds:i,targetStart:a?.startDate??n?.startDate,userLag:e.lag??0,sourceEndpointIsStart:s,targetLag:o?-ju(n,a,t):0,summarySourceId:e.type===M.START_TO_START&&i?e.source:void 0}}function Gu(e,t,r,n,i,a,s){let o=Ku(n,i),{source:c,sourceBounds:l,targetStart:d,userLag:u}=o,{sourceEndpointIsStart:f,targetLag:p,summarySourceId:m}=o,I=a;for(let C of t){let S=f?Hu(C,c,l,i):0;for(let D of r){if(String(C)===String(D))continue;let P=Yu(D,d,c,i,s);e.push($u(n,C,D,I,S,p,u+P,m,P!==0&&p===0?n.target:void 0)),I+=1}}return I}function $u(e,t,r,n,i,a,s,o,c){return{id:`virtual_${e.id}_${n}`,source:t,target:r,type:e.type,lag:e.lag,_sourceLag:i,_targetLag:a,_trueLag:s,...o===void 0?{}:{_summarySourceId:o},...c===void 0?{}:{_summaryTargetId:c}}}var dr=class{invalidate(){}get(t,r){return ys(t,r)}};function zu(e){let t=new Map,r=n=>(t.has(n)||t.set(n,new Set),t.get(n));for(let n of e)r(n.source).add(n.id),r(n.target).add(n.id);return{neighbors:t}}function qu(e,t,r){let n=new Set,i=new Map,a=new ft;for(a.enqueue(e);!a.isEmpty();){let s=a.dequeue(),o=String(s);if(n.has(o))continue;n.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}`;i.has(u)||i.set(u,d);let f=String(d.source)===o?d.target:d.source;n.has(String(f))||a.enqueue(f)}}return Array.from(i.values())}function ms(e,t){let r=new Map;for(let s of t)r.set(s.id,s);let n=zu(t),i=qu(e,r,n),a=new Set([String(e)]);for(let s of i)a.add(String(s.source)),a.add(String(s.target));return{activityIds:a,links:i}}function gs(e,t,r){let n=r.type===M.FINISH_TO_START,i=r.type===M.FINISH_TO_FINISH;if(r._targetLag!==void 0)return{sourceLag:r._sourceLag??0,targetLag:r._targetLag,trueLag:r._trueLag??r.lag??0,isFS:n,isFF:i,isZeroDurationCase:!1};let a=r.lag??0;switch(r.type){case M.FINISH_TO_START:return{sourceLag:0,targetLag:0,trueLag:a,isFS:n,isFF:i,isZeroDurationCase:!1};case M.START_TO_START:return{sourceLag:-e.durationHours,targetLag:0,trueLag:a,isFS:n,isFF:i,isZeroDurationCase:!1};case M.FINISH_TO_FINISH:return{sourceLag:0,targetLag:-t.durationHours,trueLag:a,isFS:n,isFF:i,isZeroDurationCase:!1};case M.START_TO_FINISH:return{sourceLag:-e.durationHours,targetLag:-t.durationHours,trueLag:a,isFS:n,isFF:i,isZeroDurationCase:!1};default:return{sourceLag:0,targetLag:0,trueLag:a,isFS:n,isFF:i,isZeroDurationCase:!1}}}function Ju(e,t,r){if(e._summarySourceId===void 0)return null;let n=r.getActivity(e._summarySourceId);if(!n)return null;let i=lr(e._summarySourceId,r);return i?-r.calculateDuration({startDate:i.startDate,endDate:t.endDate,task:n}):null}function Xu(e,t,r,n,i){let a=t.durationHours===0&&i;return{successorStart:n.getClosestWorkTime({date:e.endDate,dir:a?"past":"future",task:t}),link:r}}function vs(e,t,r,n){let{sourceLag:i,targetLag:a,trueLag:s,isFS:o,isFF:c}=gs(e,t,r),l=Ju(r,e,n)??i,d=l+a+s;if(!(t.durationHours===0?d!==0:l!==0||a!==0||s!==0))return Xu(e,t,r,n,o||c);let p=o?t:e,m=n.getClosestWorkTime({date:e.endDate,dir:"future",task:p});if(l!==0&&(m=n.calculateEndDate({startDate:m,durationHours:l,task:e})),a!==0&&(m=n.calculateEndDate({startDate:m,durationHours:a,task:t})),s!==0&&(m=n.calculateEndDate({startDate:m,durationHours:s,task:t})),t.durationHours===0){if(o||c)return{successorStart:n.getClosestWorkTime({date:m,dir:"past",task:t}),link:r};let I=new Date(Date.UTC(m.getUTCFullYear(),m.getUTCMonth(),m.getUTCDate()));return{successorStart:n.getClosestWorkTime({date:I,dir:"future",task:t}),link:r}}return{successorStart:n.getClosestWorkTime({date:m,dir:"future",task:t}),link:r}}function As(e,t,r,n){let{sourceLag:i,targetLag:a,trueLag:s}=gs(t,e,r),o=n.getClosestWorkTime({date:e.startDate,dir:"past",task:e});return s!==0&&(o=n.calculateEndDate({startDate:o,durationHours:-s,task:e})),a!==0&&(o=n.calculateEndDate({startDate:o,durationHours:-a,task:e})),i!==0&&(o=n.calculateEndDate({startDate:o,durationHours:-i,task:t})),o}function Cs(e,t,r){for(let n of e){let i=t.getActivity(n);if(!i)continue;let a=i.constraintType;if(!a||a===K.ASAP||a===K.ALAP)continue;let s=ss(i,t);!s.earliestStart&&!s.latestStart&&!s.earliestEnd&&!s.latestEnd||r.set(n,{activityId:n,startDate:i.startDate,endDate:i.endDate,drivingLinkId:null,kind:"asap",conflict:!1,earliestStart:s.earliestStart,latestStart:s.latestStart,earliestEnd:s.earliestEnd,latestEnd:s.latestEnd})}}function ur(e,t,r){let n={earliestStart:t.earliestStart??null,latestStart:t.latestStart??null,earliestEnd:t.earliestEnd??null,latestEnd:t.latestEnd??null},i=t.earliestSchedulingStart??t.latestSchedulingStart??null,a;i===null?a=Tn(e.startDate,n):os(i,n)?a=i:a=Tn(i,n),t.startDate=a,t.endDate=r.calculateEndDate({startDate:a,durationHours:e.durationHours,task:e})}function Is(e,t){if(!e||!t)return new Date;let{constraintType:r,constraintDate:n}=e;if(!r||!n)return t;switch(r){case K.MSO:case K.MFO:return new Date(n);case K.SNET:case K.FNET:return n>t?new Date(n):t;case K.SNLT:case K.FNLT:return n<t?new Date(n):t;default:return t}}function Zu(e,t){return t.length?t.some(r=>String(r)===String(e)):!1}function Ss(e,t,r){return bn(e.id,t,r)?{startDate:e.startDate,endDate:e.endDate}:{startDate:e.startDate,endDate:e.endDate}}function bn(e,t,r){return t.dragWithMultiple&&Zu(e,r)}async function Ds(e,t,r,n,i,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=n.draggedIds??[],d=performance.now();for(let u of e){let f=await sr(d,i);if(f.aborted)return a;d=f.newSliceStart;let p=r.getActivity(u);if(!p||!p.autoScheduling||p.progress===100||Qu(p,r))continue;let m=s.get(String(u))??[],I=null,C=null,S=!1;for(let v of m){let A=r.getActivity(v.source);if(!A)continue;let _=o(v.source),E=_.startDate.getTime()!==A.startDate.getTime()||_.endDate.getTime()!==A.endDate.getTime(),x={...A,startDate:_.startDate,endDate:_.endDate},O=Ss(x,c,l),V={...x,startDate:O.startDate,endDate:O.endDate},Y=bn(v.source,c,l)?{...v,lag:0}:v,it=vs(V,p,Y,r);(!I||it.successorStart>I)&&(I=it.successorStart,C=String(v.id),S=v._summaryTargetId!==void 0&&!E)}I!==null&&S&&I<p.startDate&&(I=new Date(p.startDate));let P=a.get(u),g=P?{...P}:{activityId:u,startDate:p.startDate,endDate:p.endDate,drivingLinkId:null,kind:"asap",conflict:!1},h=g.earliestStart||g.latestStart||g.earliestEnd||g.latestEnd;if(!(!I&&!h)){if(I){let v=I;p.type===ar.MILESTONE&&(v=Is(p,I)),g.drivingLinkId=C,g.startDate=v,g.endDate=r.calculateEndDate({startDate:v,durationHours:p.durationHours,task:p}),g.earliestSchedulingStart=v,g.earliestSchedulingEnd=g.endDate}else p.constraintType===K.MSO?g.earliestStart&&(g.startDate=g.earliestStart,g.endDate=g.earliestEnd??r.calculateEndDate({startDate:g.earliestStart,durationHours:p.durationHours,task:p})):p.constraintType===K.MFO&&g.latestStart&&(g.startDate=g.latestStart,g.endDate=g.latestEnd??r.calculateEndDate({startDate:g.latestStart,durationHours:p.durationHours,task:p}));ur(p,g,r),a.set(u,g)}}return a}function Qu(e,t){return Rt(e.type,t.getChildren(e.id).length>0)}async function Ts(e,t,r,n,i,a){let s=new Map(r),o=n.getAllActivities(),c=o.length,l=[];for(let C of o)C.constraintType===K.ALAP&&l.push(C.id);if(l.length===0)return s;let d=new Map,u=new Map;for(let C of t){let S=String(C.source);d.has(S)||d.set(S,[]),d.get(S).push(C);let D=String(C.target);u.has(D)||u.set(D,[]),u.get(D).push(C)}let f=C=>{let S=s.get(C);if(S)return{startDate:S.startDate,endDate:S.endDate};let D=n.getActivity(C);return D?{startDate:D.startDate,endDate:D.endDate}:{startDate:new Date,endDate:new Date}},p=C=>!C.parentId||L(C.parentId)?n.getProjectEnd():f(C.parentId).endDate,m=(C,S)=>{let D=C,P=0;for(;D&&!L(D)&&P++<c+1;){if(String(D)===String(S))return!0;let g=n.getActivity(D);if(!g||!g.parentId)break;D=g.parentId}return!1},I=performance.now();for(let C of e){let S=await sr(I,a);if(S.aborted)return s;I=S.newSliceStart;let D=n.getActivity(C);if(!D||D.constraintType!==K.ALAP||!D.autoScheduling||D.progress===100||Rt(D.type,n.getChildren(C).length>0))continue;let P=p(D);if(!P)continue;let g=P,h=null,v=!1,A=d.get(String(C))??[];for(let It of A){if((It.lag??0)<0)continue;let se=n.getActivity(It.target);if(!se||se.autoScheduling===!1)continue;let Zi=f(It.target),Vd={...se,startDate:Zi.startDate,endDate:Zi.endDate},Ze=As(Vd,D,It,n);Ze<g&&(g=Ze),(h===null||Ze<h)&&(h=Ze,v=D.parentId&&!L(D.parentId)?m(It.target,D.parentId):!1)}if(h!==null)if(v)g=h;else{let It=f(C).endDate,se=It.getTime()>P.getTime()?It:P;g=h<se?h:se}else g>P&&(g=P);let E=(u.get(String(C))??[]).some(It=>It.type===M.FINISH_TO_START||It.type===M.FINISH_TO_FINISH),x=new Date(Date.UTC(g.getUTCFullYear(),g.getUTCMonth(),g.getUTCDate())),O=()=>n.getClosestWorkTime({date:x,dir:"past",task:D}),V=n.getClosestWorkTime({date:g,dir:"future",task:D}).getTime()===g.getTime(),Y;D.durationHours===0&&h===null?Y=E&&V?O():n.getClosestWorkTime({date:g,dir:"past",task:D}):D.durationHours===0?E?Y=O():Y=n.getClosestWorkTime({date:g,dir:"future",task:D}):Y=n.getClosestWorkTime({date:g,dir:"future",task:D});let it=n.calculateEndDate({startDate:Y,durationHours:-D.durationHours,task:D}),Le=s.get(C),lt=Le?{...Le}:{activityId:C,startDate:it,endDate:Y,drivingLinkId:null,kind:"alap",conflict:!1};lt.startDate=it,lt.endDate=Y,lt.drivingLinkId=null,lt.kind="alap";let yn=lt.earliestSchedulingStart??null;lt.earliestSchedulingStart=null,lt.earliestSchedulingEnd=null;let mn=yn!==null&&yn.getTime()>it.getTime()?yn:it;lt.latestSchedulingStart=mn,lt.latestSchedulingEnd=mn===it?Y:n.calculateEndDate({startDate:mn,durationHours:D.durationHours,task:D}),ur(D,lt,n),s.set(C,lt)}return s}var de={warn(){},error(){}};function Ne(e,t){t.cancelled||t.updatedIds.length===0||e.batchUpdate(()=>{for(let r of t.updatedIds){let n=t.plans.get(r);if(!n)continue;let i=e.getLiveActivity(r);i&&(i.startDate=n.startDate,i.endDate=n.endDate,e.updateActivity(r))}})}function Ln(e,t){let r=String(t.source),n=String(t.target);if(r===n)return!0;let i=new Map;for(let a of e){let s=String(a.source),o=String(a.target),c=i.get(s)??[];c.push(o),i.set(s,c)}return tf(i,n,r)}function wn(e){let t=new Map,r=new Map;for(let a of e){let s=String(a.source),o=String(a.target),c=t.get(s)??[];c.push(o),t.set(s,c),r.set(s,r.get(s)??0),r.set(o,(r.get(o)??0)+1)}let n=new ft;for(let[a,s]of r)s===0&&n.enqueue(a);let i=0;for(;!n.isEmpty();){let a=n.dequeue();i+=1;for(let s of t.get(a)??[]){let o=r.get(s)-1;r.set(s,o),o===0&&n.enqueue(s)}}return i!==r.size}function tf(e,t,r){if(t===r)return!0;let n=new Set([t]),i=new ft;for(i.enqueue(t);!i.isEmpty();){let a=i.dequeue(),s=e.get(a)??[];for(let o of s){if(o===r)return!0;n.has(o)||(n.add(o),i.enqueue(o))}}return!1}function Tt(e,t){switch(e.kind){case"create":return ef(e,t);case"update":return rf(e,t);case"delete":return nf(e,t)}}function pr(e,t){if(e.length===0)return{applied:!0};let r=t.port.getAllLinks(),n=new Map,i=[];for(let o of r){let c=_s(o);n.has(c)||n.set(c,o.id),i.push({source:o.source,target:o.target})}let a=wn(i),s=null;for(let{operation:o,linkId:c}of e){if(String(o.source)===String(o.target)){s={applied:!1,rejected:"self-link"};break}if(!t.port.getActivity(o.source)||!t.port.getActivity(o.target)){s={applied:!1,rejected:"activity-missing"};break}let l=_s(o),d=n.get(l);if(d!==void 0){s={applied:!1,rejected:"duplicate",linkId:d};break}if(n.set(l,c),a&&Ln(i,{source:o.source,target:o.target}))return{applied:!1,rejected:"cycle"};i.push({source:o.source,target:o.target})}if(!a&&wn(i))return{applied:!1,rejected:"cycle"};if(s)return s;for(let{operation:o,linkId:c}of e){let l=t.preserved?.get(c);t.port.addLink({id:c,source:o.source,target:o.target,type:o.type,lag:o.lag,...l?.ganttId===void 0?{}:{ganttId:l.ganttId},...l?.sectorId===void 0?{}:{sectorId:l.sectorId},...l?.proplannerId===void 0?{}:{proplannerId:l.proplannerId}})}return{applied:!0}}function _s(e){return JSON.stringify([String(e.source),String(e.target),e.type])}function ef(e,t){let{port:r}=t;if(String(e.source)===String(e.target))return{applied:!1,rejected:"self-link"};let n=r.getActivity(e.source),i=r.getActivity(e.target);if(!n||!i)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(Ln(s,{source:e.source,target:e.target}))return{applied:!1,rejected:"cycle"};let o=(t.newLinkId??af)(),c={id:o,source:e.source,target:e.target,type:e.type,lag:e.lag};return r.addLink(c),{applied:!0,linkId:o}}function rf(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 nf(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 fr=null;function af(){return fr===null&&(fr=Date.now()),fr+=1,String(fr)}var Ps={[M.FINISH_TO_START]:"fs",[M.START_TO_START]:"ss",[M.FINISH_TO_FINISH]:"ff",[M.START_TO_FINISH]:"sf"},Jt={fs:M.FINISH_TO_START,ss:M.START_TO_START,ff:M.FINISH_TO_FINISH,sf:M.START_TO_FINISH},Rs="fs";function Es(e){if(e in Jt)return Jt[e]}var bs=";",Ls=/^(\d+)(fs|ss|ff|sf)?(?:([+-]?)(\d+(?:\.\d+)?)d?)?$/i;function hr(e){let t=[],r=[],n=e.replace(/\s+/g,"");if(n.length===0)return{specs:t,errors:r};for(let i of n.split(bs)){if(i.length===0)continue;let a=sf(i);a?t.push(a):r.push(i)}return{specs:t,errors:r}}function sf(e){let t=e.toLowerCase(),r=Ls.exec(t);if(!r)return null;let[,n,i,a,s]=r,o=i?Jt[i]:Jt[Rs],c=0;if(s!==void 0){let l=Number(s);if(Number.isNaN(l))return null;c=a==="-"?-l:l}return{correlativeId:n,type:o,lag:c}}function mr(e){let{targetActivityId:t,currentLinks:r,desiredSpecs:n}=e,i=[],a=new Map;for(let c of n){let l=e.resolveActivityByCorrelative(c.correlativeId);if(l==null){i.push(c);continue}let d=yr(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(yr(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:i}}function yr(e,t){return`${String(e)}::${t}`}function gr(e){let{sourceActivityId:t,currentLinks:r,desiredSpecs:n}=e,i=[],a=new Map;for(let c of n){let l=e.resolveActivityByCorrelative(c.correlativeId);if(l==null){i.push(c);continue}let d=yr(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(yr(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:i}}function dt(e,t){return Math.sign(e)*Math.round(Math.abs(e)*t)}var ws={rawInputToConstraintDate(e,t){let r=new Date(e);return r.setUTCHours(0,0,0,0),r.getTime()===e.getTime()?t.getClosestWorkTime({direction:X.FUTURE,date:e,unit:ot.HOUR}):t.isWorkTime(e,ot.HOUR)?e:r},computeLagBetweenTasks(e,t,r){return r.calculateDuration(e,t)}};function On(e,t,r){switch(r){case"0":return{sourceDate:e.endDate,targetDate:t.startDate};case"1":return{sourceDate:e.startDate,targetDate:t.startDate};case"2":return{sourceDate:e.endDate,targetDate:t.endDate};case"3":return{sourceDate:e.startDate,targetDate:t.endDate}}}var xn=ws;var vr=class{adapter;reporter;currentCalculationId=0;topoCache=new cr;expandedLinksCache=new dr;constructor(t,r=de){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,n=rs(r,()=>this.currentCalculationId),i={plans:new Map,updatedIds:[],cycles:[],cancelled:!1};try{df(this.adapter);let a=Wt("schedule.total"),s=Wt("schedule.expandParentLinks"),o=this.adapter.getAllLinks(),c=this.expandedLinksCache.get(o,this.adapter);Et(s);let l=c;if((await ce(n)).aborted)return{...i,cancelled:!0};let d=Wt("schedule.scoping"),u=this.adapter.getAllIds(),f=uf(t,l,this.adapter),p=f.links,m=f.idSet;Et(d);let I=Wt("schedule.topologicalSort"),C=pf(this.topoCache,u,l,m);if(Et(I),C.hasCycles)return Et(a),{...i,cycles:[C.cycleNodes]};if((await ce(n)).aborted)return{...i,cancelled:!0};let S=Wt("schedule.processConstraints"),D=new Map;if(Cs(C.ordered,this.adapter,D),Et(S),(await ce(n)).aborted)return{...i,cancelled:!0};let P=Wt("schedule.asapPass"),g=await Ds(C.ordered,p,this.adapter,t,n,D);if(Et(P),(await ce(n)).aborted)return{...i,cancelled:!0};let h=Wt("schedule.alapPass"),v=await Ts(C.reversed,p,g,this.adapter,t,n);if(Et(h),(await ce(n)).aborted)return{...i,cancelled:!0};let A=Wt("schedule.diff"),_=[];for(let[E,x]of v){let O=this.adapter.getActivity(E);if(!O)continue;let V=O.startDate.getTime()!==x.startDate.getTime(),Y=O.endDate.getTime()!==x.endDate.getTime();(V||Y)&&_.push(E)}return Et(A),Et(a),{plans:v,updatedIds:_,cycles:[],cancelled:!1}}catch(a){return this.reporter.error("[AutoScheduler] Error during scheduling",a),i}}},cf=!1;function lf(){let e=globalThis.__SCHEDULER_PHASE_LOG__;return typeof e=="boolean"?e:cf}function Wt(e){return{name:e,startedAt:performance.now()}}function df(e){let t=e;typeof t.clearCalendarCache=="function"&&t.clearCalendarCache()}function Et(e){if(!lf())return;let t=performance.now()-e.startedAt;console.log(`[scheduler] ${e.name} ${t.toFixed(1)}ms`)}function uf(e,t,r){let n=e.triggerId;if(n==null)return{idSet:null,links:t};let i=ms(n,t);return ff(i,t,r)}function ff(e,t,r){let n=new Set(e.activityIds),i=new Set;for(let s of r.getAllActivities()){let o=String(s.id);s.constraintType===K.ALAP&&!n.has(o)&&(i.add(o),n.add(o))}if(i.size===0)return{idSet:n,links:e.links};let a=[...e.links];for(let s of t)(i.has(String(s.source))||i.has(String(s.target)))&&a.push(s);return{idSet:n,links:a}}function pf(e,t,r,n){let i=e.get(t,r);if(i.hasCycles){let s=n?Array.from(n):t;return or(s,r)}if(!n)return i;let a=ls(i.ordered,n);return{ordered:a,reversed:[...a].reverse(),hasCycles:!1,cycleNodes:[]}}function Os(e,t,r){let n=t.getActivity(e);if(!n)return;let i=r?{...n,endDate:r.endDate}:n,a=t.calendarReader.getCalendar(String(n.calendarId));for(let s of t.getIncomingLinkIds(e)){let o=t.getLink(s);if(!o)continue;let c=t.getActivity(o.source);if(!c||c.constraintType==="alap"||qt(n.type)&&(o.type===M.START_TO_FINISH||o.type===M.FINISH_TO_FINISH))continue;let{sourceDate:d,targetDate:u}=On(c,i,o.type),f=xn.computeLagBetweenTasks(d,u,a);f!==o.lag&&Tt({kind:"update",linkId:o.id,lag:f},{port:t})}}function xs(e,t){let r=t.getActivity(e);r&&qt(r.type)&&(r.durationHours=0)}function ue(e){let t=0,r=!1;for(let n of e)n.ponderator>0&&(t+=n.ponderator/100*n.progress,r=!0);return r?t:null}function Ar(e){return Number(e.toFixed(2))}function pt(e,t){return(Number(e)||0)*(Number(t)||0)/100}async function fe(e,t,r=!0,n={}){let i=t?Fn(e,t):vf(e),a=r?n.progressMode??"freeze-when-no-contribution":"skip";await hf(i,e,a,{recomputeRealWork:n.recomputeRealWork??!1})}function Cr(e,t){Fs(e,t,"skip")}async function hf(e,t,r,n={recomputeRealWork:!1}){let a=0;for(let s of e)Fs(s,t,r,n.recomputeRealWork),a+=1,a%200===0&&await Z()}function Fn(e,t){let r=new Set;for(let a of t)yf(a,e,r);if(r.size===0)return[];let n=Array.from(r),i=Ns(n,e);return Ms(n,i)}function yf(e,t,r){let n=t.getParentId(e);for(;n&&!L(n);){if(r.has(n))return;r.add(n),n=t.getParentId(n)}}function mf(e,t,r){let n=null,i=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();(n===null||l<n)&&(n=l),(i===null||d>i)&&(i=d),r&&(a+=gf(c,t.getChildren(o).length>0)),s.push({progress:Number(c.progress??0),ponderator:Number(c.ponderator??0)})}return{minStart:n,maxEnd:i,realWorkSum:a,weightedChildren:s}}function Fs(e,t,r="freeze-when-no-contribution",n=!1){let i=t.getActivity(e);if(!i)return;let a=t.getChildren(e);if(a.length===0)return;let s=mf(a,t,n);if(s.minStart===null||s.maxEnd===null)return;let o=String(i.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=ue(s.weightedChildren);r!=="skip"&&(f!==null||r==="zero-when-no-contribution")&&t.setActivityField(e,"progress",Ar(f??0)),n&&t.setActivityField(e,"realWorkHours",s.realWorkSum)}function gf(e,t){return t?Number(e.realWorkHours)||0:pt(e.workHours,e.progress)}function vf(e){let t=Af(e),r=Ns(t,e);return Ms(t,r)}function Af(e){let t=new Set;return e.forEachActivity(r=>{r.parentId!==null&&t.add(r.parentId)}),Array.from(t)}function Ns(e,t){let r=new Map;for(let n of e)r.set(n,Cf(n,t));return r}function Cf(e,t){let r=0,n=e;for(;n&&!L(n)&&t.getActivity(n);)r+=1,n=t.getParentId(n);return r}function Ms(e,t){return[...e].sort((r,n)=>(t.get(n)??0)-(t.get(r)??0))}var Ws={updateActivityDuration:xs,updateTaskTiming:Sf("updateTaskTiming"),adjustLinkLagOnTaskMove:Os,recordLastStartDate:If};function If(e,t){let r=t.getActivity(e);r&&t.setLastStartDate(e,r.startDate)}function Bt(e,t,r,n){for(let i of t){let a=i in Ws?Ws[i]:void 0;if(!a){console.warn(`[replay post-processors] unknown: ${i} \u2014 skipping. Add an entry in POST_PROCESSORS if a fixture needs it.`);continue}a(e,r,n??null)}}function Sf(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 U(){return{valid:!0}}function tt(e,t){return t!==void 0?{valid:!1,reason:e,notification:t}:{valid:!1,reason:e}}function j(){return{allowed:!0}}function z(e,t){return t!==void 0?{allowed:!1,reason:e,alertKey:t}:{allowed:!1,reason:e}}function W(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 Bs={targetField:"name",canEdit(){return j()},parseInput(e){return typeof e!="string"?N("not_a_string"):w(e)},validate(){return U()},transform(e,t){return W({name:t},{autoSchedule:!1,postProcessors:[]})},trackEvent:"activity_name_entry"};var Us={targetField:"description",canEdit(){return j()},parseInput(e){return typeof e!="string"?N("not_a_string"):w(e.trim())},validate(){return U()},transform(e,t){return W({description:t},{autoSchedule:!1,postProcessors:[]})},trackEvent:"activity_description_entry"};function St(e){return e.constraintType??K.ASAP}var Ir=100;function pe(e){return e.progress>=Ir}function et(e,t){return Rt(e.type,t.hasChildren(e.id))}function js(e){return e.progress>0}function Hs(e){return e.hasLookaheadTasks}function Me(e,t){return Math.round(Math.ceil(e*t*60)/60)}var he=e=>({endDate:e});function Xt(e,t){if(t){let r=new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(e),n=i=>Number(r.find(a=>a.type===i)?.value);return new Date(Date.UTC(n("year"),n("month")-1,n("day")))}return new Date(Date.UTC(e.getFullYear(),e.getMonth(),e.getDate()))}function kr(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),n=f=>Number(r.find(p=>p.type===f)?.value),i=n("year"),a=n("month"),s=n("day"),o=Date.UTC(i,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 kf(e,t){let r=Xt(t);for(;!e.isWorkTime(r,ot.DAY);)r=new Date(r),r.setUTCDate(r.getUTCDate()+1),r=Xt(r);return r}function Nn(e,t){return e.getClosestWorkTime({direction:X.FUTURE,date:t,unit:ot.HOUR})}function Mn(e,t){let r=kf(e,t),n=new Date(r);return n.setUTCDate(n.getUTCDate()+1),n.setUTCHours(0,0,0,0),e.getClosestWorkTime({direction:X.PAST,date:n,unit:ot.HOUR})}var Sr=new Set(["snet","snlt","mso"]),Wn=new Set(["fnet","fnlt","mfo"]),Ut=new Set(["asap","alap"]),Dr="snet";function bt(e,t,r){if(!Sr.has(r)&&!Wn.has(r))return e;let n=Sr.has(r)?Nn(t,e):Mn(t,e),i=new Date(e);return i.setUTCHours(n.getUTCHours(),n.getUTCMinutes(),n.getUTCSeconds(),n.getUTCMilliseconds()),i}var Lt=()=>({constraintType:Dr});var jt=e=>({constraintDate:e}),Vs=e=>({constraintDate:e});var Ys={UPDATE_TASK_TIMING:"updateTaskTiming",ADJUST_LINK_LAG_ON_TASK_MOVE:"adjustLinkLagOnTaskMove",RECORD_LAST_START_DATE:"recordLastStartDate"};var Ks={UNCHANGED:"unchanged",OUT_OF_RANGE:"out_of_range",NEGATIVE_DURATION:"negative_duration",NOT_WORKING_DAY:"not_working_day",BEFORE_PARENT_START:"before_parent_start",BEFORE_START_DATE:"before_start_date",BEFORE_DATE_ORIGIN:"before_date_origin",CONSTRAINT_VIOLATION:"constraint_violation",MISSING_ID:"missing_id",UNKNOWN_CALENDAR:"unknown_calendar"};function ye(e,t,r){return is(e,t,r)}function me(e,t,r){return as(e,t,r)}var $s={targetField:"durationHours",canEdit(e,t){return pe(e)?z("completed","cant_edit_completed_activity"):et(e,t)?z("summary","summary_column_value"):j()},parseInput(e,t,r){let n=parseFloat(String(e));return Number.isNaN(n)?N("not_a_number"):w(r.inputUnit==="hours"?n:Me(n,r.hoursPerDay))},validate(e,t,r){return Gs(r)?tt(Ks.NEGATIVE_DURATION):Df(t,r)?tt("unchanged"):U()},transform(e,t,r){if(Gs(t))return W({},{autoSchedule:!1,postProcessors:[]});let n=Tf(e,t,r),i=_f(e,t,r,n.violated);return{...W(i,{autoSchedule:!0,postProcessors:[Ys.RECORD_LAST_START_DATE]}),...n.violated?{constraintWarning:me(n.constraintType,n.constraintDate,zs(e,t,r)??void 0)}:{}}},trackEvent:"activity_duration_entry"};function Gs(e){return Math.sign(e)===-1}function Df(e,t){return e===t}function Tf(e,t,r){let n=r.calendars.getCalendar(e.calendarId);if(!n)return{violated:!1};let i=e.constraintType;if(i!=="fnet"&&i!=="fnlt"&&i!=="mfo")return{violated:!1};let a=n.calculateEndDate(e.startDate,t);return ye(i,e.constraintDate,a)}function _f(e,t,r,n=!1){let i={};n&&Object.assign(i,Lt(),jt(e.startDate));let a=Fe(e.durationHours,t);a&&(i.type=a),i.durationHours=t;let s=zs(e,t,r);return s&&Object.assign(i,he(s)),i}function zs(e,t,r){let n=r.calendars.getCalendar(e.calendarId);return n?n.calculateEndDate(e.startDate,t):null}var ge=e=>({realWorkHours:e});var Pf=0,Rf=Ir,qs=0,Js={targetField:"progress",canEdit(e,t){return Hs(e)?z("has_lookahead_tasks","cant_edit_actvity_with_task"):et(e,t)?z("summary","summary_column_value"):j()},parseInput(e){let t=parseFloat(String(e));return Number.isNaN(t)?N("not_a_number"):w(t)},validate(e,t,r){return Ef(r)?tt("out_of_range"):U()},transform(e,t,r){let n=bf(t),i=Lf(t),a=xf(e,t,r.hierarchy),s={progress:t,autoScheduling:n,...ge(a.get(e.id)??0)},o=i?wf(e,t,n,r.hierarchy,a):[],c=i?Nf(e,t,r.hierarchy):[],l=o.length+c.length>0?[...o,...c]:void 0,d=[],u=i?Wf(e,t):void 0;return W(s,{autoSchedule:!1,postProcessors:d,cascadeMutations:l,trackingEvents:u})},trackEvent:"activity_progress_entry"};function Ef(e){return e<Pf||e>Rf}function bf(e){return e===qs}function Lf(e){return e===Ir||e===qs}function wf(e,t,r,n,i){return n.getDescendantIds(e.id).map(s=>({activityId:s,fields:Of(t,r,i.get(s)??0)}))}function Of(e,t,r){return{progress:e,autoScheduling:t,...ge(r)}}function xf(e,t,r){let n=new Map,i=s=>{let o=0;for(let c of r.getChildHhInfo(s)){let l=r.hasChildren(c.id)?i(c.id):pt(c.workHours,t);n.set(c.id,l),o+=l}return o},a=r.hasChildren(e.id)?i(e.id):pt(e.workHours,t);return n.set(e.id,a),n}function Ff(e,t){let r=[e.id,...t.getDescendantIds(e.id)],n=a=>t.getChildProgressInfo(a).some(s=>t.hasChildren(s.id)),i=a=>t.getAncestorIds(a).length;return r.filter(a=>n(String(a))).map(String).sort((a,s)=>i(s)-i(a))}function Nf(e,t,r){let n=new Map;n.set(e.id,t);for(let s of r.getDescendantIds(e.id))n.set(s,t);let i=[...Ff(e,r),...r.getAncestorIds(e.id)],a=[];for(let s of i){let o=Mf(s,n,r);n.set(s,o),a.push({activityId:s,fields:{progress:o}})}return a}function Mf(e,t,r){let n=r.getChildProgressInfo(e).map(i=>({progress:t.has(i.id)?t.get(i.id):i.progress,ponderator:i.ponderator??0}));return Number((ue(n)??0).toFixed(2))}function Wf(e,t){return[{name:"activity_progress_update_radio_button",properties:{activity_id:e.id,activity_name:e.name,progress_updated:t}}]}var Xs={targetField:"cost",canEdit(e,t){return et(e,t)?z("summary","summary_column_value"):j()},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 U()},transform(e,t,r){let n=Bf(e,t,r.hierarchy);return W({cost:t},{autoSchedule:!1,postProcessors:[],cascadeMutations:n})},trackEvent:"activity_cost_budgeted_entry"};function Bf(e,t,r){let n=new Map;n.set(e.id,t);let i=[];for(let a of r.getAncestorIds(e.id)){let s=0;for(let o of r.getChildCostInfo(a))s+=n.has(o.id)?n.get(o.id):o.cost;n.set(a,s),i.push({activityId:a,fields:{cost:s}})}return i}var Zs={targetField:"usedCost",canEdit(e,t){return et(e,t)?z("summary","summary_column_value"):j()},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 U()},transform(e,t,r){let n=Uf(e,t,r.hierarchy);return W({usedCost:t},{autoSchedule:!1,postProcessors:[],cascadeMutations:n})},trackEvent:"activity_cost_spent_entry"};function Uf(e,t,r){let n=new Map;n.set(e.id,t);let i=[];for(let a of r.getAncestorIds(e.id)){let s=0;for(let o of r.getChildUsedCostInfo(a))s+=n.has(o.id)?n.get(o.id):o.usedCost;n.set(a,s),i.push({activityId:a,fields:{usedCost:s}})}return i}var Qs={targetField:"workHours",canEdit(e,t){return et(e,t)?z("summary","summary_column_value"):j()},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 U()},transform(e,t,r,n){let i=to(t,e.progress),a=String(n).trim()===""?[]:jf(e,t,i,r.hierarchy);return W({workHours:t,...ge(i)},{autoSchedule:!1,postProcessors:[],cascadeMutations:a})},trackEvent:"activity_labor_hours_budgeted_entry"};function to(e,t){return pt(e,t)}function jf(e,t,r,n){let i=new Map,a=new Map;i.set(e.id,t),a.set(e.id,r);let s=[];for(let o of n.getAncestorIds(e.id)){let c=0,l=0;for(let d of n.getChildHhInfo(o)){let u=i.has(d.id)?i.get(d.id):d.workHours,f=a.has(d.id)?a.get(d.id):d.realWorkHours??to(d.workHours,d.progress);c+=u,l+=f}i.set(o,c),a.set(o,l),s.push({activityId:o,fields:{workHours:c,...ge(l)}})}return s}function Tr(e,t){return e.getUTCFullYear()===t.getUTCFullYear()&&e.getUTCMonth()===t.getUTCMonth()&&e.getUTCDate()===t.getUTCDate()}function Bn(e,t){return e.getTime()<t.getTime()}function ve(e){return e instanceof Date&&!Number.isNaN(e.getTime())}var _r=e=>({durationHours:e});var eo={targetField:"startDate",canEdit(e,t){return et(e,t)?z("summary","summary_column_value"):js(e)?z("has_progress","cant_edit_activity_with_progress"):j()},parseInput(e,t,r){return ve(e)?w(Xt(e,"UTC")):N("invalid_date")},validate(e,t,r,n){if(Tr(t,r))return tt("unchanged");let i=Hf(e,r,n);return i||U()},transform(e,t,r){let n=r.calendars.getCalendar(e.calendarId);if(!n)return W({startDate:t,...Lt(),...jt(t)},{autoSchedule:!0,postProcessors:["adjustLinkLagOnTaskMove"]});let i=Nn(n,t),a=e.type==="milestone",s=a?i:n.calculateEndDate(i,e.durationHours),o=i;return{...W({startDate:i,...he(s),...a?_r(0):{},...Lt(),...jt(o)},{autoSchedule:!0,postProcessors:["adjustLinkLagOnTaskMove"]}),constraintWarning:Vf(e,i,n)}},trackEvent:"activity_start_date_entry"};function Hf(e,t,r){let n=r.hierarchy.getParentStartDateIfHasPredecessors(e.id);if(!n)return null;let i=Xt(n);return t.getTime()<i.getTime()?tt("before_parent_start"):null}function Vf(e,t,r){let n=r.calculateEndDate(t,e.durationHours),i=xe(St(e),t,n),a=ye(St(e),e.constraintDate,i);if(a.violated)return me(a.constraintType,a.constraintDate,i)}var Yf=99.999,no={targetField:"endDate",canEdit(e,t){return et(e,t)?z("summary","summary_column_value"):Kf(e)?z("completed","cant_edit_completed_activity"):j()},parseInput(e,t,r){if(!ve(e))return N("invalid_date");let n=Xt(e,"UTC"),i=r.calendars.getCalendar(t.calendarId);return i?i.isWorkTime(n,ot.DAY)?w(Mn(i,n)):r.dateFormat.split(" ").length>1?w(n):w(i.getClosestWorkTime({direction:"past",date:n,unit:ot.HOUR})):w(n)},validate(e,t,r,n){if(Tr(e.endDate,r))return tt("unchanged");if(Gf(r,e))return tt("before_date_origin");if($f(r,e))return tt("before_start_date");let i=zf(r,e,n);return i||U()},transform(e,t,r){let n=qf(e,t),i=Jf(e,t,r,!!n);return{...W(i,{autoSchedule:!0,postProcessors:["updateTaskTiming"]}),...n?{constraintWarning:n}:{}}},trackEvent:"activity_end_date_entry"};function Kf(e){return e.progress>=Yf}function Gf(e,t){return t.dateOrigin?Bn(e,t.dateOrigin):!1}function $f(e,t){return Bn(e,t.startDate)}function zf(e,t,r){let n=r.calendars.getCalendar(t.calendarId);return n?n.isWorkTime(e,ot.DAY)?null:tt("not_working_day"):null}function qf(e,t){if(St(e)===K.MSO)return;let n=xe(St(e),e.startDate,t),i=ye(St(e),e.constraintDate,n);if(i.violated)return me(i.constraintType,i.constraintDate,n)}function Jf(e,t,r,n=!1){let i={};qt(e.type)&&!n&&ro(e)?Object.assign(i,jt(e.startDate)):(n||ro(e))&&Object.assign(i,Lt(),jt(e.startDate));let o=Xf(e,t,r),c=Fe(e.durationHours,o);return c&&(i.type=c),Object.assign(i,_r(o)),i.endDate=t,i}function ro(e){return Ut.has(St(e))}function Xf(e,t,r){let n=r.calendars.getCalendar(e.calendarId);return n?n.calculateDuration(e.startDate,t):e.durationHours}var Zf=new Set(Object.values(K)),io={targetField:"constraintType",canEdit(e,t){return pe(e)?z("completed","cant_edit_completed_activity"):et(e,t)?z("summary","summary_column_value"):j()},parseInput(e){let t=String(e).toLowerCase();return Qf(t)?w(t):N("invalid_constraint_type")},validate(){return U()},transform(e,t,r){let n=tp(e,t,r);return W(n,{autoSchedule:!0})}};function Qf(e){return Zf.has(e)}function tp(e,t,r){let n=rp(e,t);return{constraintType:t,...Vs(ep(e,t,n,r))}}function ep(e,t,r,n){if(e.type!=="milestone"||!r)return r;let i=n.calendars.getCalendar(String(e.calendarId));return i?bt(r,i,t):r}function rp(e,t){return Ut.has(t)?null:Sr.has(t)?e.startDate:Wn.has(t)?e.endDate:e.constraintDate}var ao={targetField:"constraintDate",canEdit(e,t){return pe(e)?z("completed","cant_edit_completed_activity"):et(e,t)?z("summary","summary_column_value"):j()},parseInput(e){return ve(e)?w(e):N("invalid_date")},validate(){return U()},transform(e,t,r){let n=so(e)?Dr:St(e),i=r.calendars.getCalendar(e.calendarId),a=i?bt(t,i,n):t,s=np(e,a);return W(s,{autoSchedule:!0})}};function np(e,t){return{constraintDate:t,...so(e)?Lt():{}}}function so(e){return Ut.has(St(e))||!e.constraintType}var oo={targetField:"calendarId",canEdit(){return j()},parseInput(e){let t=String(e).trim();return ip(t)?N("empty_calendar"):w(t)},validate(e,t,r,n){return ap(e.calendarId,r)?tt("unchanged"):n.calendars.getCalendar(r)?U():tt("unknown_calendar")},transform(e,t,r){return W(sp(e,t,r),{autoSchedule:!0,postProcessors:[]})},trackEvent:"activity_calendar_assignment"};function ip(e){return e===""}function ap(e,t){return e===t}function sp(e,t,r){let n={calendarId:t,assignedDefaultCalendar:!1},i=r.calendars.getCalendar(t);if(i){let a=e.durationHours===0,s=a?op(e.startDate):e.startDate,o=i.getClosestWorkTime({date:s,direction:"future",unit:"hour"});if((!e.autoScheduling||a||i.getWorkHours(e.startDate).length===0)&&(n.startDate=o),!e.autoScheduling)return n;let c=n.startDate??e.startDate;Object.assign(n,he(i.calculateEndDate(c,e.durationHours)))}return n}function op(e){return new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()))}var co={targetField:"customId",canEdit(e,t){return et(e,t)?z("summary","summary_column_value"):j()},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 U()},transform(e,t){return W({customId:t},{autoSchedule:!1,postProcessors:[]})},trackEvent:"schedule_custom_id_edition"};var lo={targetField:"subcontractId",canEdit(){return j()},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 U()},transform(e,t){return W({subcontractId:t},{autoSchedule:!1,postProcessors:[]})}};function We(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 Pr(e){return e.some(t=>We(t)===null)}var uo={targetField:"responsableIds",canEdit(){return j()},parseInput(e){return e==null?w([]):Array.isArray(e)?w(e):N("not_an_array")},validate(e,t,r){return Pr(r)?tt("missing_id"):U()},transform(e,t){let r=t.map(We).filter(n=>n!==null);return W({responsableIds:r},{autoSchedule:!1,postProcessors:[]})}};var fo={targetField:"tagIds",canEdit(){return j()},parseInput(e){return e==null?w([]):Array.isArray(e)?w(e):N("not_an_array")},validate(e,t,r){return Pr(r)?tt("missing_id"):U()},transform(e,t){let r=t.map(We).filter(n=>n!==null);return W({tagIds:r},{autoSchedule:!1,postProcessors:[]})}};var cp=new Map([[R.TEXT,Bs],[R.DESCRIPTION,Us],[R.DURATION,$s],[R.PROGRESS,Js],[R.COST,Xs],[R.USED_COST,Zs],[R.HH_WORK_TIME,Qs],[R.START_DATE,eo],[R.END_DATE,no],[R.CONSTRAINT_TYPE,io],[R.CONSTRAINT_DATE,ao],[R.CALENDAR_ID,oo],[R.CUSTOM_ID,co],[R.SUBCONTRACT_ID,lo],[R.RESPONSABLES,uo],[R.TAGS,fo]]);function Ht(e){return cp.get(e)}function Ae(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 b={ID:"id",PROPLANNER_ID:"proplannerId",PARENT:"parentId",NAME:"name",DESCRIPTION:"description",TYPE:"type",START_DATE:"startDate",END_DATE:"endDate",DURATION_HOURS:"durationHours",CONSTRAINT_TYPE:"constraintType",CONSTRAINT_DATE:"constraintDate",AUTO_SCHEDULING:"autoScheduling",CALENDAR_ID:"calendarId",ASSIGNED_DEFAULT_CALENDAR:"assignedDefaultCalendar",DATE_ORIGIN:"dateOrigin",PROGRESS:"progress",COST:"cost",USED_COST:"usedCost",REAL_COST:"realCost",WORK_HOURS:"workHours",REAL_WORK_HOURS:"realWorkHours",PONDERATOR:"ponderator",HAS_CUSTOM_PONDERATOR:"hasCustomPonderator",CORRELATIVE_ID:"correlativeId",UNIQUE_CORRELATIVE_ID:"uniqueCorrelativeId",CUSTOM_ID:"customId",SUBCONTRACT_ID:"subcontractId",IS_LOOKAHEAD:"isLookahead",HAS_LOOKAHEAD_TASKS:"hasLookaheadTasks",NEW_ACTIVITIES_ARRAY:"newActivityIds",HAS_NEW_ACTIVITIES:"hasNewActivities",IS_NEW_ACTIVITY:"isNewActivity",PENDING_REQUEST_IDS:"pendingRequestIds",RESPONSABLE_IDS:"responsableIds",TAG_IDS:"tagIds",BASELINE_POINTS:"baselinePoints",BASELINE_SNAPSHOT:"baselineSnapshot",SUM_OF_DURATION_RECURSIVELY:"recursiveDurationHours",IS_CRITICAL:"isCritical",FREE_SLACK_HOURS:"freeSlackHours",EXPECTED_PROGRESS:"expectedProgress",EXPECTED_PROGRESS_BASELINE:"expectedProgressBaseline",STATUS:"status",CRITICAL_PATH:"criticalPath"},Un={ID:"id",SOURCE:"source",TARGET:"target",TYPE:"type",LAG:"lag",SOURCE_LAG:"_sourceLag",TARGET_LAG:"_targetLag",TRUE_LAG:"_trueLag",SUMMARY_SOURCE_ID:"_summarySourceId",SUMMARY_TARGET_ID:"_summaryTargetId",GANTT_ID:"ganttId",SECTOR_ID:"sectorId",PROPLANNER_ID:"proplannerId"};var lp=["name","description","type","startDate","endDate","durationHours","constraintType","constraintDate","calendarId","assignedDefaultCalendar","autoScheduling","progress","cost","usedCost","workHours","realWorkHours","customId","subcontractId","responsableIds","tagIds"],po=new Set(lp);function rt(e,t,r,n){e.setActivityFieldDynamic(t,r,n)}function ho(e,t,r,n){e.setLinkFieldDynamic(t,r,n)}function Qt(e){return{...e,startDate:new Date(e.startDate),endDate:new Date(e.endDate),constraintDate:_t(e.constraintDate),dateOrigin:_t(e.dateOrigin),newActivityIds:[...e.newActivityIds],pendingRequestIds:[...e.pendingRequestIds],responsableIds:[...e.responsableIds],tagIds:[...e.tagIds],baselinePoints:e.baselinePoints.map(t=>({...t,startDate:_t(t.startDate),endDate:_t(t.endDate)})),baselineSnapshot:dp(e.baselineSnapshot),criticalPath:up(e.criticalPath)}}function _t(e){return e===null?null:new Date(e)}function dp(e){return e===null?null:{...e,startDate:_t(e.startDate),endDate:_t(e.endDate)}}function up(e){return e===null?null:{...e,earlyStart:_t(e.earlyStart),earlyFinish:_t(e.earlyFinish),lateStart:_t(e.lateStart),lateFinish:_t(e.lateFinish)}}function Q(e){return structuredClone(e)}var go=200;function Vt(e,t){let r=new Set([String(e)]);for(let n of t.cascadeMutations??[])r.add(String(n.activityId));return r}async function q(e,t){let r=new Map,n=0;for(let i of t){n+=1,n%go===0&&await Z();let a=e.getActivity(i);a&&r.set(i,J(a))}return r}function J(e){return Qt(e)}function Rr(e,t){let r=e.getActivity(t);return r?Qt(r):null}function Yt(e,t,r){yo(e,t,r.patch);for(let n of r.cascadeMutations??[])yo(e,n.activityId,n.fields)}function yo(e,t,r){for(let[n,i]of Object.entries(r)){if(!po.has(n))throw new Error(`applyFieldChanges: column write to non-writable field "${n}"`);rt(e,t,n,i)}}async function vo(e,t,r,n){let i=[],a=0;for(let s of r){a+=1,a%go===0&&await Z();let o=fp(e,t,s,n);o&&i.push(o)}return i}function fp(e,t,r,n){let i=e.getActivity(r);if(!i)return{id:r,kind:"deleted",after:null};let a=t.get(r);if(!a&&n?.has(r))return pp(r,n.get(r),i);let s=Hn(a,i);return hp(s,n,r,i),a&&Object.keys(s).length===0?null:{id:r,kind:a?"updated":"created",fields:s,after:J(i)}}function pp(e,t,r){return t===r.correlativeId?null:{id:e,kind:"updated",fields:{correlativeId:{before:t,after:r.correlativeId}},after:J(r)}}function hp(e,t,r,n){if(!t?.has(r)||Object.hasOwn(e,"correlativeId"))return;let i=t.get(r);i!==n.correlativeId&&(e.correlativeId={before:i,after:n.correlativeId})}function Hn(e,t){let r={},n=e??{},i=t,a=new Set([...Object.keys(n),...Object.keys(i)]);for(let s of a)(Object.hasOwn(n,s)!==Object.hasOwn(i,s)||!jn(n[s],i[s]))&&(r[s]={before:mo(n[s]),after:mo(i[s])});return r}function mo(e){return e===null||typeof e!="object"?e:Q(e)}function jn(e,t){if(Object.is(e,t))return!0;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if(e==null||t==null)return!1;if(Array.isArray(e)||Array.isArray(t))return!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length?!1:e.every((s,o)=>jn(s,t[o]));if(typeof e!="object"||typeof t!="object")return!1;let r=e,n=t,i=Object.keys(r),a=Object.keys(n);return i.length!==a.length?!1:i.every(s=>Object.hasOwn(n,s)&&jn(r[s],n[s]))}function Er(e,t,r){let n=new Set;n.add(e);for(let i of t)n.add(i);for(let i of r)n.add(i);return n}function Vn(e,t){let r=new Set;for(let n of e)r.add(String(n));for(let n of t)r.add(n);return r}function Ce(e,t,r,n,i){for(let a of t){if(r.has(a.activityId)||(i.add(a.activityId),n.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),n.set(a.activityId,o)}}var yp=/^(\d{4})\/(\d{1,2})\/(\d{1,2})\s+(\d{1,2}):(\d{2})$/;function wt(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(yp);if(!t)throw new Error(`[parseFromBackend] unsupported date format "${e}" (expected "YYYY/MM/DD H:MM" or ISO)`);let[,r,n,i,a,s]=t;return new Date(Date.UTC(Number(r),Number(n)-1,Number(i),Number(a),Number(s)))}function Ie(e,t,r,n){if(e.getTime()>r.getTime())return 0;if(t.getTime()<r.getTime()||e.getTime()===t.getTime())return 100;let i=n.calculateDuration(e,r),a=n.calculateDuration(e,t);return a===0?0:i*100/a}var mp=e=>e.type==="project",gp=(e,t,r)=>{let n=e.calendarId,i=n!=null?r.calendarReader.getCalendar(String(n)):null;if(!i)return 0;let a=s=>s instanceof Date?s:wt(String(s));return Ie(a(e.startDate),a(e.endDate),t,i)};function vp(e,t,r){let n=[],i=(s,o)=>{let c=r.getActivity(s);c&&c.expectedProgress!==o&&(r.setActivityField(s,"expectedProgress",o),n.push(String(s)))},a=s=>{let o=r.getActivity(s);if(!o)return 0;if(!mp(o)){let d=gp(o,t,r);return i(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 i(s,l),l};for(let s of e)a(s);return n}function te(e,t){let r=[];e.forEachActivity((n,i)=>{n.parentId===null&&r.push(i)}),vp(r,t,e)}function ut(e){let t=e?.baselinePoints;return!Array.isArray(t)||t.length===0?null:t.find(r=>r.isActiveVersion)??null}var Ap=e=>e.type==="project",Cp=e=>ut(e),Ip=(e,t,r,n)=>{let i=Cp(e);if(!i)return 0;let a=(i.baseCalendarId!=null?r.getBaseCalendar(`${i.baseCalendarId}-base`):null)??(n?r.getBaseCalendar(n):null);return!a||!i.startDate||!i.endDate?0:Ie(i.startDate,i.endDate,t,a)};function Yn(e,t,r,n=null){let i=[],a=(o,c)=>{let l=r.getActivity(o);l&&l.expectedProgressBaseline!==c&&(r.setActivityField(o,"expectedProgressBaseline",c),i.push(o))},s=o=>{let c=r.getActivity(o);if(!c)return 0;if(!Ap(c)){let u=Ip(c,t,r,n);return a(o,u),u}let l=0;for(let u of r.getChildrenIds(o)){let f=s(u),p=r.getActivity(u),m=typeof p?.ponderator=="number"?p.ponderator:0;l+=f*m}let d=l/100;return a(o,d),d};for(let o of e)s(o);return i}function Se(e,t,r=null){let n={getChildrenIds:a=>e.getChildren(String(a)).map(s=>String(s)),getActivity:a=>e.getActivity(a),setActivityField:(a,s,o)=>rt(e,a,s,o),getBaseCalendar:a=>e.calendarReader.getCalendar(a)},i=[];return e.forEachActivity((a,s)=>{a.parentId===null&&i.push(s)}),Yn(i,t,n,r)}var Ao=e=>Math.round(e*100)/100;function Sp(e,t){return(t==="Baseline"?e.expectedProgressBaseline:e.expectedProgress)??void 0}function kp(e,t){let r=Ao(e),n=Ao(t);return r>99.99?Nt.DONE:n>r?Nt.OVERDUE:e>0&&r>n?Nt.ADVANCEMENT:e===0&&t===0?Nt.WAITING:e>0&&r<n?Nt.DOING:Nt.WAITING}function Ot(e,t){let r=[];return e.forEachActivity((n,i)=>{let a=typeof n.progress=="number"?n.progress:0,s=kp(a,Sp(n,t));n.status!==s&&(rt(e,i,rr,s),r.push(i))}),r}function Kn(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=(i,a)=>s=>s===void 0?t[i]():(t[a](s),n),n={__isMomentShim:!0,clone:()=>Kn(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 n}Kn.isMoment=e=>!!e&&typeof e=="object"&&e.__isMomentShim===!0;var gt=Kn;function Dp(e){return e&&e.constructor===Date?!!(e.getFullYear&&e.getMonth&&e.getDate):!1}function br(e){return Dp(e)&&!isNaN(e.getTime())}function k(e,t,r,n){if(!br(new Date(t)))throw new Error(`Invalid date argument for calculateEndDate method. Date: ${t}, Activity: ${JSON.stringify(n)}`);let i=t;return e.calculateEndDate({start_date:new Date(i),duration:r,unit:"hour",task:n})}function ht(e){if(!br(new Date(e.dateBaseToCalculate)))throw new Error("Invalid date argument for getClosestWorkTime method");let{dateBaseToCalculate:t,activityCalendar:r,direction:n,activity:i}=e;return r.$gantt.getClosestWorkTime({date:new Date(t),dir:n,unit:"hour",task:i})}var Tp=e=>e?e.$level===1:!1,_p=e=>e.type==="project",Pp=e=>e.$level!==0,Rp=e=>e.type==="task",Ep=e=>e.type==="task"||e.type==="milestone",ct={byFirstLevel:Tp,filterByParentType:_p,avoidSubproject:Pp,byTaskType:Rp,byTaskTypeAndMilestone:Ep};var y=Object.freeze({MFO:"mfo",MSO:"mso",FNLT:"fnlt",FNET:"fnet",SNET:"snet",SNLT:"snlt",ALAP:"alap",ASAP:"asap"});var H=Object.freeze({FS:"fs",SS:"ss",FF:"ff",SF:"sf"});function ee(e){return{0:"fs",1:"ss",2:"ff",3:"sf"}[Number(e)]||"sf"}function Co(e){let{gantt:t,pendingParentsWithNoLinks:r,calculations:n,linkProperty:i}=e;try{let a=bp({gantt:t,pendingParentsWithNoLinks:r});if(a.length===0)return new Set;let s=Lp({gantt:t,subprojectsWithNoLinks:a}),o=wp({gantt:t,childrenIds:s,linkProperty:i,getArrayOfLinkedActivities:Op,calculations:n});return new Set(o.map(c=>c.id))}catch(a){throw a}}function bp(e){let{gantt:t,pendingParentsWithNoLinks:r}=e;return t.getTaskByTime().filter(ct.filterByParentType).filter(n=>r.has(n.id)).map(n=>n.id)}function Lp(e){let{gantt:t,subprojectsWithNoLinks:r}=e,n=new Set;for(let i of r)t.getChildren(i).filter(o=>{let c=t.getTask(o),l=ct.byTaskTypeAndMilestone(c),d=Number(c.progress)<100;return l&&d}).forEach(o=>n.add(o));return[...n]}function wp(e){let{gantt:t,childrenIds:r,linkProperty:n,getArrayOfLinkedActivities:i,calculations:a}=e,s=[];for(let o of r){let c=t.getTask(o),l=c[n]||[];i({gantt:t,links:l,linkDirection:n==="$source"?"target":"source"}).every(f=>a.has(f))&&s.push(c)}return s}function Op(e){let{gantt:t,links:r,linkDirection:n}=e,i=[];for(let a of r){let s=t.getLink(a);if(!s){`${a}`;continue}let o=Number(s[n]);i.push(o)}return i}function Io({gantt:e,linkProperty:t,direction:r}){try{let n=xp(e,t);if(r==="forward")return{chainStartActivities:n,activitiesStartChainButChildrenOfLinkedParents:null};if(r==="backward")return Fp(n,e,t)}catch(n){throw console.log("Critical Path",n),n}}function xp(e,t){return e.getTaskByTime().filter(ct.avoidSubproject).filter(ct.byTaskTypeAndMilestone).filter(r=>!r[t].length)}function Fp(e,t,r){let n=[],i=new Set;return e.forEach(a=>{let s=Number(a.parent),o=t.getTask(s);o&&(o[r].length>0?i.add(a.id):o.constraint_type!=="fnlt"&&n.push(a))}),{chainStartActivities:n,activitiesStartChainButChildrenOfLinkedParents:i}}function So({gantt:e,direction:t,linkProperty:r}){try{let n=Np(e),i=new Set,a=new Set,s=new Set;t==="backward"&&Bp(n).forEach(d=>{i.add(d.id)});let o=Mp(n,t,r),c=Wp(n,o);return o.forEach(l=>{a.add(l.id)}),c.forEach(l=>{s.add(l.id)}),{parentsWithFullProgress:i,pendingParentsWithNoLinks:a,pendingParentsWithLinks:s}}catch(n){throw n}}function Np(e){return e.getTaskByTime().filter(ct.filterByParentType).filter(ct.avoidSubproject)}function Mp(e,t,r){return e.filter(n=>{let i=n[r];if(!Array.isArray(i))return!1;let a=i.length>0,s=n.constraint_type||"",o=s!=="fnlt";return t==="forward"?!a&&o&&s!=="snet":!a&&o})}function Wp(e,t){let r=new Set(t.map(n=>n.id));return e.filter(n=>!r.has(n.id))}function Bp(e){return e.filter(t=>{let r=Number(t.progress);return Number.isNaN(r)?!1:r===100})}function ko({pendingParentsWithLinks:e,gantt:t,direction:r}){try{let n=new Set;return e.forEach(i=>{let a=t.getTask(i),s=Up(r),o=jp(r),c=a[s];if(!Array.isArray(c))return;Hp(t,c,o).forEach(d=>{n.add(d)})}),n}catch(n){throw n}}function Up(e){return e==="forward"?"$source":"$target"}function jp(e){return e==="forward"?"target":"source"}function Hp(e,t,r){return t.map(n=>{let a=e.getLink(n)[r];return Number(a)})}var Be={identifySecondLevelActivities:Co,identifyInitialActivities:Io,identifyParentsWithAndWithoutLinks:So,identifyForbiddenActivities:ko};function Lr(e){return e.length?e.reduce((t,r)=>r.ef>t.ef?r:t):!1}function Gn({linkType:e,lag:t,predecessorTime:r,activityCalendar:n,activity:i}){return e===H.FS&&t===0?ht({predecessorTime:r,activityCalendar:n,direction:"future",activity:i}):Ue(r,e,n,i)}function Do({duration:e,constraintDate:t,activityCalendar:r,activity:n}){let i=new Date(t);return{es:k(r,i,e,n),ef:i}}function To({duration:e,constraintDate:t,activityCalendar:r,activity:n}){let i=new Date(t),a=k(r,i,e,n);return{es:i,ef:a}}function Ue(e,t,r,n){if(![H.FS,H.SS,H.FF].includes(t))return e;let a=[H.FS,H.SS].includes(t)?"future":"past";return ht({dateBaseToCalculate:e,activityCalendar:r,direction:a,activity:n})}var $n=class{constructor(t,r,n){if(this.linkedActivitiesData=t,this.activity=r,this.gantt=n,this.activityCalendar=this.gantt.getCalendar(this.activity.calendar_id),!this.activityCalendar)throw new Error(`Error trying to get calendar with id: ${this.activity.calendar_id}`)}calculate(){let t=this.calculateLinks(),r=Lr(t),n=this.activity.constraint_type;return n==="snet"?this.handleSNETConstraint(r):n==="fnlt"?this.handleFNLTConstraint(r):r}calculateLinks(){let t=[];for(let r of this.linkedActivitiesData){let n=r.linkType,i=ee(n),a=r.linkLag,s=r.es,o=r.ef,c=null;if(i==="ss")c=this.calculateSSLink({lag:a,predecessorEs:s});else if(i==="ff")c=this.calculateFFLink({lag:a,predecessorEf:o});else if(i==="fs")c=this.calculateFSLink({lag:a,predecessorEf:o});else if(i==="sf")c=this.calculateSFLink({lag:a,predecessorEs:s,predecessorEf:o});else continue;c&&t.push(c)}return t}handleSNETConstraint(t){let r=To({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=Do({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 n=Gn({linkType:"ss",lag:t,predecessorTime:r,activityCalendar:this.activityCalendar,activity:this.activity}),i=k(this.activityCalendar,n,t,this.activity);t>0&&(i=Ue(i,"ss",this.activityCalendar,this.activity));let a=k(this.activityCalendar,i,this.activity.duration,this.activity);return{es:i,ef:a}}calculateFFLink({lag:t,predecessorEf:r}){let n=Gn({linkType:"ff",lag:t,predecessorTime:r,activityCalendar:this.activityCalendar,activity:this.activity}),i=k(this.activityCalendar,n,t,this.activity),a=k(this.activityCalendar,i,-this.activity.duration,this.activity);return t>0&&(a=Ue(a,"ff",this.activityCalendar,this.activity)),{es:a,ef:i}}calculateFSLink({lag:t,predecessorEf:r}){let n=r;t===0&&(n=ht({dateBaseToCalculate:r,activityCalendar:this.activityCalendar,direction:"future",activity:this.activity}));let i=k(this.activityCalendar,n,t,this.activity),a=k(this.activityCalendar,i,this.activity.duration,this.activity);return{es:i,ef:a}}calculateSFLink({lag:t,predecessorEs:r}){let n=k(this.activityCalendar,r,t,this.activity),i=k(this.activityCalendar,n,-this.activity.duration,this.activity);return t>0&&(i=Ue(i,"sf",this.activityCalendar,this.activity)),{es:i,ef:n}}},_o=$n;var zn=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 n=ee(r.linkType);if(r.type==="task"&&Number(r.progress)>0||r.type==="project"&&Number(r.progress)===100)continue;let i=r.linkLag,a=r.ls,s=r.lf;if(n==="ss"){let o={lag:i,workTime:a,lsDataCalculation:-i,lfDataCalculation:this.activity.duration},{ls:c,lf:l}=this.calculateSSLink(o);t.push({ls:c,lf:l})}if(n==="ff"){let o={lag:i,workTime:s,lsDataCalculation:-this.activity.duration,lfDataCalculation:-i},{ls:c,lf:l}=this.calculateFFLink(o);t.push({ls:c,lf:l})}if(n==="fs"){let o={lag:i,workTime:a,lsDataCalculation:-this.activity.duration,lfDataCalculation:-i},{ls:c,lf:l}=this.calculateFsLink(o);t.push({ls:c,lf:l})}if(n==="sf"){let o={lag:i,workTime:s,lsDataCalculation:-i,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),n=this.calculateSfRestrictionDates();return r?this.getMinLfFromLinks([n,r]):n}else{let r=this.getMinLfFromLinks(t);if(r===!1){let n=this.gantt.getSubtaskDates();return{ls:k(this.activityCalendar,n.end_date,-this.activity.duration,this.activity),lf:n.end_date}}return r}}calculateFFLink({lag:t,workTime:r,lsDataCalculation:n,lfDataCalculation:i}){let a=null,s=null;if(t===0)return a=k(this.activityCalendar,r,i,this.activity),s=k(this.activityCalendar,a,n,this.activity),{ls:s,lf:a};let o=r;return t>0&&(o=this.getLastWorkingHour(o,this.activityCalendar,"past")),a=k(this.activityCalendar,o,i,this.activity),s=k(this.activityCalendar,a,n,this.activity),{ls:s,lf:a}}calculateFsLink({lag:t,workTime:r,lsDataCalculation:n,lfDataCalculation:i,isMilestone:a=!1}){let s=null,o=null;if(t===0){let l=this.getLastWorkingHour(r,this.activityCalendar,"past");return s=k(this.activityCalendar,l,i,this.activity),s=this.getLastWorkingHour(s,this.activityCalendar,"past"),o=k(this.activityCalendar,s,n,this.activity),{ls:o,lf:s}}let c=r;return a||(c=this.getLastWorkingHour(r,this.activityCalendar)),s=k(this.activityCalendar,c,i,this.activity),o=k(this.activityCalendar,s,n,this.activity),a||(s=this.getLastWorkingHour(s,this.activityCalendar,"past")),{ls:o,lf:s}}calculateSFLink({lag:t,workTime:r,lsDataCalculation:n,lfDataCalculation:i}){let a=null,s=null,o=r;return s=k(this.activityCalendar,o,n,this.activity),a=k(this.activityCalendar,s,i,this.activity),{ls:s,lf:a}}calculateSSLink({lag:t,workTime:r,lsDataCalculation:n,lfDataCalculation:i,isMilestone:a=!1}){let s=null,o=null;if(t===0)return o=k(this.activityCalendar,r,n,this.activity),s=k(this.activityCalendar,o,i,this.activity),{ls:o,lf:s};let c=r;return t<0&&!a&&(c=this.getLastWorkingHour(c,this.activityCalendar,"future")),o=k(this.activityCalendar,c,n,this.activity),s=k(this.activityCalendar,o,i,this.activity),{ls:o,lf:s}}getMinLfFromLinks(t=[]){return t.length?t.reduce((r,n)=>n.lf<r.lf?n:r):!1}calculateSfRestrictionDates(){let t=this.activity.constraint_date,r=this.activity.duration;return{ls:k(this.activityCalendar,t,-r,this.activity),lf:t}}getLastWorkingHour(t,r,n="past"){let i=t instanceof Date?t:new Date(t),a=gt(i).clone();return this.isActivityInInitHour(r,i)&&n==="past"&&(a=a.hours(0).minutes(0).seconds(0).milliseconds(0)),ht({dateBaseToCalculate:new Date(a),direction:n,activityCalendar:r,activity:this.activity})}isActivityInInitHour(t,r){let n=r instanceof Date?r:new Date(r),a=t.getWorkHours(n)[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),gt.isMoment(r)?r.hours()===s:n.getUTCHours()===s)}},Po=zn;function Ro(e){let{parent:t,linkProperty:r,linkDirection:n,calculations:i,gantt:a,direction:s}=e,o=t[r],c=Vp(t),l=null;if(s==="forward"){let d=Yp(o,n,i,a);l=new _o(d,t,a),l=l.calculate()}else{let d=Kp(o,n,i,a);l=new Po({linksWithActivityData:d,activity:t,parentData:c,gantt:a}).calculate()}return l}function Vp(e){return{duration:e.duration,calendarId:e.calendar_id}}function Yp(e,t,r,n){return e.length===0?[]:e.map(i=>{let a=n.getLink(i);if(!a)return console.warn(`Link not found: ${i}`),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 Kp(e,t,r,n){return e.length===0?[]:e.map(i=>{let a=n.getLink(i);if(!a)return console.warn(`Link not found: ${i}`),null;let s=Number(a[t]),o=r.get(s);if(!o)return null;let c=n.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 Lo(e){let{activityData:t,calculations:r,singleParents:n,direction:i}=e;if(Gp(t.id,r))return null;let a=$p(t.id,n),s=zp(a,r);return s.length===0?null:qp(s,i)}function Gp(e,t){return t.has(e)}function $p(e,t){let r=t.get(e);return r?r.childrens:[]}function zp(e,t){return e.filter(r=>t.has(r)).map(r=>t.get(r))}function qp(e,t){if(t==="forward"){let r=Eo(e,"es"),n=bo(e,"ef");return{es:r,ef:n}}else{let r=Eo(e,"ls"),n=bo(e,"lf");return{ls:r,lf:n}}}function Eo(e,t){return e.reduce((r,n)=>n[t]<r[t]?n:r)[t]}function bo(e,t){return e.reduce((r,n)=>n[t]>r[t]?n:r)[t]}var qn={parentWithLinks:Ro,parentWithNoLinks:Lo};var Jn=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 n=[y.FNLT];if(this.shouldCalculateParentWithLinksBackward(n)){this.calculateAndStoreParentWithLinks(this.activity);return}if(this.shouldSetDatesToParentsWithLinks(n)){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),n=!this.calculationOfParentsFromLinks.has(this.activity.id);return r&&n}calculateAndStoreParentWithLinks(t){let r=qn.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),n=this.calculationOfParentsFromLinks.has(this.activity.id);return r&&n}handleParentWithNoLinks(){let t=qn.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,n=Array.from(this.calculations).filter(s=>t.includes(s[0])).map(s=>s[1]),{minEs:i,maxEf:a}=n.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(n[0].es),maxEf:new Date(n[0].ef)});this.calculations.set(this.activity.id,{es:i,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,n=Array.from(this.calculations).filter(s=>t.includes(s[0])).map(s=>s[1]),{minLs:i,maxLf:a}=n.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(n[0].ls),maxLf:new Date(n[0].lf)});this.calculations.set(this.activity.id,{ls:i,lf:a})}getArrayOfIdOfLinkedActivities(t,r=!1){return t.map(n=>{let a=this.gantt.getLink(n)[r||this.linkDirection];return Number(a)})}},wo=Jn;var Xn=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 n=this.processEachActivity(r),{activitiesByLevel:i}=n,a=this.getAllLevels(i),s=this.getDeepestLevel(a),o=this.createResult(r,n,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(ct.byFirstLevel).filter(ct.filterByParentType)}processEachActivity(t){let r=new Set,n=new Set,i=new Map;return this.initializeParent(t),this.gantt.eachTask(a=>{this.processActivity(a,r,n,i)},t.id),{parentsIds:r,allTasks:n,activitiesByLevel:i}}initializeParent(t){let r=Number(t.id),n=!!t[this.linkProperty]?.length,i=t.$level;this.singleParents.set(r,{level:i,hasLink:n,childrens:[]})}processActivity(t,r,n,i){let a=Number(t.id),s=Number(t.parent);n.add(a),this.isProjectActivity(t)&&this.addParentInfo(t,r);let c=this.doesParentExist(s);s!=null&&c&&this.addChildToParent(s,a),this.addActivityToLevel(t,i)}isProjectActivity(t){return t.type==="project"}hasLink(t){return!!t[this.linkProperty]?.length}addParentInfo(t,r){let n=Number(t.id),i=t.$level,a=this.hasLink(t),s={level:i,hasLink:a,childrens:[]};r.add(n),this.singleParents.set(n,s)}doesParentExist(t){return this.singleParents.has(t)}addChildToParent(t,r){this.singleParents.get(t).childrens.push(r)}addActivityToLevel(t,r){let n=t.$level,i=Number(t.parent);r.has(n)||r.set(n,new Map);let a=r.get(n);a.has(i)||a.set(i,[]),a.get(i).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,n,i){let{activitiesByLevel:a,parentsIds:s,allTasks:o}=r;return{parent:t.id,isALinkedParent:this.hasLink(t),levels:i,allParentChildrens:s,allChildrens:o,childrensByLevel:a,currentResolutionLevel:n,canBeCalculated:!1}}},Oo=Xn;var Zn=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:n,isALinkedParent:i}=t;if(i)return;let a=n.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(ct.avoidSubproject).forEach(t=>{this.activitiesWaitingForCalculation.add(t.id)})}catch(t){throw t}}identifyParentsWithAndWithoutLinks(){try{let{parentsWithFullProgress:t,pendingParentsWithNoLinks:r,pendingParentsWithLinks:n}=Be.identifyParentsWithAndWithoutLinks({gantt:this.gantt,direction:this.direction,linkProperty:this.linkProperty});this.parentsWithFullProgress=t,this.pendingParentsWithNoLinks=r,this.pendingParentsWithLinks=n}catch(t){throw t}}identifyForbiddenActivitiesLinkedToParentsWithLinks(){try{this.forbiddenActivitiesLinkedToParentsWithLinks=Be.identifyForbiddenActivities({pendingParentsWithLinks:this.pendingParentsWithLinks,gantt:this.gantt,direction:this.direction})}catch(t){throw t}}getArrayOfIdOfLinkedActivities(t,r=!1){return t.map(n=>{let a=this.gantt.getLink(n)[r||this.linkDirection];return Number(a)})}async identifyThirdLevelActivities(){try{let{structureOfParents:t,singleParents:r}=new Oo({gantt:this.gantt,linkProperty:this.linkProperty}).identifyThirdLevelActivities();this.structureOfParents=t,this.singleParents=r}catch(t){throw t}}processEachActivity(t){let r=new Set,n=new Set,i=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(n.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),i.has(c.$level)||i.set(c.$level,new Map);let d=i.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:n,activitiesByLevel:i,singleParents:a})})}identifySecondLevelActivities(){try{let t=Be.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}=Be.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:n,ef:i}=r;this.calculations.set(t.id,{es:n,ef:i,text:t.text}),this.activitiesWaitingForCalculation.delete(t.id)}else{let{ls:n,lf:i}=r;this.calculations.set(t.id,{ls:n,lf:i,text:t.text}),this.activitiesWaitingForCalculation.delete(t.id)}})}catch(t){throw t}}buildDependencyGraph(t){let r=new Map,n=new Set(this.calculations.keys()),i=new Map;return t.forEach(a=>{a&&i.set(a.id,a)}),i.forEach((a,s)=>{if(n.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=>i.has(l)||n.has(l)),r.set(s,o)}),{graph:r,activityMap:i,calculatedActivities:n}}topologicalSort(t,r){let n=new Set,i=new Set,a=[],s=o=>{if(i.has(o))throw new Error("Cyclical dependency detected",{cause:{nodeId:o}});if(!n.has(o)&&!r.has(o)){i.add(o);let c=t.get(o)||[];for(let l of c)s(l);i.delete(o),n.add(o),a.push(o)}};for(let o of t.keys())!n.has(o)&&!r.has(o)&&s(o);return a.reverse()}calculateStartAndFinishOfChainOrigin(t=null,r=null){try{let n=t,i=Number(n.progress);i==="0.00"&&(i=0);let a=this.gantt.getCalendar(n.calendar_id);if(!a)throw new Error(`Error trying to get calendar with id: ${n.calendar_id}`);if((r||this.direction)==="forward"){let o=n.start_date,c=n.end_date;return{es:o,ef:c}}else{if(i>=100)return{ls:gt(n.start_date).clone(),lf:gt(n.end_date).clone()};if(i===0)return this.calculateBackwardWhenZeroProgress(n,a);if(i<100&&i>0)return this.calculateWhenProgressIsBetweenZeroAndOneHundred(n,a)}}catch(n){throw n}}calculateBackwardWhenZeroProgress(t,r){let n=gt(t.start_date).clone(),i=gt(t.end_date).clone(),a=t.duration,s=[y.ASAP,y.ALAP,y.SNET,y.FNET],o=t.constraint_type||y.ASAP;if(s.includes(o))i=this.projectDates.end_date,n=k(r,i,-a,t);else{let c=[y.SNLT,y.MSO],l=[y.FNLT,y.MFO];c.includes(o)&&(n=t.constraint_date,i=k(r,n,a,t)),l.includes(o)&&(i=t.constraint_date,n=k(r,i,-a,t))}return{ls:n,lf:i}}calculateWhenProgressIsBetweenZeroAndOneHundred(t){let r=t.start_date,n=null,i=t.constraint_type||y.ASAP,a=this.projectDates.end_date,s=[y.ASAP,y.ALAP,y.SNET,y.FNET],o=[y.SNLT,y.FNLT];if(s.includes(i))n=Math.max(t.end_date,a);else if(i===y.MSO)n=t.end_date;else if(i===y.MFO||o.includes(i)){let c=Math.min(a,t.constraint_date);n=Math.max(c,t.end_date)}return{ls:r,lf:new Date(n)}}initializeActivitiesWithFullProgress(){try{Array.from(this.activitiesWaitingForCalculation).filter(n=>Number(this.gantt.getTask(n).progress)===100).map(n=>this.gantt.getTask(n)).forEach(n=>{let i=n.type==="project";this.setDatesForActivityWithFullProgress(n),this.activitiesWaitingForCalculation.delete(n.id),i&&this.pendingParentsWithLinks.has(n.id)&&(this.parentCalculationFromChildren.add(n.id),this.calculationsOfParentThatImpactChildrens.set(n.id,{[this.direction==="forward"?"es":"ls"]:n.start_date,[this.direction==="forward"?"ef":"lf"]:n.end_date}),this.calculationOfParentsFromLinks.add(n.id))})}catch(t){throw t}}doCalculationForParentType(t){let r=new wo({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()}},Kt=Zn;function Jp(e,t,r){let n={es:null,ef:null};if(!e)return n;if([y.SNET,y.SNLT].includes(t)){let i=new Date(e.constraint_date);n.es=i,n.ef=k(r,i,e.duration,e)}else if([y.FNLT,y.FNET].includes(t)){let i=new Date(e.constraint_date);n.es=k(r,i,-e.duration,e),n.ef=i}else if(t===y.MSO){let i=new Date(e.constraint_date);n.es=i,n.ef=k(r,i,e.duration,e)}else if(t===y.MFO){let i=new Date(e.constraint_date);n.es=k(r,i,-e.duration,e),n.ef=i}return n}var wr=Jp;var Qn=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,n=0,i,a=H.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===H.FS&&i===0?o=ht({dateBaseToCalculate:o,activityCalendar:s,direction:"future",activity:this.referenceActivity}):o=this.mutateTheDateToFutureOrPastInBaseRestriction(t,a,s)),[H.FF,H.SF].includes(a)?(l=k(s,o,n,this.referenceActivity),c=k(s,l,r,this.referenceActivity),!d&&i>0&&(c=this.mutateTheDateToFutureOrPastInBaseRestriction(c,a,s))):(c=k(s,o,r,this.referenceActivity),!d&&i>0&&(c=this.mutateTheDateToFutureOrPastInBaseRestriction(c,a,s)),l=k(s,c,n,this.referenceActivity)),{es:c,ef:l}}calculateSS(t){let r=this.getEsAndEfFromPreviousCalculatedActivities(Number(t.source)),n=t.lag||0,a=this.referenceActivity.duration,s=t.lag||0;return this.calculateSucessorTimes(r.es,n,a,s,H.SS)}calculateFF(t){let r=this.getEsAndEfFromPreviousCalculatedActivities(Number(t.source)),i=-this.referenceActivity.duration,a=t.lag||0,s=t.lag||0;return this.calculateSucessorTimes(r.ef,i,a,s,H.FF)}calculateFS(t){let r=this.getEsAndEfFromPreviousCalculatedActivities(Number(t.source)),n=t.lag||0,a=this.referenceActivity.duration,s=t.lag||0;return this.calculateSucessorTimes(r.ef,n,a,s,H.FS)}calculateSF(t){let r=this.getEsAndEfFromPreviousCalculatedActivities(Number(t.source)),i=-this.referenceActivity.duration,a=t.lag||0,s=t.lag||0;return this.calculateSucessorTimes(r.es,i,a,s,H.SF)}mutateTheDateToFutureOrPastInBaseRestriction(t,r,n){if(![H.FS,H.SS,H.FF].includes(r))return t;let a=[H.FS,H.SS].includes(r)?"future":"past";return ht({dateBaseToCalculate:t,activityCalendar:n,direction:a,activity:this.referenceActivity})}},xo=Qn;var je=class extends xo{constructor(t){super(t)}calculate(){if(this.links.length===0)return new Kt(this.gantt,"forward").calculateStartAndFinishOfChainOrigin(this.referenceActivity);let t=this.links.map(n=>{let i=this.gantt.getLink(n);if(!i)throw new Error("Link data not found",{cause:{linkId:n}});return this.calculateLink(i)}),r=Number(this.referenceActivity.parent);if(this.parentsWithLinks.has(r)){let n=this.gantt.getCalendar(this.referenceActivity.calendar_id),i=this.parentsCalculations.get(r).es,a=k(n,i,this.referenceActivity.duration,this.referenceActivity);t.push({es:i,ef:a})}return Lr(t)}calculateLink(t){return{0:()=>this.calculateFS(t),1:()=>this.calculateSS(t),2:()=>this.calculateFF(t),3:()=>this.calculateSF(t)}[t.type]()}};var ti=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,n=new Set(t);for(let i of t){let a=this.gantt.getTask(i);a.type==="project"?this.handleProjectActivity(i,a,r,n):this.handleNonProjectActivity(i,a,r,n)}return{activitiesThatCanBeCalculated:r,pendingActivities:n}}handleProjectActivity(t,r,n,i){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))&&(n.add(t),i.delete(t));return}if(s&&o){let c=this.singleParents.get(t)?.childrens;if(!c)return;c.every(d=>this.calculations.has(d))&&(n.add(t),i.delete(t));return}s&&!o&&this.canCalculateParentActivity(r)&&(n.add(t),i.delete(t))}canCalculateParentActivity(t){let r=(t[this.linkProperty]||[]).length===0,n=t.constraint_type;return(this.direction==="forward"?n==="fnlt"||n==="snlt":n==="fnlt")&&r?!0:this.getArrayOfLinkedActivities(t[this.linkProperty]).every(s=>this.calculations.has(s))}handleNonProjectActivity(t,r,n,i){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){n.add(t),i.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){n.add(t),i.delete(t);return}l&&(n.add(t),i.delete(t))}getLinkedActivities(t){if(!Array.isArray(t))return[];let r=[];for(let n of t){let i=this.gantt.getLink(n);if(!i)continue;let a=i[this.linkDirection],s=this.gantt.getTask(a);s&&r.push(s)}return r}getArrayOfLinkedActivities(t){if(!Array.isArray(t))return[];let r=[];for(let n of t){let i=this.gantt.getLink(n);i&&r.push(Number(i[this.linkDirection]))}return r}},Or=ti;var ei=(e,t)=>()=>t()===e;var ri=e=>!e?.fullyParsed||typeof window<"u"&&window.to_use_react_gantt?.conversionMode?.isActive;var Xp=16,He=async e=>performance.now()-e>Xp?(await Z(),performance.now()):e;var Ve=async({pending:e,activityCalculator:t,calculateFn:r,shouldKeepPending:n,isCalculated:i,onActivityProcessed:a,isCurrent:s})=>{let o=new Set(e),c=performance.now();for(;o.size>0;){if(!s())return;c=await He(c);let{activitiesThatCanBeCalculated:l,pendingActivities:d}=t.checkActivitiesThatNowCanBeCalculated(o);if(l.size===0)break;for(let u of l){if(!s())return;c=await He(c),r([u])}for(let u of l){if(!s())return;n(u)&&d.add(u),a(u),i(u)&&d.delete(u)}o=d}};var ni=class extends Kt{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 Or({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 Ve({pending:this.activitiesWaitingForCalculation,activityCalculator:r,calculateFn:n=>this.calculateStartAndFinishTimes(n),shouldKeepPending:n=>this.calculationOfParentsFromLinks.has(n)&&!this.calculations.has(n),isCalculated:n=>this.calculations.has(n),onActivityProcessed:n=>this.activitiesWaitingForCalculation.delete(n),isCurrent:t})}calculateStartAndFinishTimes(t){t.forEach(r=>{let n=this.gantt.getTask(r);if(n.type==="project")return this.doCalculationForParentType(n);if(!n)throw new Error("Error trying to get activity",{cause:{activityId:r}});let i=n.$target,a=n.constraint_type||y.ASAP,s=[y.SNET,y.SNLT,y.FNLT,y.FNET],o=[y.ASAP,y.ALAP,y.SNET,y.FNET,y.SNLT,y.FNLT],c=this.gantt.getCalendar(n.calendar_id);if(!c)throw new Error(`Error trying to get calendar with id: ${n.calendar_id}`);let l=Number(n.progress),d=null,u=null,f=null;if(l===100){this.setDatesForActivityWithFullProgress(n);return}l>0&&o.includes(a)?({es:d,ef:u}=this.getDatesForActivityWithZeroProgress(n),f=new je({links:i,activity:n,calculatedActivitiesMap:this.calculations,calculatedAlapsMap:this.alapMap,constraint:a,parentsWithLinks:this.pendingParentsWithLinks,parentsCalculations:this.calculationsOfParentThatImpactChildrens,ganttInstance:this.gantt}).calculate(),a===y.ASAP&&this.totalFloatForAsap.set(r,{es:f.es,ef:f.ef,text:n.text})):{es:d,ef:u}=new je({links:i,activity:n,calculatedActivitiesMap:this.calculations,calculatedAlapsMap:this.alapMap,constraint:a,parentsWithLinks:this.pendingParentsWithLinks,parentsCalculations:this.calculationsOfParentThatImpactChildrens,ganttInstance:this.gantt}).calculate(),a===y.ALAP&&this.alapMap.set(r,{es:n.start_date,ef:n.end_date,text:n.text});let p=wr(n,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})),[y.MSO,y.MFO].includes(a))if(this.totalFloatForMsoMfo.set(r,{es:d,ef:u}),this.constraintsMap.set(r,p),n.progress===0)d=p.es,u=p.ef;else{let m=n.end_date;a===y.MFO&&(m=Math.max(p.ef,n.end_date)),d=n.start_date,u=m}this.calculations.set(r,{es:d,ef:u}),this.activitiesWaitingForCalculation.delete(r)})}getTheGreatesDateBetweenRestrictionAndEsEf(t,r,n="greater"){if(n==="greater")return r.ef>t.ef?r:t;if(n==="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,n){let i=[y.SNET,y.FNET].includes(t)?"greater":"less",{es:a,ef:s}=this.getTheGreatesDateBetweenRestrictionAndEsEf(r,n,i);return{es:a,ef:s}}cleanAllActivityParentsFromLinks(t){return t.map(r=>{let n=this.gantt.getLink(r);if(!n)throw new Error("Error trying to get link",{cause:{linkId:r}});let i=n.source,a=n.target;if(!(!this.gantt.getTask(i)||this.gantt.getTask(i)?.type==="project")&&!(!this.gantt.getTask(a)||this.gantt.getTask(a)?.type==="project"))return r}).filter(Boolean)}},Fo=ni;var ii=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===y.ALAP?this.forwardPathCalculations.get(t):this.calculatedActivities.get(t)}calculateSuccessorTimes(t,r,n=0,i,a=H.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&&i===0){let d=k(s,o,r,this.activity),u=k(s,d,n,this.activity);return{ls:d,lf:u}}let l={lag:i,workTime:o,activityCalendar:s,lsDataCalculation:r,lfDataCalculation:n,isMilestone:c};if(a===H.FS){let{ls:d,lf:u}=this.calculateFsLink(l);return{ls:d,lf:u}}if(a===H.FF){let{ls:d,lf:u}=this.calculateFFLink(l);return{ls:d,lf:u}}if(a===H.SS){let{ls:d,lf:u}=this.calculateSSlink(l);return{ls:d,lf:u}}if(a===H.SF){let{ls:d,lf:u}=this.calculateSFLink(l);return{ls:d,lf:u}}}calculateSS(t,r=!1){let n=this.getValueForSS(t,r),i=-t.lag||0,a=this.activity.duration,s=t.lag;return this.calculateSuccessorTimes(n,i,a,s,H.SS)}calculateFF(t,r){let n=this.getForwardOrBackwardCalculations(Number(t.target)),i=r===y.ALAP?"ef":"lf",a=n[i],s=-this.activity.duration,o=-t.lag||0,c=t.lag;return this.calculateSuccessorTimes(a,s,o,c,H.FF)}calculateFS(t,r){let n="ls";n=r===y.ALAP?"es":"ls";let i=this.getForwardOrBackwardCalculations(Number(t.target),r),a=-this.activity.duration,s=t.lag||0,o=-t.lag||0;return this.calculateSuccessorTimes(i[n],a,o,s,H.FS)}calculateSF(t,r=!1){let n=r?this.getEarlyStartFromForwardPath(Number(t.target)).ef:this.getForwardOrBackwardCalculations(Number(t.target)).lf,i=-t.lag||0,a=this.activity.duration,s=t.lag;return this.calculateSuccessorTimes(n,i,a,s,H.SF)}getEarlyStartFromForwardPath(t){return this.forwardPathCalculations.get(t)}getValueForSS(t,r){return r?this.getEarlyStartFromForwardPath(Number(t.target)).es:this.getForwardOrBackwardCalculations(Number(t.target))["ls"]}calculateDate(t,r,n){let i=gt(r).clone();return k(t,new Date(i),n,this.activity)}getLastWorkingHour(t,r,n="past"){let i=t instanceof Date?t:new Date(t),a=gt(i).clone();return this.isActivityInInitHour(r,i)&&n==="past"&&(a=a.hours(0).minutes(0).seconds(0).milliseconds(0)),ht({dateBaseToCalculate:new Date(a),direction:n,activityCalendar:r,activity:this.activity})}isActivityInInitHour(t,r){let n=r instanceof Date?r:new Date(r),a=t.getWorkHours(n)[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),gt.isMoment(r)?r.hours()===s:n.getUTCHours()===s)}calculateFsLink({lag:t,workTime:r,activityCalendar:n,lsDataCalculation:i,lfDataCalculation:a,isMilestone:s=!1}){let o=null,c=null;if(t===0){let d=this.getLastWorkingHour(r,n,"past");return o=k(n,d,a,this.activity),o=this.getLastWorkingHour(o,n,"past"),c=k(n,o,i,this.activity),{ls:c,lf:o}}let l=r;return s||(l=this.getLastWorkingHour(r,n)),o=k(n,l,a,this.activity),c=k(n,o,i,this.activity),s||(o=this.getLastWorkingHour(o,n,"past",!0)),{ls:c,lf:o}}calculateFFLink({lag:t,workTime:r,activityCalendar:n,lsDataCalculation:i,lfDataCalculation:a}){let s=null,o=null;if(t===0)return s=k(n,r,a,this.activity),o=k(n,s,i,this.activity),{ls:o,lf:s};let c=r;return t>0&&(c=this.getLastWorkingHour(c,n,"past")),s=k(n,c,a,this.activity),o=k(n,s,i,this.activity),{ls:o,lf:s}}calculateSSlink({lag:t,workTime:r,activityCalendar:n,lsDataCalculation:i,lfDataCalculation:a,isMilestone:s=!1}){let o=null,c=null;if(t===0)return c=k(n,r,i,this.activity),o=k(n,c,a,this.activity),{ls:c,lf:o};let l=r;return t<0&&!s&&(l=this.getLastWorkingHour(l,n,"future")),c=k(n,l,i,this.activity),o=k(n,c,a,this.activity),{ls:c,lf:o}}calculateSFLink({lag:t,workTime:r,activityCalendar:n,lsDataCalculation:i,lfDataCalculation:a}){let s=null,o=null;return t===0?(o=k(n,r,i),s=k(n,o,a,this.activity),{ls:o,lf:s}):(o=k(n,r,i,this.activity),s=k(n,o,a,this.activity),{ls:o,lf:s})}},No=ii;var ai=class extends No{constructor(t){super(t),this.constraint=t.constraint||y.ASAP,this.parentsWithFullProgress=t.parentsWithFullProgress,this.parentsThatImpactChildrens=t.parentsThatImpactChildrens,this.projectDates=this.gantt.getSubtaskDates()}calculate(){if(this.links.length===0)return new Kt(this.gantt,"backward").calculateStartAndFinishOfChainOrigin(this.activity);let t=this.activity.progress>0&&this.activity.progress<100,r=this.gantt.getTask(this.activity.parent),n=!1;r&&(n=this.parentsThatImpactChildrens.has(Number(this.activity.parent)));let i=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(i.length!==0){let s=this.getMinLfFromLinks(i);if(i.push(this.calculateTheLsAndLfForTheActivity()),n){let d=this.parentsThatImpactChildrens.get(Number(this.activity.parent));i.push(this.calculateTheLsAndLfForTheActivity(d))}let o=this.getMinDateFromLinks(i),c=o.ls,l=o.lf;return t&&(c=this.activity.start_date,l=this.getMinCalculationLogic(o)),{ls:c,lf:l,minFromLinks:s}}if(n){i.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);i.push({ls:c,lf:o});let l=this.getMinDateFromLinks(i);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,n=this.gantt.getCalendar(this.activity.calendar_id);if(!n)throw new Error(`Calendar not found with id ${this.activity.calendar_id}`);let i=t?t.lf:this.projectDates.end_date;if(!i)throw new Error("End date not found for activity",{cause:{activityId:this.activity.id}});return{ls:k(n,i,-r,this.activity),lf:i}}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 n=this.getSpecialCalculationParamForConstraintLink(),i=this.getSpecialParamForSf(),a=this.getSpecialParamForFF();return{0:()=>this.calculateFS(t,n),1:()=>this.calculateSS(t),2:()=>this.calculateFF(t,a),3:()=>this.calculateSF(t,i)}[t.type]()}getSpecialCalculationParamForConstraintLink(){if(this.constraint===y.ALAP)return y.ALAP;if(this.constraint===y.FNET||this.constraint===y.SNET)return"snet-fnet";if(this.constraint===y.FNLT)return y.FNLT}getSpecialParamForSf(){return!![y.ALAP].includes(this.constraint)}getSpecialParamForFF(){return!![y.MFO,y.MSO].includes(this.constraint)}getMinCalculationLogic(t){if(this.constraint===y.ALAP)return this.getMinDateBasedOnConstraint(t);if(this.constraint===y.FNET)return this.getMinDateBasedOnConstraint(t);if(this.constraint===y.FNLT)return this.getMinDateBasedOnConstraint(t);if(this.constraint===y.MFO)return this.getMinDateBasedOnConstraint(t);if(this.constraint===y.SNET||this.constraint===y.SNLT||this.constraint===y.MSO)return this.SnetSnltMsoMinDate(t);if(this.constraint===y.ASAP)return this.getMinDateBasedOnConstraint(t)}getMinDateFromLinks(t){try{return this.constraint===y.ALAP||this.constraint===y.ASAP?t.reduce((n,i)=>i.lf<n.lf?i:n):t.reduce((r,n)=>n.ls<r.ls?n:r)}catch(r){throw new Error(`Function: getMinDateFromLinks in LinksConstraintCalculator - ${r.message}`)}}getMinLfFromLinks(t){return t.reduce((r,n)=>n.lf<r.lf?n:r)}getMinDateBasedOnConstraint(t,r=this.constraint){let n=Math.min(t.lf,this.projectDates.end_date),i=this.activity.end_date,a=this.activity.constraint_date;if(r===y.ASAP)return new Date(Math.max(n,i));if(r===y.FNET||r===y.FNLT){let s=Math.min(n,a);return new Date(Math.max(n,s))}if(r===y.ALAP)return new Date(Math.min(n,i))}},Mo=ai;function Zp(e,t,r){let n={ls:null,lf:null};return r===y.MSO&&(n.ls=t.constraint_date,n.lf=k(e,n.ls,t.duration,t)),r===y.MFO&&(n.lf=t.constraint_date,n.ls=k(e,n.lf,-t.duration,t)),n}var Wo=Zp;var si=class extends Kt{constructor(t,r,n){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=n,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 Or({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 Ve({pending:this.activitiesWaitingForCalculation,activityCalculator:r,calculateFn:n=>this.calculateStartAndFinishTimes(n),shouldKeepPending:n=>this.calculationOfParentsFromLinks.has(n)&&!this.calculations.has(n),isCalculated:n=>this.calculations.has(n),onActivityProcessed:n=>this.activitiesWaitingForCalculation.delete(n),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,i=Array.from(this.calculations).filter(o=>r.includes(o[0])).map(o=>o[1]),{minLs:a,maxLf:s}=i.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(i[0].ls),maxLf:new Date(i[0].lf)});this.calculations.set(t.id,{ls:a,lf:s})}calculateStartAndFinishTimes(t){t.forEach(r=>{let n=this.gantt.getTask(r);if(!n)throw new Error("Activity not found",{cause:{activityId:r}});let i=n.$source,a=n.constraint_type||y.ASAP,s=Number(n.progress);if(this.activitiesStartChainButChildrenOfLinkedParents.has(r)){if(this.calculationsOfParentThatImpactChildrens.has(Number(n.parent))&&this.calculationsOfParentThatImpactChildrens.get(Number(n.parent))===!1){let{ls:d,lf:u}=this.calculateStartAndFinishOfChainOrigin(n,this.direction);this.setCalculations(n,d,u);return}return this.doCalculationForActivitiesThatStartLinkButHisParentIsLinked(n)}if(n.type==="project")return this.doCalculationForParentType(n);if(s===100){this.setDatesForActivityWithFullProgress(n);return}if(this.allLinkedActivitiesHasProgress(i,n)){this.setWhenAllLinkedActivitiesHasProgress(n);return}if(s>0&&s<100&&(a===y.MSO||a===y.MFO)){this.setWhenActivitiesHasProgressButLessThanOneHundred(n,a);return}if(a===y.MSO||a===y.MFO){this.recalculateInBaseRestriction(n,a);return}let{ls:o,lf:c,minFromLinks:l}=this.calculateLfandLsFromLinks(i,n,a,this.parentsWithFullProgress,this.calculationsOfParentThatImpactChildrens);(a===y.SNLT||a===y.FNLT)&&({ls:o,lf:c}=this.getTheLessLateInBasEsEfConstraint(n.id,{ls:o,lf:c},a)),this.setCalculations(n,o,c),this.minFromLinks.set(n.id,{ls:l.ls,lf:l.lf})})}getTheLessLateInBasEsEfConstraint(t,r,n){let i=this.forwardConstraintsMap.get(t);if(!i){let a=this.gantt.getTask(t),s=this.gantt.getCalendar(a.calendar_id);i=wr(a,n,s)}return r.lf<i.ef?r:{ls:i.es,lf:i.ef}}allLinkedActivitiesHasProgress(t){try{let r=!0;for(let n of t){let i=this.gantt.getLink(n);if(!i)continue;let a=this.gantt.getTask(i.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:n,lf:i}=this.calculateStartAndFinishOfChainOrigin(t,"backward");if(this.calculationsOfParentThatImpactChildrens.has(r)){n=t.start_date;let a=this.calculationsOfParentThatImpactChildrens.get(r);a&&typeof a=="object"&&a.lf!=null&&(i=new Date(Math.min(i,a.lf)))}this.setCalculations(t,n,i)}setWhenActivitiesHasProgressButLessThanOneHundred(t,r){if(r===y.MSO){this.setCalculations(t,t.start_date,t.end_date);return}if(r===y.MFO){let n=Math.min(t.constraint_date,this.projectDates.end_date),i=new Date(Math.max(n,t.end_date));this.setCalculations(t,t.start_date,i);return}}setCalculations(t,r,n){this.calculations.set(t.id,{ls:r,lf:n,text:t.text})}calculateLfandLsFromLinks(t,r,n,i,a){return new Mo({links:t,activity:r,calculatedActivitiesMap:this.calculations,calculatedForwardActivitiesMap:this.forwardPathCalculations,constraint:n,parentsWithFullProgress:i,parentsThatImpactChildrens:a,ganttInstance:this.gantt}).calculate()}recalculateInBaseRestriction(t,r){try{let n=this.gantt.getCalendar(t.calendar_id);if(!n)throw new Error(`Error trying to get calendar with id: ${t.calendar_id}`);let i=Wo(n,t,r);this.constraintMap.set(t,i),this.setCalculations(t,i.ls,i.lf)}catch(n){throw new Error(n.message)}}cleanAllActivityParentsFromLinks(t){return t.map(r=>{let n=this.gantt.getLink(r).source,i=this.gantt.getLink(r).target;if(!(!this.gantt.getTask(n)||this.gantt.getTask(n)?.type==="project")&&!(!this.gantt.getTask(i)||this.gantt.getTask(i)?.type==="project"))return r}).filter(Boolean)}doCalculationForActivitiesThatStartLinkButHisParentIsLinked(t){let r=Number(t.parent),n=this.calculationsOfParentThatImpactChildrens.get(r),i=0,a=0;if([y.ASAP,y.ALAP,y.SNET,y.FNET].includes(t.constraint_type))if(Number(t.progress)>0){let l=this.projectDates.end_date;a=new Date(Math.min(l,n.lf)),i=t.start_date}else a=n.lf,i=k(this.gantt.getCalendar(t.calendar_id),a,-t.duration,t);if([y.SNLT].includes(t.constraint_type)){let l=t.constraint_date,d=this.calculationsOfParentThatImpactChildrens.get(r),u=k(this.gantt.getCalendar(t.calendar_id),d.lf,-t.duration,t);i=new Date(Math.min(l.getTime(),u.getTime())),a=k(this.gantt.getCalendar(t.calendar_id),i,t.duration,t)}if([y.FNLT].includes(t.constraint_type)){let l=t.constraint_date,d=this.calculationsOfParentThatImpactChildrens.get(r);i=new Date(Math.min(l.getTime(),d.lf.getTime())),a=k(this.gantt.getCalendar(t.calendar_id),i,t.duration,t)}[y.MSO].includes(t.constraint_type)&&(i=t.constraint_date,a=k(this.gantt.getCalendar(t.calendar_id),i,t.duration,t)),[y.MFO].includes(t.constraint_type)&&(a=t.constraint_date,i=k(this.gantt.getCalendar(t.calendar_id),a,-t.duration,t));let s=this.projectDates.end_date,o=[{ls:i,lf:a}];o.push({ls:k(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,n)=>n.lf<r.lf?n:r):!1}},Bo=si;function Uo(){return null}var jo=({forward:e,backward:t,id:r,activity:n,gantt:i,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:n,gantt:i},freeFloat:{forwardMap:e.calculations||new Map,backwardMap:t.calculations||new Map,activity:n,projectDates:a,gantt:i}});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=y.ASAP),t===y.ASAP||!t)return r===0?this.calculateAsap():this.calculateAsapWithProgress();if(t===y.ALAP)return r===0?this.calculateAlap():this.calculateAlapWithProgress();if(t===y.SNET||t===y.FNET)return r===0?this.calculateSnetFet():this.calculateSnetFnetSnltWithProgress();if(t===y.SNLT)return r===0?this.calculateSnltFnlt():this.calculateSnetFnetSnltWithProgress();if(t===y.FNLT)return r===0?this.calculateSnltFnlt():this.calculateFnltWithProgress();if(t===y.MSO||t===y.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),n=this.getMinValue(t,r),i=this.calculationWithCalendar(this.lf,this.activity.end_date);return this.getMinValue(n,i)/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 n=this.calculationWithCalendar(this.minFromLinks.lf,this.ef);return this.getMinValue(t,r,n)/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),n=this.getMinValue(t,r);if(!this.totalFloatSnltFnlt&&!this.constrainstMap)return this.getMinValue(t,r)/this.gantt.config.hoursPerDay;let i=0;return this.activity.constraint_type===y.SNLT?i=this.calculationWithCalendar(this.constrainstMap.es,this.totalFloatSnltFnlt.es):i=this.calculationWithCalendar(this.constrainstMap.ef,this.totalFloatSnltFnlt.ef),this.getMinValue(i,n)/this.gantt.config.hoursPerDay}calculateMsoMfo(){let t=this.calculationWithCalendar(this.ls,this.es),r=this.calculationWithCalendar(this.lf,this.ef),n=this.getMinValue(t,r);if(!this.totalFloatForMsoMfo&&!this.constrainstMap)return this.getMinValue(t,r)/this.gantt.config.hoursPerDay;let i=0;return this.activity.constraint_type===y.MSO?i=this.calculationWithCalendar(this.constrainstMap.es,this.totalFloatForMsoMfo.es):i=this.calculationWithCalendar(this.constrainstMap.ef,this.totalFloatForMsoMfo.ef),this.getMinValue(i,n)/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)})}},Ho=oi;var ci=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===y.MSO||t===y.MFO?this.calculateMsoMfo(t):this.calculateGeneral(t)}calculateFreeFloatOfLink(t=y.ASAP){let r=this.activity.$source.map(n=>{let{LINK:i,LINK_TYPE:a}=this.getLinkData(n),s=this.gantt.getTask(i.target);if(!s)return{linkId:i.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(i.lag),f=Math.max(0,u);return this.linksFreeFloatObject[i.id]=f,{linkId:i.id,freeFloat:f,hasProgress:o}}).filter(n=>n.freeFloat!==null&&n.freeFloat!==void 0);return this.linksFreeFloatArray=r,r}calculateGeneral(t=y.ASAP){let r=this.getMinFloat(this.linksFreeFloatArray),n=this.calculateFreeFloatForEndOfProject(t),i=0;return[y.SNLT,y.FNLT].includes(t)?i=this.doCalculationForSnltFnlt(t,n,r):i=this.doGeneralCalculation(n,r),Math.max(0,i)}getConstraintType(){let{constraint_type:t}=this.activity;return t||(t=y.ASAP),t}getDatesFromSucessorAndPredecessor(t,r,n){let i=n.constraint_type===y.ALAP,a=this.getSucessorAndPredecessorDates({constraint:r,isSuscessorAlap:i,sucessorId:n.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,n){let i=this.calculateFreeFloatOfRestriction(t);return this.getMinValue(n,r,i)}calculateFreeFloatForEndOfProject(t){return this.parseHoursToDays(this.calculationWithCalendar(this.gantt.getSubtaskDates().end_date,t===y.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===y.FNLT?this.forwardMap.get(this.activity.id).ef:this.forwardMap.get(this.activity.id).es))}getLinkData(t){let r=this.gantt.getLink(t)||{},n=ee(r.type);return{LINK:r,LINK_TYPE:n}}getSucessorAndPredecessorDates({constraint:t,isSuscessorAlap:r,sucessorId:n,predecessorId:i}){let a=({direction:s,constraint:o=y.ASAP})=>o===y.ALAP?this.backwardMap.get(i)[s]:this.forwardMap.get(i)[s];if(t===y.ASAP||t===y.SNET||t===y.FNET||t===y.MSO||t===y.MFO)return{fs:{sucessor:r?this.backwardMap.get(n).ls:this.forwardMap.get(n).es,predecessor:a({direction:"ef"})},ss:{sucessor:r?this.backwardMap.get(n).ls:this.forwardMap.get(n).es,predecessor:a({direction:"es"})},ff:{sucessor:r?this.backwardMap.get(n).lf:this.forwardMap.get(n).ef,predecessor:a({direction:"ef"})},sf:{sucessor:r?this.backwardMap.get(n).lf:this.forwardMap.get(n).ef,predecessor:a({direction:"es"})}};if(t===y.ALAP)return{fs:{sucessor:r?this.backwardMap.get(n).ls:this.forwardMap.get(n).es,predecessor:a({constraint:y.ALAP,direction:"lf"})},ss:{sucessor:r?this.backwardMap.get(n).ls:this.forwardMap.get(n).es,predecessor:a({constraint:y.ALAP,direction:"ls"})},ff:{sucessor:r?this.backwardMap.get(n).lf:this.forwardMap.get(n).ef,predecessor:a({constraint:y.ALAP,direction:"lf"})},sf:{sucessor:r?this.backwardMap.get(n).lf:this.forwardMap.get(n).ef,predecessor:a({constraint:y.ALAP,direction:"ls"})}};if(t===y.SNLT)return{fs:{sucessor:r?this.backwardMap.get(n).ls:this.forwardMap.get(n).es,predecessor:a({direction:"ef"})},ss:{sucessor:r?this.backwardMap.get(n).ls:this.forwardMap.get(n).es,predecessor:a({direction:"es"})},ff:{sucessor:r?this.backwardMap.get(n).lf:this.forwardMap.get(n).ef,predecessor:a({direction:"ef"})},sf:{sucessor:r?this.backwardMap.get(n).lf:this.forwardMap.get(n).ef,predecessor:a({direction:"es"})}};if(t===y.FNLT)return{fs:{sucessor:r?this.backwardMap.get(n).ls:this.forwardMap.get(n).es,predecessor:a({direction:"ef"})},ss:{sucessor:r?this.backwardMap.get(n).ls:this.forwardMap.get(n).es,predecessor:a({direction:"es"})},ff:{sucessor:r?this.backwardMap.get(n).lf:this.forwardMap.get(n).ef,predecessor:a({direction:"ef"})},sf:{sucessor:r?this.backwardMap.get(n).lf:this.forwardMap.get(n).ef,predecessor:a({direction:"es"})}}}calculateMsoMfo(t){let r=this.activity.constraint_date||new Date,n=t===y.MSO?this.forwardMap.get(this.activity.id).es:this.forwardMap.get(this.activity.id).ef,i=this.calculationWithCalendar(r,n);return Math.max(0,this.parseHoursToDays(i))}getMinValue(...t){let r=t.filter(n=>n!=null);return r.length?Math.min(...r):0}calculationWithCalendar(t,r){let n=`${r.getTime()}_${t.getTime()}`;if(this.durationCache.has(n))return this.durationCache.get(n);let a=this.gantt.getCalendar(this.activity.calendar_id).calculateDuration({start_date:new Date(r),end_date:new Date(t)});return this.durationCache.set(n,a),a}parseHoursToDays(t){return t?t/this.gantt.config.hoursPerDay:0}getMinFloat(t){if(!t?.length)return null;let r=t.filter(n=>!n.hasProgress).map(n=>n.freeFloat);return r.length===0?null:Math.min(...r)}},Vo=ci;var Yo=e=>({totalFloat:new Ho(e.totalFloat).getTotalFloat(),freeFloat:new Vo(e.freeFloat).getFreeFloat()});var li=async({activityIds:e,forward:t,backward:r,gantt:n,projectDates:i,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=n.getTask(l);if(!d)continue;let u=jo({forward:t,backward:r,id:l,activity:d,gantt:n,projectDates:i}),{totalFloat:f,freeFloat:p}=Yo(u);o.set(l,f),c.set(l,p),s=await He(s)}return{totalFloatMap:o,freeFloatMap:c}};var di=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,r=()=>!0){let n=++this.currentCalculationId,i=ei(n,this.getCurrentCalculationId),a=()=>i()&&r();try{let s=t||this.gantt;if(this.gantt=s||Uo(),ri(this.gantt))return!1;let o=new Fo(this.gantt);if(await o.calculateAsync(a),!a())return!1;let c=o.calculations,l=o.constraintsMap,d=new Bo(this.gantt,c,l);if(await d.calculateAsync(a),!a())return!1;this.forwardPathCalculations=c,this.backwardPathCalculations=d.calculations;let{totalFloatMap:u,freeFloatMap:f}=await this.calculateFloatsAsync(o,d,a);return a()?(this.totalFloat=u,this.freeFloat=f,this.gantt.refreshData(),!0):!1}catch(s){throw this.forwardPathCalculations?.size,s}}async calculateFloatsAsync(t,r,n){try{let i=this.gantt.getSubtaskDates(),a=Array.from(this.forwardPathCalculations.keys());return await li({activityIds:a,forward:t,backward:r,gantt:this.gantt,projectDates:i,isCurrent:n})}catch(i){throw this.forwardPathCalculations?.size,i}}},Ko=di;var Qp=e=>e==="fnet"||e==="fnlt"||e==="mfo",th=e=>new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()));function eh(e,t){let r=e.constraintDate;if(!r||!Qp(e.constraintType))return r;let n=th(r);if(r.getTime()!==n.getTime())return r;let i=t.getClosestWorkTime({date:n,dir:"future",task:e});return i.getUTCFullYear()===r.getUTCFullYear()&&i.getUTCMonth()===r.getUTCMonth()&&i.getUTCDate()===r.getUTCDate()?Dn(e,t):r}function rh(e){let t=new Map,r=new Map,n=new Map;return{calculateEndDate:({start_date:i,duration:a})=>{let s=`${i.getTime()}|${a}`,o=t.get(s);if(o!==void 0)return new Date(o);let c=e.calculateEndDate(i,a);return t.set(s,c.getTime()),c},calculateDuration:({start_date:i,end_date:a})=>{let s=`${i.getTime()}|${a.getTime()}`,o=r.get(s);if(o!==void 0)return o;let c=e.calculateDuration(i,a);return r.set(s,c),c},getWorkHours:i=>e.getWorkHours(i),$gantt:{getClosestWorkTime:({date:i,dir:a,unit:s})=>{let o=s??"hour",c=`${i.getTime()}|${a}|${o}`,l=n.get(c);if(l!==void 0)return new Date(l);let d=e.getClosestWorkTime({date:i,direction:a,unit:o});return n.set(c,d.getTime()),d}}}}function nh(e){let t=new Map;e.forEachActivity((i,a)=>t.set(String(a),i));let r=new Map,n=(i,a)=>{let s=r.get(i);if(s!=null)return s;let c=t.get(i)?.parentId??null,l=0;return c!==null&&!a.has(i)&&(a.add(i),l=n(String(c),a)+1),r.set(i,l),l};for(let i of t.keys())n(i,new Set);return r}function ih(e){let t=nh(e),r=new Map;return e.forEachActivity((n,i)=>{let a=String(i);r.set(a,{id:Number(i),parent:n.parentId===null?0:Number(n.parentId),$level:t.get(a)??0,$source:e.getOutgoingLinkIds(a),$target:e.getIncomingLinkIds(a),start_date:n.startDate,end_date:n.endDate,duration:n.durationHours,progress:n.progress,type:n.type,calendar_id:n.calendarId,constraint_type:n.constraintType,constraint_date:eh(n,e)})}),r}function ah(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=[],n=new Set,i=[],a=s=>{if(s)for(let o=s.length-1;o>=0;o-=1)i.push(s[o])};for(a(t.get(0));i.length>0;){let s=i.pop();n.has(s)||(n.add(s),r.push(s),a(t.get(s.id)))}if(r.length<e.size)for(let s of e.values())n.has(s)||r.push(s);return r}function sh(e){let t=null,r=null;return e.forEachActivity(n=>{if(n.startDate){let i=n.startDate.getTime();t=t==null?i:Math.min(t,i)}if(n.endDate){let i=n.endDate.getTime();r=r==null?i:Math.max(r,i)}}),{start_date:new Date(t??0),end_date:new Date(r??0)}}async function Go(e,t){let r=new Map,n=c=>{let l=c==null?"__default__":String(c),d=r.get(l);if(d)return d;let u=e.calendarReader.getCalendar(String(c)),f=rh(u);return r.set(l,f),f},i=sh(e);await Z();let a=ih(e);await Z();let s=[...a.values()].sort((c,l)=>(c.start_date?.getTime()??0)-(l.start_date?.getTime()??0));await Z();let o=ah(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:n,getChildren:c=>e.getChildren(c).map(l=>Number(l)),eachTask:c=>{for(let l of o)c(l)},getTaskByTime:()=>s,getSubtaskDates:()=>i,refreshData:()=>{}}}var oh=1e3;function ch(e,t,r){let n=o=>o==null?null:new Date(o),i=r.forward?.get(e),a=r.backward?.get(e),s=r.totalFloat.get(e)??null;return{criticalPath:{earlyStart:n(i?.es),earlyFinish:n(i?.ef),lateStart:n(a?.ls),lateFinish:n(a?.lf),totalSlackHours:s},isCritical:t<100&&s!=null&&s<=0,freeSlackHours:r.freeFloat.get(e)?.activityFreeFloat??null}}var xr=(e,t)=>e===t||e!==null&&t!==null&&e.getTime()===t.getTime();function ui(e,t,r){let n=e.getActivity(t),i=n?.criticalPath,a=r.criticalPath;n&&i&&xr(i.earlyStart,a.earlyStart)&&xr(i.earlyFinish,a.earlyFinish)&&xr(i.lateStart,a.lateStart)&&xr(i.lateFinish,a.lateFinish)&&Object.is(i.totalSlackHours,a.totalSlackHours)&&Object.is(n.isCritical,r.isCritical)&&Object.is(n.freeSlackHours,r.freeSlackHours)||e.setActivityFields(t,r)}async function fi(e,t,r=()=>!0){if(!r())return null;let n=await Go(e,t);if(!r())return null;let i=new Ko(n);if(!await i.calculate(n,r)){if(!r())return null;throw new Error("critical path calculation aborted")}if(!r())return null;let s={forward:i.forwardPathCalculations,backward:i.backwardPathCalculations,totalFloat:i.totalFloat,freeFloat:i.freeFloat},o=new Set([...s.forward?.keys()??[]]),c=new Map,l=0;for(let d of o){if(++l>=oh&&(l=0,await Z(),!r()))return null;let u=e.getActivity(d);if(!u)continue;let f=Number(u.progress??0);c.set(d,ch(d,f,s))}return r()?c:null}async function Fr(e,t,r=()=>!0){let n=await fi(e,t,r);if(!n||!r())return!1;for(let[i,a]of n){if(!r())return!1;ui(e,i,a)}return!0}function ke(e){let t=[],r=[];e.forEachActivity((i,a)=>{i.parentId===null&&t.push(String(a))});let n=i=>{let a=e.getActivity(String(i));if(!a)return 0;let s=[...e.getChildren(String(i))],o;if(s.length===0){let c=ut(a),l=c&&Number(c.cost)||0;o=(Number(a.progress)||0)/100*l}else{let c=0;for(let l of s)c+=n(String(l));o=c}return e.setActivityField(String(i),b.REAL_COST,o),r.push(String(i)),o};for(let i of t)n(i);return r}var $o=new Set;var zo=new Set(["activity-outdent","activity-indent"]);var Ye=new Set([R.TEXT,R.DESCRIPTION,R.COST,R.USED_COST,R.CUSTOM_ID,R.RESPONSABLES,R.SUBCONTRACT_ID,R.TAGS]),lh=new Set(["selection-toggle","selection-replace","visibility-set","filter-set","sort-set","sir-sync","activity-lookahead-sync","persistence-acknowledge","baseline-apply","ponderator-criterion-set","status-criteria-set"]),dh=new Set(["selection-toggle","selection-replace","visibility-set","filter-set","sort-set"]);function Jo(e){return!dh.has(e.kind)}var uh=new Set;function fh(e){return e.kind==="inline-edit"?Ye.has(e.column):e.kind==="bulk-edit"?e.edits.every(t=>Ye.has(t.column)):!1}function pi(e,t){return!(lh.has(e.kind)||t.has(e.kind)||fh(e))}function hi(e){return pi(e,uh)}function re(e){return pi(e,$o)}function Xo(e){return pi(e,zo)}function yi(e){return e.kind==="activity-set-progress"?!0:e.kind==="inline-edit"?e.column===R.PROGRESS:e.kind==="bulk-edit"?e.edits.some(t=>t.column===R.PROGRESS):!1}function ph(e){return Xo(e)&&yi(e)}var qo=new Set([R.PROGRESS,R.HH_WORK_TIME,R.DURATION,R.COST,R.USED_COST,R.REAL_COST]);function hh(e){return e.kind==="activity-set-progress"?!0:e.kind==="inline-edit"?qo.has(e.column):e.kind==="bulk-edit"?e.edits.some(t=>qo.has(t.column)):!1}var at={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 Zo(e,t,r){let n=new Set;t.ran&&n.add(at.AUTOSCHEDULE),n.add(at.PARENT_BOUNDS),hh(e)&&n.add(at.PARENT_PROGRESS),yi(e)&&n.add(at.REAL_WORK);let i=!r.skipAutoSchedule;return i&&Xo(e)&&n.add(at.EXPECTED_PROGRESS),i&&ph(e)&&n.add(at.REAL_COST),i&&re(e)&&!r.skipCriticalPath&&n.add(at.CRITICAL_PATH),n}async function G(e,t){let r=yh(t);r.has(at.AUTOSCHEDULE)&&await Ah(e.adapter,t);let n=r.has(at.AUTOSCHEDULE)?await mh(e,t.autoscheduleFrom):vh();return await Ch(e.adapter,t,n.scheduledIds,r),await Ih(e,r,t.now),n}function yh(e){let t=e.autoscheduleFrom!==null,r=!e.options.skipAutoSchedule&&t,n=new Set(Zo(e.action,{requested:t,ran:r},e.options));return e.recomputeParentProgress&&n.add(at.PARENT_PROGRESS),n}async function mh(e,t){let r=t==="roots"?{}:{triggerId:t},n=await e.scheduler.schedule(r),i=gh(e.adapter,n.updatedIds);return Ne(e.adapter,n),i}function gh(e,t){let r=[];for(let n of t){let i=String(n);r.push(i);let a=e.getActivity(i);a&&e.noteScheduledBefore(i,a)}return{scheduledIds:r}}function vh(){return{scheduledIds:[]}}async function Ah(e,t){let r=t.collectDirty?t.collectDirty([]):Vn(t.recomputeParentsFrom,[]);r.size!==0&&await fe(e,r,!1)}async function Ch(e,t,r,n){let i=t.collectDirty?t.collectDirty(r):Vn(t.recomputeParentsFrom,r);await fe(e,i,n.has(at.PARENT_PROGRESS),{recomputeRealWork:n.has(at.REAL_WORK),progressMode:t.recomputeParentProgress?"zero-when-no-contribution":"freeze-when-no-contribution"})}async function Ih(e,t,r){t.has(at.EXPECTED_PROGRESS)&&r!==null&&(Sh(e.adapter)&&Se(e.adapter,r,e.defaultBaseCalendarId??null),te(e.adapter,r),Ot(e.adapter,e.sector.statusCriteria)),t.has(at.REAL_COST)&&ke(e.adapter),t.has(at.CRITICAL_PATH)&&await Fr(e.adapter,e.sector.hoursPerDay)}function Sh(e){let t=!1;return e.forEachActivity(r=>{ut(r)&&(t=!0)}),t}var kh=new Set([R.CONSTRAINT_TYPE,R.CONSTRAINT_DATE]),Dh=new Set(["mso","mfo"]);function Nr(e){return kh.has(e)}function Mr(e){return e===R.CONSTRAINT_DATE}function Wr(e,t,r,n){let i=r.getActivity(e);if(!i)return!1;let a=i.constraintType;if(!a||Ut.has(a)||Dh.has(a))return!1;let s=mi(i.startDate),o=mi(r.getLastStartDate(e));if(!o||!s||s.getTime()!==o.getTime())return!1;let c=Th(t,a,String(i.calendarId??""),n),l=mi(i.constraintDate);return _h(l,c)?!1:(r.setActivityField(e,"constraintDate",c),!0)}function Th(e,t,r,n){if(e===null)return null;let i=n.getCalendar(r);return i?bt(e,i,t):e}function mi(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 _h(e,t){return e===null&&t===null?!0:e===null||t===null?!1:e.getTime()===t.getTime()}async function Br(e,{postMutationArgs:t,revertTargets:r,revert:n}){let{scheduledIds:i}=await G(e,Qo(t)),a=!1;for(let{activityId:s,priorConstraintDate:o}of r){let c=n(s,o);a=a||c}if(a){let s=await G(e,Qo(t));i=Rh(i,s.scheduledIds)}return re(t.action)&&await G(e,Ph(t)),{scheduledIds:i}}function Qo(e){return{...e,options:{...e.options,skipCriticalPath:!0}}}function Ph(e){return{action:e.action,autoscheduleFrom:null,recomputeParentsFrom:[],now:null,options:e.options}}function Rh(e,t){let r=new Set(e);for(let n of t)r.add(n);return[...r]}function Eh(e,t){let r=n=>n.getTime();return r(e.startDate)!==r(t.startDate)||r(e.endDate)!==r(t.endDate)||e.durationHours!==t.durationHours}function gi(e,t,r){let n=[];for(let i of r){let a=e.get(i);if(!a)continue;let s=a.pendingRequestIds??[];if(!oe({pendingRequestIds:s}))continue;let o=t.getActivity(i),c=o==null;if(!c&&!Eh(a,o))continue;let l=c?"activity_deleted":"date_changed";for(let d of s)n.push({kind:"sir-auto-reject",activityId:i,sirId:d,reason:l});c||t.setActivityField(i,"pendingRequestIds",[])}return n}async function B(e,t){let r=Lh(e,t),n=new Map(t.beforeSnap),i=e.peekWriteCapture();if(i){let d=Oh(i);wh(e,i,d,n,r)}let a=t.sirDetection==="before-diff"?gi(n,e,r):[],s=bh(t.correlativeShifts,r),o=await vo(e,n,r,s),c=t.sirDetection==="after-diff"?gi(n,e,r):a,l=t.warnings??[];return{source:t.source,activities:o,links:t.links??[],calendars:[],trackingEvents:t.trackingEvents??[],...c.length>0?{effects:c}:{},...l.length>0?{warnings:l}:{}}}function bh(e,t){if(!e||e.length===0)return;let r=new Map;for(let n of e)r.set(n.activityId,n.before),t.add(n.activityId);return r}function Lh(e,t){let r=new Set;for(let n of t.touchedIds)r.add(n);for(let n of t.scheduledIds)r.add(n);if(t.includeAllIds)for(let n of e.getAllIds())r.add(n);return r}function wh(e,t,r,n,i){for(let a of t.dirty){if(r.has(a)||n.has(a))continue;let s=t.before.get(a),o=e.getActivity(a);!s||!o||Object.keys(Hn(s,o)).length!==0&&(n.set(a,s),i.add(a))}}function Oh(e){return new Set(e.ops.filter(t=>t.kind==="insert").map(t=>t.activityId))}function vt(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 De(e,t,r){let n=[];for(let{op:i,finalLinkId:a,rejected:s}of e){if(s!==null)continue;if(i.kind==="create"){if(!a)continue;let d=r.getLink(a);if(!d)continue;let u=t.get(a);if(u){let f={};String(u.source)!==String(d.source)&&(f.source={before:String(u.source),after:String(d.source)}),String(u.target)!==String(d.target)&&(f.target={before:String(u.target),after:String(d.target)}),u.type!==d.type&&(f.type={before:u.type,after:d.type}),Number(u.lag)!==Number(d.lag)&&(f.lag={before:Number(u.lag),after:Number(d.lag)}),Object.keys(f).length>0&&n.push({id:String(a),kind:"updated",fields:f,after:vt(d)});continue}n.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:vt(d)});continue}if(i.kind==="delete"){if(r.getLink(i.linkId))continue;let d=t.get(i.linkId);n.push({id:String(i.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(i.linkId),c=r.getLink(i.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)}),n.push({id:String(i.linkId),kind:"updated",fields:l,after:vt(c)})}return n}function Te(e,t){let r=new Map;if(!e.getActivity(t))return r;for(let n of e.getIncomingLinkIds(t)){let i=e.getLink(n);i&&r.set(String(i.id),Number(i.lag))}return r}function _e(e,t,r){let n=[];if(!t.getActivity(r))return n;for(let i of t.getIncomingLinkIds(r)){let a=t.getLink(i);if(!a)continue;let s=e.get(String(a.id));s===void 0||s===Number(a.lag)||n.push({id:String(a.id),kind:"updated",fields:{lag:{before:s,after:Number(a.lag)}},after:vt(a)})}return n}function Ur(e,t){typeof e=="string"&&e.length>0&&t.releaseCustomId(e)}async function tc(e,t,r){let{adapter:n,ctx:i,scheduler:a,sector:s}=r,o=Ht(e.column);if(!o)throw new Error(`[ScheduleCore] no pipeline registered for column "${e.column}"`);xh(e.column)&&a.invalidateExpandedLinksCache(),e.column===b.PARENT&&a.invalidateAllCaches();let c=i.activityReader.getActivity(e.activityId);if(!c)return{ok:!1,reason:T.ACTIVITY_NOT_FOUND};let l=o.canEdit(c,i.hierarchy);if(!l.allowed)return{ok:!1,reason:l.reason??T.CANNOT_EDIT,alertKey:l.alertKey};let d=o.parseInput(e.newValue,c,i);if(!d.ok)return{ok:!1,reason:d.reason??T.PARSE_ERROR};let u=Reflect.get(c,o.targetField),f=o.validate(c,u,d.value,i);if(!f.valid)return{ok:!1,reason:f.reason??T.INVALID,alertKey:f.notification?.messageKey};if(e.column===R.CUSTOM_ID&&d.value!==null){let _=n.getActivity(e.activityId),E=_?_.customId:null,x=typeof E=="string"?E:null;if(r.customIdTracker.isCustomIdInUse(String(d.value),x))return{ok:!1,reason:T.CUSTOM_ID_DUPLICATE}}let p=o.transform(c,d.value,i,d.raw),m=Vt(e.activityId,p),I=await q(n,m),C=Te(n,String(e.activityId)),S=c.constraintDate;Yt(n,e.activityId,p),Bt(e.activityId,p.postProcessors??[],n,I.get(String(e.activityId))??null);let D=_e(C,n,String(e.activityId));if(e.column===R.CUSTOM_ID){let _=I.get(String(e.activityId)),E=_?_.customId:null,x=typeof E=="string"?E:null,O=typeof d.value=="string"?d.value:null;x!==O&&r.customIdTracker.trackCustomIdChange(x,O)}let P=()=>({action:e,autoscheduleFrom:p.needsAutoSchedule?String(e.activityId):null,recomputeParentsFrom:[],collectDirty:_=>Er(e.activityId,m,_),now:r.now,options:t}),g=Nr(e.column),{scheduledIds:h}=await(g?Br({adapter:n,scheduler:a,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{postMutationArgs:P(),revertTargets:Mr(e.column)?[]:[{activityId:e.activityId,priorConstraintDate:S}],revert:(_,E)=>Wr(_,E,n,i.calendars)}):G({adapter:n,scheduler:a,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},P())),v=(p.trackingEvents??[]).map(_=>({name:_.name,properties:_.properties??{}})),A=Ae(e.activityId,p.constraintWarning);return{ok:!0,changes:await B(n,{source:e,beforeSnap:I,touchedIds:m,scheduledIds:h,sirDetection:"before-diff",links:D,trackingEvents:v,...A?{warnings:[A]}:{},hoursPerDay:s.hoursPerDay})}}function xh(e){return e===R.DURATION||e===b.AUTO_SCHEDULING}function Fh(e,t){let r=new Set,n=new Map;for(let i of e){if(i.kind==="create"){r.add(String(i.source)),r.add(String(i.target));continue}let a=t.getLink(i.linkId);a&&(r.add(String(a.source)),r.add(String(a.target)),n.set(i.linkId,{...a}))}return{activityIds:r,links:n}}function Nh(e,t,r,n){return e.map((i,a)=>{let s=i.kind==="create"?n?.get(a):void 0,o=Tt(i,{port:t,newLinkId:s?()=>s:r.next});return{op:i,finalLinkId:o.applied?o.linkId:null,rejected:o.applied?null:o.rejected??"link_op_rejected"}})}function Mh(e){return new Map([...e].map(([t,r])=>[String(t),r]))}async function ec(e,t,r){if(e.kind==="link-create"||e.kind==="link-update"){let n=e.type;if(n!==void 0&&!Object.values(M).some(a=>a===n))return{ok:!1,reason:T.INVALID_LINK_TYPE};let i=e.lag;if(i!==void 0&&!Number.isFinite(i))return{ok:!1,reason:T.INVALID_LINK_LAG}}return vi([Hh(e,r.sector.hoursPerDay)],e,t,r,e.kind==="link-create"&&e.linkId?new Map([[0,e.linkId]]):void 0)}async function rc(e,t,r){let{hoursPerDay:n}=r.sector,i=e.operations.map(s=>Bh(s,n)),a=Wh(e.operations);return vi(i,e,t,r,a)}function Wh(e){let t=new Map;return e.forEach((r,n)=>{r.kind==="create"&&r.linkId&&t.set(n,r.linkId)}),t.size>0?t:void 0}function Bh(e,t){return e.kind==="create"?{kind:"create",source:e.source,target:e.target,type:e.type,lag:dt(e.lag??0,t)}:e.kind==="update"?{kind:"update",linkId:e.linkId,type:e.type,lag:e.lag===void 0?void 0:dt(e.lag,t)}:{kind:"delete",linkId:e.linkId}}async function vi(e,t,r,n,i){let{adapter:a,scheduler:s,sector:o,linkIdGen:c}=n;s.invalidateAllCaches();let{activityIds:l,links:d}=Fh(e,a),u=await q(a,l),f=Nh(e,a,c,i);if(e.length===1&&f[0]&&f[0].rejected!==null&&t.kind!=="inline-edit")return{ok:!1,reason:f[0].rejected};let p=Uh(f,d,a),{scheduledIds:m}=await G({adapter:a,scheduler:s,sector:n.sector,defaultBaseCalendarId:n.defaultBaseCalendarId},{action:t,autoscheduleFrom:p,recomputeParentsFrom:l,now:n.now,options:r}),I=De(f,d,a);return{ok:!0,linkVerdicts:f.map((C,S)=>C.rejected===null?{operationIndex:S,kind:C.op.kind,ok:!0,linkId:String(C.finalLinkId)}:{operationIndex:S,kind:C.op.kind,ok:!1,reason:C.rejected}),__beforeLinks:Mh(d),changes:await B(a,{source:t,beforeSnap:u,touchedIds:l,scheduledIds:m,links:I,hoursPerDay:o.hoursPerDay})}}function Uh(e,t,r){for(let n of e){if(n.rejected!==null)continue;let i=jh(n.op,t,r);if(i!==null)return r.hasChildren(i)?"roots":String(i)}return null}function jh(e,t,r){return e.kind==="create"?e.target:e.kind==="delete"?t.get(e.linkId)?.target??null:r.getLink(e.linkId)?.target??null}function Hh(e,t){return e.kind==="link-create"?{kind:"create",source:e.source,target:e.target,type:e.type,lag:dt(e.lag,t)}:e.kind==="link-update"?{kind:"update",linkId:e.linkId,type:e.type,lag:e.lag===void 0?void 0:dt(e.lag,t)}:{kind:"delete",linkId:e.linkId}}async function nc(e,t,r){let{adapter:n,sector:i}=r;if(typeof e.newValue!="string")return{ok:!1,reason:T.INVALID_VALUE};if(!n.getActivity(e.activityId))return{ok:!1,reason:T.ACTIVITY_NOT_FOUND};let s=e.column===R.CUSTOM_PREDECESSORS,{specs:o}=hr(e.newValue),c=o.map(m=>({...m,lag:dt(m.lag,i.hoursPerDay)})),l=new Map;n.forEachActivity(m=>{m.correlativeId!=null&&l.set(String(m.correlativeId),m.id)});let d=m=>l.get(m)??null,u=s?n.getIncomingLinkIds(e.activityId):n.getOutgoingLinkIds(e.activityId),f=[];for(let m of u){let I=n.getLink(m);I&&f.push(I)}let p=s?mr({targetActivityId:e.activityId,currentLinks:f,desiredSpecs:c,resolveActivityByCorrelative:d}):gr({sourceActivityId:e.activityId,currentLinks:f,desiredSpecs:c,resolveActivityByCorrelative:d});return vi(p.operations,e,t,r)}var At={ACTIVITY_CREATION:"schedule_activity_creation",ACTIVITY_DELETION:"schedule_activity_deletion",ACTIVITY_MOVE:"schedule_activity_move",ACTIVITY_INDENT:"schedule_activity_indent",ACTIVITY_OUTDENT:"schedule_activity_outdent"};function st(e){e.invalidateVisualOrderIds?.();let t=[];e.forEachActivity(a=>{L(a.parentId)&&t.push(a)}),t.sort(sc);let r=[];ic(r,t);let n=[],i=0;for(;r.length>0;){let a=r.pop();if(a.correlativeId!==i){let o=typeof a.correlativeId=="number"?a.correlativeId:void 0;n.push({activityId:String(a.id),before:o}),o!==void 0&&e.noteCorrelativeBefore?.(String(a.id),o),Vh(a,i)}i+=1;let s=we(String(a.id),e);s.sort(sc),ic(r,s)}return n}function ic(e,t){for(let r=t.length-1;r>=0;r-=1)e.push(t[r])}function ac(e){let t=e.correlativeId,r=typeof t=="number"?t:Number(t);return Number.isFinite(r)?r:Cn}var sc=(e,t)=>ac(e)-ac(t);function Vh(e,t){e.correlativeId=t}function Ci(e,t){if(!e||e==="0")return;let r=String(e);for(;r!==null;){let n=t.getChildren(r),i=0,a=0;for(let c of n){let l=t.getActivity(c);if(!l)continue;let d=Ai(l,b.WORK_HOURS),u=Yh(c,l,d,t);i+=d,a+=u}t.setActivityField(r,b.WORK_HOURS,i),t.setActivityField(r,b.REAL_WORK_HOURS,a);let s=t.getActivity(r);if(!s)break;let o=s.parentId;if(!o||L(o))break;r=o}}function oc(e,t){let r=t.getActivity(e);if(!r)return;let n=r.parentId;!n||L(n)||Ci(n,t)}function Ai(e,t){let r=e[t];return typeof r=="number"&&Number.isFinite(r)?r:0}function Yh(e,t,r,n){return n.hasChildren(e)?Ai(t,b.REAL_WORK_HOURS):pt(r,Ai(t,b.PROGRESS))}function Ii(e,t){if(!e||e==="0")return;let r=String(e);for(;r!==null;){let n=t.getChildren(r),i=0;for(let o of n){let c=t.getActivity(o);c&&(i+=Kh(c,b.USED_COST))}t.setActivityField(r,b.USED_COST,i);let a=t.getActivity(r);if(!a)break;let s=a.parentId;if(!s||L(s))break;r=s}}function cc(e,t){let r=t.getActivity(e);if(!r)return;let n=r.parentId;!n||L(n)||Ii(n,t)}function Kh(e,t){let r=e[t];return typeof r=="number"&&Number.isFinite(r)?r:0}function Si(e,t){if(!e||e==="0")return;let r=String(e);for(;r!==null;){let n=t.getChildren(r),i=0;for(let o of n){let c=t.getActivity(o);c&&(i+=Gh(c,b.COST))}t.setActivityField(r,b.COST,i);let a=t.getActivity(r);if(!a)break;let s=a.parentId;if(!s||L(s))break;r=s}}function lc(e,t){let r=t.getActivity(e);if(!r)return;let n=r.parentId;!n||L(n)||Si(n,t)}function Gh(e,t){let r=e[t];return typeof r=="number"&&Number.isFinite(r)?r:0}var jr=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}),dc="New Master Plan",uc="New Activity";var $h=["name","description","type","startDate","durationHours","constraintType","constraintDate","calendarId","assignedDefaultCalendar","autoScheduling","progress","cost","usedCost","realCost","workHours","realWorkHours","ponderator","hasCustomPonderator","customId","subcontractId","responsableIds","tagIds","isLookahead"],fc=new Set($h);function zh(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"||!fc.has(r))throw new Error(`activity-create: rejected override key "${String(r)}" \u2014 not a creation-writable canonical field`);return e}function pc(e,t){let r=e.parentId!=null?t.getActivity(e.parentId):null,n=zh(e.activityOverrides??{}),i=e.numTasksInGantt===0?dc:uc,a=n.name??i,s=n.durationHours??e.sector.hoursPerDay,o=n.calendarId??e.sector.defaultCalendar,c=qh(r,e.fallbackStartDate,n.startDate),l={...jr,...n,id:e.id,parentId:e.parentId,uniqueCorrelativeId:e.nextUniqueCorrelativeId,name:a,durationHours:s,calendarId:o,startDate:c,endDate:c},d=n.startDate?new Date(l.startDate):t.getClosestWorkTime({date:l.startDate,dir:X.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 qh(e,t,r){return r?new Date(r):e?new Date(e.startDate):t?new Date(t):new Date}function Jh(e){let t=e.type;if(t!=="task"&&t!=="milestone")return null;let r=e.startDate,n=e.endDate;return!(r instanceof Date)||!(n instanceof Date)?null:{type:t,startDate:new Date(r),endDate:new Date(n),durationHours:Number(e.durationHours??0),expectedProgressBaseline:typeof e.expectedProgressBaseline=="number"?e.expectedProgressBaseline:null,constraintType:e.constraintType??null,constraintDate:e.constraintDate instanceof Date?new Date(e.constraintDate):null,progress:Number(e.progress??0)}}function Pe(e){let t=e.getParent(e.parentId);if(!t)return null;let r=e.isCurrentlyLeaf!==void 0?e.isCurrentlyLeaf&&Mt(t.type):Xh(t),n=Array.isArray(t.newActivityIds)?t.newActivityIds:[],a={isLookahead:!1,hasNewActivities:!0,newActivityIds:n.some(s=>String(s)===String(e.newChildId))?[...n]:[...n,e.newChildId]};return t.customId!=null&&t.customId!==""&&(a.customId=null),r&&(a.type=En,(e.promotionSource??"create")==="create"&&(a.constraintType=K.ASAP,a.constraintDate=null,a.progress=0)),{parentId:e.parentId,fields:a,promotionSnapshot:Jh(t)}}function Xh(e){return Mt(e.type)&&(!Array.isArray(e.newActivityIds)||e.newActivityIds.length===0)}function Hr(e,t,r,n){let i=t,a=i==="0",s=Ke(e,i);if(n!==void 0){let c=s.find(l=>l.id===n);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 ne=Number.MAX_SAFE_INTEGER,hc=Number.MAX_SAFE_INTEGER-1;function nt(e){let t=e.correlativeId,r=typeof t=="number"?t:Number(t);return Number.isFinite(r)?r:ne}function Ke(e,t){return we(t,e)}function yc(e,t,r){let n=e,i=Gt(e,r);for(;i!=null&&t.has(i);)n=i,i=Gt(i,r);return n}function Vr(e,t,r){let n=new Set([e]),i=Ft(r.getActivity(e)?.parentId);for(;i!=="0"&&!n.has(i);){if(t.has(i))return!0;n.add(i),i=Ft(r.getActivity(i)?.parentId)}return!1}function Gt(e,t){let r=t.getActivity(e);if(!r)return null;let n=Ft(r.parentId),i=mt(n,t),a=i.findIndex(s=>String(s)===String(e));return a<=0?null:i[a-1]??null}function mc(e,t,r,n){let i=mt(t,e).filter(c=>String(c)!==String(n)).map(c=>e.getActivity(c)).filter(c=>c!==null);if(i.length===0)return 0;let a=i.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}async function Ge(e,t,r={}){let{adapter:n,scheduler:i,sector:a,calendars:s,activityIdGen:o,uidGen:c}=t;r.skipCacheInvalidation||i.invalidateAllCaches();let l=Zh(e,n);if(!l.ok)return l;let{parent:d,anchorSiblingId:u,isRoot:f}=l,p=ty(e.activityId,n,o),m=c.next(),I={id:p,parentId:f?null:e.parentId,sector:{id:a.id,hoursPerDay:a.hoursPerDay,defaultCalendar:sy(s)},numTasksInGantt:n.activityCount(),nextUniqueCorrelativeId:m,activityOverrides:e.overrides??{}},S=pc(I,{getActivity:A=>n.getActivity(A),calculateEndDate:A=>n.calculateEndDate(A),getClosestWorkTime:A=>n.getClosestWorkTime(A)}).newTask;S.realWorkHours=pt(S.workHours,S.progress),ry(S,e,t,u,d,r);let D=r.insertionCorrelativeId??Hr(n,f?"0":e.parentId,e.afterSiblingId,e.beforeSiblingId);S.correlativeId=D;let P=new Set([p]);d&&P.add(d.id);let g=d!==null&&n.getChildren(d.id).length===0,h=g?d?.customId:null,v=r.skipBeforeSnap?new Map:await q(n,P);return n.addActivity(S),ny(e,p,d,n,g),h&&t.customIdTracker.releaseCustomId(h),r.skipRollupCascades||(oc(p,n),cc(p,n),lc(p,n)),iy(n,p,v,P,r),{ok:!0,newId:p,parent:d,newActivity:S,beforeSnap:v,initialTouched:P}}function Zh(e,t){let r=L(e.parentId),n=r?null:t.getActivity(e.parentId);if(!r&&!n)return{ok:!1,reason:T.PARENT_NOT_FOUND};if(n!==null&&oe(n))return{ok:!1,reason:T.PARENT_FROZEN_BY_SIR};if(e.afterSiblingId!==void 0&&e.beforeSiblingId!==void 0)return{ok:!1,reason:T.ANCHOR_SIBLING_CONFLICT};let s=e.afterSiblingId??e.beforeSiblingId,o=Qh(e,t,r,s);return o||{ok:!0,parent:n,anchorSiblingId:s,isRoot:r}}function Qh(e,t,r,n){if(n===void 0)return null;let i=t.getActivity(n);if(!i)return{ok:!1,reason:T.ANCHOR_SIBLING_NOT_FOUND};let a=r?"0":e.parentId;return(i.parentId==null?"0":String(i.parentId))!==a?{ok:!1,reason:T.ANCHOR_SIBLING_WRONG_PARENT}:null}function ty(e,t,r){return e===void 0||t.activityExists(e)?r.next():(r.bump(e),e)}function ey(e){let t=e.overrides?.customId;return typeof t=="string"?t:void 0}function ry(e,t,r,n,i,a){let{adapter:s,customIdTracker:o}=r,c=ey(t);if(c!==void 0){if(c.length===0)return;if(!o.isCustomIdInUse(c)){o.registerCustomId(c);return}}let l=a.customIdReferenceId??n,d=l!==void 0,u=d?s.getActivity(l):i;e.customId=o.generateCustomIdForNewChild({activity:u??{},useActivityCustomIdAsReference:d})}function ny(e,t,r,n,i){if(!r)return;let a=Pe({parentId:e.parentId,newChildId:t,isCurrentlyLeaf:i,getParent:s=>n.getActivity(s)??null});if(a){for(let[s,o]of Object.entries(a.fields))rt(n,a.parentId,s,o);a.promotionSnapshot&&n.setPromotionSnapshot(a.parentId,a.promotionSnapshot)}}function iy(e,t,r,n,i){if(i.skipCorrelativeRecompute)return;let a=st(e);i.skipBeforeSnap||Ce(e,a,new Set([String(t)]),r,n)}async function ay(e,t,r,n,i){let{newId:a,newActivity:s,beforeSnap:o,initialTouched:c}=r,l={name:At.ACTIVITY_CREATION,properties:{parent_id:t.parentId,activity_id:a,created_duration:s.durationHours}};return t.eventSource!==void 0&&(l.properties.event_source=t.eventSource),B(e,{source:t,beforeSnap:o,touchedIds:c,scheduledIds:n,trackingEvents:[l],hoursPerDay:i})}async function gc(e,t,r){let{adapter:n,scheduler:i,sector:a}=r,s=await Ge(e,r);if(!s.ok)return s;let{newId:o}=s,c=s.newActivity.autoScheduling;n.setActivityField(o,"autoScheduling",!1);let l;try{l=await G({adapter:n,scheduler:i,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:"roots",recomputeParentsFrom:[o],now:r.now,options:t})}finally{n.setActivityField(o,"autoScheduling",c)}let{scheduledIds:d}=l;return{ok:!0,changes:await ay(n,e,s,d,a.hoursPerDay)}}function sy(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 kt(e,t){Ci(e,t),Ii(e,t),Si(e,t)}function vc(e,t){let r=new Set,n=[];for(let i of e){let a=String(i);r.has(a)||(r.add(a),n.push(a))}for(;n.length>0;){let i=n.pop(),a=t.getChildren(i);for(let s of a){let o=String(s);r.has(o)||(r.add(o),n.push(o))}}return r}function Ac(e,t){let r=new Set;for(let n of e){for(let i of t.getOutgoingLinkIds(n))r.add(String(i));for(let i of t.getIncomingLinkIds(n))r.add(String(i))}return[...r]}function oy(e){return e?{type:e.type,startDate:new Date(e.startDate),endDate:new Date(e.endDate),durationHours:e.durationHours,expectedProgressBaseline:e.expectedProgressBaseline,constraintType:e.constraintType,constraintDate:e.constraintDate?new Date(e.constraintDate):null,progress:e.progress}:null}function cy(e,t,r){let n=e.startDate;return!r||!(n instanceof Date)?{}:{endDate:r(n,t)}}function Re(e){if(e.remainingChildIds.length>0)return null;let t=e.parent,r=e.defaultDurationHours,n=Number.isFinite(r),i=oy(e.promotionSnapshot)??(n?{type:le,durationHours:r,progress:0,autoScheduling:!0,constraintType:"asap",constraintDate:null,hasNewActivities:!1,...cy(t,r,e.computeEndDate)}:{type:le});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&&(i.newActivityIds=s)}}return t.hasLookaheadTasks&&(i.isLookahead=!0),{parentId:String(t.id),fields:i}}function Cc(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,n=r.filter(i=>!e.idsRemoved.has(i)&&!e.idsRemoved.has(String(i)));return n.length===r.length?null:{parentId:String(e.parent.id),fields:{newActivityIds:[...n],hasNewActivities:n.length>0}}}var Ic=200;async function Sc(e,t,r){let{adapter:n,scheduler:i,customIdTracker:a,sector:s}=r;if(i.invalidateAllCaches(),e.activityIds.length===0)return{ok:!1,reason:T.ACTIVITY_IDS_EMPTY};for(let A of e.activityIds)if(!n.getActivity(A))return{ok:!1,reason:T.ACTIVITY_NOT_FOUND};let o=vc(e.activityIds,n),c=Ac(o,n),l=new Set;for(let A of e.activityIds){let _=n.getActivity(A);if(!_)continue;let E=_.parentId;if(L(E))continue;let x=String(E);o.has(x)||l.add(x)}let d=new Set([...o,...l]),u=await q(n,d),f=new Map;for(let A of c){let _=n.getLink(A);_&&f.set(A,{..._})}let p=new Set,m=0;for(let A of o){m+=1,m%Ic===0&&await Z();let _=n.getActivity(A);if(!_)continue;let E=L(_.parentId)?null:n.getActivity(String(_.parentId)),x=E?.hasNewActivities===!0&&E.newActivityIds.some(V=>String(V)===String(A));(_.isNewActivity===!0||x)&&p.add(A);let O=_.customId;typeof O=="string"&&O.length>0&&a.releaseCustomId(O)}for(let A of c)n.removeLink(A);let I=ki(n,o),C=0;for(let A of o)C+=1,C%Ic===0&&await Z(),n.removeActivity(A);for(let A of l){let _=n.getActivity(A);if(!_)continue;ly(_,p,n);let E=n.getChildren(A),x=Re({parent:_,remainingChildIds:E.map(String),defaultDurationHours:s.hoursPerDay,promotionSnapshot:n.getPromotionSnapshot(A),computeEndDate:(O,V)=>n.calculateEndDate({startDate:O,durationHours:V,task:_}),idsRemoved:o});if(!x){Cr(A,n);continue}for(let[O,V]of Object.entries(x.fields))rt(n,A,O,V);if(_.customId==null||_.customId===""){let O=Gt(A,n),V=O?n.getActivity(O)?.customId:null,Y=a.generateCustomIdForRestoredChild(typeof V=="string"&&V?V:null);n.setActivityField(A,b.CUSTOM_ID,Y)}}for(let A of l)kt(A,n);let S=st(n),{scheduledIds:D}=await G({adapter:n,scheduler:i,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:"roots",recomputeParentsFrom:l,now:r.now,options:t}),P={name:At.ACTIVITY_DELETION,properties:{activity_ids:[...e.activityIds],cascade_count:o.size}};e.eventSource!==void 0&&(P.properties.event_source=e.eventSource);let g=new Map;for(let[A,_]of f)g.set(A,_);let h=new Map;for(let A of o){let _=u.get(String(A));_&&h.set(String(A),_)}let v=await B(n,{source:e,beforeSnap:u,touchedIds:d,scheduledIds:D,sirDetection:"after-diff",links:dy(f),trackingEvents:[P],hoursPerDay:s.hoursPerDay,correlativeShifts:S});return{ok:!0,changes:I.length>0?{...v,viewState:I}:v,__beforeSnap:h,__beforeLinks:g}}function ly(e,t,r){let n=Cc({parent:e,idsRemoved:t});if(n)for(let[i,a]of Object.entries(n.fields))rt(r,n.parentId,i,a)}function ki(e,t){let r=[];for(let n of t){let i=e.isChecked(n),a=e.isVisible(n);!i&&a||r.push({activityId:String(n),...i?{checked:{before:!0,after:!1}}:{},...a?{}:{visible:{before:!1,after:!0}}})}return r}function dy(e){let t=[];for(let[r,n]of e.entries())t.push({id:r,kind:"deleted",fields:{source:{before:String(n.source),after:void 0},target:{before:String(n.target),after:void 0},type:{before:n.type,after:void 0},lag:{before:Number(n.lag),after:void 0}},after:null});return t}async function Tc(e,t,r){let n=uy(e,r);if(n)return{ok:!1,reason:n};let i=py(e,r);if(!i.ok)return i;let a=e.mode==="replace"?new Set(r.adapter.getAllIds().map(g=>String(g))):new Set,s=e.mode==="replace"?await q(r.adapter,a):new Map,o=e.mode==="replace"?gy(r):new Map,c=e.mode==="replace"?ki(r.adapter,a):[];r.scheduler.invalidateAllCaches();let l=[];if(e.mode==="replace"){for(let g of o.keys()){let h=Tt({kind:"delete",linkId:g},{port:r.adapter});if(!h.applied)return{ok:!1,reason:h.rejected??T.INVALID};l.push({op:{kind:"delete",linkId:g},finalLinkId:g,rejected:null})}for(let g of a){let h=r.adapter.getActivity(g)?.customId;typeof h=="string"&&h.length>0&&r.customIdTracker.releaseCustomId(h),r.adapter.removeActivity(g)}}let d=await my(e,i.plan.items,r);if(!d.ok)return d;let u=_c(e)?[]:st(r.adapter),f=new Set(i.plan.items.map(g=>String(g.activityId))),p=u.filter(g=>!f.has(g.activityId)),m=e.mode==="replace"?new Set(a):new Set;Ce(r.adapter,u,f,s,m);for(let g of i.plan.items)m.add(String(g.activityId));let I=i.plan.links.map(g=>({operation:{kind:"create",source:g.source,target:g.target,type:g.type,lag:t.inputUnit==="hours"?g.lag:dt(g.lag,r.sector.hoursPerDay)},linkId:g.linkId})),C=pr(I,{port:r.adapter,preserved:o});if(!C.applied)return{ok:!1,reason:C.rejected??T.INVALID};for(let{operation:g,linkId:h}of I)l.push({op:g,finalLinkId:h,rejected:null});let S=i.plan.items.map(g=>g.activityId),{scheduledIds:D}=await G({adapter:r.adapter,scheduler:r.scheduler,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:e.items.length>0||e.links.length>0?"roots":null,recomputeParentsFrom:S,now:r.now,options:t}),P=await B(r.adapter,{source:e,beforeSnap:s,touchedIds:m,scheduledIds:D,links:De(l,o,r.adapter),hoursPerDay:r.sector.hoursPerDay,correlativeShifts:p,...e.mode==="replace"?{sirDetection:"after-diff"}:{}});return{ok:!0,changes:c.length>0?{...P,viewState:c}:P,...e.mode==="replace"?{__beforeSnap:s,__beforeLinks:vy(o)}:{}}}function uy(e,t){if(e.mode!=="append"&&e.mode!=="replace")return T.INVALID;let r=new Set,n=new Set;for(let a of e.items){if(a.batchId.length===0||r.has(a.batchId))return T.INVALID;if(r.add(a.batchId),a.index!==void 0&&(!Number.isInteger(a.index)||a.index<0))return T.INVALID;if(a.activityId!==void 0){let s=String(a.activityId);if(s.length===0||s==="0"||n.has(s)||e.mode==="append"&&t.adapter.getActivity(s)!==null)return T.INVALID;n.add(s)}}for(let a of e.items)if(!Di(a.parent,!0,e.mode,r,t))return T.PARENT_NOT_FOUND;if(fy(e.items))return T.INVALID;let i=new Set;for(let a of e.links){if(!Object.values(M).includes(a.type)||!Number.isFinite(a.lag))return Number.isFinite(a.lag)?T.INVALID_LINK_TYPE:T.INVALID_LINK_LAG;if(!Di(a.source,!1,e.mode,r,t)||!Di(a.target,!1,e.mode,r,t))return T.ACTIVITY_NOT_FOUND;if(a.linkId!==void 0){let s=String(a.linkId);if(s.length===0||i.has(s)||e.mode==="append"&&t.adapter.getLink(s)!==null)return T.INVALID;i.add(s)}}return null}function Di(e,t,r,n,i){return typeof e=="string"?e==="0"?t:r==="append"&&i.adapter.getActivity(String(e))!==null:e!==null&&e.batchId.length>0&&n.has(e.batchId)}function fy(e){let t=new Map;for(let n of e)typeof n.parent!="string"&&t.set(n.batchId,n.parent.batchId);let r=new Set;for(let n of e){let i=new Set,a=n.batchId;for(;a!==void 0&&!r.has(a);){if(i.has(a))return!0;i.add(a),a=t.get(a)}for(let s of i)r.add(s)}return!1}function py(e,t){for(let o of e.items)o.activityId!==void 0&&t.activityIdGen.bump(o.activityId);let r=new Map;for(let o of e.items)r.set(o.batchId,o.activityId??t.activityIdGen.next());for(let o of e.links)o.linkId!==void 0&&t.linkIdGen.bump(o.linkId);let n=e.links.map(o=>o.linkId??t.linkIdGen.next()),i=hy(e,r,t),a=[];for(let o of e.items){let c=r.get(o.batchId),l=i.get(o.batchId);if(c===void 0||l===void 0)return{ok:!1,reason:T.INVALID};let d=typeof o.parent=="string"?null:o.parent.batchId,u=typeof o.parent=="string"?o.parent:r.get(o.parent.batchId);if(u===void 0)return{ok:!1,reason:T.PARENT_NOT_FOUND};a.push({input:o,activityId:c,parentId:u,parentBatchId:d,insertionCorrelativeId:l})}let s=[];for(let[o,c]of e.links.entries()){let l=Dc(c.source,r),d=Dc(c.target,r),u=n[o];if(l===null||d===null||u===void 0)return{ok:!1,reason:T.ACTIVITY_NOT_FOUND};s.push({source:l,target:d,type:c.type,lag:c.lag,linkId:u})}return{ok:!0,plan:{items:a,links:s}}}function hy(e,t,r){if(_c(e)){let o=r.adapter.activityCount();return new Map(e.items.map((c,l)=>[c.batchId,o+l]))}let n=new Set(Array.from(t.values(),o=>String(o))),i=new Map;for(let o of e.items){let c=t.get(o.batchId);if(c===void 0)continue;let l=typeof o.parent=="string"?o.parent:t.get(o.parent.batchId);if(l===void 0)continue;let d=String(l),u=i.get(d);u||(u={existing:e.mode==="replace"||typeof o.parent!="string"&&t.has(o.parent.batchId)?[]:Ke(r.adapter,d).sort((I,C)=>nt(I)-nt(C)||String(I.id).localeCompare(String(C.id))).map(I=>String(I.id)),newIdsByTarget:new Map},i.set(d,u));let f=o.index===void 0?u.existing.length:Math.min(o.index,u.existing.length),p=u.newIdsByTarget.get(f)??[];p.push(String(c)),u.newIdsByTarget.set(f,p)}let a=new Map,s=new Map(Array.from(t,([o,c])=>[String(c),o]));for(let o of i.values()){let c=[];for(let d=0;d<=o.existing.length;d+=1){for(let f of o.newIdsByTarget.get(d)??[])c.push(f);let u=o.existing[d];u!==void 0&&c.push(u)}let l=0;for(;l<c.length;){if(!n.has(c[l])){l+=1;continue}let d=l;for(;l<c.length&&n.has(c[l]);)l+=1;let u=l-d,f=d>0?kc(c[d-1],r):null,p=l<c.length?kc(c[l],r):null;for(let m=0;m<u;m+=1){let I=c[d+m],C=s.get(I);C!==void 0&&a.set(C,yy(f,p,m+1,u))}}}return a}function _c(e){return e.mode==="append"&&e.items.every(t=>t.parent==="0"&&t.index===void 0)}function kc(e,t){let r=t.adapter.getActivity(e);return r?nt(r):0}function yy(e,t,r,n){return e!==null&&t!==null&&t>e?e+(t-e)*r/(n+1):e!==null?e+r:t!==null?t-(n-r+1):r-1}async function my(e,t,r){let n=new Map,i=[];for(let s of t){if(s.parentBatchId===null){i.push(s);continue}let o=n.get(s.parentBatchId)??[];o.push(s),n.set(s.parentBatchId,o)}for(let s=0;s<i.length;s+=1){let o=i[s],c=await Ge({kind:"activity-create",parentId:o.parentId,activityId:o.activityId,...o.input.overrides===void 0?{}:{overrides:o.input.overrides},...e.eventSource===void 0?{}:{eventSource:e.eventSource}},r,{skipCorrelativeRecompute:!0,skipBeforeSnap:!0,skipCacheInvalidation:!0,skipRollupCascades:!0,insertionCorrelativeId:o.insertionCorrelativeId});if(!c.ok)return c;for(let l of n.get(o.input.batchId)??[])i.push(l)}if(i.length!==t.length)return{ok:!1,reason:T.INVALID};let a=new Set;for(let s=i.length-1;s>=0;s-=1){let o=i[s].parentId;o==="0"||a.has(String(o))||(a.add(String(o)),kt(o,r.adapter))}return{ok:!0}}function Dc(e,t){return typeof e=="string"?e:t.get(e.batchId)??null}function gy(e){return new Map(e.adapter.getAllLinks().map(t=>[String(t.id),{...t}]))}function vy(e){return new Map(Array.from(e,([t,r])=>[String(t),r]))}function Ay(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:T.ANCHOR_SIBLING_NOT_FOUND}}let r=e.parentId,i=Ke(t,r).sort((a,s)=>nt(a)-nt(s))[e.index]?.id;return{ok:!0,parentId:r,firstBefore:i}}function Cy(e){let{customId:t,...r}=e;return{...r,progress:0,ponderator:0,usedCost:0,workHours:0,isLookahead:!1}}async function Pc(e,t,r){let{adapter:n,scheduler:i,sector:a}=r,s=Ay(e.destination,n);if(!s.ok)return s;let o=await q(n,new Set),c=new Set,l=new Map,d=[],u;for(let S of e.activities){let D=l.get(S.originalParentId),P,g,h;D!==void 0?P=D:(P=s.parentId,u===void 0?(g=s.firstAfter,h=s.firstBefore):g=u);let v=await Ge({kind:"activity-create",parentId:P,afterSiblingId:g,beforeSiblingId:h,...S.activityId?{activityId:S.activityId}:{},overrides:Cy(S.overrides),eventSource:e.eventSource},r,{skipCorrelativeRecompute:!0,skipBeforeSnap:!0,customIdReferenceId:e.referenceActivityId});if(!v.ok)return v;if(S.baselineSnapshot!==void 0){let A=S.baselineSnapshot;n.setActivityField(v.newId,"baselineSnapshot",A?{...A,startDate:A.startDate?new Date(A.startDate):null,endDate:A.endDate?new Date(A.endDate):null}:null)}l.set(S.originalId,v.newId),d.push(v.newId),D===void 0&&(u=v.newId)}let f=st(n),p=new Set(d.map(String));Ce(n,f,p,o,c);for(let S of d)c.add(String(S));let m=[];for(let S of e.links){let D=l.get(S.source),P=l.get(S.target);if(D===void 0||P===void 0)continue;let g={kind:"create",source:D,target:P,type:S.type,lag:dt(S.lag,a.hoursPerDay)},h=Tt(g,{port:n,newLinkId:S.linkId?()=>S.linkId:r.linkIdGen.next});m.push({op:g,finalLinkId:h.applied?h.linkId:null,rejected:h.applied?null:h.rejected??"link_op_rejected"})}let{scheduledIds:I}=await G({adapter:n,scheduler:i,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:d[0]??null,recomputeParentsFrom:d,now:r.now,options:t}),C=De(m,new Map,n);return{ok:!0,changes:await B(n,{source:e,beforeSnap:o,touchedIds:c,scheduledIds:I,links:C,hoursPerDay:a.hoursPerDay})}}function Rc(e,t){let{adapter:r}=t,n=e.activityId,i=r.getActivity(n);if(!i)return{ok:!1,reason:T.ACTIVITY_NOT_FOUND};let a=i.pendingRequestIds??[],s=e.pendingRequests.map(c=>c.id);return r.setActivityField(e.activityId,"pendingRequestIds",s),{ok:!0,changes:{source:e,activities:[{id:n,kind:"updated",fields:{pendingRequestIds:{before:a,after:s}},after:{id:n,pendingRequestIds:s}}],links:[],calendars:[],trackingEvents:[]}}}function Ec(e,t){let r=[...new Set(e.activityIds.map(String))],n=r.map(a=>t.adapter.getActivity(a));if(n.some(a=>!a))return{ok:!1,reason:T.ACTIVITY_NOT_FOUND};let i=[];for(let[a,s]of r.entries()){let o=n[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&&i.push({id:s,kind:"updated",fields:c,after:{...o,isLookahead:e.isLookahead,hasLookaheadTasks:e.hasLookaheadTasks}})}return{ok:!0,changes:{source:e,activities:i,links:[],calendars:[],trackingEvents:[]}}}function Yr(e,t){let r=new Set;for(let i of e)r.add(String(i));let n=[];for(let i of t.getAllLinks()){let a=String(i.source),s=String(i.target);!r.has(a)&&!r.has(s)||(bc(s,a,t)||bc(a,s,t))&&n.push(String(i.id))}return n}function bc(e,t,r){let n=String(e),i=new Set;for(;n!=null;){if(i.has(n))return!1;i.add(n);let a=r.getActivity(n);if(!a)return!1;let s=a.parentId;if(s===null||L(s))return!1;let o=s;if(o===t)return!0;n=o}return!1}async function Lc(e,t,r){let{adapter:n,scheduler:i,sector:a}=r;i.invalidateAllCaches();let s=n.getActivity(e.activityId);if(!s)return{ok:!1,reason:T.ACTIVITY_NOT_FOUND};let o=L(e.parentId);if(!o&&!n.getActivity(e.parentId))return{ok:!1,reason:T.PARENT_NOT_FOUND};if(!o&&(e.parentId===e.activityId||n.isChildOf(e.parentId,e.activityId)))return{ok:!1,reason:T.CANNOT_MOVE_INTO_OWN_DESCENDANT};if(e.afterSiblingId!==void 0&&e.beforeSiblingId!==void 0)return{ok:!1,reason:T.ANCHOR_SIBLING_CONFLICT};let c=e.afterSiblingId??e.beforeSiblingId;if(c!==void 0){let h=n.getActivity(c);if(!h)return{ok:!1,reason:T.ANCHOR_SIBLING_NOT_FOUND};if((h.parentId===null?"0":String(h.parentId))!==e.parentId)return{ok:!1,reason:T.ANCHOR_SIBLING_WRONG_PARENT}}let l=s.parentId,d=Ft(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 m=await q(n,p);f&&n.setActivityField(e.activityId,b.PARENT,u);let I=Hr(n,e.parentId,e.afterSiblingId,e.beforeSiblingId);if(n.setActivityField(e.activityId,b.CORRELATIVE_ID,I),f){if(!o){let h=n.getActivity(e.parentId);if(h){let v=h.customId,A=Mt(h.type)&&n.getChildren(e.parentId).filter(E=>E!==e.activityId).length===0,_=Pe({parentId:e.parentId,newChildId:e.activityId,getParent:E=>n.getActivity(E)??null,isCurrentlyLeaf:A,promotionSource:"reparent"});if(_){for(let[E,x]of Object.entries(_.fields))rt(n,_.parentId,E,x);_.promotionSnapshot&&n.setPromotionSnapshot(_.parentId,_.promotionSnapshot),_.fields.customId===null&&Ur(v,r.customIdTracker)}}}if(d!=="0"){let h=n.getActivity(d);if(h){let v=n.getChildren(d),A=Re({parent:h,remainingChildIds:v.map(String),defaultDurationHours:a.hoursPerDay,promotionSnapshot:n.getPromotionSnapshot(d),computeEndDate:(_,E)=>n.calculateEndDate({startDate:_,durationHours:E,task:h}),idsRemoved:new Set([e.activityId])});if(A){for(let[V,Y]of Object.entries(A.fields))rt(n,d,V,Y);let _=Gt(d,n),E=_?n.getActivity(_)?.customId:null,x=typeof E=="string"&&E?E:null,O=r.customIdTracker.generateCustomIdForRestoredChild(x);n.setActivityField(d,b.CUSTOM_ID,O)}}}}f&&(d!=="0"&&kt(d,n),o||kt(e.parentId,n));let C=st(n);for(let h of C){if(p.add(h.activityId),m.has(h.activityId))continue;let v=n.getActivity(h.activityId);if(!v)continue;let A=J(v);h.before!==void 0&&(A.correlativeId=h.before),m.set(h.activityId,A)}let S=f&&d!=="0"?n.getChildren(d).map(String):[],{scheduledIds:D}=await G({adapter:n,scheduler:i,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:e.activityId,recomputeParentsFrom:[e.activityId,e.parentId,...S],now:r.now,options:t,recomputeParentProgress:f}),P=f?Yr([e.activityId],n):[],g={name:At.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:P.map(String)}};return e.eventSource!==void 0&&(g.properties.event_source=e.eventSource),{ok:!0,changes:await B(n,{source:e,beforeSnap:m,touchedIds:p,scheduledIds:D,sirDetection:"before-diff",trackingEvents:[g],hoursPerDay:a.hoursPerDay})}}async function wc(e,t,r){let{adapter:n,scheduler:i,sector:a}=r;if(i.invalidateAllCaches(),e.activityIds.length===0)return{ok:!1,reason:T.ACTIVITY_IDS_EMPTY};let s=new Set(e.activityIds),o=new Set,c=[],l=[],d=[],u=new Set,f=new Set(s),p=[...e.activityIds].sort((h,v)=>{let A=n.getActivity(h),_=n.getActivity(v),E=A?nt(A):ne,x=_?nt(_):ne;return E-x});for(let h of p){if(!n.getActivity(h)){c.push({activityId:h,reason:T.ACTIVITY_NOT_FOUND}),f.delete(h);continue}if(Vr(h,u,n))continue;let A=ha(h,f,n);if(A==null){c.push({activityId:h,reason:T.INDENT_NO_ELIGIBLE_SIBLING}),f.delete(h);continue}let _=n.getActivity(h)?.parentId,E=L(_)?"0":String(_);d.push({activityId:h,newParentId:A,oldParentId:E}),u.add(h),o.add(h),o.add(A),E!=="0"&&o.add(E)}let m=await q(n,o);for(let{activityId:h,newParentId:v}of d)n.setActivityField(h,b.PARENT,v),n.setActivityField(h,b.CORRELATIVE_ID,hc),l.push(h);let I=new Set;for(let{activityId:h,newParentId:v}of d){if(I.has(v))continue;I.add(v);let A=n.getActivity(v);if(!A)continue;let _=A.customId,E=Mt(A.type)&&n.getChildren(v).filter(V=>!l.includes(V)).length===0,x=A.hasNewActivities&&A.newActivityIds.some(V=>String(V)===String(h)),O=Pe({parentId:v,newChildId:h,getParent:V=>n.getActivity(V)??null,isCurrentlyLeaf:E,promotionSource:"reparent"});if(O){for(let[V,Y]of Object.entries(O.fields))rt(n,O.parentId,V,Y);O.promotionSnapshot&&n.setPromotionSnapshot(O.parentId,O.promotionSnapshot),x||(n.setActivityField(v,b.HAS_NEW_ACTIVITIES,!1),n.setActivityField(v,b.NEW_ACTIVITIES_ARRAY,[]))}n.setActivityField(v,b.CONSTRAINT_TYPE,"asap"),n.setActivityField(v,b.CONSTRAINT_DATE,null),n.setActivityField(v,b.CUSTOM_ID,null),Ur(_,r.customIdTracker)}let C=new Set;for(let h of d)h.oldParentId!=="0"&&C.add(h.oldParentId),C.add(h.newParentId);for(let h of C)kt(h,n);let S=st(n);for(let h of S){if(o.add(h.activityId),m.has(h.activityId))continue;let v=n.getActivity(h.activityId);if(!v)continue;let A=J(v);h.before!==void 0&&(A.correlativeId=h.before),m.set(h.activityId,A)}let{scheduledIds:D}=await G({adapter:n,scheduler:i,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:null,recomputeParentsFrom:l,now:r.now,options:t}),P=Yr(l,n),g={name:At.ACTIVITY_INDENT,properties:{activity_ids:l,failed:c.map(h=>({activity_id:h.activityId,reason:h.reason})),invalid_link_ids:P}};return e.eventSource!==void 0&&(g.properties.event_source=e.eventSource),{ok:!0,activityVerdicts:e.activityIds.map(h=>{let v=c.find(A=>String(A.activityId)===String(h));return v?{activityId:String(h),ok:!1,reason:v.reason}:{activityId:String(h),ok:!0}}),changes:await B(n,{source:e,beforeSnap:m,touchedIds:o,scheduledIds:D,trackingEvents:[g],hoursPerDay:a.hoursPerDay})}}async function Oc(e,t,r){let{adapter:n,scheduler:i,sector:a}=r;if(i.invalidateAllCaches(),e.activityIds.length===0)return{ok:!1,reason:T.ACTIVITY_IDS_EMPTY};let s=new Set(e.activityIds),o=new Map,c=new Map;for(let h of e.activityIds){let v=h;n.getActivity(v)&&(o.set(v,In(v,n)),c.set(v,yc(v,s,n)))}let l=new Set,d=[],u=[],f=new Set,p=[],m=new Set,I=[...e.activityIds].sort((h,v)=>{let A=n.getActivity(h),_=n.getActivity(v),E=A?nt(A):ne,x=_?nt(_):ne;return E-x});for(let h of I){let v=h,A=n.getActivity(v);if(!A){d.push({activityId:v,reason:T.ACTIVITY_NOT_FOUND});continue}if(Vr(v,m,n))continue;let _=A.parentId;if(L(_)){d.push({activityId:v,reason:T.OUTDENT_ROOT_LEVEL_NOT_EDITABLE});continue}let E=String(_),x=n.getActivity(E);if(!x){d.push({activityId:v,reason:T.ACTIVITY_NOT_FOUND});continue}let O=x.parentId;if(L(O)){d.push({activityId:v,reason:T.OUTDENT_ROOT_LEVEL_NOT_EDITABLE});continue}let V=String(O),Y=In(E,n)+1,it=c.get(v);if(it!=null&&s.has(it)){let Le=o.get(it)??-1,lt=o.get(v)??-1;Le>=0&<>=0&&(Y+=lt-Le)}p.push({activityId:v,grandparentKey:V,oldParentKey:E,targetIndexInGrandparent:Y}),m.add(v),l.add(String(v)),l.add(String(E)),V!=="0"&&l.add(String(V)),f.add(E)}let C=await q(n,l);for(let h of p){n.setActivityField(h.activityId,b.PARENT,h.grandparentKey);let v=mc(n,h.grandparentKey,h.targetIndexInGrandparent,h.activityId);n.setActivityField(h.activityId,b.CORRELATIVE_ID,v),u.push(h.activityId)}for(let h of f){let v=n.getActivity(h);if(!v)continue;let A=n.getChildren(h),_=Re({parent:v,remainingChildIds:A.map(String),defaultDurationHours:a.hoursPerDay,promotionSnapshot:n.getPromotionSnapshot(h),computeEndDate:(Y,it)=>n.calculateEndDate({startDate:Y,durationHours:it,task:v}),idsRemoved:new Set(p.filter(Y=>Y.oldParentKey===h).map(Y=>Y.activityId))});if(!_){Cr(h,n);continue}for(let[Y,it]of Object.entries(_.fields))rt(n,h,Y,it);let E=Gt(h,n),x=E?n.getActivity(E)?.customId:null,O=typeof x=="string"&&x?x:null,V=r.customIdTracker.generateCustomIdForRestoredChild(O);n.setActivityField(h,b.CUSTOM_ID,V)}let S=new Set;for(let h of f)S.add(String(h));for(let h of p)h.grandparentKey!=="0"&&S.add(String(h.grandparentKey));for(let h of S)kt(h,n);let D=st(n);for(let h of D){if(l.add(h.activityId),C.has(h.activityId))continue;let v=n.getActivity(h.activityId);if(!v)continue;let A=J(v);h.before!==void 0&&(A.correlativeId=h.before),C.set(h.activityId,A)}let{scheduledIds:P}=await G({adapter:n,scheduler:i,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:u.length>0?"roots":null,recomputeParentsFrom:u,now:r.now,options:t}),g={name:At.ACTIVITY_OUTDENT,properties:{activity_ids:u.map(String),failed:d.map(h=>({activity_id:String(h.activityId),reason:h.reason}))}};return e.eventSource!==void 0&&(g.properties.event_source=e.eventSource),{ok:!0,activityVerdicts:e.activityIds.map(h=>{let v=d.find(A=>String(A.activityId)===String(h));return v?{activityId:String(h),ok:!1,reason:v.reason}:{activityId:String(h),ok:!0}}),changes:await B(n,{source:e,beforeSnap:C,touchedIds:l,scheduledIds:P,trackingEvents:[g],hoursPerDay:a.hoursPerDay})}}async function xc(e,t,r){let{adapter:n,ctx:i,scheduler:a,sector:s}=r;if(e.newValue!==0&&e.newValue!==100)return{ok:!1,reason:T.INVALID_PROGRESS_VALUE};let o=i.activityReader.getActivity(e.activityId);if(!o)return{ok:!1,reason:T.ACTIVITY_NOT_FOUND};let c=Ht(R.PROGRESS);if(!c)throw new Error("[ScheduleCore] progressPipeline not registered \u2014 cannot dispatch activity-set-progress");let l=c.transform(o,e.newValue,i,e.newValue),d=Vt(e.activityId,l),u=await q(n,d);Yt(n,e.activityId,l),Bt(e.activityId,l.postProcessors??[],n);let{scheduledIds:f}=await G({adapter:n,scheduler:a,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:l.needsAutoSchedule?e.activityId:null,recomputeParentsFrom:[],collectDirty:m=>Er(e.activityId,d,m),now:r.now,options:t}),p=(l.trackingEvents??[]).map(m=>({name:m.name,properties:m.properties??{}}));return{ok:!0,changes:await B(n,{source:e,beforeSnap:u,touchedIds:d,scheduledIds:f,trackingEvents:p,hoursPerDay:s.hoursPerDay})}}async function Fc(e,t,r){let{adapter:n,scheduler:i,sector:a}=r,s=[],o=new Map,c=new Set,l=[],d=[],u=[],f=!1;for(let m of e.edits){let I=Iy(m,r);if(s.push(I.verdict),!I.verdict.ok||!I.changes)continue;let C=Vt(m.activityId,I.changes);Sy(o,C,r);for(let g of C)c.add(g);let S=Te(n,m.activityId),D=Rr(n,String(m.activityId));Yt(n,m.activityId,I.changes),Bt(m.activityId,I.changes.postProcessors??[],n,D),d.push(..._e(S,n,m.activityId)),f||=!!I.changes.needsAutoSchedule;for(let g of I.changes.trackingEvents??[])l.push({name:g.name,properties:g.properties??{}});let P=Ae(m.activityId,I.changes.constraintWarning);P&&u.push(P)}let{scheduledIds:p}=await G({adapter:n,scheduler:i,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:await B(n,{source:e,beforeSnap:o,touchedIds:c,scheduledIds:p,sirDetection:"before-diff",links:d,trackingEvents:l,warnings:u,hoursPerDay:a.hoursPerDay})}}function Iy(e,t){let{ctx:r}=t,n=e.activityId,i=Ht(e.column);if(!i)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=i.canEdit(a,r.hierarchy);if(!s.allowed)return{verdict:{activityId:n,ok:!1,reason:s.reason??T.CANNOT_EDIT,...s.alertKey?{alertKey:s.alertKey}:{}},changes:null};let o=i.parseInput(e.newValue,a,r);if(!o.ok)return{verdict:{activityId:n,ok:!1,reason:o.reason??T.PARSE_ERROR},changes:null};let c=Reflect.get(a,i.targetField),l=i.validate(a,c,o.value,r);if(!l.valid)return{verdict:{activityId:n,ok:!1,reason:l.reason??T.INVALID,...l.notification?.messageKey?{alertKey:l.notification.messageKey}:{}},changes:null};let d=i.transform(a,o.value,r,o.raw);return{verdict:{activityId:n,ok:!0},changes:d}}function Sy(e,t,r){let n=new Set;for(let i of t)e.has(i)||n.add(i);if(n.size!==0)for(let i of n){let a=r.adapter.getActivity(i);a&&e.set(i,J(a))}}var Ti=R.CUSTOM_ID;async function Nc(e,t,r){let{adapter:n,scheduler:i,sector:a}=r;e.edits.some(P=>P.column===R.DURATION)&&i.invalidateExpandedLinksCache();let o=[],c=new Map,l=new Map,d=new Set,u=new Set,f=[],p=[],m=[],I=!1;for(let P of e.edits){let g=ky(P,r);if(o.push(g.verdict),!g.verdict.ok||!g.changes)continue;let h=Ae(P.activityId,g.changes.constraintWarning);h&&m.push(h);let v=Vt(P.activityId,g.changes);Py(c,v,r);for(let O of v)u.add(O);_y(l,P,c),Mr(P.column)&&d.add(String(P.activityId));let A=Te(n,P.activityId),_=Rr(n,String(P.activityId)),E=Dy(P,r),x=g.changes;Yt(n,P.activityId,x),Bt(P.activityId,g.changes.postProcessors??[],n,_),Ty(P,E,r),p.push(..._e(A,n,P.activityId)),I||=!!g.changes.needsAutoSchedule;for(let O of g.changes.trackingEvents??[])f.push({name:O.name,properties:O.properties??{}})}let C={action:e,autoscheduleFrom:I?"roots":null,recomputeParentsFrom:u,now:r.now,options:t},S=l.size>0,{scheduledIds:D}=await(S?Br({adapter:n,scheduler:i,sector:a,defaultBaseCalendarId:r.defaultBaseCalendarId},{postMutationArgs:C,revertTargets:[...l].filter(([P])=>!d.has(P)).map(([P,g])=>({activityId:P,priorConstraintDate:g})),revert:(P,g)=>Wr(P,g,n,r.ctx.calendars)}):G({adapter:n,scheduler:i,sector:a,defaultBaseCalendarId:r.defaultBaseCalendarId},C));return{ok:!0,verdicts:o,changes:await B(n,{source:e,beforeSnap:c,touchedIds:u,scheduledIds:D,sirDetection:"before-diff",links:p,trackingEvents:f,warnings:m,hoursPerDay:a.hoursPerDay})}}function ky(e,t){let{ctx:r}=t,n=e.activityId,i=Ht(e.column);if(!i)return{verdict:{activityId:n,ok:!1,reason:T.NO_PIPELINE_FOR_COLUMN},changes:null};let a=r.activityReader.getActivity(e.activityId);if(!a)return{verdict:{activityId:n,ok:!1,reason:T.ACTIVITY_NOT_FOUND},changes:null};let s=i.canEdit(a,r.hierarchy);if(!s.allowed)return{verdict:{activityId:n,ok:!1,reason:s.reason??T.CANNOT_EDIT,...s.alertKey?{alertKey:s.alertKey}:{}},changes:null};let o=i.parseInput(e.newValue,a,r);if(!o.ok)return{verdict:{activityId:n,ok:!1,reason:o.reason??T.PARSE_ERROR},changes:null};let c=Reflect.get(a,i.targetField),l=i.validate(a,c,o.value,r);if(!l.valid)return{verdict:{activityId:n,ok:!1,reason:l.reason??T.INVALID,...l.notification?.messageKey?{alertKey:l.notification.messageKey}:{}},changes:null};if(e.column===Ti&&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:n,ok:!1,reason:T.CUSTOM_ID_DUPLICATE},changes:null}}let d=i.transform(a,o.value,r,o.raw);return{verdict:{activityId:n,ok:!0},changes:d}}function Dy(e,t){if(e.column!==Ti)return null;let r=t.adapter.getActivity(e.activityId),n=r?r.customId:null;return typeof n=="string"?n:null}function Ty(e,t,r){if(e.column!==Ti)return;let n=r.adapter.getActivity(e.activityId),i=n?n.customId:null,a=typeof i=="string"?i:null;t!==a&&r.customIdTracker.trackCustomIdChange(t,a)}function _y(e,t,r){if(!Nr(t.column))return;let n=String(t.activityId);if(e.has(n))return;let i=r.get(n);i&&e.set(n,i.constraintDate??null)}function Py(e,t,r){let n=new Set;for(let i of t)e.has(i)||n.add(i);if(n.size!==0)for(let i of n){let a=r.adapter.getActivity(i);a&&e.set(i,J(a))}}function Ry(e,t,r,n,i,a){let s=String(e.id);if(s.length===0||i.has(s))throw new Error(`persistence-acknowledge: duplicate or empty ${t} id "${s}"`);if(!Number.isSafeInteger(e.proplannerId)||e.proplannerId<=0)throw new Error(`persistence-acknowledge: invalid ${t} proplannerId ${String(e.proplannerId)}`);if(a.has(e.proplannerId))throw new Error(`persistence-acknowledge: duplicate ${t} proplannerId ${String(e.proplannerId)}`);let o=r(s);if(!o.exists)throw new Error(`persistence-acknowledge: unknown ${t} id "${s}"`);if(o.current!==null&&o.current!==e.proplannerId)throw new Error(`persistence-acknowledge: ${t} "${s}" already has proplannerId ${String(o.current)}`);let c=n.get(e.proplannerId);if(c!==void 0&&c!==s)throw new Error(`persistence-acknowledge: ${t} proplannerId ${String(e.proplannerId)} already belongs to "${c}"`);i.add(s),a.add(e.proplannerId)}function Mc(e,t,r,n){let i=new Set,a=new Set;for(let s of e)Ry(s,t,r,n,i,a)}function Wc(e,t){let r=e.activities??[],n=e.links??[],i=new Map;for(let c of t.adapter.getAllActivities())c.proplannerId!=null&&i.set(c.proplannerId,String(c.id));let a=new Map;for(let c of t.adapter.getAllLinks())c.proplannerId!=null&&a.set(c.proplannerId,String(c.id));Mc(r,"activity",c=>{let l=t.adapter.getActivity(c);return{exists:l!==null,current:l?.proplannerId??null}},i),Mc(n,"link",c=>{let l=t.adapter.getLink(c);return{exists:l!==null,current:l?.proplannerId??null}},a);let s=[],o=[];return t.adapter.batchUpdate(()=>{for(let c of r){let l=t.adapter.getActivity(c.id);if(!l||l.proplannerId===c.proplannerId)continue;let d=l.proplannerId;t.adapter.setActivityField(c.id,"proplannerId",c.proplannerId),s.push({id:c.id,kind:"updated",fields:{proplannerId:{before:d,after:c.proplannerId}},after:{...l,proplannerId:c.proplannerId}})}for(let c of n){let l=t.adapter.getLink(c.id);if(!l||l.proplannerId===c.proplannerId)continue;let d=l.proplannerId;t.adapter.setLinkProplannerId(c.id,c.proplannerId),o.push({id:c.id,kind:"updated",fields:{proplannerId:{before:d,after:c.proplannerId}},after:{...l,proplannerId:c.proplannerId}})}}),{ok:!0,changes:{source:e,activities:s,links:o,calendars:[],trackingEvents:[]}}}function Bc(e){return typeof e=="string"&&e.length>0?wt(e):e instanceof Date?e:null}function _i(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 Kr(e,t){let r=_i(e.duration),n=_i(e.cost),i=_i(e.hh_work);return r===null||n===null||i===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:Bc(e.start_date),endDate:Bc(e.end_date),durationDays:r,cost:n,workHours:i,versionId:typeof e.sectorbaselineversionId=="number"?e.sectorbaselineversionId:null,isActiveVersion:!!e.sectorbaselineversion?.active,isVisibleVersion:!!e.sectorbaselineversion?.visible,baseCalendarId:e.baseCalendarId!=null?String(e.baseCalendarId):null,hoursPerDay:typeof e.hoursPerDay=="number"?e.hoursPerDay:null,hoursPerWeek:typeof e.hoursPerWeek=="number"?e.hoursPerWeek:null}}function Uc(e,t,r){let n=new Map;e.forEachActivity((s,o)=>{let c=s.proplannerId;typeof c=="number"&&n.set(c,o)});let i=new Map;for(let s of t){let o=s.activityId;if(typeof o!="number")continue;let c=n.get(o);if(c===void 0)continue;let l=i.get(c);l?l.push(s):i.set(c,[s])}let a=[];for(let[s,o]of i)e.setActivityField(s,"baselinePoints",o.map(c=>Kr(c,r)).filter(c=>c!==null)),a.push(s);return e.forEachActivity((s,o)=>{if(i.has(o))return;let c=s.baselinePoints;Array.isArray(c)&&c.length>0&&(e.setActivityField(o,"baselinePoints",[]),a.push(o))}),a}function Ey(e){let t=ut(e);return t?{startDate:t.startDate,endDate:t.endDate,durationDays:t.durationDays,cost:t.cost,workHours:t.workHours}:null}function jc(e){let t=[];return e.forEachActivity((r,n)=>{let i=Ey(r);if(!i){r.baselineSnapshot!==null&&(e.setActivityField(n,"baselineSnapshot",null),t.push(n));return}e.setActivityField(n,"baselineSnapshot",i),t.push(n)}),t}function Gr(e,t,r,n,i=null){let a=new Set;for(let s of Uc(e,t,n))a.add(s);if(r)for(let s of Se(e,r,i))a.add(s);for(let s of jc(e))a.add(s);for(let s of ke(e))a.add(s);return[...a]}function Hc(e,t,r){if(!e||e==="0")return;let n=r.getChildren(e);if(n.length===0)return;let i=new Map,a=0;for(let o of n){let c=by(String(o),t,r);i.set(String(o),c),a+=c}let s=a?100/a:0;for(let o of n){let c=r.getActivity(o);if(!c)continue;let l=c.baselinePoints;if(ut(c)){let u=i.get(String(o))??0;r.setActivityField(o,R.PONDERATOR,s*u)}else(!Array.isArray(l)||l.length===0)&&r.setActivityField(o,R.PONDERATOR,0)}}function by(e,t,r){let n=r.getActivity(e);if(!n)return 0;let i=ut(n);if(!i)return 0;if(t==="COST")return $r(i.cost);if(t==="HH")return $r(i.workHours);let a=n.type;return a==="project"?Vc(e,r):a==="milestone"?0:$r(i.durationDays)}function Vc(e,t){let r=0;for(let n of t.getChildren(e)){let i=t.getActivity(n);if(!i)continue;let a=ut(i);if(!a)continue;let s=i.type;s==="project"?r+=Vc(String(n),t):s!=="milestone"&&(r+=$r(a.durationDays))}return r}function $r(e){let t=typeof e=="string"?parseFloat(e):e;return typeof t=="number"&&Number.isFinite(t)?t:0}function Yc(e,t){t.forEachActivity((r,n)=>{t.setActivityField(n,R.PONDERATOR,0)}),t.forEachActivity((r,n)=>{t.getChildren(n).length>0&&Hc(String(n),e,t)})}function Kc(e){for(let t of Ly(e))Oy(t,e)}function Ly(e){let t=new Set;e.forEachActivity((n,i)=>{e.getChildren(i).length>0&&t.add(i)});let r=new Map;for(let n of t)r.set(n,wy(n,e));return[...t].sort((n,i)=>(r.get(i)??0)-(r.get(n)??0))}function wy(e,t){let r=0,n=e;for(;n&&n!=="0"&&t.getActivity(n);)r+=1,n=t.getParentId(n);return r}function Oy(e,t){let r=t.getChildren(e);if(r.length===0)return;let n=[];for(let a of r){let s=t.getActivity(a);s&&n.push({progress:Number(s.progress??0),ponderator:Number(s.ponderator??0)})}let i=ue(n);i!==null&&t.setActivityField(e,R.PROGRESS,Ar(i))}function zr(e,t){Yc(t,e.adapter),Kc(e.adapter),e.now&&(Se(e.adapter,e.now,e.defaultBaseCalendarId??null),te(e.adapter,e.now)),ke(e.adapter),e.now&&Ot(e.adapter,e.sector.statusCriteria)}function Gc(e){return JSON.stringify(e.adapter.getAllIds().map(t=>{let r=e.adapter.getActivity(t)?.baselinePoints.find(n=>n.isActiveVersion);return r?[String(t),r.versionId,r.startDate?.getTime()??null,r.endDate?.getTime()??null,r.durationDays,r.cost,r.workHours,r.baseCalendarId,r.hoursPerDay,r.hoursPerWeek]:[String(t),null]}))}async function $c(e,t){let r=await q(t.adapter,new Set(t.adapter.getAllIds())),n=Gc(t),i=Gr(t.adapter,e.points,t.now,t.reporter,t.defaultBaseCalendarId??null);return Gc(t)!==n&&zr(t,t.sector.activityCreter??"DURATION"),{ok:!0,changes:await B(t.adapter,{source:e,beforeSnap:r,touchedIds:i,scheduledIds:[],hoursPerDay:t.sector.hoursPerDay})}}function xy(e){if(!(e==="DURATION"||e==="COST"||e==="HH"))throw new Error(`ponderator-criterion-set: invalid criterion "${String(e)}"`)}async function zc(e,t){xy(e.criterion);let r=new Set(t.adapter.getAllIds()),n=await q(t.adapter,r);return zr(t,e.criterion),t.sector.activityCreter=e.criterion,{ok:!0,changes:await B(t.adapter,{source:e,beforeSnap:n,touchedIds:r,scheduledIds:[],hoursPerDay:t.sector.hoursPerDay})}}async function qc(e,t){let r=nr(e.criteria),n=new Set(t.adapter.getAllIds()),i=await q(t.adapter,n),a=Ot(t.adapter,r);return t.sector.statusCriteria=r,{ok:!0,changes:await B(t.adapter,{source:e,beforeSnap:i,touchedIds:a,scheduledIds:[],hoursPerDay:t.sector.hoursPerDay})}}async function Jc(e,t,r){return e.kind==="activity-batch"?Tc(e,t,r):e.kind==="persistence-acknowledge"?Wc(e,r):e.kind==="baseline-apply"?$c(e,r):e.kind==="ponderator-criterion-set"?zc(e,r):e.kind==="status-criteria-set"?qc(e,r):e.kind==="link-create"||e.kind==="link-update"||e.kind==="link-delete"?ec(e,t,r):e.kind==="links-batch"?rc(e,t,r):e.kind==="activity-create"?gc(e,t,r):e.kind==="activity-paste"?Pc(e,t,r):e.kind==="activity-delete"?Sc(e,t,r):e.kind==="activity-move"?Lc(e,t,r):e.kind==="activity-indent"?wc(e,t,r):e.kind==="activity-outdent"?Oc(e,t,r):e.kind==="activity-set-progress"?xc(e,t,r):e.kind==="dates-batch"?Fc(e,t,r):e.kind==="bulk-edit"?Nc(e,t,r):e.kind==="selection-toggle"?ra(e,Pi(r)):e.kind==="selection-replace"?na(e,Pi(r)):e.kind==="visibility-set"?ia(e,Pi(r)):e.kind==="filter-set"?ua(e,{adapter:r.adapter,hoursPerDay:r.sector.hoursPerDay}):e.kind==="sort-set"?ma(e,{adapter:r.adapter}):e.kind==="sir-sync"?Rc(e,r):e.kind==="activity-lookahead-sync"?Ec(e,r):e.kind==="inline-edit"&&(e.column===R.CUSTOM_PREDECESSORS||e.column===R.CUSTOM_SUCESSORS)?nc(e,t,r):e.kind!=="inline-edit"?es(e,`[ScheduleCore] dispatch kind "${e.kind}" not supported yet`):tc(e,t,r)}function Pi(e){return{adapter:e.adapter}}var Fy=new Set(["startDate","endDate","constraintDate"]);function Xc(e,t){return Fy.has(e)&&typeof t=="string"?new Date(t):t}function Zc(e,t={}){let r=t.defaultUnit??"hour";return{getCalendar(n){let i=e.getCalendar(String(n));return i?Ny(i,r):null}}}function Ny(e,t){return{getClosestWorkTime(r){return e.getClosestWorkTime({date:r.date,dir:r.direction,unit:r.unit})},calculateEndDate(r,n){return e.calculateEndDate({start_date:r,duration:n,unit:t})},calculateDuration(r,n){return e.calculateDuration({start_date:r,end_date:n,unit:t})},isWorkTime(r,n){return e.isWorkTime({date:r,unit:n})},getWorkHours(r){return e.getWorkHours(r)}}}function My(e){return Array.isArray?Array.isArray(e):e&&e.length!==void 0&&e.pop&&e.push}function ie(e){return e&&typeof e=="object"?!!(e.getFullYear&&e.getMonth&&e.getDate):!1}function ae(e){return ie(e)&&!isNaN(e.getTime())}var Wy={}.constructor.toString();function By(e){var t=e.constructor.toString();return t!==Wy}function Uy(e){return e.$$typeof&&e.$$typeof.toString().includes("react.")}function Dt(e){var t,r;if(e&&typeof e=="object")switch(!0){case ie(e):r=new Date(e);break;case My(e):for(r=new Array(e.length),t=0;t<e.length;t++)r[t]=Dt(e[t]);break;default:if(By(e))r=Object.create(e);else{if(Uy(e))return r=e,r;r={}}for(t in e)Object.prototype.hasOwnProperty.apply(e,[t])&&(r[t]=Dt(e[t]));break}return r||e}function Ee(e,t,r){for(var n in t)(e[n]===void 0||r)&&(e[n]=t[n]);return e}function Qc(e){return typeof e<"u"}var qr;function Ri(){return qr||(qr=new Date().valueOf()),qr++,qr}function yt(e,t){return e.bind?e.bind(t):function(){return e.apply(t,arguments)}}var Hy=(e,t,r)=>{e=e.replace(/%[a-zA-Z]/g,i=>{switch(i){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 i}});let n=new Function("date","to_fixed","locale","getISOWeek","getWeek",`return "${e}";`);return i=>n(i,r.date.to_fixed,r.locale,r.date.getISOWeek,r.date.getWeek)},Vy=(e,t,r)=>{let n="var temp=date.match(/[a-zA-Z]+|[0-9]+/g);",i=e.match(/%[a-zA-Z]/g);for(let o=0;o<i.length;o++)switch(i[o]){case"%j":case"%d":n+=`set[2]=temp[${o}]||1;`;break;case"%n":case"%m":n+=`set[1]=(temp[${o}]||1)-1;`;break;case"%y":n+=`set[0]=temp[${o}]*1+(temp[${o}]>50?1900:2000);`;break;case"%g":case"%G":case"%h":case"%H":n+=`set[3]=temp[${o}]||0;`;break;case"%i":n+=`set[4]=temp[${o}]||0;`;break;case"%Y":n+=`set[0]=temp[${o}]||0;`;break;case"%a":case"%A":n+=`set[3]=set[3]%12+((temp[${o}]||'').toLowerCase()=='am'?0:12);`;break;case"%s":n+=`set[5]=temp[${o}]||0;`;break;case"%M":n+=`set[1]=locale.date.month_short_hash[temp[${o}]]||0;`;break;case"%F":n+=`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]; ${n} return new Date(${a});`);return o=>s(o,r.locale)},tl={date_to_str:Hy,str_to_date:Vy},Yy=(e,t,r)=>n=>e.replace(/%[a-zA-Z]/g,i=>{switch(i){case"%d":return t?r.date.to_fixed(n.getUTCDate()):r.date.to_fixed(n.getDate());case"%m":return t?r.date.to_fixed(n.getUTCMonth()+1):r.date.to_fixed(n.getMonth()+1);case"%j":return t?n.getUTCDate():n.getDate();case"%n":return t?n.getUTCMonth()+1:n.getMonth()+1;case"%y":return t?r.date.to_fixed(n.getUTCFullYear()%100):r.date.to_fixed(n.getFullYear()%100);case"%Y":return t?n.getUTCFullYear():n.getFullYear();case"%D":return t?r.locale.date.day_short[n.getUTCDay()]:r.locale.date.day_short[n.getDay()];case"%l":return t?r.locale.date.day_full[n.getUTCDay()]:r.locale.date.day_full[n.getDay()];case"%M":return t?r.locale.date.month_short[n.getUTCMonth()]:r.locale.date.month_short[n.getMonth()];case"%F":return t?r.locale.date.month_full[n.getUTCMonth()]:r.locale.date.month_full[n.getMonth()];case"%h":return t?r.date.to_fixed((n.getUTCHours()+11)%12+1):r.date.to_fixed((n.getHours()+11)%12+1);case"%g":return t?(n.getUTCHours()+11)%12+1:(n.getHours()+11)%12+1;case"%G":return t?n.getUTCHours():n.getHours();case"%H":return t?r.date.to_fixed(n.getUTCHours()):r.date.to_fixed(n.getHours());case"%i":return t?r.date.to_fixed(n.getUTCMinutes()):r.date.to_fixed(n.getMinutes());case"%a":return t?n.getUTCHours()>11?"pm":"am":n.getHours()>11?"pm":"am";case"%A":return t?n.getUTCHours()>11?"PM":"AM":n.getHours()>11?"PM":"AM";case"%s":return t?r.date.to_fixed(n.getUTCSeconds()):r.date.to_fixed(n.getSeconds());case"%W":return t?r.date.to_fixed(r.date.getUTCISOWeek(n)):r.date.to_fixed(r.date.getISOWeek(n));case"%w":return r.date.to_fixed(r.date.getWeek(n));default:return i}}),Ky=(e,t,r)=>n=>{let i=[0,0,1,0,0,0],a=n.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":i[2]=a[o]||1;break;case"%n":case"%m":i[1]=(a[o]||1)-1;break;case"%y":i[0]=a[o]*1+(a[o]>50?1900:2e3);break;case"%g":case"%G":case"%h":case"%H":i[3]=a[o]||0;break;case"%i":i[4]=a[o]||0;break;case"%Y":i[0]=a[o]||0;break;case"%a":case"%A":i[3]=i[3]%12+((a[o]||"").toLowerCase()==="am"?0:12);break;case"%s":i[5]=a[o]||0;break;case"%M":i[1]=r.locale.date.month_short_hash[a[o]]||0;break;case"%F":i[1]=r.locale.date.month_full_hash[a[o]]||0;break}return t?new Date(Date.UTC(i[0],i[1],i[2],i[3],i[4],i[5])):new Date(i[0],i[1],i[2],i[3],i[4],i[5])},el={date_to_str:Yy,str_to_date:Ky};function rl(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 n=null;function i(){try{new Function("canUseCsp = false;")}catch{n=!0}}function a(){var o=!1;return e.config.csp==="auto"?(n===null&&i(),o=n):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=tl;return a()&&(l=el),l.date_to_str(o,c,e)},str_to_date:function(o,c){var l=tl;return a()&&(l=el),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 Ei(e,t,r,n,i){return this.date=e,this.unit=t,this.task=r,this.id=n,this.calendar=i,this}function bi(e,t,r,n,i,a){return this.date=e,this.dir=t,this.unit=r,this.task=n,this.id=i,this.calendar=a,this}function Li(e,t,r,n,i,a,s){return this.start_date=e,this.duration=t,this.unit=r,this.step=n,this.task=i,this.id=a,this.calendar=s,this}function Gy(e,t,r,n){return this.start_date=e,this.end_date=t,this.task=r,this.calendar=n,this.unit=null,this.step=null,this}var nl=function(e){return{getWorkHoursArguments:function(){var t=arguments[0];if(ie(t)?t={date:t}:t=Ee({},t),!ae(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 Ei)return t;var r;if(t.date?r=new Ei(t.date,t.unit,t.task,null,t.calendar):r=new Ei(arguments[0],arguments[1],arguments[2],null,arguments[3]),r.unit=r.unit||e.config.duration_unit,!ae(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 bi)return r;var n;if(ie(r)?n=new bi(r):n=new bi(r.date,r.dir,r.unit,r.task,null,r.calendar),r.id&&(n.task=r),n.dir=r.dir||"any",n.unit=r.unit||e.config.duration_unit,!ae(n.date))throw e.assert(!1,"Invalid date argument for getClosestWorkTime method"),new Error("Invalid date argument for getClosestWorkTime method");return n},_getStartEndConfig:function(t){var r=Gy,n;if(t instanceof r)return t;if(ie(t)?n=new r(arguments[0],arguments[1],arguments[2],arguments[3]):(n=new r(t.start_date,t.end_date,t.task),t.id!==null&&t.id!==void 0&&(n.task=t)),n.unit=n.unit||e.config.duration_unit,n.step=n.step||e.config.duration_step,n.start_date=n.start_date||n.start||n.date,!ae(n.start_date))throw e.assert(!1,"Invalid start_date argument for getDuration method"),new Error("Invalid start_date argument for getDuration method");if(!ae(n.end_date))throw e.assert(!1,"Invalid end_date argument for getDuration method"),new Error("Invalid end_date argument for getDuration method");return n},getDurationArguments:function(t,r,n,i){return this._getStartEndConfig.apply(this,arguments)},hasDurationArguments:function(t,r,n,i){return this._getStartEndConfig.apply(this,arguments)},calculateEndDateArguments:function(t,r,n,i){var a=arguments[0];if(a instanceof Li)return a;var s;if(ie(a)?s=new Li(arguments[0],arguments[1],arguments[2],void 0,arguments[3],void 0,arguments[4]):s=new Li(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,!ae(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 il(){}il.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 n(a){var s=Math.floor(a/3600),o=a-s*60*60,c=Math.floor(o/60);return s+":"+r(c)}for(var i=0;i<e.length;i++)t.push(n(e[i].start)+"-"+n(e[i].end));return t},_intersectHourRanges:function(e,t){var i=[],r=e.length>t.length?e:t,n=e===r?t:e;r=r.slice(),n=n.slice();for(var i=[],a=0;a<r.length;a++)for(var s=r[a],o=0;o<n.length;o++){var c=n[o];c.start<s.end&&c.end>s.start&&(i.push({start:Math.max(s.start,c.start),end:Math.min(s.end,c.end)}),s.end>c.end&&(n.splice(o,1),o--,a--))}return i},_mergeAdjacentIntervals:function(e){var t=e.slice();t.sort(function(a,s){return a.start-s.start});for(var r=t[0],n=1;n<t.length;n++){var i=t[n];i.start<=r.end?(i.end>r.end&&(r.end=i.end),t.splice(n,1),n--):r=i}return t},_mergeHoursConfig:function(e,t){return this._mergeAdjacentIntervals(this._intersectHourRanges(e,t))},merge:function(e,t){let r=Dt(e.getConfig()),n=Dt(t.getConfig()),i=r.parsed,a=n.parsed;i.customWeeks=r.customWeeks,a.customWeeks=n.customWeeks;var s={hours:this._toHoursArray(this._mergeHoursConfig(i.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 m=d.dates[p];if(p==u&&(s.dates[u]=!!(f&&m)),Array.isArray(f)){let I=Array.isArray(m)?m:d.hours;s.dates[u]=this._toHoursArray(this._mergeHoursConfig(f,I))}}}};if(o(i,a),o(a,i),i.customWeeks)for(var c in i.customWeeks)s.customWeeks[c]=i.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 wi=class{constructor(){this.clear()}getItem(t,r,n){if(this._cache.has(t)){let a=this._cache.get(t)[n.getUTCFullYear()];if(a&&a.has(r))return a.get(r)}return-1}setItem(t,r,n,i){if(!t||!r)return;let a=this._cache,s=i.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,n)}clear(){this._cache=new Map}},Oi=class{constructor(){this.clear()}getItem(t,r,n){let i=this._cache;if(i&&i[t]){let a=i[t];if(a===void 0)return-1;let s=a[n.getUTCFullYear()];if(s&&s[r]!==void 0)return s[r]}return-1}setItem(t,r,n,i){if(!t||!r)return;let a=this._cache;if(!a)return;a[t]||(a[t]=[]);let s=a[t],o=i.getUTCFullYear(),c=s[o];c||(c=s[o]={}),c[r]=n}clear(){this._cache={}}},xi=class{constructor(t){this.getMinutesPerWeek=r=>{let n=r.valueOf();if(this._weekCache.has(n))return this._weekCache.get(n);let i=this._calendar,a=this._calendar.$gantt,s=0,o=a.date.week_start(new Date(r));for(let c=0;c<7;c++)s+=i.getHoursPerDay(o)*60,o=a.date.add(o,1,"day");return this._weekCache.set(n,s),s},this.getMinutesPerMonth=r=>{let n=r.valueOf();if(this._monthCache.has(n))return this._monthCache.get(n);let i=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+=i.getHoursPerDay(o)*60,o=a.date.add(o,1,"day");return this._monthCache.set(n,s),s},this.clear=()=>{this._weekCache=new Map,this._monthCache=new Map},this.clear(),this._calendar=t}};function $y(){return typeof Map<"u"?new wi:new Oi}var Fi=class{constructor(){this.clear()}_getCacheObject(t,r,n){let i=this._cache;i[r]||(i[r]=[]);let a=i[r];a||(a=i[r]={});let s=a[n];s||(s=a[n]={});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,n,i,a){let s=this._getCacheObject(t,n,i),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,n,i,a){let s=this._getCacheObject(t,n,i),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 Ni(e,t){this.argumentsHelper=t,this.$gantt=e,this._workingUnitsCache=$y(),this._largeUnitsCache=new xi(this),this._dateDurationCache=new Fi,this._worktime=null,this._cached_timestamps={},this._cached_timestamps_count=0}Ni.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)),n=this.$gantt.date.add(r,1,t);return this.hasDuration(r,n)}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(),n=0;n<t.length;n++)if(r>=t[n].startHour&&r<t[n].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),n=0;n<t.length;n++)if(r>=t[n].start&&r<t[n].end)return!0;return!1},_nextDate:function(e,t,r){return this.$gantt.date.add(e,r,t)},_getWorkUnitsBetweenGeneric:function(e,t,r,n){var i=this.$gantt.date,a=new Date(e),s=new Date(t);n=n||1;var o=0,c=null,l,d,u=!1;l=i[r+"_start"](new Date(a)),l.valueOf()!=a.valueOf()&&(u=!0);var f=!1;d=i[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,n),p=c.valueOf()>s.valueOf(),this._isWorkTime(a,r))(u||f&&p)&&(l=i[r+"_start"](new Date(a)),d=i.add(l,n,r)),u?(u=!1,c=this._nextDate(l,r,n),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 m=this._getUnitOrder(r),I=this.units[m-1];I&&!this._isWorkTime(a,I)&&(c=this._getClosestWorkTimeFuture(a,I))}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 n=this._getWorkHours(e),i=0;i<n.length;i++){var a=n[i];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(n){r+=n.durationMinutes}),r},getHoursPerDay:function(e){var t=this._getWorkHours(e),r=0;return t.forEach(function(n){r+=n.durationHours}),r},_getWorkUnitsForRange:function(e,t,r,n){var i=0,a=new Date(e),s=new Date(t),o;for(r=="minute"?o=yt(this._getMinutesPerDay,this):o=yt(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),i+=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),i+=c,a=this.$gantt.date.add(a,7,"day");continue}}i+=o(a),a=this._nextDate(a,"day",1)}return i/n},_getMinutesBetweenSingleDay:function(e,t){for(var r=this._getIntervalTimestamp(e,t),n=this._getWorkHours(e),i=0,a=0;a<n.length;a++){var s=n[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);i+=(c-o)/60,r.start=c}}return Math.floor(i)},_getMinutesBetween:function(e,t,r,n){var i=new Date(e),a=new Date(t);n=n||1;var s=new Date(i),o=this.$gantt.date.add(this.$gantt.date.day_start(new Date(i)),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,n),p=d+f+u;return p},_getHoursBetween:function(e,t,r,n){var i=new Date(e),a=new Date(t);n=n||1;var s=new Date(i),o=this.$gantt.date.add(this.$gantt.date.day_start(new Date(i)),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,n)/60,u=this._getMinutesBetweenSingleDay(c,l,r,n)/60,f=this._getWorkUnitsForRange(o,c,r,n),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,n=null;for(var t in e.customWeeks){var i=e.customWeeks[t];if(i.from&&i.to){var a=i.from,s=i.to;(!r||r>a.valueOf())&&(r=a.valueOf()),(!n||n<s.valueOf())&&(n=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:i.from,to:i.to,hours:this._parseHours(i.hours),dates:{}};if(i.days&&!i.dates){i.dates=i.dates||{};for(var t=0;t<i.days.length;t++)i.dates[t]=i.days[t],i.days[t]instanceof Array||(i.dates[t]=!!i.days[t]);delete i.days}for(var c in i.dates)o.dates[c]=this._parseHours(i.dates[c])}}e.parsed.customWeeksRangeStart=r,e.parsed.customWeeksRangeEnd=n}},_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),n=Object.keys(t.dates);if(r.sort(),n.sort(),!this._arraysEqual(r,n))return!1;for(var i=0;i<r.length;i++){var a=r[i],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 Ni))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 n in t.parsed.customWeeks){var i=t.parsed.customWeeks[n],a=r.parsed.customWeeks[n];if(!a||!this._compareSettings(i,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 n=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()));var i=this._timestamp({date:n});if(r.haveCustomWeeks&&r.customWeeksRangeStart<=i&&r.customWeeksRangeEnd>i){for(var a=0;a<r.customWeeksBoundaries.length;a++)if(r.customWeeksBoundaries[a].from<=i&&r.customWeeksBoundaries[a].to>i){r=r.customWeeks[r.customWeeksBoundaries[a].name];break}}var s=!0;return r.dates[i]!==void 0?s=r.dates[i]: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 n=t.getUTCHours();return!n&&!t.getUTCMinutes()&&!t.getUTCSeconds()&&e.valueOf()<t.valueOf()&&(n=24),r.end=n*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=[],n=0;n<t.length;n+=2){var i=t[n],a=t[n+1],s=a-i;r.push({start:i,end:a,startHour:Math.floor(i/3600),startMinute:Math.floor(i/60),endHour:Math.ceil(a/3600),endMinute:Math.ceil(a/60),durationSeconds:s,durationMinutes:s/60,durationHours:s/3600})}return r}else return e},setWorkTime:function(e){return this._tryChangeCalendarSettings(yt(function(){var t=e.hours!==void 0?e.hours:!0,r=this._timestamp(e),n=this.getConfig();if(r!==null?n.dates[r]=t:e.customWeeks||(n.hours=t),e.customWeeks){if(n.customWeeks||(n.customWeeks={}),typeof e.customWeeks=="string")r!==null?n.customWeeks[e.customWeeks].dates[r]=t:e.customWeeks||(n.customWeeks[e.customWeeks].hours=t);else if(typeof e.customWeeks=="object"&&e.customWeeks.constructor===Object)for(var i in e.customWeeks)n.customWeeks[i]=e.customWeeks[i]}this._parseSettings(),this._clearCaches()},this))},unsetWorkTime:function(e){return this._tryChangeCalendarSettings(yt(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,n=null;return n=String(e.valueOf()),r=this._workingUnitsCache.getItem(t,n,e),r==-1&&(r=this._checkIfWorkingUnit(e,t),this._workingUnitsCache.setItem(t,n,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,n){var i=0,a=1;if(e.valueOf()>t.valueOf()){var s=t;t=e,e=s,a=-1}return r=="hour"&&n==1?i=this._getHoursBetween(e,t,r,n):r=="minute"&&n==1?i=this._getMinutesBetween(e,t,r,n):i=this._getWorkUnitsBetweenGeneric(e,t,r,n),a*Math.round(i)},hasDuration:function(){var e=this.argumentsHelper.getDurationArguments.apply(this.argumentsHelper,arguments),t=e.start_date,r=e.end_date,n=e.unit,i=e.step;if(!n)return!1;var a=new Date(t),s=new Date(r);for(i=i||1;a.valueOf()<s.valueOf();){if(this._isWorkTime(a,n))return!0;a=this._nextDate(a,n,i)}return!1},calculateEndDate:function(){var e=this.argumentsHelper.calculateEndDateArguments.apply(this.argumentsHelper,arguments),t=e.start_date,r=e.duration,n=e.unit,i=e.step;if(!n)return!1;var a=e.duration>=0?1:-1;r=Math.abs(r*1);var s=this;return this._dateDurationCache.getEndDate(t,r,n,i*a,function(){return s._calculateEndDate(t,r,n,i*a)})},_calculateEndDate:function(e,t,r,n){if(!r)return!1;if(n==1&&r=="minute")return this._calculateMinuteEndDate(e,t,n);if(n==-1&&r=="minute")return this._subtractMinuteDate(e,t,n);if(n==1&&r=="hour")return this._calculateHourEndDate(e,t,n);var i=this._addInterval(e,t,r,n,null);return i.end},_addInterval:function(e,t,r,n,i){for(var a=0,s=e;a<t&&!(i&&i(s));){var o=this._nextDate(s,r,n),c=new Date(o.valueOf()+1);n>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"),n=0,i=t,a=this._getIntervalTimestamp(e,r),s=this._getWorkHours(e),o=0;o<s.length&&n<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>i&&(u=i,d=l+i*60*60);var f=Math.round((d-l)/3600);n+=f,i-=f,a.start=d}}var p=r;return n===t&&(p=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate(),0,0,a.start))),{added:n,end:p}},_calculateHourEndDate:function(e,t,r){var n=new Date(e),i=0;r=r||1,t=Math.abs(t*1);var a=this._addHoursUntilDayEnd(n,t);i=a.added,n=a.end;var s=t-i;if(s){for(var o=n;i<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)),i+l>=t)break;i+=l,o=c}n=o}if(i<t){var s=t-i;a=this._addHoursUntilDayEnd(n,s),n=a.end}return n},_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"),n=0,i=t,a=this._getIntervalTimestamp(e,r),s=this._getWorkHours(e),o=0;o<s.length&&n<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>i&&(u=i,d=l+i*60);var f=Math.round((d-l)/60);i-=f,n+=f,a.start=d}}var p=r;return n===t&&(p=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate(),0,0,a.start))),{added:n,end:p}},_subtractMinutesUntilHourStart:function(e,t){for(var r=this.$gantt.date.hour_start(new Date(e)),n=0,i=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&&n<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>i&&(f=i,u=d-i*60);var p=Math.abs(Math.round((d-u)/60));i-=p,n+=p,s=u}}var m=r;return n===t&&(m=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate(),0,0,s))),{added:n,end:m}},_subtractMinuteDate:function(e,t,r){var n=this.getClosestWorkTime({date:e,dir:"past",unit:"minute"}),i=0;r=r||-1,t=Math.abs(t*1),t=Math.round(t);let a=this._isMinutePrecision(n),s=this._subtractMinutesUntilHourStart(n,t);i+=s.added,n=s.end;for(var o=0,c=[],l=0;i<t;){var d=this.$gantt.date.day_start(new Date(n)),u=!1;n.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-i,m=this._getTimeOfDayStamp(n,u);if(!c.length||!l){n=this.$gantt.date.add(n,-1,"day");continue}if(c[c.length-1].end<=m&&p>l){i+=l,n=this.$gantt.date.add(n,-1,"day");continue}for(var I=!1,C=null,S=null,D=c.length-1;D>=0;D--)if(c[D].start<m-1&&c[D].end>=m-1){I=!0,C=c[D],S=c[D-1];break}if(I)if(m===C.end&&p>=C.durationMinutes)i+=C.durationMinutes,n=this.$gantt.date.add(n,-C.durationMinutes,"minute");else if(!a&&p<=m/60-C.startMinute)i+=p,n=this.$gantt.date.add(n,-p,"minute");else if(a)p<=m/60-C.startMinute?(i+=p,n=this.$gantt.date.add(n,-p,"minute")):(i+=m/60-C.startMinute,S?n=new Date(Date.UTC(n.getUTCFullYear(),n.getUTCMonth(),n.getUTCDate(),0,0,S.end)):n=this.$gantt.date.day_start(n));else{var P=this._getMinutesPerHour(n);P<=p?(i+=P,n=this._nextDate(n,"hour",r)):(s=this._subtractMinutesUntilHourStart(n,p),i+=s.added,n=s.end)}else if(n.getUTCHours()===0&&n.getUTCMinutes()===0&&n.getUTCSeconds()===0){var g=this._getClosestWorkTimePast(n,"hour");if(g.valueOf()===n.valueOf()){var g=this.$gantt.date.add(n,-1,"day"),h=this._getWorkHours(g);if(h.length){var v=h[h.length-1];g.setUTCSeconds(v.durationSeconds)}}n=g}else n=this._getClosestWorkTimePast(new Date(n-1),"hour")}if(i<t){var A=t-i;s=this._subtractMinutesUntilHourStart(n,A),i+=s.added,n=s.end}return n},_calculateMinuteEndDate:function(e,t,r){var n=new Date(e),i=0;r=r||1,t=Math.abs(t*1),t=Math.round(t);var a=this._addMinutesUntilHourEnd(n,t);i+=a.added,n=a.end;for(var s=0,o=[],c=0,l=this._isMinutePrecision(n);i<t;){var d=this.$gantt.date.day_start(new Date(n)).valueOf();d!==s&&(o=this._getWorkHours(n),c=this._getMinutesPerDay(n),s=d);var u=t-i,f=this._getTimeOfDayStamp(n);if(!o.length||!c){n=this.$gantt.date.add(this.$gantt.date.day_start(n),1,"day");continue}if(o[0].start>=f&&u>=c){if(i+=c,u==c){n=new Date(Date.UTC(n.getUTCFullYear(),n.getUTCMonth(),n.getUTCDate(),0,0,o[o.length-1].end));break}else n=this.$gantt.date.add(n,1,"day"),n=this.$gantt.date.day_start(n);continue}for(var p=!1,m=null,I=0;I<o.length;I++)if(o[I].start<=f&&o[I].end>f){p=!0,m=o[I];break}if(p)if(f===m.start&&u>=m.durationMinutes)i+=m.durationMinutes,n=this.$gantt.date.add(n,m.durationMinutes,"minute");else if(u<=m.endMinute-f/60)i+=u,n=this.$gantt.date.add(n,u,"minute");else{var C=this._getMinutesPerHour(n);C<=u?(i+=C,l?n=this.$gantt.date.add(n,C,"minute"):n=this._nextDate(n,"hour",r)):(a=this._addMinutesUntilHourEnd(n,u),i+=a.added,n=a.end)}else n=this._getClosestWorkTimeFuture(n,"hour")}if(i<t){var S=t-i;a=this._addMinutesUntilHourEnd(n,S),i+=a.added,n=a.end}return n},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 n=new Date(e);if(this._isWorkTime(n,t))return n;if(n=this.$gantt.date[t+"_start"](n),r=="any"||!r){var i=this._getClosestWorkTimeFuture(n,t),a=this._getClosestWorkTimePast(n,t);Math.abs(i-e)<=Math.abs(e-a)?n=i:n=a}else r=="past"?n=this._getClosestWorkTimePast(n,t):n=this._getClosestWorkTimeFuture(n,t);return n},_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 n=new Date(e),i=null,a=!1;this._getWorkHours(n).length||(n=this._getClosestWorkTime(n,"day",t<0?"past":"future"),t<0&&(n=new Date(n.valueOf()-1),a=!0),r=this._getWorkHours(n));var s=this._getTimeOfDayStamp(n);if(a&&(s=this._getTimeOfDayStamp(new Date(n.valueOf()+1),a)),t>0){for(var o=0;o<r.length;o++)if(r[o].start>=s){i=new Date(Date.UTC(n.getUTCFullYear(),n.getUTCMonth(),n.getUTCDate(),0,0,r[o].start));break}}else for(var o=r.length-1;o>=0;o--)if(r[o].end<=s){i=new Date(Date.UTC(n.getUTCFullYear(),n.getUTCMonth(),n.getUTCDate(),0,0,r[o].end));break}else if(r[o].end>s&&r[o].start<=s){i=new Date(Date.UTC(n.getUTCFullYear(),n.getUTCMonth(),n.getUTCDate(),0,0,s));break}return i},_getClosestWorkMinute:function(e,t,r){var n=new Date(e),i=this._getWorkHours(n),a=this._findClosestTimeInDay(n,r,i);return a||(r>0?(n=this.calculateEndDate(n,r,t),n=this.$gantt.date.day_start(n)):(n=this.calculateEndDate(n,r,"day"),n=this.$gantt.date.day_start(n),n=this.$gantt.date.add(n,1,"day"),n=new Date(n.valueOf()-1)),i=this._getWorkHours(n),a=this._findClosestTimeInDay(n,r,i)),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 n=this._getUnitOrder(t),i=this.units[n-1],a=e,s=3e3,o=0;!this._isWorkTime(a,t)&&!(i&&!this._isWorkTime(a,i)&&(r>0?a=this._getClosestWorkTimeFuture(a,i):a=this._getClosestWorkTimePast(a,i),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 n in e.dates);var i=this._checkWorkHours(e.hours),a=!1;return r.forEach((function(s){if(!a){var o=t[s];o===!0?a=i: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 $e={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 n in e){r=n;break}return r},getCalendarIdFromLegacyConfig:function(e,t){if(t)for(var r in t){var n=t[r];if(e[r]){var i=n[e[r]];if(i)return i}}return null}};function zy(){function e(i){return i.map(function(a){return a&&a.resource_id?a.resource_id:a}).sort().join("-")}var t={};function r(i,a){return a.mergeCalendars(i.map(function(s){var o=s&&s.resource_id?s.resource_id:s;return a.getResourceCalendar(o)}))}function n(i,a){var s=e(i);if(i.length){if(i.length===1)return a.getResourceCalendar(s).id;if(t[s])return t[s].id;var o=r(i,a);return t[s]=o,a.addCalendar(o)}else return null}return{getCalendarIdFromMultipleResources:n}}var qy=zy();function al(e){this.$gantt=e,this._calendars={},this._legacyConfig=void 0,this.$gantt.attachEvent("onGanttReady",(function(){this.$gantt.config.resource_calendars&&(this._isLegacyConfig=$e.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))}al.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 n=0;n<7;n++)r[n]=t.weekdays[n];t?.dates&&Object.entries(t.dates).forEach(([n,i])=>{r[new Date(n).valueOf()]=i}),Object.entries(r).forEach(([n,i])=>{i instanceof Array||(r[n]=!!i)}),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 n=new il,i;return e.forEach((function(a){i?i=this._createCalendarFromConfig(n.merge(i,a)):i=a}).bind(this)),this.createCalendar(i)},_createCalendarFromConfig:function(e){var t=new Ni(this.$gantt,nl(this.$gantt));t.id=String(Ri());var r=this._convertWorkTimeSettings(e);if(r.customWeeks)for(var n in r.customWeeks)r.customWeeks[n]=this._convertWorkTimeSettings(r.customWeeks[n]);return t._setConfig(r),t},createCalendar:function(e){var t;e||(e={}),e.getConfig?t=Dt(e.getConfig()):e.worktime?t=Dt(e.worktime):t=Dt(e);var r=Dt(this.defaults.fulltime.worktime);return Ee(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,n,i;if(this._legacyConfig===!1?i=t.resource_property:i=$e.getResourceProperty(t),Array.isArray(e[i])&&e[i].length)t.dynamic_resource_calendars?n=qy.getCalendarIdFromMultipleResources(e[i],this):r=this.getResourceCalendar(e[i]);else if(this._legacyConfig===void 0&&(this._legacyConfig=$e.isLegacyResourceCalendarFormat(t.resource_calendars)),this._legacyConfig)var n=$e.getCalendarIdFromLegacyConfig(e,t.resource_calendars);else if(i&&e[i]&&t.resource_calendars[e[i]])var r=this.getResourceCalendar(e[i]);if(n&&(r=this.getCalendar(n)),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,n=r.resource_calendars,i=null;if(Array.isArray(e)&&e.length===1&&(typeof e[0]=="object"?t=e[0].resource_id:t=e[0]),n){if(this._legacyConfig===void 0&&(this._legacyConfig=$e.isLegacyResourceCalendarFormat(r.resource_calendars)),this._legacyConfig){for(var a in n)if(n[a][t]){i=n[a][t];break}}else var i=n[t];if(i)return this.getCalendar(i)}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 n=this._getOwnCalendar(r),i=!!t.getState().group_mode;if(!n&&t.config.inherit_calendar&&t.isTaskExists(r.parent)){for(var a=r;t.isTaskExists(a.parent)&&(a=t.getTask(a.parent),!(t.isSummaryTask(a)&&(n=this._getOwnCalendar(a),n))););i&&!n&&e.$effective_calendar&&(n=this.getCalendar(e.$effective_calendar))}return n||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||Ri(),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],n=this.createCalendar(r);n.id=t,this.addCalendar(n)}},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 Mi(e,t){this.argumentsHelper=t,this.$gantt=e}Mi.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,n=e.unit,i=e.step;return this._calculateDuration(t,r,n,i)},_calculateDuration:function(e,t,r,n){var i=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)/(n*a[r]));else{for(var o=new Date(e),c=new Date(t);o.valueOf()<c.valueOf();)s+=1,o=i.add(o,n,r);o.valueOf()!=t.valueOf()&&(s+=(c-o)/(i.add(o,n,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,n=e.unit;return n?(t=new Date(t),r=new Date(r),t.valueOf()<r.valueOf()):!1},hasWorkTime:function(){return!0},equals:function(e){return e instanceof Mi},calculateEndDate:function(){var e=this.argumentsHelper.calculateEndDateArguments.apply(this.argumentsHelper,arguments),t=e.start_date,r=e.duration,n=e.unit,i=e.step;return this.$gantt.date.add(t,i*r,n)}};function sl(e){this.$gantt=e.$gantt,this.argumentsHelper=nl(this.$gantt),this.calendarManager=e,this.$disabledCalendar=new Mi(this.$gantt,this.argumentsHelper)}sl.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,n){var i=this.argumentsHelper.isWorkTimeArguments.apply(this.argumentsHelper,arguments);return n=this._getCalendar(i),n.isWorkTime(i)},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 Jy=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,n,i){return t.isWorkTime(r,n,i)},getClosestWorkTime:function(r){return t.getClosestWorkTime(r)},calculateDuration:function(r,n,i){return t.calculateDuration(r,n,i)},_hasDuration:function(r,n,i){return t.hasDuration(r,n,i)},calculateEndDate:function(r,n,i,a){return t.calculateEndDate(r,n,i,a)},mergeCalendars:yt(e.mergeCalendars,e),createCalendar:yt(e.createCalendar,e),addCalendar:yt(e.addCalendar,e),getCalendar:yt(e.getCalendar,e),getCalendars:yt(e.getCalendars,e),getResourceCalendar:yt(e.getResourceCalendar,e),getTaskCalendar:yt(e.getTaskCalendar,e),deleteCalendar:yt(e.deleteCalendar,e)}},Xy={create:Jy};function ol(e){var t=new al(e),r=new sl(t),n=Xy.create(t,r);Ee(e,n)}var cl={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 ll(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||cl,templates:e.templates||{},getTask:e.getTask||function(n){return null},isTaskExists:e.isTaskExists||function(n){return!1},isSummaryTask:e.isSummaryTask||function(n){return!1},getState:function(){return{group_mode:!1}},callEvent:function(n,i){let a=e.onEvent;return a&&a(n,i),!0},attachEvent:function(){return 0},checkEvent:function(){return!1},detachEvent:function(){},defined:Qc,mixin:Ee,copy:Dt,assert:function(n,i){if(!n){if(e.throwOnAssert)throw new Error("[calendar] "+i);e.silent!==!0&&console.error("[calendar]",i)}},$services:{getService:function(){return null}},$ui:{getView:function(){return null}}};return r._correct_dst_change=function(n){return n},r.date=rl(r),r.date.init(),ol(r),r}function Zy(e={}){let t=ll(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 dl={createCalendar:Zy};var lO=3600*1e3;function hl(e){return{getActivity(t){return e.getActivity(t)}}}var{createCalendar:Qy}=dl,ze="__replay_default__";function tm(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],n=t[t.length-1];return t.every((a,s)=>a===r+s)?[`${r}:00-${n+1}:00`]:e}var ul={hours:["8:00-16:00"],days:[!1,!0,!0,!0,!0,!0,!1]},fl="__main_global__",em={hours:["8:00-12:00","13:00-17:00"],days:[!1,!0,!0,!0,!0,!0,!1]};function pl(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 rm(e){let t={};if(Array.isArray(e.days))for(let n=0;n<e.days.length;n+=1)t[n]=e.days[n];if(e.dates)for(let[n,i]of Object.entries(e.dates))t[n]=i;let r={hours:tm(e.hours),dates:t};return e.customWeeks&&(r.customWeeks=e.customWeeks),r}function yl(e){let t=Qy({config:{work_time:!0}});t.addCalendar({id:ze,worktime:ul}),t.addCalendar({id:fl,worktime:em});let r=new Set(e.filter(d=>!pl(d.worktime)).map(d=>String(d.id))),n=e.filter(d=>pl(d.worktime));for(let d of n)t.addCalendar({id:d.id,worktime:d.worktime?rm(d.worktime):ul});let i=Zc(t),a=i.getCalendar(ze),s=i.getCalendar(fl);if(!a||!s)throw new Error("[replay-calendar] fallback calendars failed to register in work-calendar instance");let o=new Set([ze]);for(let d of n)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=i.getCalendar(d)??a:r.has(u)&&(p=s),c.set(u,p),p}}}}function ml(e){return{hasChildren(t){return e.hasChildren(t)},getParentStartDateIfHasPredecessors(t){let r=e.getActivity(t);if(!r)return null;let n=e.getParent(r.id);return!n||e.getIncomingLinkIds(n.id).length===0?null:n.startDate},getDescendantIds(t){return nm(e,t).map(r=>String(r))},getAncestorIds(t){let r=[],n=e.getActivity(t);for(;n;){let i=n.parentId;if(i===null)break;let a=e.getActivity(i);if(!a)break;r.push(String(i)),n=a}return r},getChildProgressInfo(t){return e.getChildren(t).map(n=>{let i=e.getActivity(n);return{id:n,progress:Number(i?.progress??0),ponderator:Number(i?.ponderator??0)}})},getChildHhInfo(t){return e.getChildren(t).map(n=>{let i=e.getActivity(n);return{id:n,workHours:Number(i?.workHours??0),progress:Number(i?.progress??0),realWorkHours:Number(i?.realWorkHours??0)}})},getChildUsedCostInfo(t){return e.getChildren(t).map(n=>{let i=e.getActivity(n);return{id:n,usedCost:Number(i?.usedCost??0)}})},getChildCostInfo(t){return e.getChildren(t).map(n=>{let i=e.getActivity(n);return{id:n,cost:Number(i?.cost??0)}})}}}function nm(e,t){let r=[],n=new ft;for(let i of e.getChildren(t))n.enqueue(i);for(;!n.isEmpty();){let i=n.dequeue();r.push(i);for(let a of e.getChildren(i))n.enqueue(a)}return r}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 n=this._journal;n&&(n.before.has(t)||n.before.set(t,Qt(r)),n.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:Qt(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:gl(r)})}noteCorrelativeBefore(t,r){let n=this._journal;!n||n.correlativeBefore.has(t)||n.correlativeBefore.set(t,r)}noteScheduledBefore(t,r){let n=this._journal;if(!n)return;let i=Qt(r);n.scheduledBefore.has(t)||n.scheduledBefore.set(t,i),n.before.has(t)||n.before.set(t,i),n.dirty.add(t)}noteLinkField(t,r){let n=this._journal;!n||n.linkFieldCaptured.has(t)||(n.linkFieldCaptured.add(t),n.ops.push({kind:"link-field",linkId:t,before:gl(r)}))}};function gl(e){return{...e}}var Xr=class{_cache={closestWorkTime:new Map,endDate:new Map,duration:new Map};reader;constructor(t){this.reader=t.reader}resolveCalendar(t){let r=vl(t);return this.reader.getCalendar(r??ze)}getClosestWorkTime(t){let r=`${Bi(t.task)}|${t.dir}|${t.date.getTime()}`;return Wi(this._cache.closestWorkTime,r,()=>this.resolveCalendar(t.task).getClosestWorkTime({direction:t.dir,date:t.date,unit:ot.HOUR}))}calculateEndDate(t){let r=`${Bi(t.task)}|${t.startDate.getTime()}|${t.durationHours}`;return Wi(this._cache.endDate,r,()=>this.resolveCalendar(t.task).calculateEndDate(t.startDate,t.durationHours))}calculateDuration(t){let r=`${Bi(t.task)}|${t.startDate.getTime()}|${t.endDate.getTime()}`;return Wi(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 Wi(e,t,r){let n=e.get(t);if(n!==void 0)return n;let i=r();return e.set(t,i),i}var im="__default__";function vl(e){if(!e)return null;let t=e.calendarId;return t==null?null:String(t)}function Bi(e){return vl(e)??im}var Zr=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 n=this.activities.get(t)?.parentId,i=0,a=this.activities.size;for(;n&&!L(n);){if(n===r)return!0;if(++i>a)return!1;n=this.activities.get(n)?.parentId}return!1}getParent(t){let r=this.activities.get(t)?.parentId;return!r||L(r)?null:this.activities.get(r)??null}getParentId(t){return this.activities.get(t)?.parentId??null}addChild(t,r){if(this._dirty)return;if(L(t)){this._roots.push(r);return}let n=String(t),i=this._childrenByParent.get(n);i?i.push(r):this._childrenByParent.set(n,[r])}rebuild(){this._childrenByParent.clear(),this._roots=[];for(let r of this.activities.values()){if(L(r.parentId)){this._roots.push(r.id);continue}let n=String(r.parentId),i=this._childrenByParent.get(n)??[];i.push(r.id),this._childrenByParent.set(n,i)}let t=(r,n)=>{let i=this.activities.get(r),a=this.activities.get(n);return i&&a?er(i,a):String(r).localeCompare(String(n))};this._roots.sort(t);for(let r of this._childrenByParent.values())r.sort(t)}};var Qr=class{checkedSet=new Set;hiddenSet=new Set;activeFilter=null;activeOrder=null;isChecked(t){return this.checkedSet.has(t)}isVisible(t){return!this.hiddenSet.has(t)}hiddenIds(){return[...this.hiddenSet]}getActiveFilter(){return this.activeFilter}setActiveFilter(t){this.activeFilter=t}getActiveOrder(){return this.activeOrder}setActiveOrder(t){this.activeOrder=t}checkedIds(){return[...this.checkedSet]}checkedCount(){return this.checkedSet.size}setChecked(t,r){return r===this.checkedSet.has(t)?!1:(r?this.checkedSet.add(t):this.checkedSet.delete(t),!0)}setVisible(t,r){return r===!this.hiddenSet.has(t)?!1:(r?this.hiddenSet.delete(t):this.hiddenSet.add(t),!0)}forget(t){this.checkedSet.delete(t),this.hiddenSet.delete(t)}hydrate(t){this.checkedSet=new Set(t.checkedIds??[]),this.hiddenSet=new Set(t.hiddenIds??[]),this.activeFilter=null,this.activeOrder=null}snapshot(){return{checked:new Set(this.checkedSet),hidden:new Set(this.hiddenSet),activeFilter:this.activeFilter,activeOrder:this.activeOrder}}restore(t){this.checkedSet=new Set(t.checked),this.hiddenSet=new Set(t.hidden),this.activeFilter=t.activeFilter,this.activeOrder=t.activeOrder}};var be=class{_activities=new Map;_lastStartDate=new Map;_promotionSnapshot=new Map;_links=new Map;_outgoing=new Map;_incoming=new Map;_hierarchy;_buildOrderComparator;_cache={ids:null,visualOrderIds:null,orderComparator:null};_writeCapture=new Jr;_viewState=new Qr;_filterProjection=null;_viewStateBefore=null;_lastStartDateBefore=null;_promotionSnapshotBefore=null;_calendar;_flags;constructor(t,r=()=>null){this._buildOrderComparator=r;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._indexLink(n);this._calendar=new Xr(yl(t.calendars)),this._flags=sm(t),this._hierarchy=new Zr(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=pa(this).map(t=>String(t.id)),this._cache.visualOrderIds)}invalidateVisualOrderIds(){this._cache.visualOrderIds=null}forEachActivity(t){for(let[r,n]of this._activities)t(n,r)}getParentId(t){return this._hierarchy.getParentId(t)}getActivity(t){return this._activities.get(String(t))??null}getLastStartDate(t){return this._lastStartDate.get(String(t))??null}setLastStartDate(t,r){this._captureLastStartDateOnce(),this._lastStartDate.set(String(t),r)}getPromotionSnapshot(t){return this._promotionSnapshot.get(String(t))??null}setPromotionSnapshot(t,r){this._capturePromotionSnapshotOnce(),this._promotionSnapshot.set(String(t),r)}_capturePromotionSnapshotOnce(){this._writeCapture.peek()!==null&&this._promotionSnapshotBefore===null&&(this._promotionSnapshotBefore=new Map(this._promotionSnapshot))}_captureLastStartDateOnce(){this._writeCapture.peek()!==null&&this._lastStartDateBefore===null&&(this._lastStartDateBefore=new Map(this._lastStartDate))}getLink(t){return this._links.get(String(t))??null}activityExists(t){return this._activities.has(String(t))}isChecked(t){return this._viewState.isChecked(String(t))}isVisible(t){return this._viewState.isVisible(String(t))}checkedIds(){return this._viewState.checkedIds()}hiddenIds(){return this._viewState.hiddenIds()}setChecked(t,r){return this._captureViewStateOnce(),this._viewState.setChecked(String(t),r)}setVisible(t,r){return this._captureViewStateOnce(),this._viewState.setVisible(String(t),r)}getActiveFilter(){return this._viewState.getActiveFilter()}setActiveFilter(t){this._captureViewStateOnce(),this._viewState.setActiveFilter(t),this._filterProjection=null}getFilterProjection(){return this._filterProjection}setFilterProjection(t){this._filterProjection=t}getActiveOrder(){return this._viewState.getActiveOrder()}setActiveOrder(t){this._captureViewStateOnce(),this._viewState.setActiveOrder(t),this.invalidateDerivedOrder()}getOrderComparator(){let t=this._viewState.getActiveOrder();return t===null?(this._cache.orderComparator=null,null):this._cache.orderComparator?this._cache.orderComparator:(this._cache.orderComparator=this._buildOrderComparator(t),this._cache.orderComparator)}invalidateDerivedOrder(){this._cache.orderComparator=null,this._cache.visualOrderIds=null}hydrateViewState(t){this._viewState.hydrate(t),this._filterProjection=null,this.invalidateDerivedOrder()}_captureViewStateOnce(){this._writeCapture.peek()!==null&&this._viewStateBefore===null&&(this._viewStateBefore=this._viewState.snapshot())}getOutgoingLinkIds(t){return this._outgoing.get(String(t))??Al}getIncomingLinkIds(t){return this._incoming.get(String(t))??Al}getChildren(t){return this._hierarchy.getChildren(t)}hasChildren(t){return this._hierarchy.hasChildren(t)}isChildOf(t,r){return this._hierarchy.isChildOf(t,r)}getParent(t){return this._hierarchy.getParent(t)}getRootIds(){return this._hierarchy.getRootIds()}getClosestWorkTime(t){return this._calendar.getClosestWorkTime(t)}calculateEndDate(t){return this._calendar.calculateEndDate(t)}calculateDuration(t){return this._calendar.calculateDuration(t)}clearCalendarCache(){this._calendar.clearCache()}get calendarReader(){return this._calendar.reader}batchUpdate(t){t()}updateActivity(t){}getLiveActivity(t){return this.getActivity(t)}getFlags(){return{...this._flags,allCheckedTaskIds:this._viewState.checkedIds()}}getProjectEnd(){return null}beginWriteCapture(){this._writeCapture.begin(),this._viewStateBefore=null,this._lastStartDateBefore=null,this._promotionSnapshotBefore=null}peekWriteCapture(){return this._writeCapture.peek()}endWriteCapture(){this._writeCapture.end(),this._viewStateBefore=null,this._lastStartDateBefore=null,this._promotionSnapshotBefore=null}setActivityField(t,r,n){let i=this.getActivity(t);i&&(this._writeCapture.note(String(t),i),i[r]=n,r===b.PARENT&&this._hierarchy.markDirty(),Ui(r)&&(this._cache.visualOrderIds=null))}setActivityFieldDynamic(t,r,n){let i=this.getActivity(t);if(i){if(!Object.hasOwn(i,r))throw new Error(`setActivityFieldDynamic: unknown CoreActivity field "${r}"`);this._writeCapture.note(String(t),i),Reflect.set(i,r,Xc(r,n)),r===b.PARENT&&this._hierarchy.markDirty(),Ui(r)&&(this._cache.visualOrderIds=null)}}setActivityFields(t,r){let n=this.getActivity(t);if(!n)return;this._writeCapture.note(String(t),n);let i=!1;for(let a of Object.keys(r))Reflect.set(n,a,Reflect.get(r,a)),a===b.PARENT&&(i=!0),Ui(a)&&(this._cache.visualOrderIds=null);i&&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){Il(this._outgoing,String(t.source),t.id),Il(this._incoming,String(t.target),t.id)}_deindexLink(t){let r=this._outgoing.get(String(t.source));r&&this._outgoing.set(String(t.source),Cl(r,t.id));let n=this._incoming.get(String(t.target));n&&this._incoming.set(String(t.target),Cl(n,t.id))}setLinkField(t,r,n){let i=this.getLink(t);i&&(this._writeCapture.noteLinkField(String(t),i),i[r]=n)}setLinkFieldDynamic(t,r,n){if(!am(r))return;let i=this.getLink(t);i&&(this._writeCapture.noteLinkField(String(t),i),Reflect.set(i,r,n))}setLinkProplannerId(t,r){let n=this.getLink(t);n&&(this._writeCapture.noteLinkField(String(t),n),n.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 n=String(t);(this._viewState.isChecked(n)||!this._viewState.isVisible(n))&&(this._captureViewStateOnce(),this._viewState.forget(n)),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:n,correlativeBefore:i,scheduledBefore:a}=t;this._undoLinkAdds(r),this._undoInserts(r),this._reInsertRemovedActivities(r),this._reAddRemovedLinks(r),this._restoreLinkFields(r),this._restoreCorrelatives(i),this._restoreActivityFields(a),this._restoreActivityFields(n),this._viewStateBefore!==null&&(this._viewState.restore(this._viewStateBefore),this._filterProjection=null,this.invalidateDerivedOrder()),this._promotionSnapshotBefore!==null&&(this._promotionSnapshot=this._promotionSnapshotBefore),this._lastStartDateBefore!==null&&(this._lastStartDate=this._lastStartDateBefore),this._cache.ids=null,this._cache.visualOrderIds=null,this._hierarchy.markDirty()}_restoreCorrelatives(t){for(let[r,n]of t){let i=this._activities.get(r);i&&(i.correlativeId=n)}}_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,n]of t){let i=this._activities.get(r);i&&this._restoreScalarFields(i,n)}}_restoreScalarFields(t,r){for(let n of Object.keys(t))Object.hasOwn(r,n)||Reflect.deleteProperty(t,n);for(let n of Object.keys(r))Reflect.set(t,n,Reflect.get(r,n))}_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))}},Al=[];function am(e){return e===Un.LAG||e===Un.TYPE}function Ui(e){return e===b.PARENT||e===b.CORRELATIVE_ID}function Cl(e,t){return e.filter(r=>String(r)!==String(t))}function Il(e,t,r){let n=e.get(t);n?n.push(r):e.set(t,[r])}function sm(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 Sl(e,t){let r=e.getActivity(t);return r?Q(r):null}function kl(e){return e.getAllActivities().map(Q)}function Dl(e){return e.getAllIds().map(String)}function Tl(e,t){e.forEachActivity((r,n)=>t(n))}function _l(e,t){let r=t==="0"?ji(e,"0"):e.getChildren(t),n=[];for(let i of r){let a=e.getActivity(i);a&&n.push(Q(a))}return n.sort((i,a)=>(i.correlativeId??0)-(a.correlativeId??0)),n}function ji(e,t){let r=t;if(r==="0"){let n=[];return e.forEachActivity((i,a)=>{L(i.parentId)&&n.push(a)}),n}return mt(r,e)}function Pl(e){return e.checkedIds().map(String)}function Rl(e,t){if(t==="0"){let r=!1;return e.forEachActivity(n=>{r||=L(n.parentId)}),r}return e.getChildren(t).length>0}function El(e,t){let r=e.getLink(t);return r?vt(r):null}function bl(e){return e.getAllLinks().map(t=>vt(t))}function tn(e){let[t,r]=e.split(":");return Number(t)*60+Number(r??0)}function om(e){return e.reduce((t,r)=>tn(r)<tn(t)?r:t)}function cm(e){return e.reduce((t,r)=>tn(r)>tn(t)?r:t)}function lm(e){return e.worktime.days.flatMap(t=>Array.isArray(t)?t:t===!0?e.worktime.hours:[])}function Ll(e){let t=[...e].find(a=>a.is_default);if(!t)return null;let r=lm(t);if(r.length===0)return null;let n=r.map(a=>a.split("-")[0]),i=r.map(a=>a.split("-")[1]);return{startHour:om(n),endHour:cm(i)}}function wl(e,t){return{calendars:e.calendarReader,hierarchy:ml(e),activityReader:hl(e),dateFormat:t.dateFormat??"YYYY-MM-DD",customHours:t.customHours??{},hoursPerDay:t.hoursPerDay,inputUnit:t.inputUnit??"days"}}function Ol(e){return re(e)}function Nl(e){let t=e.activities.map(i=>({...i,after:null})),r=e.links.map(i=>({...i,after:null})),n=e.source.kind==="activity-batch"?{...e.source,items:[],links:[]}:e.source;return Q({...e,source:n,activities:t,links:r})}function Hi(e,t,r,n,i){return{changeSet:e,beforeSnap:t,beforeLinks:r,afterSnap:n,afterLinks:i}}function Ml(e,t){let r=new Map,n=new Map;for(let i of t.activities){if(i.kind!=="created")continue;let a=e.getActivity(String(i.id));a&&r.set(String(i.id),J(a))}for(let i of t.links){if(i.kind==="deleted")continue;let a=e.getLink(String(i.id));a&&n.set(String(i.id),{...a})}return{afterSnap:r,afterLinks:n}}function Wl(e){return e.kind!=="inline-edit"||!Ye.has(e.column)?null:`inline-edit:${String(e.activityId)}:${e.column}`}function xl(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 Bl(e,t){if(!xl(e)||!xl(t))return!1;let r=e.changeSet.activities[0],n=t.changeSet.activities[0];return!!r&&!!n&&String(r.id)===String(n.id)}function Ul(e,t){let r=e.changeSet.activities[0],n=t.changeSet.activities[0];if(!r||!n)return t;let i=r.fields??{},a=n.fields??{},s={};for(let c of new Set([...Object.keys(i),...Object.keys(a)])){let l=i[c],d=a[c];s[c]={before:l?l.before:d?.before,after:d?d.after:l?.after}}let o={...t.changeSet,activities:[{...n,fields:s}]};return Hi(o)}function jl(e){return e.kind==="persistence-acknowledge"?"clear-on-success":e.kind==="sir-sync"||e.kind==="activity-lookahead-sync"||e.kind==="baseline-apply"||e.kind==="ponderator-criterion-set"||e.kind==="status-criteria-set"||e.kind==="selection-toggle"||e.kind==="selection-replace"||e.kind==="visibility-set"||e.kind==="filter-set"||e.kind==="sort-set"?"skip":"record"}function Vi(e){for(let t of e.changeSet.activities)if(t.kind==="created"||t.kind==="deleted"||t.kind==="updated"&&t.fields&&R.CUSTOM_ID in t.fields)return!0;return!1}function Yi(e,t,r){let n=[],i=[];for(let s of t.changeSet.activities){let o=String(s.id);if(s.kind==="updated"){let c=e.getActivity(o);n.push({id:o,kind:"updated",fields:Fl(s.fields,r),after:c?J(c):null})}else if(s.kind==="deleted")if(r==="before"){let c=e.getActivity(o);n.push({id:o,kind:"created",after:c?J(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.getActivity(o);n.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);i.push({id:o,kind:"updated",fields:Fl(s.fields,r),after:c?vt(c):null})}else if(s.kind==="deleted")if(r==="before"){let c=e.getLink(o);i.push({id:o,kind:"created",after:c?vt(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.getLink(o);i.push({id:o,kind:"created",after:c?vt(c):null})}}let a=(t.changeSet.viewState??[]).map(s=>r==="before"?dm(s):s);return{source:{kind:r==="before"?"undo":"redo"},activities:n,links:i,calendars:[],trackingEvents:[],effects:[],viewState:a}}function Fl(e,t){if(e!=null)return Object.fromEntries(Object.entries(e).map(([r,n])=>[r,t==="before"?{before:Q(n.after),after:Q(n.before)}:{before:Q(n.before),after:Q(n.after)}]))}function dm(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 Ki(e){return e.activities.length>0||e.links.length>0||(e.viewState?.length??0)>0||(e.effects?.length??0)>0}function Hl(e,t){Yl(e,t,"before")}function Vl(e,t){Yl(e,t,"after")}function Yl(e,t,r){let n=t.changeSet;for(let i of n.activities)if(i.kind==="updated"){if(!i.fields)continue;for(let[a,s]of Object.entries(i.fields))rt(e,i.id,a,r==="before"?s.before:s.after)}else if(i.kind==="deleted")if(r==="before"){let a=t.beforeSnap?.get(String(i.id));if(!a)throw new Error(`undo: missing beforeSnap for resurrecting activity ${i.id}`);e.addActivity(J(a))}else e.removeActivity(String(i.id));else if(r==="before")e.removeActivity(String(i.id));else{let a=t.afterSnap?.get(String(i.id));if(!a)throw new Error(`redo: missing afterSnap for re-creating activity ${i.id}`);e.addActivity(J(a))}for(let i of n.links)if(i.kind==="updated"){if(!i.fields)continue;if(Object.hasOwn(i.fields,"source")||Object.hasOwn(i.fields,"target")){let a=r==="before"?t.beforeLinks?.get(String(i.id)):t.afterLinks?.get(String(i.id));if(!a)throw new Error(`${r==="before"?"undo":"redo"}: missing link snapshot for ${i.id}`);e.removeLink(String(i.id)),e.addLink({...a});continue}for(let[a,s]of Object.entries(i.fields))ho(e,String(i.id),a,r==="before"?s.before:s.after)}else if(i.kind==="deleted")if(r==="before"){let a=t.beforeLinks?.get(String(i.id));if(!a)throw new Error(`undo: missing beforeLinks for re-adding link ${i.id}`);e.addLink(a)}else e.removeLink(String(i.id));else if(r==="before")e.removeLink(String(i.id));else{let a=t.afterLinks?.get(String(i.id));if(!a)throw new Error(`redo: missing afterLinks for re-creating link ${i.id}`);e.addLink(a)}for(let i of n.viewState??[])i.checked&&e.setChecked(i.activityId,r==="before"?i.checked.before:i.checked.after),i.visible&&e.setVisible(i.activityId,r==="before"?i.visible.before:i.visible.after)}var um=100,fm=600,en=class{constructor(t=um){this.maxDepth=t}maxDepth;undoStack=[];redoStack=[];_lastKey=null;_lastTime=0;record(t,r=null,n=0){let i=this.undoStack[this.undoStack.length-1];r!=null&&r===this._lastKey&&n-this._lastTime<=fm&&i!==void 0&&Bl(i,t)?this.undoStack[this.undoStack.length-1]=Ul(i,t):(this.undoStack.push(t),this.undoStack.length>this.maxDepth&&this.undoStack.splice(0,this.undoStack.length-this.maxDepth)),this._lastKey=r,this._lastTime=n,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,this.resetCoalesce()}};var pm=["parentId","correlativeId"];function Gl(e,t){let r=new Set,n=i=>{let a=t(i);r.add(a===null?"0":String(a))};for(let i of e.activities){let a=String(i.id);if(i.kind==="created"){n(a);continue}if(i.kind==="deleted"){let c=i.fields;c&&"parentId"in c&&r.add(Kl(c.parentId?.before));continue}let s=i.fields;!s||!pm.some(c=>c in s)||(n(a),"parentId"in s&&r.add(Kl(s.parentId?.before)))}return r}function Kl(e){return e==null?"0":String(e)}function hm(e){return{...e,id:String(e.id),source:String(e.source),target:String(e.target),type:e.type,lag:Number(e.lag)}}function ym(e){return{days:e.days,hours:e.hours,...e.dates?{dates:e.dates}:{},...e.customWeeks?{customWeeks:e.customWeeks}:{}}}function $l(e){return{id:String(e.id),worktime:ym(e.worktime)}}function rn(e,t,r,n=[]){let i=t.map(hm),a=[...r.map($l),...n.map($l)];return{activities:[...e],links:i,calendars:a}}var zl=["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","responsableIds","tagIds"],ql=new Set(["startDate","endDate","constraintDate","dateOrigin"]),Jl=new Set(["newActivityIds","responsableIds","tagIds"]);function Xl(e){let t=zl.map(r=>[r,mm(r,e[r])]);return Object.fromEntries(t)}function mm(e,t){return ql.has(e)?t instanceof Date?new Date(t):null:Jl.has(e)?Array.isArray(t)?[...t]:[]:t}function qe(e,t){if(e.assignedDefaultCalendar)return!0;for(let r of zl)if(!gm(r,e[r],t[r]))return!0;return!1}function gm(e,t,r){return ql.has(e)?vm(t,r):Jl.has(e)?Am(t,r):(t??null)===(r??null)}function vm(e,t){let r=e instanceof Date?e.getTime():null,n=t instanceof Date?t.getTime():null;return r===n}function Am(e,t){let r=Array.isArray(e)?[...e].map(String).sort():[],n=Array.isArray(t)?[...t].map(String).sort():[];return r.length!==n.length?!1:r.every((i,a)=>i===n[a])}function nn(e,t){return e.source!==t.source||e.target!==t.target||e.lag!==t.lag||e.type!==t.type}function Zl(e,t){let r=new Map(e.map(n=>[String(n.id),n]));return t.filter(n=>{let i=r.get(String(n.id));return i?nn(i,n):!1})}var an=class{initialized=!1;dirtyActivityIds=new Set;dirtyLinkIds=new Set;linksAtLastSave=new Map;activitiesAtLastSave=new Map;init(t,r){this.snapshotActivities(t),this.snapshotLinks(r),this.initialized=!0}snapshotActivities(t){this.activitiesAtLastSave.clear(),this.dirtyActivityIds.clear();for(let r of t){let n=String(r.id);if(r.proplannerId==null){this.dirtyActivityIds.add(n);continue}let i=Xl(r);this.activitiesAtLastSave.set(String(r.id),{persistable:i,deletedSnapshot:{id:r.id,proplannerId:r.proplannerId,parentId:r.parentId,hadBaseline:r.baselineSnapshot!==null||r.baselinePoints.length>0}}),qe(r,i)&&this.dirtyActivityIds.add(n)}}snapshotLinks(t){this.linksAtLastSave.clear(),this.dirtyLinkIds.clear();for(let r of t){let n=String(r.id);if(r.proplannerId==null){this.dirtyLinkIds.add(n);continue}this.linksAtLastSave.set(String(r.id),{id:r.id,proplannerId:r.proplannerId,source:r.source,target:r.target,lag:r.lag,type:r.type})}}recordChanges(t,r,n,i){if(this.initialized){for(let a of t){let s=String(a.id),o=n(s),c=this.activitiesAtLastSave.get(s);(o===null?c!==void 0:o.proplannerId==null||c===void 0||qe(o,c.persistable))?this.dirtyActivityIds.add(s):this.dirtyActivityIds.delete(s)}for(let a of r){let s=String(a.id),o=i(s),c=this.linksAtLastSave.get(s);(o===null?c!==void 0:o.proplannerId==null||c===void 0||nn(c,o))?this.dirtyLinkIds.add(s):this.dirtyLinkIds.delete(s)}}}acknowledgePersistedLookahead(t,r){if(this.initialized)for(let n of t){let i=r(n),a=this.activitiesAtLastSave.get(n);if(i===null||a===void 0)continue;let s={...a.persistable,isLookahead:i.isLookahead};this.activitiesAtLastSave.set(n,{...a,persistable:s}),i.proplannerId==null||qe(i,s)?this.dirtyActivityIds.add(n):this.dirtyActivityIds.delete(n)}}hasUnsavedChanges(){return this.initialized&&(this.dirtyActivityIds.size>0||this.dirtyLinkIds.size>0)}deletedActivities(t){if(!this.initialized)return[];let r=new Set(t.map(i=>String(i.id))),n=[];for(let[i,a]of this.activitiesAtLastSave)r.has(i)||n.push({...a.deletedSnapshot});return n}deletedLinks(t){if(!this.initialized)return[];let r=new Set(t.map(n=>String(n.id)));return Array.from(this.linksAtLastSave.entries(),([n,i])=>r.has(n)?null:{...i}).filter(n=>n!==null)}modifiedActivities(t){return this.initialized?t.filter(r=>{if(r.proplannerId==null)return!1;if(r.assignedDefaultCalendar)return!0;let n=this.activitiesAtLastSave.get(String(r.id));return n?qe(r,n.persistable):!0}):[]}modifiedLinks(t){return this.initialized?t.filter(r=>{if(r.proplannerId==null)return!1;let n=this.linksAtLastSave.get(String(r.id));return n?nn(n,r):!0}):[]}clear(){this.initialized=!1,this.dirtyActivityIds.clear(),this.dirtyLinkIds.clear(),this.linksAtLastSave.clear(),this.activitiesAtLastSave.clear()}};var Ql=/^(\d{4})[/-](\d{1,2})[/-](\d{1,2})/;var Gi=[!1,!0,!0,!0,!0,!0,!1],td=new Set(["1","true"]),$i="DURATION",ed="asap",rd={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 nd(e,t){let r=[],n=e.map(a=>{let s=Rm(a,t);return a.should_be_showed===!1&&r.push(s.id),s});bm(n);let i=new Set(n.map(a=>a.id));return Lm(n,i,t.reporter),{activities:n,activityIds:i,hiddenIds:r}}function Cm(e){return e===0}function Im(e,t){if(!e)return null;let r=rd[e.toUpperCase()];return r===void 0?(t.warn(`[parseFromBackend] unknown constraint label "${e}" \u2014 defaulting to "asap"`),ed):r}function Sm(e,t){let r=Im(e.constraint,t),i=r!=="asap"&&r!=="alap"&&e.constraint_date?wt(e.constraint_date):null;return{constraintType:r,constraintDate:i}}function km(e,t,r){if(e==null)return r;let n=String(e);return t.has(n)?n:r}function Dm(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 Tm(e){if(typeof e!="object"||e===null||!("id"in e))return!1;let t=e.id;return typeof t=="string"||typeof t=="number"}function zi(e){if(!Array.isArray(e))return[];let t=[];for(let r of e)Tm(r)&&t.push(String(r.id));return t}function _m(e){return e==="0"?null:String(e)}function Pm(e,t){return Array.isArray(e)?e.map(r=>Kr(r,t)).filter(r=>r!==null):[]}function Rm(e,t){let r=km(e.calendarId,t.knownCalendarIds,t.defaultCalendarId),n=e.calendarId==null||!t.knownCalendarIds.has(String(e.calendarId)),i=Number(e.progress),{constraintType:a,constraintDate:s}=Sm(e,t.reporter),o=e.type==="milestone",c=wt(e.start_date),l=o?c:wt(e.end_date),d=o?0:Number(e.duration);return{id:String(e.unique_id),proplannerId:typeof e.id=="number"?e.id:null,parentId:_m(e.parent_id),name:e.name,description:e.description??"",type:e.type,startDate:c,endDate:l,durationHours:Me(d,t.hoursPerDay),constraintType:a,constraintDate:s,autoScheduling:Cm(i),calendarId:r,assignedDefaultCalendar:r!=null&&n,dateOrigin:e.date_origin==null?null:wt(e.date_origin),progress:i,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:Em(e),subcontractId:e.subcontractId,isLookahead:e.isOnLookahead,hasLookaheadTasks:Array.isArray(e.tasks)&&e.tasks.length>0,newActivityIds:Dm(e.newActivitiesArray),hasNewActivities:e.hasNewActivities??!1,...e.isNewActivity===!0?{isNewActivity:!0}:{},pendingRequestIds:zi(e.pendingRequests),responsableIds:zi(e.responsables),tagIds:zi(e.tags),baselinePoints:Pm(e.baseline_points,t.reporter),baselineSnapshot:null,recursiveDurationHours:Me(Number(e.sumOfDurationRecursively??0),t.hoursPerDay),isCritical:!!e.is_critical,freeSlackHours:e.freeSlack,expectedProgress:null,expectedProgressBaseline:null,status:null,criticalPath:null}}function Em(e){return e.has_childs?null:e.custom_id}function bm(e){let t=e.find(r=>r.correlativeId===0&&r.type==="project");t&&(t.parentId=null)}function Lm(e,t,r){for(let n of e)n.parentId!==null&&(t.has(n.parentId)||(r.warn(`[parseFromBackend] activity "${n.id}" references unknown parent "${n.parentId}" \u2014 re-parenting to root (null)`),n.parentId=null))}function od(e,t,r,n=null){let s=(e!==void 0&&e.length>0?e:t??[]).map(c=>xm(c,n)),o=(r??[]).map(c=>Fm(c,n));return{calendars:s,baseCalendars:o,knownCalendarIds:new Set(s.map(c=>c.id)),defaultCalendarId:Om(s)}}function Om(e){let t=e.find(n=>n.is_default);if(t)return t.id;let r=e[0];return r?r.id:null}function cd(e,t){let r=jm(e.working_days),{days:n,hours:i}=Um(e,r),a=Nm(t.exceptionsSource,t.exceptionRange),s={days:n,hours:i};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 xm(e,t){let r=e.baseDefault,n=typeof r=="boolean"?r:void 0;return cd(e,{idSuffix:"",isDefault:!!e.is_default,baseDefault:n,exceptionsSource:e.exceptiondays,exceptionRange:t})}function Fm(e,t){return cd(e,{idSuffix:"-base",isDefault:!1,baseDefault:!!e.is_default,exceptionsSource:e.baseexceptiondays??e.exceptiondays,exceptionRange:t})}function Nm(e,t){if(!Array.isArray(e)||e.length===0)return null;let r={};for(let n of e){if(!n)continue;let i=Mm(n.from_date,n.to_date,t);if(i.length===0)continue;let a=Wm(n);if(a!==void 0)for(let s of i)r[s]=a}return Object.keys(r).length>0?r:null}function Mm(e,t,r){let n=id(e),i=id(t);if(n===null||i===null)return[];if(r&&(i<r.start||n>r.end))return[];let a=[],s=r?Math.max(n,r.start):n,o=r?Math.min(i,r.end):i;for(;s<=o;)a.push(String(s)),s+=864e5;return a}function id(e){if(typeof e!="string")return null;let t=Ql.exec(e.trim());if(!t)return null;let r=Number(t[1]),n=Number(t[2]),i=Number(t[3]);return Number.isFinite(r)&&Number.isFinite(n)&&Number.isFinite(i)?Date.UTC(r,n-1,i):null}function Wm(e){if(e.workable===!1)return!1;let t=e.shifts;if(Array.isArray(t)&&t.length>0){let r=Bm(t);if(r.length>0)return r}}var ad=/^\d{1,2}:\d{2}$/;function Bm(e){let t=[];for(let r of e){let n=ud(r?.shift_string);if(!n)continue;if(!n.startsCsv.includes(",")&&!n.endsCsv.includes(",")){let o=n.startsCsv.trim(),c=n.endsCsv.trim();!sn(o)&&!sn(c)&&ad.test(o)&&ad.test(c)&&t.push(`${o}-${c}`);continue}let s=dd(n.startsCsv,n.endsCsv).find(o=>o!==null);s&&t.push(s)}return t.sort(ld),t}function sd(e){let t=e.indexOf("-"),r=t>0?e.slice(0,t):e,[n,i]=r.split(":");return(Number(n)||0)*60+(Number(i)||0)}function ld(e,t){return sd(e)-sd(t)}function Um(e,t){let r=Array.from({length:7},()=>[]),n=(l,d)=>{let u=dd(l,d);for(let f=0;f<7;f+=1){let p=u[f],m=r[f];p&&m&&m.push(p)}},i=Array.isArray(e.shifts)&&e.shifts.length>0,a=typeof e.shift_start=="string"&&typeof e.shift_end=="string";if(i)for(let l of e.shifts){let d=ud(l?.shift_string);d&&n(d.startsCsv,d.endsCsv)}else a&&n(e.shift_start,e.shift_end);for(let l of r)l.sort(ld);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 dd(e,t){let r=Array.from({length:7},()=>null);if(typeof e!="string"||typeof t!="string")return r;let n=e.split(",").map(o=>o.trim()),i=t.split(",").map(o=>o.trim());if(!(n.length===i.length&&n.length>0&&n.length<=7))return r;let s=[...r];for(let o=0;o<n.length;o+=1){let c=n[o],l=i[o];sn(c)||sn(l)||(s[o]=`${c}-${l}`)}return s}function ud(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 jm(e){if(typeof e!="string")return[...Gi];let t=e.split(",").map(r=>r.trim());return t.length!==7?[...Gi]:t.map(r=>td.has(r))}var Hm=new Set(["false","null"]);function sn(e){return!e||Hm.has(e)}function Vm(e){return e==="0"||e==="1"||e==="2"||e==="3"}function Ym(e){if(typeof e!="string")return null;let t=Es(e);return t||(Vm(e)?e:null)}function pd(e,t){let r=[];for(let n of e)try{r.push(Km(n,t.knownActivityIds,t.hoursPerDay))}catch(i){t.reporter.warn("[parseFromBackend] dropping invalid link",i)}return Gm(r)}function Km(e,t,r){let n=String(e.unique_id??e.id),i=String(e.source_id??e.source??""),a=String(e.target_id??e.target??"");if(!t.has(i))throw new Error(`[parseFromBackend] link "${n}" source "${i}" does not exist`);if(!t.has(a))throw new Error(`[parseFromBackend] link "${n}" target "${a}" does not exist`);let s=Ym(e.type);if(s===null)throw new Error(`[parseFromBackend] link "${n}" has invalid type "${String(e.type)}"`);let o=e.ganttId,c=e.sectorId,l=e.id;return{id:n,source:i,target:a,type:s,lag:dt(Number(e.lag??0),r),...typeof o=="number"?{ganttId:o}:{},...typeof c=="number"?{sectorId:c}:{},...typeof l=="number"?{proplannerId:l}:{}}}function Gm(e){let t=new Map;for(let r of e){let n=`${r.source}-${r.target}-${r.type}`,i=t.get(n);(!i||fd(r)>fd(i))&&t.set(n,r)}return[...t.values()]}function fd(e){let t=Number(e.id);return Number.isFinite(t)?t:-1/0}function $m(e){if(typeof e!="string")return $i;switch(e.toUpperCase()){case"DURATION":return"DURATION";case"COST":return"COST";case"HH":return"HH";default:return $i}}function zm(e){let t=e.custom_id_prefix;return typeof t=="string"&&t.length>0?t:void 0}function qm(e){let t=e.custom_id_increment;return typeof t=="string"?t:typeof t=="number"&&Number.isFinite(t)?String(t):void 0}function hd(e){let t=zm(e),r=qm(e),n=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}:{},...n?{updateDurationForPrimaveraEndDate:!0}:{},activityCreter:$m(e.activity_creter),statusCriteria:kn}}function on(e,t=de){let r=hd(e.sector),{calendars:n,baseCalendars:i,knownCalendarIds:a,defaultCalendarId:s}=od(e.calendars,e.sector.calendars,e.baseCalendars,Jm(e.activities)),{activities:o,activityIds:c,hiddenIds:l}=nd(e.activities,{knownCalendarIds:a,defaultCalendarId:s,hoursPerDay:r.hoursPerDay,reporter:t}),d=pd(e.links,{knownActivityIds:c,hoursPerDay:r.hoursPerDay,reporter:t});return{sector:r,activities:o,links:d,calendars:n,baseCalendars:i,viewStateSeed:{hiddenIds:l}}}function Jm(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 n=new Date(t),i=new Date(r);return n.setFullYear(n.getFullYear()-1),i.setFullYear(i.getFullYear()+1),{start:n.getTime(),end:i.getTime()}}function yd(e={}){let t=e.seed??0,r=n=>{n>t&&(t=n)};if(e.knownIds)for(let n of e.knownIds){let i=typeof n=="number"?n:Number(n);Number.isFinite(i)&&r(i)}return{next(){return t+=1,String(t)},bump(n){let i=typeof n=="number"?n:Number(n);Number.isFinite(i)&&r(i)},snapshot(){return t},restore(n){t=n}}}function md(e={}){let t=e.seed??Date.now(),r=n=>{n>t&&(t=n)};if(e.knownIds)for(let n of e.knownIds){let i=typeof n=="number"?n:Number(n);Number.isFinite(i)&&r(i)}return{next(){return t+=1,String(t)},bump(n){let i=typeof n=="number"?n:Number(n);Number.isFinite(i)&&r(i)},snapshot(){return t},restore(n){t=n}}}function gd(e={}){let t=e.seed??0,r=n=>{Number.isFinite(n)&&n>0&&n<=9999999&&n>t&&(t=n)};if(e.knownIds)for(let n of e.knownIds){if(n==null)continue;let i=typeof n=="number"?n:Number(n);r(i)}return{next(){return t+=1,String(t)},bump(n){if(n==null)return;let i=typeof n=="number"?n:Number(n);r(i)},snapshot(){return t},restore(n){t=n}}}function vd(e){return!!e&&typeof e=="string"&&e.trim().length>0}function cn(e){if(!e||typeof e!="string"||e.trim().length===0)return"";let t=e.match(/^(.*?)(\d+)$/);return t?t[1]??"":e}function ln(e){if(!e||typeof e!="string"||e.trim().length===0)return"";let t=e.match(/(\d+)$/);return t?t[1]??"":""}function Ad(e){if(!e||typeof e!="object")return"";let t=e.customId;return typeof t=="string"?t:""}function Cd(e,t){return!t&&vd(e)}function Id(e,t){return t&&vd(e)}function Xe(e){return typeof e=="string"&&e.length>0&&/^\d+$/.test(e)}function Je(e){if(!Xe(e))return 0n;try{return BigInt(e)}catch{return 0n}}function Xm(e,t){if(typeof e!="bigint")return"";let r=e.toString();if(!Xe(t))return r;let n=t.length;return r.padStart(n,"0")}function Ct(e,t){let r=Je(e),n=Je(t),i=r+n;return Xm(i,e)}function dn(e,t){let r=Je(e),n=Je(t);return r<n?-1:r>n?1:0}function un(e,t){return dn(e,t)<=0?e:t}function fn(e,t){return dn(e,t)>=0?e:t}function Sd(e){if(!e||e.length===0)throw new Error("minSuffixFromArray requires non-empty array");return e.reduce((t,r)=>un(t,r))}function kd(e){if(!e||e.length===0)throw new Error("maxSuffixFromArray requires non-empty array");return e.reduce((t,r)=>fn(t,r))}function Dd(e){return{prefix:e,baseSuffix:null}}function Td(e,t){let r=ln(e);return{prefix:cn(e),baseSuffix:Ct(r,t)}}function _d(e){return{prefix:e,baseSuffix:null}}function Pd(e,t){return Cd(e,t)?"parentConversion":Id(e,t)?"pasteReference":"noContext"}function Zm(e){return{...e,usedSuffixes:new Set(e.usedSuffixes)}}var pn=class{prefixMap=new Map;processedIds=new Set;_journalPrefixBefore=null;_journalIds=null;beginCustomIdTransaction(){this._journalPrefixBefore=new Map,this._journalIds=[]}commitCustomIdTransaction(){this._journalPrefixBefore=null,this._journalIds=null}rollbackCustomIdTransaction(){let t=this._journalPrefixBefore,r=this._journalIds;if(!(t===null||r===null)){for(let[n,i]of t)i===null?this.prefixMap.delete(n):this.prefixMap.set(n,i);for(let n of[...r].reverse())n.hadId?this.processedIds.add(n.customId):this.processedIds.delete(n.customId);this._journalPrefixBefore=null,this._journalIds=null}}_noteCustomIdBefore(t){if(this._journalPrefixBefore===null||this._journalIds===null)return;let{prefix:r}=this.analyzeCustomId(t);if(!this._journalPrefixBefore.has(r)){let n=this.prefixMap.get(r);this._journalPrefixBefore.set(r,n?Zm(n):null)}this._journalIds.push({customId:t,hadId:this.processedIds.has(t)})}_ensureFreshBounds(t){let r=this.prefixMap.get(t);if(!r?.boundsDirty)return;r.boundsDirty=!1;let n=Array.from(r.usedSuffixes);r.min=Sd(n),r.max=kd(n),r.quantity=n.length,this._recalculateNext(t)}defaultPrefix;suffixIncrement;constructor(t={}){this.defaultPrefix=t.defaultPrefix??"A",this.suffixIncrement=t.suffixIncrement??"10"}extractPrefix(t){return cn(t)}extractSuffix(t){return ln(t)}analyzeCustomId(t){return{prefix:this.extractPrefix(t),suffix:this.extractSuffix(t)}}_updatePrefixStats(t,r){if(this._ensureFreshBounds(t),!this.prefixMap.has(t)){this.prefixMap.set(t,{min:r,max:r,next:r,quantity:1,usedSuffixes:new Set([r])}),this._recalculateNext(t);return}let n=this.prefixMap.get(t);n.usedSuffixes.has(r)||(n.usedSuffixes.add(r),n.min=un(r,n.min),n.max=fn(r,n.max),n.quantity+=1,this._recalculateNext(t))}_recalculateNext(t){let r=this.prefixMap.get(t);if(!r)return;let n=this.getNextAvailableSuffix(t);r.next=n??this.suffixIncrement}getPrefixStats(t){this._ensureFreshBounds(t);let r=this.prefixMap.get(t);return r?{min:r.min,max:r.max,next:r.next,quantity:r.quantity}:null}getNextSuffix(t){this._ensureFreshBounds(t);let r=this.prefixMap.get(t);return r?r.next:this.suffixIncrement}getAllPrefixes(){return Array.from(this.prefixMap.keys())}registerCustomId(t){if(!t||typeof t!="string")return{prefix:"",suffix:""};let{prefix:r,suffix:n}=this.analyzeCustomId(t);if(!r&&!n)return{prefix:r,suffix:n};if(this._noteCustomIdBefore(t),this._ensureFreshBounds(r),this.prefixMap.has(r)){let i=this.prefixMap.get(r);i.usedSuffixes.has(n)||(i.usedSuffixes.add(n),i.min=un(n,i.min),i.max=fn(n,i.max),i.quantity+=1,this._recalculateNext(r))}else this.prefixMap.set(r,{min:n,max:n,next:Ct(n,this.suffixIncrement),quantity:1,usedSuffixes:new Set([n])});return this.processedIds.add(t),{prefix:r,suffix:n}}releaseCustomId(t=null){if(!t||typeof t!="string")return{prefix:"",suffix:""};let{prefix:r,suffix:n}=this.analyzeCustomId(t);if(!this.prefixMap.has(r))return{prefix:r,suffix:n};this._noteCustomIdBefore(t);let i=this.prefixMap.get(r);return i.usedSuffixes.has(n)&&(i.usedSuffixes.delete(n),i.quantity-=1,i.usedSuffixes.size===0?this.prefixMap.delete(r):i.boundsDirty=!0),this.processedIds.delete(t),{prefix:r,suffix:n}}trackCustomIdChange(t,r){let n=this.releaseCustomId(t),i=this.registerCustomId(r);return{oldPrefix:n.prefix,oldSuffix:n.suffix,newPrefix:i.prefix,newSuffix:i.suffix}}_exceedsMaxLength(t){return t.length>20}_shouldSearchForGaps(t){if(this._ensureFreshBounds(t),!this.prefixMap.has(t))return!1;let r=this.prefixMap.get(t);return`${t}${Ct(r.max,this.suffixIncrement)}`.length>20}_suffixForUnknownPrefix(t,r){let n=r&&Xe(r)?r:this.suffixIncrement;return`${t}${n}`.length>20?null:n}_findFirstAvailableGap(t){if(this._ensureFreshBounds(t),!this.prefixMap.has(t))return null;let r=this.prefixMap.get(t),n=this.suffixIncrement;for(;dn(n,r.max)<0;){if(`${t}${n}`.length>20)return null;if(!r.usedSuffixes.has(n))return n;n=Ct(n,this.suffixIncrement)}return null}_generateDefaultCustomId(){let t=this.getNextAvailableSuffix(this.defaultPrefix);if(t===null){if(this._shouldSearchForGaps(this.defaultPrefix)){let r=this._findFirstAvailableGap(this.defaultPrefix);if(r!==null)return`${this.defaultPrefix}${r}`}return`${this.defaultPrefix}${this.suffixIncrement}`}return`${this.defaultPrefix}${t}`}getNextAvailableSuffix(t,r=null){if(this._ensureFreshBounds(t),!this.prefixMap.has(t))return this._suffixForUnknownPrefix(t,r);let n=this.prefixMap.get(t),i=this.suffixIncrement;if(!r||!Xe(r)){let o=Ct(n.max,i);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(!n.usedSuffixes.has(a))return a;a=Ct(a,i)}let s=Ct(n.max,i);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 i=this.prefixMap.get(t),a=0;for(;i.usedSuffixes.has(r)&&a<1e4;){let s=this.getNextAvailableSuffix(t,Ct(r,this.suffixIncrement));if(s===null)return this._generateDefaultCustomId();r=s,a++}}let n=`${t}${r}`;return this._exceedsMaxLength(n)&&(n=this._generateDefaultCustomId()),n}populateFromActivities(t){if(!Array.isArray(t))return this;let r=[...new Set(t.filter(n=>n&&typeof n.customId=="string"&&n.customId).map(n=>n.customId))];for(let n of r){if(this.processedIds.has(n))continue;let{prefix:i,suffix:a}=this.analyzeCustomId(n);(i||a)&&(this._updatePrefixStats(i,a),this.processedIds.add(n))}return this}getDefaults(){return{prefix:this.defaultPrefix,increment:this.suffixIncrement}}generateCustomIdForNewChild(t){let{activity:r,useActivityCustomIdAsReference:n=!1}=t,i=Ad(r),a=Pd(i,n),{prefix:s,baseSuffix:o}=this._applyGenerationStrategy(a,i),c=null;if(a==="parentConversion"&&this.prefixMap.has(s)){this._ensureFreshBounds(s);let f=this.prefixMap.get(s).max;c=Ct(f,this.suffixIncrement)}a==="parentConversion"&&this.releaseCustomId(i);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 Dd(this.defaultPrefix);case"pasteReference":return Td(r,this.suffixIncrement);default:return _d(this.defaultPrefix)}}generateCustomIdForRestoredChild(t=null){if(t){let n=t.trim();if(n.length>0){let i=this.extractPrefix(n),a=this.extractSuffix(n),s=Ct(a,this.suffixIncrement),o=this.getNextAvailableSuffix(i,s);if(o===null){let l=this._generateDefaultCustomId();return this.registerCustomId(l),l}let c=`${i}${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 n=t.trim();return r&&n===r.trim()?!1:this.processedIds.has(n)}};var Qm=1,tg=-1;function eg(e,t){return!e&&!t?null:e&&t?0:e?Qm:tg}function Rd(e){return e==null}function Ed(e,t){let r=t.indexOf(String(e));return r===-1?t.length:r}function rg(e,t,r){return e instanceof Date&&t instanceof Date?e.getTime()-t.getTime():typeof e=="number"&&typeof t=="number"?e-t:typeof e=="boolean"&&typeof t=="boolean"?Number(e)-Number(t):Array.isArray(e)&&Array.isArray(t)?e.length-t.length:String(e).localeCompare(String(t),r,{sensitivity:"base",numeric:!0})}function ng(e,t){let r=xt(e.field);return r===null?null:(n,i)=>{let a=r.extract(n,t),s=r.extract(i,t),o=eg(Rd(a),Rd(s));if(o!==null)return o;let c=r.valueKind==="enum"?Ed(a,r.order)-Ed(s,r.order):rg(a,s,t.locale);return e.direction==="desc"?-c:c}}function bd(e,t){let r=e.rules.map(n=>ng(n,t)).filter(n=>n!==null);return r.length===0?null:(n,i)=>{for(let a of r){let s=a(n,i);if(s!==0)return s}return 0}}function Ld(e){let t=[];e.forEachActivity((r,n)=>{r.type==="project"&&e.getChildren(String(n)).length===0&&t.push(String(n))});for(let r of t)e.setActivityField(r,b.TYPE,le),ig(e,r)}function ig(e,t){let r=e.getActivity(t);if(!r||!r.startDate||r.durationHours==null)return;let n=new Date(r.startDate);n.setUTCHours(0,0,0,0);let i=e.getClosestWorkTime({date:n,dir:X.FUTURE,task:r});if(i.getTime()===r.startDate.getTime())return;let a=e.calculateEndDate({startDate:i,durationHours:r.durationHours,task:r});e.setActivityField(t,b.START_DATE,i),e.setActivityField(t,b.END_DATE,a)}function wd(e){let t=[],r=[];e.forEachActivity((i,a)=>{i.parentId===null&&t.push(String(a))});let n=i=>{let a=e.getActivity(i);if(!a)return 0;let s=[...e.getChildren(i)],o=s.length===0?pt(a.workHours,a.progress):s.reduce((c,l)=>c+n(String(l)),0);return e.setActivityField(i,b.REAL_WORK_HOURS,o),r.push(i),o};for(let i of t)n(i);return r}async function Od(e){let{state:t,sector:r,scheduler:n,skipAutoSchedule:i,now:a}=e;if(st(t),r.updateDurationForPrimaveraEndDate&&sg(t),og(t),wd(t),i){a&&(te(t,a),Ot(t,r.statusCriteria));return}let s=await n.schedule({});Ne(t,s),cg(t),ag(t),await fe(t,void 0,!1),a&&(te(t,a),Ot(t,r.statusCriteria))}function ag(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 sg(e){e.forEachActivity(t=>{!t.startDate||!t.endDate||(t.durationHours=e.calculateDuration({startDate:t.startDate,endDate:t.endDate,task:t}))})}function og(e){e.forEachActivity(t=>{let r=t.constraintType;if(!r||!t.constraintDate)return;let n=t.constraintDate;if(t.type==="milestone"&&(n.getUTCHours()!==0||n.getUTCMinutes()!==0))return;let i=e.calendarReader.getCalendar(String(t.calendarId));i&&(t.constraintDate=bt(t.constraintDate,i,r))})}function cg(e){e.forEachActivity(t=>{if(t.type!=="milestone")return;let r=t.constraintType;if(!r||!t.constraintDate)return;let n=e.calendarReader.getCalendar(String(t.calendarId));n&&(t.constraintDate=bt(t.constraintDate,n,r))})}var Pt={READY:"ready",DESTROYED:"destroyed",POISONED:"poisoned"};function xd(e){let t=e.clock??null,r=t?kr(t()):null,n=e.reporter??de,i=on({sector:e.sector,activities:e.activities,links:e.links,calendars:e.calendars,baseCalendars:e.baseCalendars},n),a=i.sector;a.statusCriteria=nr(e.statusCriteria);let s=i.calendars,o=i.baseCalendars??[],c=rn(i.activities,i.links,i.calendars,o),l=S=>bd(S,zt(a.hoursPerDay)),d=new be(c,l);d.hydrateViewState({hiddenIds:i.viewStateSeed.hiddenIds});let u=new vr(d,n);Ld(d);let f=yd({knownIds:i.activities.map(S=>S.id)}),p=md({knownIds:i.links.map(S=>S.id)}),m=gd({knownIds:i.activities.map(S=>S.uniqueCorrelativeId)}),I=new pn({defaultPrefix:a.customIdPrefix,suffixIncrement:a.customIdIncrement});if(I.populateFromActivities(i.activities),e.baselinePoints&&e.baselinePoints.length>0){let S=o.find(D=>D.baseDefault)?.id??null;Gr(d,e.baselinePoints,r,n,S)}let C=Od({state:d,sector:a,scheduler:u,skipAutoSchedule:e.skipInitialAutoSchedule===!0,now:r??void 0});return{sector:a,state:d,scheduler:u,activityIdGen:f,linkIdGen:p,uidGen:m,customIdTracker:I,calendars:s,baseCalendars:o,clock:t,reporter:n,initPromise:C}}var lg=()=>({constantStart:null,variableStartOffset:null,constantEnd:null,variableEndOffset:null}),Ji=(e,t)=>e===null?t:Math.min(e,t),Xi=(e,t)=>e===null?t:Math.max(e,t);function Nd(e,t,r){let n=[...new Set(t.kind==="move"?t.activityIds.map(String):[String(t.activityId)])];if(n.length===0)throw new Error("[ScheduleCore] date gesture has no participants");let i=dg(e,t,n);return ug(e,n,i),{getDates(a,s){if(r(),!Number.isFinite(s))throw new Error("[ScheduleCore] invalid date gesture edge");let o=i.get(String(a));if(!o)return null;let c=pg(o,s),l=hg(o,s);if(c===null||l===null)throw new Error(`[ScheduleCore] incomplete date gesture bounds for ${String(a)}`);return{startTimeMs:c,endTimeMs:l}}}}function dg(e,t,r){let n=new Map,i=t.kind==="move"?String(t.anchorActivityId):null,a=i===null?null:Fd(e,i);if(i!==null&&!r.includes(i))throw new Error("[ScheduleCore] move anchor is not a participant");for(let s of r){let o=Fd(e,s);if(t.kind==="move"){let c=a.startDate.getTime();n.set(s,{constantStart:null,variableStartOffset:o.startDate.getTime()-c,constantEnd:null,variableEndOffset:o.endDate.getTime()-c})}else t.kind==="resize-start"?n.set(s,{constantStart:null,variableStartOffset:0,constantEnd:o.endDate.getTime(),variableEndOffset:null}):n.set(s,{constantStart:o.startDate.getTime(),variableStartOffset:null,constantEnd:null,variableEndOffset:0})}return n}function ug(e,t,r){let n=Fn(e,new Set(t));for(let i of n){let a=lg();for(let s of e.getChildren(i)){let o=r.get(s);if(o){fg(a,o);continue}let c=e.getActivity(s);if(!c)throw new Error(`[ScheduleCore] missing child ${s} while previewing parent ${i}`);a.constantStart=Ji(a.constantStart,c.startDate.getTime()),a.constantEnd=Xi(a.constantEnd,c.endDate.getTime())}r.set(i,a)}}function Fd(e,t){let r=e.getActivity(t);if(!r)throw new Error(`[ScheduleCore] missing date gesture activity ${t}`);if(e.hasChildren(t))throw new Error(`[ScheduleCore] summary activity ${t} cannot be dragged directly`);return r}function fg(e,t){t.constantStart!==null&&(e.constantStart=Ji(e.constantStart,t.constantStart)),t.variableStartOffset!==null&&(e.variableStartOffset=Ji(e.variableStartOffset,t.variableStartOffset)),t.constantEnd!==null&&(e.constantEnd=Xi(e.constantEnd,t.constantEnd)),t.variableEndOffset!==null&&(e.variableEndOffset=Xi(e.variableEndOffset,t.variableEndOffset))}function pg(e,t){if(e.variableStartOffset===null)return e.constantStart;let r=t+e.variableStartOffset;return e.constantStart===null?r:Math.min(e.constantStart,r)}function hg(e,t){if(e.variableEndOffset===null)return e.constantEnd;let r=t+e.variableEndOffset;return e.constantEnd===null?r:Math.max(e.constantEnd,r)}function yg(e){for(let t of e.activities)if(t.kind==="deleted"||t.kind==="updated"&&t.fields!==void 0&&"parentId"in t.fields)return!0;return!1}function mg(e,t){let r=[];for(let n of e.activities){let i=t.getActivity(n.id);if(i===null)return null;r.push(i)}return r}function gg(e,t,r){if(e===null||e.filter!==t)return!1;let n=e.context.hoursPerDay===r.hoursPerDay,i=e.context.locale===r.locale;return n&&i}var hn=class{_status=Pt.READY;coreRuntime;_undo=new en;_opQueue=Promise.resolve();_scheduleRevision=0;_pendingScheduleRevision=0;_criticalPathRevision=-1;_activeCriticalPath=null;constructor(t){let r=xd(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(i=>[i.id,i])),baseCalendars:r.baseCalendars,reporter:r.reporter},this._initPromise=r.initPromise.then(()=>{this._status!==Pt.DESTROYED&&this._saveTracker.init(this.coreRuntime.state.getAllActivities(),this.getAllLinksView())}),this._criticalPathReady=this._initPromise.then(()=>this._enqueue(async()=>{let i=await this._runCriticalPathAndCapture();return this._criticalPathRevision=this._scheduleRevision,i}));let n=t.criticalPathOnLoad===!0;this._ready=n?this._criticalPathReady.then(()=>{}):this._initPromise}get ready(){return this._ready}get criticalPathReady(){return this._criticalPathReady}get status(){return this._status}getSector(){return Q(this.coreRuntime.sector)}getActivityView(t){return this.assertReady(),Sl(this.coreRuntime.state,t)}createDateGesturePreview(t){this.assertReady();let r=this._scheduleRevision;return Nd(this.coreRuntime.state,t,()=>{if(this.assertReady(),this._scheduleRevision!==r)throw new Error("[ScheduleCore] date gesture preview is stale")})}getAllActivitiesView(){return this.assertReady(),kl(this.coreRuntime.state)}getChildrenView(t){return this.assertReady(),_l(this.coreRuntime.state,t)}getLinkView(t){return this.assertReady(),El(this.coreRuntime.state,t)}getAllLinksView(){return this.assertReady(),bl(this.coreRuntime.state)}getProperty(t,r){this.assertReady();let n=this.coreRuntime.state.getActivity(t);return n?Q(n[r]):null}getAllIds(){return this.assertReady(),Dl(this.coreRuntime.state)}forEachActivityId(t){this.assertReady(),Tl(this.coreRuntime.state,t)}getChildrenIds(t){return this.assertReady(),ji(this.coreRuntime.state,t)}getSelectedActivityIds(){return this.assertReady(),Pl(this.coreRuntime.state)}getHiddenActivityIds(){return this.assertReady(),this.coreRuntime.state.hiddenIds().map(String)}getActiveFilter(){return this.assertReady(),this.coreRuntime.state.getActiveFilter()}getActiveOrder(){return this.assertReady(),this.coreRuntime.state.getActiveOrder()}getVisualOrderIds(){return this.assertReady(),[...this.coreRuntime.state.getVisualOrderIds()]}hasChild(t){return this.assertReady(),Rl(this.coreRuntime.state,t)}getCalendar(t){this.assertReady();let r=this.coreRuntime.calendars.get(t);return r?Q(r):null}getAllCalendars(){return this.assertReady(),Array.from(this.coreRuntime.calendars.values(),t=>Q(t))}getBaseCalendars(){return this.assertReady(),this.coreRuntime.baseCalendars.map(t=>Q(t))}isCustomIdInUse(t,r=null){return this.assertReady(),this.coreRuntime.customIdTracker.isCustomIdInUse(t,r)}getProjectWorkHours(){return this.assertReady(),Ll(this.coreRuntime.calendars.values())}getModifiedLinks(){return this.assertReady(),this._saveTracker.modifiedLinks(this.getAllLinksView())}getModifiedActivities(){return this.assertReady(),this._saveTracker.modifiedActivities(this.coreRuntime.state.getAllActivities()).map(Q)}hasUnsavedChanges(){return this.assertReady(),this._saveTracker.hasUnsavedChanges()}getDeletedActivitiesSinceLastSave(){return this.assertReady(),this._saveTracker.deletedActivities(this.coreRuntime.state.getAllActivities()).map(Q)}getDeletedLinksSinceLastSave(){return this.assertReady(),this._saveTracker.deletedLinks(this.getAllLinksView()).map(Q)}_enqueue(t){let r=this._opQueue.then(t,t);return this._opQueue=r.then(()=>{},()=>{}),r}_beginScheduleMutation(t){return hi(t)?this._admitScheduleMutation():!1}_admitScheduleMutation(){return this._pendingScheduleRevision++,this._activeCriticalPath&&(this._activeCriticalPath.cancellation.cancelled=!0),!0}_settleScheduleMutation(t,r){t&&(r||(this._pendingScheduleRevision=Math.max(this._pendingScheduleRevision-1,this._scheduleRevision),this._pendingScheduleRevision===this._scheduleRevision&&this._criticalPathRevision!==this._scheduleRevision&&this.recomputeCriticalPath().catch(n=>{this.coreRuntime.reporter.error("[ScheduleCore] Critical Path re-arm after a barren mutation failed",n)})))}async dispatch(t,r={}){let n=this._beginScheduleMutation(t);return this._enqueue(()=>this._dispatchInner(t,r,n))}async applyActivityBatch(t,r={}){let n=this._beginScheduleMutation(t);return this._enqueue(()=>this._dispatchInner(t,r,n))}async _dispatchInner(t,r={},n=!1){let i=!1;try{let a=await this._runDispatch(t,r);return i=a.changedState,a.result}finally{this._settleScheduleMutation(n,i)}}async _runDispatch(t,r){this.assertReady();let n=wl(this.coreRuntime.state,{hoursPerDay:this.coreRuntime.sector.hoursPerDay,dateFormat:this.coreRuntime.sector.dateFormat,inputUnit:r.inputUnit??"days"}),i=jl(t),a=[this.coreRuntime.activityIdGenerator.snapshot(),this.coreRuntime.linkIdGenerator.snapshot(),this.coreRuntime.uniqueCorrelativeIdGenerator.snapshot()];this.coreRuntime.state.beginWriteCapture(),this.coreRuntime.customIdTracker.beginCustomIdTransaction();let s;try{s=await Jc(t,r,{adapter:this.coreRuntime.state,ctx:n,scheduler:this.coreRuntime.scheduler,sector:this.coreRuntime.sector,calendars:this.coreRuntime.calendars,activityIdGen:this.coreRuntime.activityIdGenerator,linkIdGen:this.coreRuntime.linkIdGenerator,uidGen:this.coreRuntime.uniqueCorrelativeIdGenerator,customIdTracker:this.coreRuntime.customIdTracker,reporter:this.coreRuntime.reporter,defaultBaseCalendarId:this.coreRuntime.baseCalendars.find(o=>o.baseDefault)?.id??null,now:this.coreRuntime.clock?kr(this.coreRuntime.clock()):null}),s.ok||this._rollback(a)}catch(o){throw this._rollback(a),o}finally{this.coreRuntime.state.endWriteCapture(),this.coreRuntime.customIdTracker.commitCustomIdTransaction()}if(s.ok&&i==="record"&&Ki(s.changes)){let o=Ml(this.coreRuntime.state,s.changes);this._undo.record(Hi(Nl(s.changes),s.__beforeSnap,s.__beforeLinks,o.afterSnap,o.afterLinks),Wl(t),Date.now())}return s.ok&&(i==="clear-on-success"?(this._saveTracker.snapshotActivities(this.coreRuntime.state.getAllActivities()),this._saveTracker.snapshotLinks(this.getAllLinksView()),this._undo.clear()):t.kind==="activity-lookahead-sync"&&t.acknowledgePersistedLookahead===!0?this._saveTracker.acknowledgePersistedLookahead(t.activityIds,o=>this.coreRuntime.state.getActivity(o)):this._saveTracker.recordChanges(s.changes.activities,s.changes.links,o=>this.coreRuntime.state.getActivity(o),o=>this.coreRuntime.state.getLink(o))),s=this._withReappliedViewState(t,s),s.ok?hi(t)&&Ki(s.changes)?(this._recordScheduleMutation(r.skipAutoSchedule!==!0&&r.skipCriticalPath!==!0&&re(t)),{result:Md(s),changedState:!0}):{result:Md(s),changedState:!1}:{result:s,changedState:!1}}recomputeCriticalPath(){let t=this._enqueue(async()=>({job:this._startCriticalPathForCurrentRevision()})).then(({job:r})=>r);return this._criticalPathReady=t,t}isCriticalPathSettled(){return this._criticalPathRevision===this._scheduleRevision&&this._pendingScheduleRevision===this._scheduleRevision&&this._activeCriticalPath===null}async whenCriticalPathSettled(){for(;!this.isCriticalPathSettled();)await this.recomputeCriticalPath()}_withReappliedViewState(t,r){if(!r.ok||(t.kind==="visibility-set"&&this.coreRuntime.state.setFilterProjection(null),!Jo(t)))return r;let n=this._reapplyViewState(r.changes);return n===null?r:{...r,changes:n}}_reapplyViewState(t){let r=this._reapplyActiveFilter(t),n=this._emitTouchedBranchOrder(r??t),a=this._reapplyActiveOrder(n.changes??r??t,n.touchedParents)??n.changes??r,s=a??t,o=s.activities.filter(u=>u.kind==="created").map(u=>String(u.id));if(o.length===0)return a;let c=new Set(o),l=this.coreRuntime.state.getFilterProjection();for(let u of o){l!==null&&l.pinnedVisibleIds.add(u);let f=u;for(;f!==null&&f!=="0";)c.add(f),l!==null&&(l.visibleIds.add(f),l.visibleReferenceCounts.set(f,(l.visibleReferenceCounts.get(f)??0)+1)),f=this.coreRuntime.state.getParentId(f)}let d=$t(this.coreRuntime.state,c,c);return d.length===0?a:{...s,viewState:[...s.viewState??[],...d]}}_emitTouchedBranchOrder(t){let r=this.coreRuntime.state,n=Gl(t,a=>r.getParentId(a));if(r.getActiveOrder()!==null)return{changes:null,touchedParents:n};if(n.size===0)return{changes:null,touchedParents:n};let i=Sn(r,n);return i.length===0?{changes:null,touchedParents:n}:{changes:{...t,order:i},touchedParents:n}}_reapplyActiveOrder(t,r){let n=this.coreRuntime.state;if(n.getActiveOrder()===null)return null;if(n.invalidateDerivedOrder(),t.links.length>0||t.calendars.length>0)return{...t,order:Oe(n)};let a=new Set(r);for(let o of t.activities){if(o.kind==="deleted")return{...t,order:Oe(n)};let c=n.getParentId(o.id);a.add(c===null?"0":String(c))}let s=Sn(n,a);return s.length===0?null:{...t,order:s}}_reapplyActiveFilter(t){let r=this.coreRuntime.state,n=r.getActiveFilter();if(n===null)return null;let i=zt(this.coreRuntime.sector.hoursPerDay),a=r.getFilterProjection(),s=gg(a,n,i),o=yg(t)?null:mg(t,r),c,l;if(o===null||!s){let f=tr({activities:r.getAllActivities(),parentOf:p=>r.getParentId(p),filter:n,context:i,...s?{pinnedVisibleIds:a.pinnedVisibleIds}:{}});r.setFilterProjection(f),l=f.visibleIds,c=r.getAllIds()}else c=ca(a,o,f=>r.getParentId(f)),l=a.visibleIds;let u=$t(r,l,c);return u.length===0?null:{...t,viewState:[...t.viewState??[],...u]}}_recordScheduleMutation(t){this._scheduleRevision++,this._pendingScheduleRevision=Math.max(this._pendingScheduleRevision,this._scheduleRevision),this._activeCriticalPath&&(this._activeCriticalPath.cancellation.cancelled=!0),t&&(this._criticalPathRevision=this._scheduleRevision)}_startCriticalPathForCurrentRevision(){if(this._status===Pt.DESTROYED)return Promise.resolve(null);let t=this._scheduleRevision;if(this._criticalPathRevision===t)return Promise.resolve(null);if(this._activeCriticalPath?.revision===t)return this._activeCriticalPath.promise;this._activeCriticalPath&&(this._activeCriticalPath.cancellation.cancelled=!0);let r={cancelled:!1},n=new be(rn(this.coreRuntime.state.getAllActivities().map(o=>J(o)),this.coreRuntime.state.getAllLinks().map(o=>({...o})),Array.from(this.coreRuntime.calendars.values()),this.coreRuntime.baseCalendars)),i=()=>!r.cancelled&&this._status!==Pt.DESTROYED&&this._scheduleRevision===t&&this._pendingScheduleRevision===this._scheduleRevision,a=(async()=>{let o=await fi(n,this.coreRuntime.sector.hoursPerDay,i);return!i()||o===null?null:this._enqueue(async()=>{if(!i())return null;this.coreRuntime.state.beginWriteCapture(),this.coreRuntime.customIdTracker.beginCustomIdTransaction();let c;try{for(let[l,d]of o)ui(this.coreRuntime.state,l,d);c=await B(this.coreRuntime.state,{source:{kind:"init"},beforeSnap:new Map,touchedIds:[],scheduledIds:[],hoursPerDay:this.coreRuntime.sector.hoursPerDay}),this._criticalPathRevision=t}catch(l){throw this._rollback(),l}finally{this.coreRuntime.state.endWriteCapture(),this.coreRuntime.customIdTracker.commitCustomIdTransaction()}return{changes:c}})})();this._activeCriticalPath={revision:t,cancellation:r,promise:a};let s=()=>{this._activeCriticalPath?.promise===a&&(this._activeCriticalPath=null)};return a.then(s,s),a}async _runCriticalPathAndCapture(){if(this._status===Pt.DESTROYED)return{changes:{source:{kind:"init"},activities:[],links:[],calendars:[],trackingEvents:[]}};this.coreRuntime.state.beginWriteCapture(),this.coreRuntime.customIdTracker.beginCustomIdTransaction();let t;try{await Fr(this.coreRuntime.state,this.coreRuntime.sector.hoursPerDay),t=await B(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(t={}){let r=this._admitScheduleMutation(),n=!1,i=this._enqueue(async()=>{try{return await this._runUndo(t,a=>{n=a})}finally{this._settleScheduleMutation(r,n)}});return i.then(a=>{a&&t.skipCriticalPath!==!0&&this.recomputeCriticalPath().catch(s=>{this.coreRuntime.reporter.error("[ScheduleCore] Critical Path recompute after undo failed",s)})},()=>{}),i}async _runUndo(t,r){{if(this.assertReady(),t.expectedUndoDepth!==void 0&&this._undo.undoDepth()!==t.expectedUndoDepth)return null;let n=this._undo.takeUndo();if(!n)return null;Hl(this.coreRuntime.state,n),this._recordScheduleMutation(!1),r(!0),Vi(n)&&this._resyncCustomIdTrackerFromModel(),this._undo.pushRedo(n),this._undo.resetCoalesce();let i=Yi(this.coreRuntime.state,n,"before");return this._saveTracker.recordChanges(i.activities,i.links,a=>this.coreRuntime.state.getActivity(a),a=>this.coreRuntime.state.getLink(a)),this._reapplyViewState(i)??i}}redo(t={}){let r=this._admitScheduleMutation(),n=!1,i=this._enqueue(async()=>{try{return await this._runRedo(a=>{n=a})}finally{this._settleScheduleMutation(r,n)}});return i.then(a=>{a&&t.skipCriticalPath!==!0&&this.recomputeCriticalPath().catch(s=>{this.coreRuntime.reporter.error("[ScheduleCore] Critical Path recompute after redo failed",s)})},()=>{}),i}async _runRedo(t){this.assertReady();let r=this._undo.takeRedo();if(!r)return null;Vl(this.coreRuntime.state,r),this._recordScheduleMutation(!1),t(!0),Vi(r)&&this._resyncCustomIdTrackerFromModel(),this._undo.pushUndo(r),this._undo.resetCoalesce();let n=Yi(this.coreRuntime.state,r,"after");return this._saveTracker.recordChanges(n.activities,n.links,i=>this.coreRuntime.state.getActivity(i),i=>this.coreRuntime.state.getLink(i)),this._reapplyViewState(n)??n}canUndo(){return this._undo.canUndo()}canRedo(){return this._undo.canRedo()}clearHistory(){this._undo.clear()}undoDepth(){return this._undo.undoDepth()}_resyncCustomIdTrackerFromModel(){this.coreRuntime.customIdTracker.clear(),this.coreRuntime.customIdTracker.populateFromActivities(this.coreRuntime.state.getAllActivities())}destroy(){this._activeCriticalPath&&(this._activeCriticalPath.cancellation.cancelled=!0),this.coreRuntime.calendars.clear(),this._saveTracker.clear(),this._status=Pt.DESTROYED}_initPromise;_criticalPathReady;_ready;_saveTracker=new an;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(t){try{this.coreRuntime.state.restoreFromCapture(),this.coreRuntime.customIdTracker.rollbackCustomIdTransaction(),t&&(this.coreRuntime.activityIdGenerator.restore(t[0]),this.coreRuntime.linkIdGenerator.restore(t[1]),this.coreRuntime.uniqueCorrelativeIdGenerator.restore(t[2]))}catch(r){throw this._status=Pt.POISONED,this.coreRuntime.reporter.error("[ScheduleCore] rollback failed \u2014 core poisoned",r),r}}};function Md(e){let{__beforeSnap:t,__beforeLinks:r,...n}=e;return n}var Wd=(e=[])=>(e??[]).filter(t=>!t.proplannerId);var Bd={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 Ud=8;var $={PERSISTENCE_ACKNOWLEDGE:"persistence-acknowledge",BASELINE_APPLY:"baseline-apply",PONDERATOR_CRITERION_SET:"ponderator-criterion-set",STATUS_CRITERIA_SET:"status-criteria-set",INLINE_EDIT:"inline-edit",DATES_BATCH:"dates-batch",BULK_EDIT:"bulk-edit",LINK_CREATE:"link-create",LINK_UPDATE:"link-update",LINK_DELETE:"link-delete",LINKS_BATCH:"links-batch",ACTIVITY_CREATE:"activity-create",ACTIVITY_DELETE:"activity-delete",ACTIVITY_MOVE:"activity-move",ACTIVITY_INDENT:"activity-indent",ACTIVITY_OUTDENT:"activity-outdent",ACTIVITY_SET_PROGRESS:"activity-set-progress",ACTIVITY_PASTE:"activity-paste",SELECTION_TOGGLE:"selection-toggle",SELECTION_REPLACE:"selection-replace",VISIBILITY_SET:"visibility-set",FILTER_SET:"filter-set",SORT_SET:"sort-set",SIR_SYNC:"sir-sync",ACTIVITY_LOOKAHEAD_SYNC:"activity-lookahead-sync"},vg={[$.PERSISTENCE_ACKNOWLEDGE]:!0,[$.BASELINE_APPLY]:!0,[$.PONDERATOR_CRITERION_SET]:!0,[$.STATUS_CRITERIA_SET]:!0,[$.INLINE_EDIT]:!0,[$.DATES_BATCH]:!0,[$.BULK_EDIT]:!0,[$.LINK_CREATE]:!0,[$.LINK_UPDATE]:!0,[$.LINK_DELETE]:!0,[$.LINKS_BATCH]:!0,[$.ACTIVITY_CREATE]:!0,[$.ACTIVITY_DELETE]:!0,[$.ACTIVITY_MOVE]:!0,[$.ACTIVITY_INDENT]:!0,[$.ACTIVITY_OUTDENT]:!0,[$.ACTIVITY_SET_PROGRESS]:!0,[$.ACTIVITY_PASTE]:!0,[$.SELECTION_TOGGLE]:!0,[$.SELECTION_REPLACE]:!0,[$.VISIBILITY_SET]:!0,[$.FILTER_SET]:!0,[$.SORT_SET]:!0,[$.SIR_SYNC]:!0,[$.ACTIVITY_LOOKAHEAD_SYNC]:!0},jd=Object.keys(vg);var Hd={CHILD:"child",CHILD_CONFIRMED:"child-confirmed",LINE:"line",ROOT:"root"};return qd(Ag);})();
|
|
1
|
+
"use strict";var ScheduleCore=(()=>{var gn=Object.defineProperty;var Yd=Object.getOwnPropertyDescriptor;var Kd=Object.getOwnPropertyNames;var Gd=Object.prototype.hasOwnProperty;var $d=(e,t)=>{for(var r in t)gn(e,r,{get:t[r],enumerable:!0})},zd=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Kd(t))!Gd.call(e,i)&&i!==r&&gn(e,i,{get:()=>t[i],enumerable:!(n=Yd(t,i))||n.enumerable});return e};var qd=e=>zd(gn({},"__esModule",{value:!0}),e);var vg={};$d(vg,{ACTIVITY_TYPE:()=>ar,CALENDAR_UNIT:()=>ot,COLUMN:()=>E,CONSTRAINT_TYPE:()=>K,CONSTRAINT_TYPE_TO_LABEL:()=>Bd,CREATION_KIND:()=>Hd,DEFAULT_HOURS_PER_DAY:()=>Ud,DISPATCH_ACTION_KIND:()=>$,DISPATCH_ACTION_KINDS:()=>jd,DISPATCH_TRACK_EVENT:()=>At,LINK_CODE_TO_TYPE:()=>Jt,LINK_TYPE:()=>M,LINK_TYPE_CODE:()=>Ps,NEW_ACTIVITY_DEFAULTS:()=>jr,REJECTION_REASON:()=>D,ROOT_PARENT_ID:()=>F,SCHEDULE_CORE_STATUS:()=>It,STATUS:()=>_t,ScheduleCore:()=>hn,WORK_TIME_DIRECTION:()=>J,checkNoUpdatedLinks:()=>Zl,computeExpectedProgress:()=>Vn,expectedProgressFromBaseline:()=>Ie,getActiveBaseline:()=>ut,getUnsavedActivities:()=>Wd,isRootParent:()=>L,normalizeParentKey:()=>Mt,parseFromBackend:()=>on,willRunCriticalPath:()=>Ol,yieldToBrowser:()=>Z});var ft=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 Qe=e=>String(e);function Qi(e){let{clickedId:t,isChecked:r,currentSelection:n,hierarchy:i,isFrozen:a,exists:s,autoCheckParents:o}=e,c=Qe(t),l=new Set([...n].map(String)),d=new Set(l),u=Jd(c,i).filter(s),f=u.filter(m=>!a(m)),p=r&&f.length<u.length;r&&!p?d.add(c):d.delete(c);for(let m of f)r?d.add(m):d.delete(m);return p||Xd({id:c,isChecked:r,autoCheckParents:o,hierarchy:i,isFrozen:a,exists:s,next:d}),{nextSelection:d,changed:Zd(l,d),parentBlocked:p}}function Jd(e,t){let r=[],n=new ft;n.enqueue(e);let i=new Set([e]);for(;!n.isEmpty();){let a=n.dequeue();for(let s of t.getChildrenIds(a)){let o=Qe(s);i.has(o)||(i.add(o),r.push(o),n.enqueue(o))}}return r}function Xd(e){let{id:t,isChecked:r,autoCheckParents:n,hierarchy:i,isFrozen:a,exists:s,next:o}=e,c=i.getParentId(t);for(;c!==null&&typeof c<"u";){let l=Qe(c);if(a(l))return;let d=i.getChildrenIds(l).map(Qe).filter(s),u=d.some(a),f=d.filter(I=>!a(I)),m=f.length>0&&f.every(I=>o.has(I))&&!u;if(r){if(!n||!m||o.has(l))return;o.add(l)}else{if(m||!o.has(l))return;o.delete(l)}c=i.getParentId(l)}}function Zd(e,t){let r=[],n=[];for(let i of t)e.has(i)||r.push(i);for(let i of e)t.has(i)||n.push(i);return{checked:r,unchecked:n}}function oe(e){return(e.pendingRequestIds?.length??0)>0}var D={CANNOT_EDIT:"cannot_edit",PARSE_ERROR:"parse_error",INVALID:"invalid",CUSTOM_ID_DUPLICATE:"custom_id_duplicate",INVALID_LINK_TYPE:"invalid_link_type",INVALID_LINK_LAG:"invalid_link_lag",INVALID_VALUE:"invalid_value",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 ta=(e,t)=>{let r=e.getActivity(t);return r!=null&&oe(r)},ea=(e,t,r)=>{let n=[],i=(a,s)=>{let o=t.isChecked(a);t.setChecked(a,s)&&n.push({activityId:a,checked:{before:o,after:s}})};for(let a of r.checked)i(a,!0);for(let a of r.unchecked)i(a,!1);return{source:e,activities:[],links:[],calendars:[],trackingEvents:[],viewState:n}};function ra(e,t){let{adapter:r}=t,n=e.activityId;if(!r.getActivity(n))return{ok:!1,reason:D.ACTIVITY_NOT_FOUND};let i=e.frozenIds?new Set(e.frozenIds):null,a=i?o=>i.has(o):o=>ta(r,o),s=Qi({clickedId:n,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:ea(e,r,s.changed)}}function na(e,t){let{adapter:r}=t,n=new Set(e.activityIds.map(String).filter(s=>r.activityExists(s)).filter(s=>!ta(r,s))),i=new Set(r.checkedIds().map(String)),a={checked:[...n].filter(s=>!i.has(s)),unchecked:[...i].filter(s=>!n.has(s))};return{ok:!0,changes:ea(e,r,a)}}function zt(e,t,r=e.getAllIds()){let n=[];for(let i of r){let a=String(i),s=t.has(a),o=e.isVisible(a);o!==s&&(e.setVisible(a,s),n.push({activityId:a,visible:{before:o,after:s}}))}return n}function ia(e,t){let{adapter:r}=t,n=new Set(e.visibleIds.map(String)),i=zt(r,n);return{ok:!0,changes:{source:e,activities:[],links:[],calendars:[],trackingEvents:[],viewState:i}}}var Qd=["Waiting","Done","Doing","Overdue","Advancement"],tu=["mfo","mso","snlt","snet","alap","asap","fnet","fnlt"];function vn(e,t){return e===null||t<=0?null:e/t}function eu(e,t){let r=t.getTime()-e.getTime();return Math.floor(r/864e5)+1}var ru={name:{valueKind:"string",extract:e=>e.name},description:{valueKind:"string",extract:e=>e.description},customId:{valueKind:"string",extract:e=>e.customId},correlativeId:{valueKind:"number",extract:e=>e.correlativeId},uniqueCorrelativeId:{valueKind:"number",extract:e=>Number(e.uniqueCorrelativeId)},progress:{valueKind:"number",extract:e=>e.progress},durationDays:{valueKind:"number",extract:(e,t)=>vn(e.durationHours,t.hoursPerDay)},calendarDuration:{valueKind:"number",extract:e=>eu(e.startDate,e.endDate)},cost:{valueKind:"number",extract:e=>e.cost},usedCost:{valueKind:"number",extract:e=>e.usedCost},realCost:{valueKind:"number",extract:e=>e.realCost},workHours:{valueKind:"number",extract:e=>e.workHours},realWorkHours:{valueKind:"number",extract:e=>e.realWorkHours},ponderator:{valueKind:"number",extract:e=>e.ponderator},freeSlackDays:{valueKind:"number",extract:(e,t)=>vn(e.freeSlackHours,t.hoursPerDay)},totalSlackDays:{valueKind:"number",extract:(e,t)=>vn(e.criticalPath?.totalSlackHours??null,t.hoursPerDay)},expectedProgressBaseline:{valueKind:"number",extract:e=>e.expectedProgressBaseline},baselineDurationDays:{valueKind:"number",extract:e=>e.baselineSnapshot?.durationDays??null},baselineCost:{valueKind:"number",extract:e=>e.baselineSnapshot?.cost??null},baselineWorkHours:{valueKind:"number",extract:e=>e.baselineSnapshot?.workHours??null},startDate:{valueKind:"date",extract:e=>e.startDate},endDate:{valueKind:"date",extract:e=>e.endDate},constraintDate:{valueKind:"date",extract:e=>e.constraintDate},baselineStartDate:{valueKind:"date",extract:e=>e.baselineSnapshot?.startDate??null},baselineEndDate:{valueKind:"date",extract:e=>e.baselineSnapshot?.endDate??null},earlyStart:{valueKind:"date",extract:e=>e.criticalPath?.earlyStart??null},earlyFinish:{valueKind:"date",extract:e=>e.criticalPath?.earlyFinish??null},lateStart:{valueKind:"date",extract:e=>e.criticalPath?.lateStart??null},lateFinish:{valueKind:"date",extract:e=>e.criticalPath?.lateFinish??null},responsableIds:{valueKind:"id-array",extract:e=>e.responsableIds},tagIds:{valueKind:"id-array",extract:e=>e.tagIds},status:{valueKind:"enum",order:Qd,extract:e=>e.status},constraintType:{valueKind:"enum",order:tu,extract:e=>e.constraintType},calendarId:{valueKind:"reference",extract:e=>e.calendarId===null?null:String(e.calendarId)},subcontractId:{valueKind:"reference",extract:e=>e.subcontractId===null?null:String(e.subcontractId)},isCritical:{valueKind:"boolean",extract:e=>e.isCritical}};function Nt(e){return ru[e]??null}function nu(e){return e instanceof Date?e:typeof e=="string"||typeof e=="number"?new Date(e):new Date(Number.NaN)}function iu(e,t,r){let n=e===null;return r==="includes"?!n&&String(e).toLowerCase().includes(t.toLowerCase()):r==="notIncludes"?n||!String(e).toLowerCase().includes(t.toLowerCase()):r==="is"?!n&&String(e)===t:r==="isNot"?n||String(e)!==t:!1}function au(e,t,r){return e===null||typeof e!="number"?r==="notEquals":r==="equals"?e===t:r==="notEquals"?e!==t:r==="greaterThan"?e>t:r==="lessThan"?e<t:r==="greaterOrEqual"?e>=t:r==="lessOrEqual"?e<=t:!1}function su(e,t,r){return e instanceof Date?r==="after"?e.getTime()>t.getTime():r==="before"?e.getTime()<t.getTime():!1:!1}function ou(e,t,r){let i=(Array.isArray(e)?e:[]).some(a=>t.has(String(a)));return r==="someOf"?i:r==="notSomeOf"?!i:!1}function cu(e,t,r){let n=e!==null&&t.has(String(e));return r==="someOf"?n:r==="notSomeOf"?!n:!1}function aa(e){let t=Array.isArray(e)?e:[e];return new Set(t.map(r=>String(r)))}function sa(e,t,r){let n=Nt(t.field);if(n===null)return!1;let i=n.extract(e,r),{operator:a}=t;return n.valueKind==="string"?iu(i,String(t.value),a):n.valueKind==="number"?au(i,Number(t.value),a):n.valueKind==="date"?su(i,nu(t.value),a):n.valueKind==="id-array"?ou(i,aa(t.value),a):cu(i,aa(t.value),a)}function lu(e,t,r){return t.criteria.length===0?!0:t.logic==="or"?t.criteria.some(n=>sa(e,n,r)):t.criteria.every(n=>sa(e,n,r))}function du(e,t){let r=e.startDate.getTime(),n=e.endDate.getTime(),i=t.start.getTime(),a=t.end.getTime(),s=r>=i&&n<=a,o=r>=i&&r<=a,c=i>=r&&i<=n;return s||o||c}function An(e,t,r){let n=lu(e,t,r),i=t.dateRange,a=i===void 0||du(e,i);return n&&a}function uu(e,t,r){let n=t(e);for(;n!==null&&!r.has(String(n));)r.add(String(n)),n=t(n)}function oa(e){let{activities:t,parentOf:r,filter:n,context:i}=e,a=new Set,s=[];for(let o of t)An(o,n,i)&&(a.add(String(o.id)),s.push(o.id));for(let o of s)uu(o,r,a);return a}function fu(e){let{activities:t,parentOf:r,filter:n,context:i}=e,a=new Set,s=new Set,o=new Map,c=new Map,l=new Map;for(let d of t){let u=String(d.id),f=r(u);c.set(u,f),l.set(u,l.get(u)??0),f!==null&&l.set(f,(l.get(f)??0)+1);let p=An(d,n,i),m=e.pinnedVisibleIds?.has(u)===!0;o.set(u,(p?1:0)+(m?1:0)),p&&a.add(u),m&&s.add(u)}return{matchedIds:a,pinnedVisibleIds:s,visibleReferenceCounts:o,parentIds:c,remainingChildren:l}}function pu(e){let{visibleReferenceCounts:t,parentIds:r,remainingChildren:n}=e,i=[];for(let a of r.keys())n.get(a)===0&&i.push(a);for(;i.length>0;){let a=i.pop();if(a===void 0)break;let s=r.get(a);if(s==null)continue;let o=t.get(a)??0;t.set(s,(t.get(s)??0)+o);let c=(n.get(s)??1)-1;n.set(s,c),c===0&&i.push(s)}}function hu(e){let t=new Set;for(let[r,n]of e)n>0&&t.add(r);return t}function tr(e){let t=fu(e);pu(t);let r=hu(t.visibleReferenceCounts);return{filter:e.filter,context:e.context,matchedIds:t.matchedIds,pinnedVisibleIds:t.pinnedVisibleIds,visibleIds:r,visibleReferenceCounts:t.visibleReferenceCounts}}function ca(e,t,r){let n=new Set;for(let i of t){let a=String(i.id);n.add(a);let s=e.matchedIds.has(a),o=An(i,e.filter,e.context);if(s===o)continue;o?e.matchedIds.add(a):e.matchedIds.delete(a);let c=o?1:-1,l=a;for(;l!==null;){let d=e.visibleReferenceCounts.get(l)??0,u=d+c;e.visibleReferenceCounts.set(l,u);let f=d>0,p=u>0;f!==p&&(n.add(l),p?e.visibleIds.add(l):e.visibleIds.delete(l)),l=r(l)}}return n}function qt(e){return{hoursPerDay:e,locale:"en"}}var yu={string:new Set(["includes","notIncludes","is","isNot"]),number:new Set(["equals","notEquals","greaterThan","lessThan","greaterOrEqual","lessOrEqual"]),date:new Set(["after","before"]),"id-array":new Set(["someOf","notSomeOf"]),enum:new Set(["someOf","notSomeOf"]),boolean:new Set(["someOf","notSomeOf"]),reference:new Set(["someOf","notSomeOf"])};function la(e){let t=Nt(e.field);return t===null?"unknown_field":yu[t.valueKind].has(e.operator)?mu(e,t.valueKind):"unknown_operator"}function mu(e,t){let{value:r}=e;return t==="id-array"||t==="enum"?Array.isArray(r)?null:"invalid_value":Array.isArray(r)?"invalid_value":t==="number"?Number.isFinite(Number(r))?null:"invalid_value":t==="date"?gu(r)?null:"invalid_value":null}function gu(e){return e instanceof Date?!0:typeof e=="string"||typeof e=="number"?!Number.isNaN(new Date(e).getTime()):!1}function da(e){return e.criteria.length===0&&e.dateRange===void 0}function vu(e,t,r){let n=e.getAllActivities();if(da(t))return{visibleIds:oa({activities:n,parentOf:a=>e.getParentId(a),filter:t,context:qt(r)}),projection:null};let i=tr({activities:n,parentOf:a=>e.getParentId(a),filter:t,context:qt(r)});return{visibleIds:i.visibleIds,projection:i}}function ua(e,t){let{adapter:r,hoursPerDay:n}=t;for(let l of e.criteria){let d=la(l);if(d!==null)return{ok:!1,reason:d}}let i=e.dateRange===void 0?{criteria:e.criteria,logic:e.logic}:{criteria:e.criteria,logic:e.logic,dateRange:e.dateRange};r.setActiveFilter(da(i)?null:i);let{visibleIds:a,projection:s}=vu(r,i,n);r.setFilterProjection(s);let o=zt(r,a);return{ok:!0,changes:{source:e,activities:[],links:[],calendars:[],trackingEvents:[],viewState:o}}}var F="0";function L(e){return e==null||e===0||e==="0"}function Mt(e){return L(e)?"0":String(e)}var Cn=Number.MAX_SAFE_INTEGER;function mt(e,t){let r=we(e,t),n=t.getOrderComparator?.()??null;return r.sort(n===null?er:(i,a)=>n(i,a)||er(i,a)),r.map(i=>String(i.id))}function pa(e){let t=[],r=i=>{t.push(i);let a=mt(String(i.id),e);for(let s of a){let o=e.getActivity(s);o&&r(o)}},n=mt("0",e);for(let i of n){let a=e.getActivity(i);a&&r(a)}return t}function ha(e,t,r){let n=r.getActivity(e);if(!n)return null;let i=ya(n),a=mt(i,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&&!Au(t,c))return c}return null}function In(e,t){let r=t.getActivity(e);if(!r)return-1;let n=ya(r);return mt(n,t).findIndex(a=>String(a)===String(e))}function we(e,t){let r=String(e)==="0"?t.getRootIds?.()??t.getChildren("0"):t.getChildren(e),n=[];for(let i of r){let a=t.getActivity(i);a&&n.push(a)}return n}function er(e,t){let r=fa(e),n=fa(t);return r!==n?r-n:String(e.id).localeCompare(String(t.id))}function fa(e){let t=e.correlativeId,r=typeof t=="number"?t:Number(t);return Number.isFinite(r)?r:Cn}function ya(e){let t=e.parentId;return t===null?"0":t}function Au(e,t){return e.has(t)?!0:e.has(String(t))}function Oe(e){let t=[],r=n=>{let i=mt(n,e);i.length>1&&t.push({parentId:n,childIds:i});for(let a of i)r(a)};return r("0"),t}function Sn(e,t){let r=[];for(let n of t){let i=mt(n,e);i.length>1&&r.push({parentId:n,childIds:i})}return r}function Cu(e){return Nt(e.field)===null?"unknown_field":e.direction!=="asc"&&e.direction!=="desc"?"unknown_operator":null}function ma(e,t){let{adapter:r}=t;for(let a of e.rules){let s=Cu(a);if(s!==null)return{ok:!1,reason:s}}let n=e.rules.length===0?null:{rules:e.rules};return r.setActiveOrder(n),{ok:!0,changes:{source:e,activities:[],links:[],calendars:[],trackingEvents:[],order:Oe(r)}}}var ga="text";var va="description";var Aa="duration";var Ca="progress";var Ia="cost";var Sa="used_cost";var ka="hhWorkTime";var Da="start_date";var Ta="end_date";var _a="constraint_type";var Pa="constraint_date";var Ea="calendar_id";var Ra="custom_id";var ba="subcontractId";var La="responsables";var wa="tags";var Oa="custom_predecessors";var xa="custom_sucessors";var Fa="real_work";var Na="real_cost";var Ma="expected_progress";var Wa="expected_progress_base";var Ba="start_base";var Ua="end_base";var ja="duration_base";var Ha="cost_base";var Va="work_base";var Ya="calendarDuration";var Ka="is_critical",Ga="earlyStart",$a="earlyFinish",za="lateStart",qa="lateFinish",Ja="freeSlack",Xa="totalSlack";var Za="correlative_id";var Qa="unique_correlative_id";var ts="ponderator";var J={FUTURE:"future",PAST:"past"},ot={HOUR:"hour",DAY:"day"},_t={DONE:"Done",OVERDUE:"Overdue",ADVANCEMENT:"Advancement",WAITING:"Waiting",DOING:"Doing"};var rr="status";var kn="Baseline";function nr(e){return e==="Actual"?"Actual":kn}var Iu={TEXT:ga,DESCRIPTION:va,DURATION:Aa,PROGRESS:Ca,COST:Ia,USED_COST:Sa,HH_WORK_TIME:ka,START_DATE:Da,END_DATE:Ta,CONSTRAINT_TYPE:_a,CONSTRAINT_DATE:Pa,CALENDAR_ID:Ea,CUSTOM_ID:Ra,SUBCONTRACT_ID:ba,RESPONSABLES:La,TAGS:wa,CUSTOM_PREDECESSORS:Oa,CUSTOM_SUCESSORS:xa},Su={REAL_WORK:Fa,REAL_COST:Na,EXPECTED_PROGRESS:Ma,EXPECTED_PROGRESS_BASE:Wa,START_BASE:Ba,END_BASE:Ua,DURATION_BASE:ja,COST_BASE:Ha,WORK_BASE:Va,CALENDAR_DURATION:Ya,IS_CRITICAL:Ka,EARLY_START:Ga,EARLY_FINISH:$a,LATE_START:za,LATE_FINISH:qa,FREE_SLACK:Ja,TOTAL_SLACK:Xa,CORRELATIVE_ID:Za,UNIQUE_CORRELATIVE_ID:Qa,PONDERATOR:ts,STATUS:rr},E={...Iu,...Su};function es(e,t){throw new Error(t)}function rs(e,t){return()=>t()===e}var K={ASAP:"asap",ALAP:"alap",SNET:"snet",SNLT:"snlt",FNET:"fnet",FNLT:"fnlt",MSO:"mso",MFO:"mfo"},ku={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 is(e,t,r){if(!t)return{violated:!1};let n=ku[e];return n?n(t,r)?{violated:!0,constraintType:e,constraintDate:t}:{violated:!1}:{violated:!1}}var Du=new Set(["mso","snet","snlt"]);function xe(e,t,r){return Du.has(e)?t:r}function as(e,t,r){return{type:"constraint",messageKey:"constraint_violation",data:{constraintType:e,constraintDate:t,...r?{projectedDate:r}:{}}}}var Tu={snet:{startOfDay:!0,direction:J.FUTURE},snlt:{startOfDay:!0,direction:J.PAST},fnet:{startOfDay:!1,direction:J.FUTURE},fnlt:{startOfDay:!1,direction:J.PAST},mso:{startOfDay:!0,direction:J.FUTURE},mfo:{startOfDay:!1,direction:J.PAST}},ir=e=>new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate())),ns=(e,t)=>new Date(e.getTime()+t*864e5),_u=(e,t)=>e.getUTCFullYear()===t.getUTCFullYear()&&e.getUTCMonth()===t.getUTCMonth()&&e.getUTCDate()===t.getUTCDate();function Dn(e,t){if(!e.constraintDate||!e.constraintType)return null;let r=Tu[e.constraintType];if(!r)return e.constraintDate;let n=e.constraintDate,i=t.getClosestWorkTime({date:ir(n),dir:J.FUTURE,task:e});if(_u(i,n))return n.getTime()!==ir(n).getTime()?n:r.startOfDay?i:t.getClosestWorkTime({date:ns(ir(n),1),dir:J.PAST,task:e});let a=ir(t.getClosestWorkTime({date:n,dir:r.direction,task:e}));return r.startOfDay?t.getClosestWorkTime({date:a,dir:J.FUTURE,task:e}):t.getClosestWorkTime({date:ns(a,1),dir:J.PAST,task:e})}function ss(e,t){let r={earliestStart:null,latestStart:null,earliestEnd:null,latestEnd:null},n=e.constraintType;if(!n||n==="asap"||n==="alap")return r;let i=Dn(e,t);if(!i)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(n){case"snet":return{earliestStart:i,latestStart:null,earliestEnd:a(i),latestEnd:null};case"snlt":return{earliestStart:null,latestStart:i,earliestEnd:null,latestEnd:a(i)};case"fnet":return{earliestStart:s(i),latestStart:null,earliestEnd:i,latestEnd:null};case"fnlt":return{earliestStart:null,latestStart:s(i),earliestEnd:null,latestEnd:i};case"mso":{let o=a(i);return{earliestStart:i,latestStart:i,earliestEnd:o,latestEnd:o}}case"mfo":{let o=s(i);return{earliestStart:o,latestStart:o,earliestEnd:i,latestEnd:i}}default:return r}}function os(e,t){return!(t.earliestStart&&e<t.earliestStart||t.latestStart&&e>t.latestStart)}function Tn(e,t){return t.latestStart&&e>t.latestStart?t.latestStart:t.earliestStart&&e<t.earliestStart?t.earliestStart:e}var M={FINISH_TO_START:"0",START_TO_START:"1",FINISH_TO_FINISH:"2",START_TO_FINISH:"3"};var ar={TASK:"task",PROJECT:"project",MILESTONE:"milestone"},cs={ALAP_DEBOUNCE_MS:1e3,CRITICAL_PATH_DEBOUNCE_MS:1e3,YIELD_SLICE_MS:8};var _n=typeof window>"u",Pu=!_n&&typeof MessageChannel<"u";function Z(){return Pu?new Promise(e=>{let t=new MessageChannel;t.port1.onmessage=()=>{t.port1.close(),t.port2.close(),e()},t.port2.postMessage(null)}):Promise.resolve()}async function sr(e,t){return performance.now()-e<cs.YIELD_SLICE_MS?{aborted:!1,newSliceStart:e}:(await Z(),t()?{aborted:!1,newSliceStart:performance.now()}:{aborted:!0,newSliceStart:performance.now()})}async function ce(e){return _n||await Z(),e()?{aborted:!1}:{aborted:!0}}function or(e,t){let{inDegree:r,successors:n}=Eu(e,t),i=Ru(r),a=bu(i,r,n),s=a.length<e.length,o=s?Lu(e,a):[],c=[...a].reverse();return{ordered:a,reversed:c,hasCycles:s,cycleNodes:o}}function Eu(e,t){let r=new Map,n=new Map;for(let i of e)r.set(i,0),n.set(i,[]);for(let i of t){let a=i.source,s=i.target;!r.has(a)||!r.has(s)||(n.get(a).push(s),r.set(s,(r.get(s)??0)+1))}return{inDegree:r,successors:n}}function Ru(e){let t=new ft;for(let[r,n]of e)n===0&&t.enqueue(r);return t}function bu(e,t,r){let n=[];for(;!e.isEmpty();){let i=e.dequeue();n.push(i);for(let a of r.get(i)??[]){let s=(t.get(a)??1)-1;t.set(a,s),s===0&&e.enqueue(a)}}return n}function Lu(e,t){let r=new Set(t);return e.filter(n=>!r.has(n))}var cr=class{cached=null;invalidate(){this.cached=null}get(t,r){return this.cached?this.cached:(this.cached=or(t,r),this.cached)}};function ls(e,t){let r=[];for(let n of e)t.has(n)&&r.push(n);return r}var Pn={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 En(e){return e==="project"||e==="task"||e==="milestone"}function Rt(e,t){return t||En(e)&&Pn[e].alwaysSummary}function bt(e){return e==="milestone"}function Wt(e){return En(e)&&Pn[e].promotesToProjectOnFirstChild}var Rn="project",le="task";function Fe(e,t){return t===0?"milestone":e===0&&t>0?"task":null}function ds(e,t){let r=t.getActivity(e);return r?Rt(r.type,t.getChildren(e).length>0):!1}function us(e,t,r){let n=String(t),i=r.getActivity(e);for(;i?.parentId&&String(i.parentId)!=="0";){if(String(i.parentId)===n)return!0;i=r.getActivity(i.parentId)}return!1}function hs(e,t){let r=[],n=[e];for(;n.length>0;){let i=n.pop(),a=t.getChildren(i);if(a.length===0){String(i)!==String(e)&&r.push(i);continue}for(let s of a)n.push(s)}return r}function wu(e){let t=new Map;for(let r of e)fs(t,String(r.source),r),fs(t,String(r.target),r);return t}function fs(e,t,r){let n=e.get(t);if(n){n.push(r);return}e.set(t,[r])}function Ou(e,t,r,n){if(e.length<=1)return e;let i=new Set(e.map(String)),a=[];for(let s of e)xu(s,i,t,r,n)||a.push(s);return a.length>0?a:e}function xu(e,t,r,n,i){let a=String(e),s=r.getActivity(e);if(!s||s.autoScheduling===!1)return!1;let o=n.get(a)??[];for(let c of o)if(Fu(c,a,s,t,r,i))return!0;return!1}function Fu(e,t,r,n,i,a){if(Nu(e)||!(a?String(e.source)===t:String(e.target)===t))return!1;let o=Mu(e,t);if(!n.has(String(o)))return!1;let c=i.getActivity(o);return!!(c?.autoScheduling!==!1&&c&&Wu(e,r,c))}function Nu(e){return e.source===e.target}function Mu(e,t){return String(e.source)===t?e.target:e.source}function Wu(e,t,r){let n=e.lag??0,i=Math.abs(n);return String(e.target)===String(r.id)&&i<=r.durationHours||String(e.target)===String(t.id)&&i<=t.durationHours}function ys(e,t){let r=[],n=wu(e),i=0;for(let a of e){let s=ds(a.source,t),o=ds(a.target,t);if(Bu(a,s,o,t))continue;if(!s&&!o){r.push(a);continue}let c=ps(a.source,s,t,n,!0),l=ps(a.target,o,t,n,!1);i=Gu(r,c,l,a,t,i,n)}return r}function Bu(e,t,r,n){return r&&us(e.source,e.target,n)||t&&us(e.target,e.source,n)}function ps(e,t,r,n,i){return t?Ou(hs(e,r),r,n,i):[e]}function Uu(e,t,r){let n=hs(e,t);if(n.length===0)return null;let i=null,a=null;for(let s of n){let o=r(s);if(!o)continue;(i===null||o.startDate<i)&&(i=o.startDate),(a===null||o.endDate>a)&&(a=o.endDate)}return i===null||a===null?null:{startDate:i,endDate:a}}function lr(e,t){return Uu(e,t,r=>{let n=t.getActivity(r);return n?{startDate:n.startDate,endDate:n.endDate}:null})}function ju(e,t,r){return e?t?r.calculateDuration({startDate:t.startDate,endDate:t.endDate,task:e}):e.durationHours:0}function Hu(e,t,r,n){if(!t)return 0;let i=n.getActivity(e);return!r||!i?-t.durationHours:-n.calculateDuration({startDate:r.startDate,endDate:i.endDate,task:t})}function Vu(e,t){let r=String(e);return(t.get(r)??[]).some(i=>String(i.target)===r)}function Yu(e,t,r,n,i){if(Vu(e,i))return 0;let a=n.getActivity(e);return!t||!a||!r?0:n.calculateDuration({startDate:t,endDate:a.startDate,task:r})}function Ku(e,t){let r=t.getActivity(e.source),n=t.getActivity(e.target),i=lr(e.source,t),a=lr(e.target,t),s=e.type===M.START_TO_START||e.type===M.START_TO_FINISH,o=e.type===M.FINISH_TO_FINISH||e.type===M.START_TO_FINISH;return{source:r,sourceBounds:i,targetStart:a?.startDate??n?.startDate,userLag:e.lag??0,sourceEndpointIsStart:s,targetLag:o?-ju(n,a,t):0,summarySourceId:e.type===M.START_TO_START&&i?e.source:void 0}}function Gu(e,t,r,n,i,a,s){let o=Ku(n,i),{source:c,sourceBounds:l,targetStart:d,userLag:u}=o,{sourceEndpointIsStart:f,targetLag:p,summarySourceId:m}=o,I=a;for(let C of t){let _=f?Hu(C,c,l,i):0;for(let S of r){if(String(C)===String(S))continue;let P=Yu(S,d,c,i,s);e.push($u(n,C,S,I,_,p,u+P,m,P!==0&&p===0?n.target:void 0)),I+=1}}return I}function $u(e,t,r,n,i,a,s,o,c){return{id:`virtual_${e.id}_${n}`,source:t,target:r,type:e.type,lag:e.lag,_sourceLag:i,_targetLag:a,_trueLag:s,...o===void 0?{}:{_summarySourceId:o},...c===void 0?{}:{_summaryTargetId:c}}}var dr=class{invalidate(){}get(t,r){return ys(t,r)}};function zu(e){let t=new Map,r=n=>(t.has(n)||t.set(n,new Set),t.get(n));for(let n of e)r(n.source).add(n.id),r(n.target).add(n.id);return{neighbors:t}}function qu(e,t,r){let n=new Set,i=new Map,a=new ft;for(a.enqueue(e);!a.isEmpty();){let s=a.dequeue(),o=String(s);if(n.has(o))continue;n.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}`;i.has(u)||i.set(u,d);let f=String(d.source)===o?d.target:d.source;n.has(String(f))||a.enqueue(f)}}return Array.from(i.values())}function ms(e,t){let r=new Map;for(let s of t)r.set(s.id,s);let n=zu(t),i=qu(e,r,n),a=new Set([String(e)]);for(let s of i)a.add(String(s.source)),a.add(String(s.target));return{activityIds:a,links:i}}function gs(e,t,r){let n=r.type===M.FINISH_TO_START,i=r.type===M.FINISH_TO_FINISH;if(r._targetLag!==void 0)return{sourceLag:r._sourceLag??0,targetLag:r._targetLag,trueLag:r._trueLag??r.lag??0,isFS:n,isFF:i,isZeroDurationCase:!1};let a=r.lag??0;switch(r.type){case M.FINISH_TO_START:return{sourceLag:0,targetLag:0,trueLag:a,isFS:n,isFF:i,isZeroDurationCase:!1};case M.START_TO_START:return{sourceLag:-e.durationHours,targetLag:0,trueLag:a,isFS:n,isFF:i,isZeroDurationCase:!1};case M.FINISH_TO_FINISH:return{sourceLag:0,targetLag:-t.durationHours,trueLag:a,isFS:n,isFF:i,isZeroDurationCase:!1};case M.START_TO_FINISH:return{sourceLag:-e.durationHours,targetLag:-t.durationHours,trueLag:a,isFS:n,isFF:i,isZeroDurationCase:!1};default:return{sourceLag:0,targetLag:0,trueLag:a,isFS:n,isFF:i,isZeroDurationCase:!1}}}function Ju(e,t,r){if(e._summarySourceId===void 0)return null;let n=r.getActivity(e._summarySourceId);if(!n)return null;let i=lr(e._summarySourceId,r);return i?-r.calculateDuration({startDate:i.startDate,endDate:t.endDate,task:n}):null}function Xu(e,t,r,n,i){let a=t.durationHours===0&&i;return{successorStart:n.getClosestWorkTime({date:e.endDate,dir:a?"past":"future",task:t}),link:r}}function vs(e,t,r,n){let{sourceLag:i,targetLag:a,trueLag:s,isFS:o,isFF:c}=gs(e,t,r),l=Ju(r,e,n)??i,d=l+a+s;if(!(t.durationHours===0?d!==0:l!==0||a!==0||s!==0))return Xu(e,t,r,n,o||c);let p=o?t:e,m=n.getClosestWorkTime({date:e.endDate,dir:"future",task:p});if(l!==0&&(m=n.calculateEndDate({startDate:m,durationHours:l,task:e})),a!==0&&(m=n.calculateEndDate({startDate:m,durationHours:a,task:t})),s!==0&&(m=n.calculateEndDate({startDate:m,durationHours:s,task:t})),t.durationHours===0){if(o||c)return{successorStart:n.getClosestWorkTime({date:m,dir:"past",task:t}),link:r};let I=new Date(Date.UTC(m.getUTCFullYear(),m.getUTCMonth(),m.getUTCDate()));return{successorStart:n.getClosestWorkTime({date:I,dir:"future",task:t}),link:r}}return{successorStart:n.getClosestWorkTime({date:m,dir:"future",task:t}),link:r}}function As(e,t,r,n){let{sourceLag:i,targetLag:a,trueLag:s}=gs(t,e,r),o=n.getClosestWorkTime({date:e.startDate,dir:"past",task:e});return s!==0&&(o=n.calculateEndDate({startDate:o,durationHours:-s,task:e})),a!==0&&(o=n.calculateEndDate({startDate:o,durationHours:-a,task:e})),i!==0&&(o=n.calculateEndDate({startDate:o,durationHours:-i,task:t})),o}function Cs(e,t,r){for(let n of e){let i=t.getActivity(n);if(!i)continue;let a=i.constraintType;if(!a||a===K.ASAP||a===K.ALAP)continue;let s=ss(i,t);!s.earliestStart&&!s.latestStart&&!s.earliestEnd&&!s.latestEnd||r.set(n,{activityId:n,startDate:i.startDate,endDate:i.endDate,drivingLinkId:null,kind:"asap",conflict:!1,earliestStart:s.earliestStart,latestStart:s.latestStart,earliestEnd:s.earliestEnd,latestEnd:s.latestEnd})}}function ur(e,t,r){let n={earliestStart:t.earliestStart??null,latestStart:t.latestStart??null,earliestEnd:t.earliestEnd??null,latestEnd:t.latestEnd??null},i=t.earliestSchedulingStart??t.latestSchedulingStart??null,a;i===null?a=Tn(e.startDate,n):os(i,n)?a=i:a=Tn(i,n),t.startDate=a,t.endDate=r.calculateEndDate({startDate:a,durationHours:e.durationHours,task:e})}function Is(e,t){if(!e||!t)return new Date;let{constraintType:r,constraintDate:n}=e;if(!r||!n)return t;switch(r){case K.MSO:case K.MFO:return new Date(n);case K.SNET:case K.FNET:return n>t?new Date(n):t;case K.SNLT:case K.FNLT:return n<t?new Date(n):t;default:return t}}function Zu(e,t){return t.length?t.some(r=>String(r)===String(e)):!1}function Ss(e,t,r){return bn(e.id,t,r)?{startDate:e.startDate,endDate:e.endDate}:{startDate:e.startDate,endDate:e.endDate}}function bn(e,t,r){return t.dragWithMultiple&&Zu(e,r)}async function Ds(e,t,r,n,i,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=n.draggedIds??[],d=performance.now();for(let u of e){let f=await sr(d,i);if(f.aborted)return a;d=f.newSliceStart;let p=r.getActivity(u);if(!p||!p.autoScheduling||p.progress===100||Qu(p,r))continue;let m=s.get(String(u))??[],I=null,C=null,_=!1;for(let v of m){let A=r.getActivity(v.source);if(!A)continue;let T=o(v.source),R=T.startDate.getTime()!==A.startDate.getTime()||T.endDate.getTime()!==A.endDate.getTime(),x={...A,startDate:T.startDate,endDate:T.endDate},O=Ss(x,c,l),V={...x,startDate:O.startDate,endDate:O.endDate},Y=bn(v.source,c,l)?{...v,lag:0}:v,it=vs(V,p,Y,r);(!I||it.successorStart>I)&&(I=it.successorStart,C=String(v.id),_=v._summaryTargetId!==void 0&&!R)}I!==null&&_&&I<p.startDate&&(I=new Date(p.startDate));let P=a.get(u),g=P?{...P}:{activityId:u,startDate:p.startDate,endDate:p.endDate,drivingLinkId:null,kind:"asap",conflict:!1},h=g.earliestStart||g.latestStart||g.earliestEnd||g.latestEnd;if(!(!I&&!h)){if(I){let v=I;p.type===ar.MILESTONE&&(v=Is(p,I)),g.drivingLinkId=C,g.startDate=v,g.endDate=r.calculateEndDate({startDate:v,durationHours:p.durationHours,task:p}),g.earliestSchedulingStart=v,g.earliestSchedulingEnd=g.endDate}else p.constraintType===K.MSO?g.earliestStart&&(g.startDate=g.earliestStart,g.endDate=g.earliestEnd??r.calculateEndDate({startDate:g.earliestStart,durationHours:p.durationHours,task:p})):p.constraintType===K.MFO&&g.latestStart&&(g.startDate=g.latestStart,g.endDate=g.latestEnd??r.calculateEndDate({startDate:g.latestStart,durationHours:p.durationHours,task:p}));ur(p,g,r),a.set(u,g)}}return a}function Qu(e,t){return Rt(e.type,t.getChildren(e.id).length>0)}async function Ts(e,t,r,n,i,a){let s=new Map(r),o=n.getAllActivities(),c=o.length,l=[];for(let C of o)C.constraintType===K.ALAP&&l.push(C.id);if(l.length===0)return s;let d=new Map,u=new Map;for(let C of t){let _=String(C.source);d.has(_)||d.set(_,[]),d.get(_).push(C);let S=String(C.target);u.has(S)||u.set(S,[]),u.get(S).push(C)}let f=C=>{let _=s.get(C);if(_)return{startDate:_.startDate,endDate:_.endDate};let S=n.getActivity(C);return S?{startDate:S.startDate,endDate:S.endDate}:{startDate:new Date,endDate:new Date}},p=C=>!C.parentId||L(C.parentId)?n.getProjectEnd():f(C.parentId).endDate,m=(C,_)=>{let S=C,P=0;for(;S&&!L(S)&&P++<c+1;){if(String(S)===String(_))return!0;let g=n.getActivity(S);if(!g||!g.parentId)break;S=g.parentId}return!1},I=performance.now();for(let C of e){let _=await sr(I,a);if(_.aborted)return s;I=_.newSliceStart;let S=n.getActivity(C);if(!S||S.constraintType!==K.ALAP||!S.autoScheduling||S.progress===100||Rt(S.type,n.getChildren(C).length>0))continue;let P=p(S);if(!P)continue;let g=P,h=null,v=!1,A=d.get(String(C))??[];for(let St of A){if((St.lag??0)<0)continue;let se=n.getActivity(St.target);if(!se||se.autoScheduling===!1)continue;let Zi=f(St.target),Vd={...se,startDate:Zi.startDate,endDate:Zi.endDate},Ze=As(Vd,S,St,n);Ze<g&&(g=Ze),(h===null||Ze<h)&&(h=Ze,v=S.parentId&&!L(S.parentId)?m(St.target,S.parentId):!1)}if(h!==null)if(v)g=h;else{let St=f(C).endDate,se=St.getTime()>P.getTime()?St:P;g=h<se?h:se}else g>P&&(g=P);let R=(u.get(String(C))??[]).some(St=>St.type===M.FINISH_TO_START||St.type===M.FINISH_TO_FINISH),x=new Date(Date.UTC(g.getUTCFullYear(),g.getUTCMonth(),g.getUTCDate())),O=()=>n.getClosestWorkTime({date:x,dir:"past",task:S}),V=n.getClosestWorkTime({date:g,dir:"future",task:S}).getTime()===g.getTime(),Y;S.durationHours===0&&h===null?Y=R&&V?O():n.getClosestWorkTime({date:g,dir:"past",task:S}):S.durationHours===0?R?Y=O():Y=n.getClosestWorkTime({date:g,dir:"future",task:S}):Y=n.getClosestWorkTime({date:g,dir:"future",task:S});let it=n.calculateEndDate({startDate:Y,durationHours:-S.durationHours,task:S}),Le=s.get(C),lt=Le?{...Le}:{activityId:C,startDate:it,endDate:Y,drivingLinkId:null,kind:"alap",conflict:!1};lt.startDate=it,lt.endDate=Y,lt.drivingLinkId=null,lt.kind="alap";let yn=lt.earliestSchedulingStart??null;lt.earliestSchedulingStart=null,lt.earliestSchedulingEnd=null;let mn=yn!==null&&yn.getTime()>it.getTime()?yn:it;lt.latestSchedulingStart=mn,lt.latestSchedulingEnd=mn===it?Y:n.calculateEndDate({startDate:mn,durationHours:S.durationHours,task:S}),ur(S,lt,n),s.set(C,lt)}return s}var de={warn(){},error(){}};function Ne(e,t){t.cancelled||t.updatedIds.length===0||e.batchUpdate(()=>{for(let r of t.updatedIds){let n=t.plans.get(r);if(!n)continue;let i=e.getLiveActivity(r);i&&(i.startDate=n.startDate,i.endDate=n.endDate,e.updateActivity(r))}})}function Ln(e,t){let r=String(t.source),n=String(t.target);if(r===n)return!0;let i=new Map;for(let a of e){let s=String(a.source),o=String(a.target),c=i.get(s)??[];c.push(o),i.set(s,c)}return tf(i,n,r)}function wn(e){let t=new Map,r=new Map;for(let a of e){let s=String(a.source),o=String(a.target),c=t.get(s)??[];c.push(o),t.set(s,c),r.set(s,r.get(s)??0),r.set(o,(r.get(o)??0)+1)}let n=new ft;for(let[a,s]of r)s===0&&n.enqueue(a);let i=0;for(;!n.isEmpty();){let a=n.dequeue();i+=1;for(let s of t.get(a)??[]){let o=r.get(s)-1;r.set(s,o),o===0&&n.enqueue(s)}}return i!==r.size}function tf(e,t,r){if(t===r)return!0;let n=new Set([t]),i=new ft;for(i.enqueue(t);!i.isEmpty();){let a=i.dequeue(),s=e.get(a)??[];for(let o of s){if(o===r)return!0;n.has(o)||(n.add(o),i.enqueue(o))}}return!1}function Pt(e,t){switch(e.kind){case"create":return ef(e,t);case"update":return rf(e,t);case"delete":return nf(e,t)}}function pr(e,t){if(e.length===0)return{applied:!0};let r=t.port.getAllLinks(),n=new Map,i=[];for(let o of r){let c=_s(o);n.has(c)||n.set(c,o.id),i.push({source:o.source,target:o.target})}let a=wn(i),s=null;for(let{operation:o,linkId:c}of e){if(String(o.source)===String(o.target)){s={applied:!1,rejected:"self-link"};break}if(!t.port.getActivity(o.source)||!t.port.getActivity(o.target)){s={applied:!1,rejected:"activity-missing"};break}let l=_s(o),d=n.get(l);if(d!==void 0){s={applied:!1,rejected:"duplicate",linkId:d};break}if(n.set(l,c),a&&Ln(i,{source:o.source,target:o.target}))return{applied:!1,rejected:"cycle"};i.push({source:o.source,target:o.target})}if(!a&&wn(i))return{applied:!1,rejected:"cycle"};if(s)return s;for(let{operation:o,linkId:c}of e){let l=t.preserved?.get(c);t.port.addLink({id:c,source:o.source,target:o.target,type:o.type,lag:o.lag,...l?.ganttId===void 0?{}:{ganttId:l.ganttId},...l?.sectorId===void 0?{}:{sectorId:l.sectorId},...l?.proplannerId===void 0?{}:{proplannerId:l.proplannerId}})}return{applied:!0}}function _s(e){return JSON.stringify([String(e.source),String(e.target),e.type])}function ef(e,t){let{port:r}=t;if(String(e.source)===String(e.target))return{applied:!1,rejected:"self-link"};let n=r.getActivity(e.source),i=r.getActivity(e.target);if(!n||!i)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(Ln(s,{source:e.source,target:e.target}))return{applied:!1,rejected:"cycle"};let o=(t.newLinkId??af)(),c={id:o,source:e.source,target:e.target,type:e.type,lag:e.lag};return r.addLink(c),{applied:!0,linkId:o}}function rf(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 nf(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 fr=null;function af(){return fr===null&&(fr=Date.now()),fr+=1,String(fr)}var Ps={[M.FINISH_TO_START]:"fs",[M.START_TO_START]:"ss",[M.FINISH_TO_FINISH]:"ff",[M.START_TO_FINISH]:"sf"},Jt={fs:M.FINISH_TO_START,ss:M.START_TO_START,ff:M.FINISH_TO_FINISH,sf:M.START_TO_FINISH},Es="fs";function Rs(e){if(e in Jt)return Jt[e]}var bs=";",Ls=/^(\d+)(fs|ss|ff|sf)?(?:([+-]?)(\d+(?:\.\d+)?)d?)?$/i;function hr(e){let t=[],r=[],n=e.replace(/\s+/g,"");if(n.length===0)return{specs:t,errors:r};for(let i of n.split(bs)){if(i.length===0)continue;let a=sf(i);a?t.push(a):r.push(i)}return{specs:t,errors:r}}function sf(e){let t=e.toLowerCase(),r=Ls.exec(t);if(!r)return null;let[,n,i,a,s]=r,o=i?Jt[i]:Jt[Es],c=0;if(s!==void 0){let l=Number(s);if(Number.isNaN(l))return null;c=a==="-"?-l:l}return{correlativeId:n,type:o,lag:c}}function mr(e){let{targetActivityId:t,currentLinks:r,desiredSpecs:n}=e,i=[],a=new Map;for(let c of n){let l=e.resolveActivityByCorrelative(c.correlativeId);if(l==null){i.push(c);continue}let d=yr(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(yr(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:i}}function yr(e,t){return`${String(e)}::${t}`}function gr(e){let{sourceActivityId:t,currentLinks:r,desiredSpecs:n}=e,i=[],a=new Map;for(let c of n){let l=e.resolveActivityByCorrelative(c.correlativeId);if(l==null){i.push(c);continue}let d=yr(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(yr(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:i}}function dt(e,t){return Math.sign(e)*Math.round(Math.abs(e)*t)}var ws={rawInputToConstraintDate(e,t){let r=new Date(e);return r.setUTCHours(0,0,0,0),r.getTime()===e.getTime()?t.getClosestWorkTime({direction:J.FUTURE,date:e,unit:ot.HOUR}):t.isWorkTime(e,ot.HOUR)?e:r},computeLagBetweenTasks(e,t,r){return r.calculateDuration(e,t)}};function On(e,t,r){switch(r){case"0":return{sourceDate:e.endDate,targetDate:t.startDate};case"1":return{sourceDate:e.startDate,targetDate:t.startDate};case"2":return{sourceDate:e.endDate,targetDate:t.endDate};case"3":return{sourceDate:e.startDate,targetDate:t.endDate}}}var xn=ws;var vr=class{adapter;reporter;currentCalculationId=0;topoCache=new cr;expandedLinksCache=new dr;constructor(t,r=de){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,n=rs(r,()=>this.currentCalculationId),i={plans:new Map,updatedIds:[],cycles:[],cancelled:!1};try{df(this.adapter);let a=Bt("schedule.total"),s=Bt("schedule.expandParentLinks"),o=this.adapter.getAllLinks(),c=this.expandedLinksCache.get(o,this.adapter);Lt(s);let l=c;if((await ce(n)).aborted)return{...i,cancelled:!0};let d=Bt("schedule.scoping"),u=this.adapter.getAllIds(),f=uf(t,l,this.adapter),p=f.links,m=f.idSet;Lt(d);let I=Bt("schedule.topologicalSort"),C=pf(this.topoCache,u,l,m);if(Lt(I),C.hasCycles)return Lt(a),{...i,cycles:[C.cycleNodes]};if((await ce(n)).aborted)return{...i,cancelled:!0};let _=Bt("schedule.processConstraints"),S=new Map;if(Cs(C.ordered,this.adapter,S),Lt(_),(await ce(n)).aborted)return{...i,cancelled:!0};let P=Bt("schedule.asapPass"),g=await Ds(C.ordered,p,this.adapter,t,n,S);if(Lt(P),(await ce(n)).aborted)return{...i,cancelled:!0};let h=Bt("schedule.alapPass"),v=await Ts(C.reversed,p,g,this.adapter,t,n);if(Lt(h),(await ce(n)).aborted)return{...i,cancelled:!0};let A=Bt("schedule.diff"),T=[];for(let[R,x]of v){let O=this.adapter.getActivity(R);if(!O)continue;let V=O.startDate.getTime()!==x.startDate.getTime(),Y=O.endDate.getTime()!==x.endDate.getTime();(V||Y)&&T.push(R)}return Lt(A),Lt(a),{plans:v,updatedIds:T,cycles:[],cancelled:!1}}catch(a){return this.reporter.error("[AutoScheduler] Error during scheduling",a),i}}},cf=!1;function lf(){let e=globalThis.__SCHEDULER_PHASE_LOG__;return typeof e=="boolean"?e:cf}function Bt(e){return{name:e,startedAt:performance.now()}}function df(e){let t=e;typeof t.clearCalendarCache=="function"&&t.clearCalendarCache()}function Lt(e){if(!lf())return;let t=performance.now()-e.startedAt;console.log(`[scheduler] ${e.name} ${t.toFixed(1)}ms`)}function uf(e,t,r){let n=e.triggerId;if(n==null)return{idSet:null,links:t};let i=ms(n,t);return ff(i,t,r)}function ff(e,t,r){let n=new Set(e.activityIds),i=new Set;for(let s of r.getAllActivities()){let o=String(s.id);s.constraintType===K.ALAP&&!n.has(o)&&(i.add(o),n.add(o))}if(i.size===0)return{idSet:n,links:e.links};let a=[...e.links];for(let s of t)(i.has(String(s.source))||i.has(String(s.target)))&&a.push(s);return{idSet:n,links:a}}function pf(e,t,r,n){let i=e.get(t,r);if(i.hasCycles){let s=n?Array.from(n):t;return or(s,r)}if(!n)return i;let a=ls(i.ordered,n);return{ordered:a,reversed:[...a].reverse(),hasCycles:!1,cycleNodes:[]}}function Os(e,t,r){let n=t.getActivity(e);if(!n)return;let i=r?{...n,endDate:r.endDate}:n,a=t.calendarReader.getCalendar(String(n.calendarId));for(let s of t.getIncomingLinkIds(e)){let o=t.getLink(s);if(!o)continue;let c=t.getActivity(o.source);if(!c||c.constraintType==="alap"||bt(n.type)&&(o.type===M.START_TO_FINISH||o.type===M.FINISH_TO_FINISH))continue;let{sourceDate:d,targetDate:u}=On(c,i,o.type),f=xn.computeLagBetweenTasks(d,u,a);f!==o.lag&&Pt({kind:"update",linkId:o.id,lag:f},{port:t})}}function xs(e,t){let r=t.getActivity(e);r&&bt(r.type)&&(r.durationHours=0)}function ue(e){let t=0,r=!1;for(let n of e)n.ponderator>0&&(t+=n.ponderator/100*n.progress,r=!0);return r?t:null}function Ar(e){return Number(e.toFixed(2))}function pt(e,t){return(Number(e)||0)*(Number(t)||0)/100}async function fe(e,t,r=!0,n={}){let i=t?Fn(e,t):vf(e),a=r?n.progressMode??"freeze-when-no-contribution":"skip";await hf(i,e,a,{recomputeRealWork:n.recomputeRealWork??!1})}function Cr(e,t){Fs(e,t,"skip")}async function hf(e,t,r,n={recomputeRealWork:!1}){let a=0;for(let s of e)Fs(s,t,r,n.recomputeRealWork),a+=1,a%200===0&&await Z()}function Fn(e,t){let r=new Set;for(let a of t)yf(a,e,r);if(r.size===0)return[];let n=Array.from(r),i=Ns(n,e);return Ms(n,i)}function yf(e,t,r){let n=t.getParentId(e);for(;n&&!L(n);){if(r.has(n))return;r.add(n),n=t.getParentId(n)}}function mf(e,t,r){let n=null,i=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();(n===null||l<n)&&(n=l),(i===null||d>i)&&(i=d),r&&(a+=gf(c,t.getChildren(o).length>0)),s.push({progress:Number(c.progress??0),ponderator:Number(c.ponderator??0)})}return{minStart:n,maxEnd:i,realWorkSum:a,weightedChildren:s}}function Fs(e,t,r="freeze-when-no-contribution",n=!1){let i=t.getActivity(e);if(!i)return;let a=t.getChildren(e);if(a.length===0)return;let s=mf(a,t,n);if(s.minStart===null||s.maxEnd===null)return;let o=String(i.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=ue(s.weightedChildren);r!=="skip"&&(f!==null||r==="zero-when-no-contribution")&&t.setActivityField(e,"progress",Ar(f??0)),n&&t.setActivityField(e,"realWorkHours",s.realWorkSum)}function gf(e,t){return t?Number(e.realWorkHours)||0:pt(e.workHours,e.progress)}function vf(e){let t=Af(e),r=Ns(t,e);return Ms(t,r)}function Af(e){let t=new Set;return e.forEachActivity(r=>{r.parentId!==null&&t.add(r.parentId)}),Array.from(t)}function Ns(e,t){let r=new Map;for(let n of e)r.set(n,Cf(n,t));return r}function Cf(e,t){let r=0,n=e;for(;n&&!L(n)&&t.getActivity(n);)r+=1,n=t.getParentId(n);return r}function Ms(e,t){return[...e].sort((r,n)=>(t.get(n)??0)-(t.get(r)??0))}var Ws={updateActivityDuration:xs,updateTaskTiming:Sf("updateTaskTiming"),adjustLinkLagOnTaskMove:Os,recordLastStartDate:If};function If(e,t){let r=t.getActivity(e);r&&t.setLastStartDate(e,r.startDate)}function Ut(e,t,r,n){for(let i of t){let a=i in Ws?Ws[i]:void 0;if(!a){console.warn(`[replay post-processors] unknown: ${i} \u2014 skipping. Add an entry in POST_PROCESSORS if a fixture needs it.`);continue}a(e,r,n??null)}}function Sf(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 U(){return{valid:!0}}function tt(e,t){return t!==void 0?{valid:!1,reason:e,notification:t}:{valid:!1,reason:e}}function j(){return{allowed:!0}}function z(e,t){return t!==void 0?{allowed:!1,reason:e,alertKey:t}:{allowed:!1,reason:e}}function W(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 Bs={targetField:"name",canEdit(){return j()},parseInput(e){return typeof e!="string"?N("not_a_string"):w(e)},validate(){return U()},transform(e,t){return W({name:t},{autoSchedule:!1,postProcessors:[]})},trackEvent:"activity_name_entry"};var Us={targetField:"description",canEdit(){return j()},parseInput(e){return typeof e!="string"?N("not_a_string"):w(e.trim())},validate(){return U()},transform(e,t){return W({description:t},{autoSchedule:!1,postProcessors:[]})},trackEvent:"activity_description_entry"};function kt(e){return e.constraintType??K.ASAP}var Ir=100;function pe(e){return e.progress>=Ir}function et(e,t){return Rt(e.type,t.hasChildren(e.id))}function js(e){return e.progress>0}function Hs(e){return e.hasLookaheadTasks}function Me(e,t){return Math.round(Math.ceil(e*t*60)/60)}var he=e=>({endDate:e});function Xt(e,t){if(t){let r=new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(e),n=i=>Number(r.find(a=>a.type===i)?.value);return new Date(Date.UTC(n("year"),n("month")-1,n("day")))}return new Date(Date.UTC(e.getFullYear(),e.getMonth(),e.getDate()))}function kr(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),n=f=>Number(r.find(p=>p.type===f)?.value),i=n("year"),a=n("month"),s=n("day"),o=Date.UTC(i,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 kf(e,t){let r=Xt(t);for(;!e.isWorkTime(r,ot.DAY);)r=new Date(r),r.setUTCDate(r.getUTCDate()+1),r=Xt(r);return r}function Nn(e,t){return e.getClosestWorkTime({direction:J.FUTURE,date:t,unit:ot.HOUR})}function Mn(e,t){let r=kf(e,t),n=new Date(r);return n.setUTCDate(n.getUTCDate()+1),n.setUTCHours(0,0,0,0),e.getClosestWorkTime({direction:J.PAST,date:n,unit:ot.HOUR})}var Sr=new Set(["snet","snlt","mso"]),Wn=new Set(["fnet","fnlt","mfo"]),jt=new Set(["asap","alap"]),Dr="snet";function wt(e,t,r){if(!Sr.has(r)&&!Wn.has(r))return e;let n=Sr.has(r)?Nn(t,e):Mn(t,e),i=new Date(e);return i.setUTCHours(n.getUTCHours(),n.getUTCMinutes(),n.getUTCSeconds(),n.getUTCMilliseconds()),i}var Ot=()=>({constraintType:Dr});var Ht=e=>({constraintDate:e}),Vs=e=>({constraintDate:e});var Ys={UPDATE_TASK_TIMING:"updateTaskTiming",ADJUST_LINK_LAG_ON_TASK_MOVE:"adjustLinkLagOnTaskMove",RECORD_LAST_START_DATE:"recordLastStartDate"};var Ks={UNCHANGED:"unchanged",OUT_OF_RANGE:"out_of_range",NEGATIVE_DURATION:"negative_duration",NOT_WORKING_DAY:"not_working_day",BEFORE_PARENT_START:"before_parent_start",BEFORE_START_DATE:"before_start_date",BEFORE_DATE_ORIGIN:"before_date_origin",CONSTRAINT_VIOLATION:"constraint_violation",MISSING_ID:"missing_id",UNKNOWN_CALENDAR:"unknown_calendar"};function ye(e,t,r){return is(e,t,r)}function me(e,t,r){return as(e,t,r)}var $s={targetField:"durationHours",canEdit(e,t){return pe(e)?z("completed","cant_edit_completed_activity"):et(e,t)?z("summary","summary_column_value"):j()},parseInput(e,t,r){let n=parseFloat(String(e));return Number.isNaN(n)?N("not_a_number"):w(r.inputUnit==="hours"?n:Me(n,r.hoursPerDay))},validate(e,t,r){return Gs(r)?tt(Ks.NEGATIVE_DURATION):Df(t,r)?tt("unchanged"):U()},transform(e,t,r){if(Gs(t))return W({},{autoSchedule:!1,postProcessors:[]});let n=Tf(e,t,r),i=_f(e,t,r,n.violated);return{...W(i,{autoSchedule:!0,postProcessors:[Ys.RECORD_LAST_START_DATE]}),...n.violated?{constraintWarning:me(n.constraintType,n.constraintDate,zs(e,t,r)??void 0)}:{}}},trackEvent:"activity_duration_entry"};function Gs(e){return Math.sign(e)===-1}function Df(e,t){return e===t}function Tf(e,t,r){let n=r.calendars.getCalendar(e.calendarId);if(!n)return{violated:!1};let i=e.constraintType;if(i!=="fnet"&&i!=="fnlt"&&i!=="mfo")return{violated:!1};let a=n.calculateEndDate(e.startDate,t);return ye(i,e.constraintDate,a)}function _f(e,t,r,n=!1){let i={};n&&Object.assign(i,Ot(),Ht(e.startDate));let a=Fe(e.durationHours,t);a&&(i.type=a),i.durationHours=t;let s=zs(e,t,r);return s&&Object.assign(i,he(s)),i}function zs(e,t,r){let n=r.calendars.getCalendar(e.calendarId);return n?n.calculateEndDate(e.startDate,t):null}var ge=e=>({realWorkHours:e});var Pf=0,Ef=Ir,qs=0,Js={targetField:"progress",canEdit(e,t){return Hs(e)?z("has_lookahead_tasks","cant_edit_actvity_with_task"):et(e,t)?z("summary","summary_column_value"):j()},parseInput(e){let t=parseFloat(String(e));return Number.isNaN(t)?N("not_a_number"):w(t)},validate(e,t,r){return Rf(r)?tt("out_of_range"):U()},transform(e,t,r){let n=bf(t),i=Lf(t),a=xf(e,t,r.hierarchy),s={progress:t,autoScheduling:n,...ge(a.get(e.id)??0)},o=i?wf(e,t,n,r.hierarchy,a):[],c=i?Nf(e,t,r.hierarchy):[],l=o.length+c.length>0?[...o,...c]:void 0,d=[],u=i?Wf(e,t):void 0;return W(s,{autoSchedule:!1,postProcessors:d,cascadeMutations:l,trackingEvents:u})},trackEvent:"activity_progress_entry"};function Rf(e){return e<Pf||e>Ef}function bf(e){return e===qs}function Lf(e){return e===Ir||e===qs}function wf(e,t,r,n,i){return n.getDescendantIds(e.id).map(s=>({activityId:s,fields:Of(t,r,i.get(s)??0)}))}function Of(e,t,r){return{progress:e,autoScheduling:t,...ge(r)}}function xf(e,t,r){let n=new Map,i=s=>{let o=0;for(let c of r.getChildHhInfo(s)){let l=r.hasChildren(c.id)?i(c.id):pt(c.workHours,t);n.set(c.id,l),o+=l}return o},a=r.hasChildren(e.id)?i(e.id):pt(e.workHours,t);return n.set(e.id,a),n}function Ff(e,t){let r=[e.id,...t.getDescendantIds(e.id)],n=a=>t.getChildProgressInfo(a).some(s=>t.hasChildren(s.id)),i=a=>t.getAncestorIds(a).length;return r.filter(a=>n(String(a))).map(String).sort((a,s)=>i(s)-i(a))}function Nf(e,t,r){let n=new Map;n.set(e.id,t);for(let s of r.getDescendantIds(e.id))n.set(s,t);let i=[...Ff(e,r),...r.getAncestorIds(e.id)],a=[];for(let s of i){let o=Mf(s,n,r);n.set(s,o),a.push({activityId:s,fields:{progress:o}})}return a}function Mf(e,t,r){let n=r.getChildProgressInfo(e).map(i=>({progress:t.has(i.id)?t.get(i.id):i.progress,ponderator:i.ponderator??0}));return Number((ue(n)??0).toFixed(2))}function Wf(e,t){return[{name:"activity_progress_update_radio_button",properties:{activity_id:e.id,activity_name:e.name,progress_updated:t}}]}var Xs={targetField:"cost",canEdit(e,t){return et(e,t)?z("summary","summary_column_value"):j()},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 U()},transform(e,t,r){let n=Bf(e,t,r.hierarchy);return W({cost:t},{autoSchedule:!1,postProcessors:[],cascadeMutations:n})},trackEvent:"activity_cost_budgeted_entry"};function Bf(e,t,r){let n=new Map;n.set(e.id,t);let i=[];for(let a of r.getAncestorIds(e.id)){let s=0;for(let o of r.getChildCostInfo(a))s+=n.has(o.id)?n.get(o.id):o.cost;n.set(a,s),i.push({activityId:a,fields:{cost:s}})}return i}var Zs={targetField:"usedCost",canEdit(e,t){return et(e,t)?z("summary","summary_column_value"):j()},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 U()},transform(e,t,r){let n=Uf(e,t,r.hierarchy);return W({usedCost:t},{autoSchedule:!1,postProcessors:[],cascadeMutations:n})},trackEvent:"activity_cost_spent_entry"};function Uf(e,t,r){let n=new Map;n.set(e.id,t);let i=[];for(let a of r.getAncestorIds(e.id)){let s=0;for(let o of r.getChildUsedCostInfo(a))s+=n.has(o.id)?n.get(o.id):o.usedCost;n.set(a,s),i.push({activityId:a,fields:{usedCost:s}})}return i}var Qs={targetField:"workHours",canEdit(e,t){return et(e,t)?z("summary","summary_column_value"):j()},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 U()},transform(e,t,r,n){let i=to(t,e.progress),a=String(n).trim()===""?[]:jf(e,t,i,r.hierarchy);return W({workHours:t,...ge(i)},{autoSchedule:!1,postProcessors:[],cascadeMutations:a})},trackEvent:"activity_labor_hours_budgeted_entry"};function to(e,t){return pt(e,t)}function jf(e,t,r,n){let i=new Map,a=new Map;i.set(e.id,t),a.set(e.id,r);let s=[];for(let o of n.getAncestorIds(e.id)){let c=0,l=0;for(let d of n.getChildHhInfo(o)){let u=i.has(d.id)?i.get(d.id):d.workHours,f=a.has(d.id)?a.get(d.id):d.realWorkHours??to(d.workHours,d.progress);c+=u,l+=f}i.set(o,c),a.set(o,l),s.push({activityId:o,fields:{workHours:c,...ge(l)}})}return s}function Tr(e,t){return e.getUTCFullYear()===t.getUTCFullYear()&&e.getUTCMonth()===t.getUTCMonth()&&e.getUTCDate()===t.getUTCDate()}function Bn(e,t){return e.getTime()<t.getTime()}function ve(e){return e instanceof Date&&!Number.isNaN(e.getTime())}var _r=e=>({durationHours:e});var eo={targetField:"startDate",canEdit(e,t){return et(e,t)?z("summary","summary_column_value"):js(e)?z("has_progress","cant_edit_activity_with_progress"):j()},parseInput(e,t,r){return ve(e)?w(Xt(e,"UTC")):N("invalid_date")},validate(e,t,r,n){if(Tr(t,r))return tt("unchanged");let i=Hf(e,r,n);return i||U()},transform(e,t,r){let n=r.calendars.getCalendar(e.calendarId);if(!n)return W({startDate:t,...Ot(),...Ht(t)},{autoSchedule:!0,postProcessors:["adjustLinkLagOnTaskMove"]});let i=Nn(n,t),a=e.type==="milestone",s=a?i:n.calculateEndDate(i,e.durationHours),o=i;return{...W({startDate:i,...he(s),...a?_r(0):{},...Ot(),...Ht(o)},{autoSchedule:!0,postProcessors:["adjustLinkLagOnTaskMove"]}),constraintWarning:Vf(e,i,n)}},trackEvent:"activity_start_date_entry"};function Hf(e,t,r){let n=r.hierarchy.getParentStartDateIfHasPredecessors(e.id);if(!n)return null;let i=Xt(n);return t.getTime()<i.getTime()?tt("before_parent_start"):null}function Vf(e,t,r){let n=r.calculateEndDate(t,e.durationHours),i=xe(kt(e),t,n),a=ye(kt(e),e.constraintDate,i);if(a.violated)return me(a.constraintType,a.constraintDate,i)}var Yf=99.999,no={targetField:"endDate",canEdit(e,t){return et(e,t)?z("summary","summary_column_value"):Kf(e)?z("completed","cant_edit_completed_activity"):j()},parseInput(e,t,r){if(!ve(e))return N("invalid_date");let n=Xt(e,"UTC"),i=r.calendars.getCalendar(t.calendarId);return i?i.isWorkTime(n,ot.DAY)?w(Mn(i,n)):r.dateFormat.split(" ").length>1?w(n):w(i.getClosestWorkTime({direction:"past",date:n,unit:ot.HOUR})):w(n)},validate(e,t,r,n){if(Tr(e.endDate,r))return tt("unchanged");if(Gf(r,e))return tt("before_date_origin");if($f(r,e))return tt("before_start_date");let i=zf(r,e,n);return i||U()},transform(e,t,r){let n=qf(e,t),i=Jf(e,t,r,!!n);return{...W(i,{autoSchedule:!0,postProcessors:["updateTaskTiming"]}),...n?{constraintWarning:n}:{}}},trackEvent:"activity_end_date_entry"};function Kf(e){return e.progress>=Yf}function Gf(e,t){return t.dateOrigin?Bn(e,t.dateOrigin):!1}function $f(e,t){return Bn(e,t.startDate)}function zf(e,t,r){let n=r.calendars.getCalendar(t.calendarId);return n?n.isWorkTime(e,ot.DAY)?null:tt("not_working_day"):null}function qf(e,t){if(kt(e)===K.MSO)return;let n=xe(kt(e),e.startDate,t),i=ye(kt(e),e.constraintDate,n);if(i.violated)return me(i.constraintType,i.constraintDate,n)}function Jf(e,t,r,n=!1){let i={};bt(e.type)&&!n&&ro(e)?Object.assign(i,Ht(e.startDate)):(n||ro(e))&&Object.assign(i,Ot(),Ht(e.startDate));let o=Xf(e,t,r),c=Fe(e.durationHours,o);return c&&(i.type=c),Object.assign(i,_r(o)),i.endDate=t,i}function ro(e){return jt.has(kt(e))}function Xf(e,t,r){let n=r.calendars.getCalendar(e.calendarId);return n?n.calculateDuration(e.startDate,t):e.durationHours}var Zf=new Set(Object.values(K)),io={targetField:"constraintType",canEdit(e,t){return pe(e)?z("completed","cant_edit_completed_activity"):et(e,t)?z("summary","summary_column_value"):j()},parseInput(e){let t=String(e).toLowerCase();return Qf(t)?w(t):N("invalid_constraint_type")},validate(){return U()},transform(e,t,r){let n=tp(e,t,r);return W(n,{autoSchedule:!0})}};function Qf(e){return Zf.has(e)}function tp(e,t,r){let n=rp(e,t);return{constraintType:t,...Vs(ep(e,t,n,r))}}function ep(e,t,r,n){if(e.type!=="milestone"||!r)return r;let i=n.calendars.getCalendar(String(e.calendarId));return i?wt(r,i,t):r}function rp(e,t){return jt.has(t)?null:Sr.has(t)?e.startDate:Wn.has(t)?e.endDate:e.constraintDate}var ao={targetField:"constraintDate",canEdit(e,t){return pe(e)?z("completed","cant_edit_completed_activity"):et(e,t)?z("summary","summary_column_value"):j()},parseInput(e){return ve(e)?w(e):N("invalid_date")},validate(){return U()},transform(e,t,r){let n=so(e)?Dr:kt(e),i=r.calendars.getCalendar(e.calendarId),a=i?wt(t,i,n):t,s=np(e,a);return W(s,{autoSchedule:!0})}};function np(e,t){return{constraintDate:t,...so(e)?Ot():{}}}function so(e){return jt.has(kt(e))||!e.constraintType}var oo={targetField:"calendarId",canEdit(){return j()},parseInput(e){let t=String(e).trim();return ip(t)?N("empty_calendar"):w(t)},validate(e,t,r,n){return ap(e.calendarId,r)?tt("unchanged"):n.calendars.getCalendar(r)?U():tt("unknown_calendar")},transform(e,t,r){return W(sp(e,t,r),{autoSchedule:!0,postProcessors:[]})},trackEvent:"activity_calendar_assignment"};function ip(e){return e===""}function ap(e,t){return e===t}function sp(e,t,r){let n={calendarId:t,assignedDefaultCalendar:!1},i=r.calendars.getCalendar(t);if(i){let a=e.durationHours===0,s=a?op(e.startDate):e.startDate,o=i.getClosestWorkTime({date:s,direction:"future",unit:"hour"});if((!e.autoScheduling||a||i.getWorkHours(e.startDate).length===0)&&(n.startDate=o),!e.autoScheduling)return n;let c=n.startDate??e.startDate;Object.assign(n,he(i.calculateEndDate(c,e.durationHours)))}return n}function op(e){return new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()))}var co={targetField:"customId",canEdit(e,t){return et(e,t)?z("summary","summary_column_value"):j()},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 U()},transform(e,t){return W({customId:t},{autoSchedule:!1,postProcessors:[]})},trackEvent:"schedule_custom_id_edition"};var lo={targetField:"subcontractId",canEdit(){return j()},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 U()},transform(e,t){return W({subcontractId:t},{autoSchedule:!1,postProcessors:[]})}};function We(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 Pr(e){return e.some(t=>We(t)===null)}var uo={targetField:"responsableIds",canEdit(){return j()},parseInput(e){return e==null?w([]):Array.isArray(e)?w(e):N("not_an_array")},validate(e,t,r){return Pr(r)?tt("missing_id"):U()},transform(e,t){let r=t.map(We).filter(n=>n!==null);return W({responsableIds:r},{autoSchedule:!1,postProcessors:[]})}};var fo={targetField:"tagIds",canEdit(){return j()},parseInput(e){return e==null?w([]):Array.isArray(e)?w(e):N("not_an_array")},validate(e,t,r){return Pr(r)?tt("missing_id"):U()},transform(e,t){let r=t.map(We).filter(n=>n!==null);return W({tagIds:r},{autoSchedule:!1,postProcessors:[]})}};var cp=new Map([[E.TEXT,Bs],[E.DESCRIPTION,Us],[E.DURATION,$s],[E.PROGRESS,Js],[E.COST,Xs],[E.USED_COST,Zs],[E.HH_WORK_TIME,Qs],[E.START_DATE,eo],[E.END_DATE,no],[E.CONSTRAINT_TYPE,io],[E.CONSTRAINT_DATE,ao],[E.CALENDAR_ID,oo],[E.CUSTOM_ID,co],[E.SUBCONTRACT_ID,lo],[E.RESPONSABLES,uo],[E.TAGS,fo]]);function Vt(e){return cp.get(e)}function Ae(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 lp=["name","description","type","startDate","endDate","durationHours","constraintType","constraintDate","calendarId","assignedDefaultCalendar","autoScheduling","progress","cost","usedCost","workHours","realWorkHours","customId","subcontractId","responsableIds","tagIds"],po=new Set(lp);function rt(e,t,r,n){e.setActivityFieldDynamic(t,r,n)}function ho(e,t,r,n){e.setLinkFieldDynamic(t,r,n)}function Qt(e){return{...e,startDate:new Date(e.startDate),endDate:new Date(e.endDate),constraintDate:Et(e.constraintDate),dateOrigin:Et(e.dateOrigin),newActivityIds:[...e.newActivityIds],pendingRequestIds:[...e.pendingRequestIds],responsableIds:[...e.responsableIds],tagIds:[...e.tagIds],baselinePoints:e.baselinePoints.map(t=>({...t,startDate:Et(t.startDate),endDate:Et(t.endDate)})),baselineSnapshot:dp(e.baselineSnapshot),criticalPath:up(e.criticalPath)}}function Et(e){return e===null?null:new Date(e)}function dp(e){return e===null?null:{...e,startDate:Et(e.startDate),endDate:Et(e.endDate)}}function up(e){return e===null?null:{...e,earlyStart:Et(e.earlyStart),earlyFinish:Et(e.earlyFinish),lateStart:Et(e.lateStart),lateFinish:Et(e.lateFinish)}}function Q(e){return structuredClone(e)}var go=200;function Yt(e,t){let r=new Set([String(e)]);for(let n of t.cascadeMutations??[])r.add(String(n.activityId));return r}async function q(e,t){let r=new Map,n=0;for(let i of t){n+=1,n%go===0&&await Z();let a=e.getActivity(i);a&&r.set(i,X(a))}return r}function X(e){return Qt(e)}function Er(e,t){let r=e.getActivity(t);return r?Qt(r):null}function Kt(e,t,r){yo(e,t,r.patch);for(let n of r.cascadeMutations??[])yo(e,n.activityId,n.fields)}function yo(e,t,r){for(let[n,i]of Object.entries(r)){if(!po.has(n))throw new Error(`applyFieldChanges: column write to non-writable field "${n}"`);rt(e,t,n,i)}}async function vo(e,t,r,n){let i=[],a=0;for(let s of r){a+=1,a%go===0&&await Z();let o=fp(e,t,s,n);o&&i.push(o)}return i}function fp(e,t,r,n){let i=e.getActivity(r);if(!i)return{id:r,kind:"deleted",after:null};let a=t.get(r);if(!a&&n?.has(r))return pp(r,n.get(r),i);let s=jn(a,i);return hp(s,n,r,i),a&&Object.keys(s).length===0?null:{id:r,kind:a?"updated":"created",fields:s,after:X(i)}}function pp(e,t,r){return t===r.correlativeId?null:{id:e,kind:"updated",fields:{correlativeId:{before:t,after:r.correlativeId}},after:X(r)}}function hp(e,t,r,n){if(!t?.has(r)||Object.hasOwn(e,"correlativeId"))return;let i=t.get(r);i!==n.correlativeId&&(e.correlativeId={before:i,after:n.correlativeId})}function jn(e,t){let r={},n=e??{},i=t,a=new Set([...Object.keys(n),...Object.keys(i)]);for(let s of a)(Object.hasOwn(n,s)!==Object.hasOwn(i,s)||!Un(n[s],i[s]))&&(r[s]={before:mo(n[s]),after:mo(i[s])});return r}function mo(e){return e===null||typeof e!="object"?e:Q(e)}function Un(e,t){if(Object.is(e,t))return!0;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if(e==null||t==null)return!1;if(Array.isArray(e)||Array.isArray(t))return!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length?!1:e.every((s,o)=>Un(s,t[o]));if(typeof e!="object"||typeof t!="object")return!1;let r=e,n=t,i=Object.keys(r),a=Object.keys(n);return i.length!==a.length?!1:i.every(s=>Object.hasOwn(n,s)&&Un(r[s],n[s]))}function Rr(e,t,r){let n=new Set;n.add(e);for(let i of t)n.add(i);for(let i of r)n.add(i);return n}function Hn(e,t){let r=new Set;for(let n of e)r.add(String(n));for(let n of t)r.add(n);return r}function Ce(e,t,r,n,i){for(let a of t){if(r.has(a.activityId)||(i.add(a.activityId),n.has(a.activityId)))continue;let s=e.getActivity(a.activityId);if(!s)continue;let o=X(s);a.before!==void 0&&(o.correlativeId=a.before),n.set(a.activityId,o)}}var yp=/^(\d{4})\/(\d{1,2})\/(\d{1,2})\s+(\d{1,2}):(\d{2})$/;function xt(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(yp);if(!t)throw new Error(`[parseFromBackend] unsupported date format "${e}" (expected "YYYY/MM/DD H:MM" or ISO)`);let[,r,n,i,a,s]=t;return new Date(Date.UTC(Number(r),Number(n)-1,Number(i),Number(a),Number(s)))}function Ie(e,t,r,n){if(e.getTime()>r.getTime())return 0;if(t.getTime()<r.getTime()||e.getTime()===t.getTime())return 100;let i=n.calculateDuration(e,r),a=n.calculateDuration(e,t);return a===0?0:i*100/a}var mp=e=>e.type==="project",gp=(e,t,r)=>{let n=e.calendarId,i=n!=null?r.calendarReader.getCalendar(String(n)):null;if(!i)return 0;let a=s=>s instanceof Date?s:xt(String(s));return Ie(a(e.startDate),a(e.endDate),t,i)};function vp(e,t,r){let n=[],i=(s,o)=>{let c=r.getActivity(s);c&&c.expectedProgress!==o&&(r.setActivityField(s,"expectedProgress",o),n.push(String(s)))},a=s=>{let o=r.getActivity(s);if(!o)return 0;if(!mp(o)){let d=gp(o,t,r);return i(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 i(s,l),l};for(let s of e)a(s);return n}function te(e,t){let r=[];e.forEachActivity((n,i)=>{n.parentId===null&&r.push(i)}),vp(r,t,e)}function ut(e){let t=e?.baselinePoints;return!Array.isArray(t)||t.length===0?null:t.find(r=>r.isActiveVersion)??null}var Ap=e=>e.type==="project",Cp=e=>ut(e),Ip=(e,t,r,n)=>{let i=Cp(e);if(!i)return 0;let a=(i.baseCalendarId!=null?r.getBaseCalendar(`${i.baseCalendarId}-base`):null)??(n?r.getBaseCalendar(n):null);return!a||!i.startDate||!i.endDate?0:Ie(i.startDate,i.endDate,t,a)};function Vn(e,t,r,n=null){let i=[],a=(o,c)=>{let l=r.getActivity(o);l&&l.expectedProgressBaseline!==c&&(r.setActivityField(o,"expectedProgressBaseline",c),i.push(o))},s=o=>{let c=r.getActivity(o);if(!c)return 0;if(!Ap(c)){let u=Ip(c,t,r,n);return a(o,u),u}let l=0;for(let u of r.getChildrenIds(o)){let f=s(u),p=r.getActivity(u),m=typeof p?.ponderator=="number"?p.ponderator:0;l+=f*m}let d=l/100;return a(o,d),d};for(let o of e)s(o);return i}function Se(e,t,r=null){let n={getChildrenIds:a=>e.getChildren(String(a)).map(s=>String(s)),getActivity:a=>e.getActivity(a),setActivityField:(a,s,o)=>rt(e,a,s,o),getBaseCalendar:a=>e.calendarReader.getCalendar(a)},i=[];return e.forEachActivity((a,s)=>{a.parentId===null&&i.push(s)}),Vn(i,t,n,r)}var Ao=e=>Math.round(e*100)/100;function Sp(e,t){return(t==="Baseline"?e.expectedProgressBaseline:e.expectedProgress)??void 0}function kp(e,t){let r=Ao(e),n=Ao(t);return r>99.99?_t.DONE:n>r?_t.OVERDUE:e>0&&r>n?_t.ADVANCEMENT:e===0&&t===0?_t.WAITING:e>0&&r<n?_t.DOING:_t.WAITING}function Ft(e,t){let r=[];return e.forEachActivity((n,i)=>{let a=typeof n.progress=="number"?n.progress:0,s=kp(a,Sp(n,t));n.status!==s&&(rt(e,i,rr,s),r.push(i))}),r}function Yn(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=(i,a)=>s=>s===void 0?t[i]():(t[a](s),n),n={__isMomentShim:!0,clone:()=>Yn(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 n}Yn.isMoment=e=>!!e&&typeof e=="object"&&e.__isMomentShim===!0;var gt=Yn;function Dp(e){return e&&e.constructor===Date?!!(e.getFullYear&&e.getMonth&&e.getDate):!1}function br(e){return Dp(e)&&!isNaN(e.getTime())}function k(e,t,r,n){if(!br(new Date(t)))throw new Error(`Invalid date argument for calculateEndDate method. Date: ${t}, Activity: ${JSON.stringify(n)}`);let i=t;return e.calculateEndDate({start_date:new Date(i),duration:r,unit:"hour",task:n})}function ht(e){if(!br(new Date(e.dateBaseToCalculate)))throw new Error("Invalid date argument for getClosestWorkTime method");let{dateBaseToCalculate:t,activityCalendar:r,direction:n,activity:i}=e;return r.$gantt.getClosestWorkTime({date:new Date(t),dir:n,unit:"hour",task:i})}var Tp=e=>e?e.$level===1:!1,_p=e=>e.type==="project",Pp=e=>e.$level!==0,Ep=e=>e.type==="task",Rp=e=>e.type==="task"||e.type==="milestone",ct={byFirstLevel:Tp,filterByParentType:_p,avoidSubproject:Pp,byTaskType:Ep,byTaskTypeAndMilestone:Rp};var y=Object.freeze({MFO:"mfo",MSO:"mso",FNLT:"fnlt",FNET:"fnet",SNET:"snet",SNLT:"snlt",ALAP:"alap",ASAP:"asap"});var H=Object.freeze({FS:"fs",SS:"ss",FF:"ff",SF:"sf"});function ee(e){return{0:"fs",1:"ss",2:"ff",3:"sf"}[Number(e)]||"sf"}function Co(e){let{gantt:t,pendingParentsWithNoLinks:r,calculations:n,linkProperty:i}=e;try{let a=bp({gantt:t,pendingParentsWithNoLinks:r});if(a.length===0)return new Set;let s=Lp({gantt:t,subprojectsWithNoLinks:a}),o=wp({gantt:t,childrenIds:s,linkProperty:i,getArrayOfLinkedActivities:Op,calculations:n});return new Set(o.map(c=>c.id))}catch(a){throw a}}function bp(e){let{gantt:t,pendingParentsWithNoLinks:r}=e;return t.getTaskByTime().filter(ct.filterByParentType).filter(n=>r.has(n.id)).map(n=>n.id)}function Lp(e){let{gantt:t,subprojectsWithNoLinks:r}=e,n=new Set;for(let i of r)t.getChildren(i).filter(o=>{let c=t.getTask(o),l=ct.byTaskTypeAndMilestone(c),d=Number(c.progress)<100;return l&&d}).forEach(o=>n.add(o));return[...n]}function wp(e){let{gantt:t,childrenIds:r,linkProperty:n,getArrayOfLinkedActivities:i,calculations:a}=e,s=[];for(let o of r){let c=t.getTask(o),l=c[n]||[];i({gantt:t,links:l,linkDirection:n==="$source"?"target":"source"}).every(f=>a.has(f))&&s.push(c)}return s}function Op(e){let{gantt:t,links:r,linkDirection:n}=e,i=[];for(let a of r){let s=t.getLink(a);if(!s){`${a}`;continue}let o=Number(s[n]);i.push(o)}return i}function Io({gantt:e,linkProperty:t,direction:r}){try{let n=xp(e,t);if(r==="forward")return{chainStartActivities:n,activitiesStartChainButChildrenOfLinkedParents:null};if(r==="backward")return Fp(n,e,t)}catch(n){throw console.log("Critical Path",n),n}}function xp(e,t){return e.getTaskByTime().filter(ct.avoidSubproject).filter(ct.byTaskTypeAndMilestone).filter(r=>!r[t].length)}function Fp(e,t,r){let n=[],i=new Set;return e.forEach(a=>{let s=Number(a.parent),o=t.getTask(s);o&&(o[r].length>0?i.add(a.id):o.constraint_type!=="fnlt"&&n.push(a))}),{chainStartActivities:n,activitiesStartChainButChildrenOfLinkedParents:i}}function So({gantt:e,direction:t,linkProperty:r}){try{let n=Np(e),i=new Set,a=new Set,s=new Set;t==="backward"&&Bp(n).forEach(d=>{i.add(d.id)});let o=Mp(n,t,r),c=Wp(n,o);return o.forEach(l=>{a.add(l.id)}),c.forEach(l=>{s.add(l.id)}),{parentsWithFullProgress:i,pendingParentsWithNoLinks:a,pendingParentsWithLinks:s}}catch(n){throw n}}function Np(e){return e.getTaskByTime().filter(ct.filterByParentType).filter(ct.avoidSubproject)}function Mp(e,t,r){return e.filter(n=>{let i=n[r];if(!Array.isArray(i))return!1;let a=i.length>0,s=n.constraint_type||"",o=s!=="fnlt";return t==="forward"?!a&&o&&s!=="snet":!a&&o})}function Wp(e,t){let r=new Set(t.map(n=>n.id));return e.filter(n=>!r.has(n.id))}function Bp(e){return e.filter(t=>{let r=Number(t.progress);return Number.isNaN(r)?!1:r===100})}function ko({pendingParentsWithLinks:e,gantt:t,direction:r}){try{let n=new Set;return e.forEach(i=>{let a=t.getTask(i),s=Up(r),o=jp(r),c=a[s];if(!Array.isArray(c))return;Hp(t,c,o).forEach(d=>{n.add(d)})}),n}catch(n){throw n}}function Up(e){return e==="forward"?"$source":"$target"}function jp(e){return e==="forward"?"target":"source"}function Hp(e,t,r){return t.map(n=>{let a=e.getLink(n)[r];return Number(a)})}var Be={identifySecondLevelActivities:Co,identifyInitialActivities:Io,identifyParentsWithAndWithoutLinks:So,identifyForbiddenActivities:ko};function Lr(e){return e.length?e.reduce((t,r)=>r.ef>t.ef?r:t):!1}function Kn({linkType:e,lag:t,predecessorTime:r,activityCalendar:n,activity:i}){return e===H.FS&&t===0?ht({predecessorTime:r,activityCalendar:n,direction:"future",activity:i}):Ue(r,e,n,i)}function Do({duration:e,constraintDate:t,activityCalendar:r,activity:n}){let i=new Date(t);return{es:k(r,i,e,n),ef:i}}function To({duration:e,constraintDate:t,activityCalendar:r,activity:n}){let i=new Date(t),a=k(r,i,e,n);return{es:i,ef:a}}function Ue(e,t,r,n){if(![H.FS,H.SS,H.FF].includes(t))return e;let a=[H.FS,H.SS].includes(t)?"future":"past";return ht({dateBaseToCalculate:e,activityCalendar:r,direction:a,activity:n})}var Gn=class{constructor(t,r,n){if(this.linkedActivitiesData=t,this.activity=r,this.gantt=n,this.activityCalendar=this.gantt.getCalendar(this.activity.calendar_id),!this.activityCalendar)throw new Error(`Error trying to get calendar with id: ${this.activity.calendar_id}`)}calculate(){let t=this.calculateLinks(),r=Lr(t),n=this.activity.constraint_type;return n==="snet"?this.handleSNETConstraint(r):n==="fnlt"?this.handleFNLTConstraint(r):r}calculateLinks(){let t=[];for(let r of this.linkedActivitiesData){let n=r.linkType,i=ee(n),a=r.linkLag,s=r.es,o=r.ef,c=null;if(i==="ss")c=this.calculateSSLink({lag:a,predecessorEs:s});else if(i==="ff")c=this.calculateFFLink({lag:a,predecessorEf:o});else if(i==="fs")c=this.calculateFSLink({lag:a,predecessorEf:o});else if(i==="sf")c=this.calculateSFLink({lag:a,predecessorEs:s,predecessorEf:o});else continue;c&&t.push(c)}return t}handleSNETConstraint(t){let r=To({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=Do({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 n=Kn({linkType:"ss",lag:t,predecessorTime:r,activityCalendar:this.activityCalendar,activity:this.activity}),i=k(this.activityCalendar,n,t,this.activity);t>0&&(i=Ue(i,"ss",this.activityCalendar,this.activity));let a=k(this.activityCalendar,i,this.activity.duration,this.activity);return{es:i,ef:a}}calculateFFLink({lag:t,predecessorEf:r}){let n=Kn({linkType:"ff",lag:t,predecessorTime:r,activityCalendar:this.activityCalendar,activity:this.activity}),i=k(this.activityCalendar,n,t,this.activity),a=k(this.activityCalendar,i,-this.activity.duration,this.activity);return t>0&&(a=Ue(a,"ff",this.activityCalendar,this.activity)),{es:a,ef:i}}calculateFSLink({lag:t,predecessorEf:r}){let n=r;t===0&&(n=ht({dateBaseToCalculate:r,activityCalendar:this.activityCalendar,direction:"future",activity:this.activity}));let i=k(this.activityCalendar,n,t,this.activity),a=k(this.activityCalendar,i,this.activity.duration,this.activity);return{es:i,ef:a}}calculateSFLink({lag:t,predecessorEs:r}){let n=k(this.activityCalendar,r,t,this.activity),i=k(this.activityCalendar,n,-this.activity.duration,this.activity);return t>0&&(i=Ue(i,"sf",this.activityCalendar,this.activity)),{es:i,ef:n}}},_o=Gn;var $n=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 n=ee(r.linkType);if(r.type==="task"&&Number(r.progress)>0||r.type==="project"&&Number(r.progress)===100)continue;let i=r.linkLag,a=r.ls,s=r.lf;if(n==="ss"){let o={lag:i,workTime:a,lsDataCalculation:-i,lfDataCalculation:this.activity.duration},{ls:c,lf:l}=this.calculateSSLink(o);t.push({ls:c,lf:l})}if(n==="ff"){let o={lag:i,workTime:s,lsDataCalculation:-this.activity.duration,lfDataCalculation:-i},{ls:c,lf:l}=this.calculateFFLink(o);t.push({ls:c,lf:l})}if(n==="fs"){let o={lag:i,workTime:a,lsDataCalculation:-this.activity.duration,lfDataCalculation:-i},{ls:c,lf:l}=this.calculateFsLink(o);t.push({ls:c,lf:l})}if(n==="sf"){let o={lag:i,workTime:s,lsDataCalculation:-i,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),n=this.calculateSfRestrictionDates();return r?this.getMinLfFromLinks([n,r]):n}else{let r=this.getMinLfFromLinks(t);if(r===!1){let n=this.gantt.getSubtaskDates();return{ls:k(this.activityCalendar,n.end_date,-this.activity.duration,this.activity),lf:n.end_date}}return r}}calculateFFLink({lag:t,workTime:r,lsDataCalculation:n,lfDataCalculation:i}){let a=null,s=null;if(t===0)return a=k(this.activityCalendar,r,i,this.activity),s=k(this.activityCalendar,a,n,this.activity),{ls:s,lf:a};let o=r;return t>0&&(o=this.getLastWorkingHour(o,this.activityCalendar,"past")),a=k(this.activityCalendar,o,i,this.activity),s=k(this.activityCalendar,a,n,this.activity),{ls:s,lf:a}}calculateFsLink({lag:t,workTime:r,lsDataCalculation:n,lfDataCalculation:i,isMilestone:a=!1}){let s=null,o=null;if(t===0){let l=this.getLastWorkingHour(r,this.activityCalendar,"past");return s=k(this.activityCalendar,l,i,this.activity),s=this.getLastWorkingHour(s,this.activityCalendar,"past"),o=k(this.activityCalendar,s,n,this.activity),{ls:o,lf:s}}let c=r;return a||(c=this.getLastWorkingHour(r,this.activityCalendar)),s=k(this.activityCalendar,c,i,this.activity),o=k(this.activityCalendar,s,n,this.activity),a||(s=this.getLastWorkingHour(s,this.activityCalendar,"past")),{ls:o,lf:s}}calculateSFLink({lag:t,workTime:r,lsDataCalculation:n,lfDataCalculation:i}){let a=null,s=null,o=r;return s=k(this.activityCalendar,o,n,this.activity),a=k(this.activityCalendar,s,i,this.activity),{ls:s,lf:a}}calculateSSLink({lag:t,workTime:r,lsDataCalculation:n,lfDataCalculation:i,isMilestone:a=!1}){let s=null,o=null;if(t===0)return o=k(this.activityCalendar,r,n,this.activity),s=k(this.activityCalendar,o,i,this.activity),{ls:o,lf:s};let c=r;return t<0&&!a&&(c=this.getLastWorkingHour(c,this.activityCalendar,"future")),o=k(this.activityCalendar,c,n,this.activity),s=k(this.activityCalendar,o,i,this.activity),{ls:o,lf:s}}getMinLfFromLinks(t=[]){return t.length?t.reduce((r,n)=>n.lf<r.lf?n:r):!1}calculateSfRestrictionDates(){let t=this.activity.constraint_date,r=this.activity.duration;return{ls:k(this.activityCalendar,t,-r,this.activity),lf:t}}getLastWorkingHour(t,r,n="past"){let i=t instanceof Date?t:new Date(t),a=gt(i).clone();return this.isActivityInInitHour(r,i)&&n==="past"&&(a=a.hours(0).minutes(0).seconds(0).milliseconds(0)),ht({dateBaseToCalculate:new Date(a),direction:n,activityCalendar:r,activity:this.activity})}isActivityInInitHour(t,r){let n=r instanceof Date?r:new Date(r),a=t.getWorkHours(n)[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),gt.isMoment(r)?r.hours()===s:n.getUTCHours()===s)}},Po=$n;function Eo(e){let{parent:t,linkProperty:r,linkDirection:n,calculations:i,gantt:a,direction:s}=e,o=t[r],c=Vp(t),l=null;if(s==="forward"){let d=Yp(o,n,i,a);l=new _o(d,t,a),l=l.calculate()}else{let d=Kp(o,n,i,a);l=new Po({linksWithActivityData:d,activity:t,parentData:c,gantt:a}).calculate()}return l}function Vp(e){return{duration:e.duration,calendarId:e.calendar_id}}function Yp(e,t,r,n){return e.length===0?[]:e.map(i=>{let a=n.getLink(i);if(!a)return console.warn(`Link not found: ${i}`),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 Kp(e,t,r,n){return e.length===0?[]:e.map(i=>{let a=n.getLink(i);if(!a)return console.warn(`Link not found: ${i}`),null;let s=Number(a[t]),o=r.get(s);if(!o)return null;let c=n.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 Lo(e){let{activityData:t,calculations:r,singleParents:n,direction:i}=e;if(Gp(t.id,r))return null;let a=$p(t.id,n),s=zp(a,r);return s.length===0?null:qp(s,i)}function Gp(e,t){return t.has(e)}function $p(e,t){let r=t.get(e);return r?r.childrens:[]}function zp(e,t){return e.filter(r=>t.has(r)).map(r=>t.get(r))}function qp(e,t){if(t==="forward"){let r=Ro(e,"es"),n=bo(e,"ef");return{es:r,ef:n}}else{let r=Ro(e,"ls"),n=bo(e,"lf");return{ls:r,lf:n}}}function Ro(e,t){return e.reduce((r,n)=>n[t]<r[t]?n:r)[t]}function bo(e,t){return e.reduce((r,n)=>n[t]>r[t]?n:r)[t]}var zn={parentWithLinks:Eo,parentWithNoLinks:Lo};var qn=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 n=[y.FNLT];if(this.shouldCalculateParentWithLinksBackward(n)){this.calculateAndStoreParentWithLinks(this.activity);return}if(this.shouldSetDatesToParentsWithLinks(n)){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),n=!this.calculationOfParentsFromLinks.has(this.activity.id);return r&&n}calculateAndStoreParentWithLinks(t){let r=zn.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),n=this.calculationOfParentsFromLinks.has(this.activity.id);return r&&n}handleParentWithNoLinks(){let t=zn.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,n=Array.from(this.calculations).filter(s=>t.includes(s[0])).map(s=>s[1]),{minEs:i,maxEf:a}=n.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(n[0].es),maxEf:new Date(n[0].ef)});this.calculations.set(this.activity.id,{es:i,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,n=Array.from(this.calculations).filter(s=>t.includes(s[0])).map(s=>s[1]),{minLs:i,maxLf:a}=n.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(n[0].ls),maxLf:new Date(n[0].lf)});this.calculations.set(this.activity.id,{ls:i,lf:a})}getArrayOfIdOfLinkedActivities(t,r=!1){return t.map(n=>{let a=this.gantt.getLink(n)[r||this.linkDirection];return Number(a)})}},wo=qn;var Jn=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 n=this.processEachActivity(r),{activitiesByLevel:i}=n,a=this.getAllLevels(i),s=this.getDeepestLevel(a),o=this.createResult(r,n,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(ct.byFirstLevel).filter(ct.filterByParentType)}processEachActivity(t){let r=new Set,n=new Set,i=new Map;return this.initializeParent(t),this.gantt.eachTask(a=>{this.processActivity(a,r,n,i)},t.id),{parentsIds:r,allTasks:n,activitiesByLevel:i}}initializeParent(t){let r=Number(t.id),n=!!t[this.linkProperty]?.length,i=t.$level;this.singleParents.set(r,{level:i,hasLink:n,childrens:[]})}processActivity(t,r,n,i){let a=Number(t.id),s=Number(t.parent);n.add(a),this.isProjectActivity(t)&&this.addParentInfo(t,r);let c=this.doesParentExist(s);s!=null&&c&&this.addChildToParent(s,a),this.addActivityToLevel(t,i)}isProjectActivity(t){return t.type==="project"}hasLink(t){return!!t[this.linkProperty]?.length}addParentInfo(t,r){let n=Number(t.id),i=t.$level,a=this.hasLink(t),s={level:i,hasLink:a,childrens:[]};r.add(n),this.singleParents.set(n,s)}doesParentExist(t){return this.singleParents.has(t)}addChildToParent(t,r){this.singleParents.get(t).childrens.push(r)}addActivityToLevel(t,r){let n=t.$level,i=Number(t.parent);r.has(n)||r.set(n,new Map);let a=r.get(n);a.has(i)||a.set(i,[]),a.get(i).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,n,i){let{activitiesByLevel:a,parentsIds:s,allTasks:o}=r;return{parent:t.id,isALinkedParent:this.hasLink(t),levels:i,allParentChildrens:s,allChildrens:o,childrensByLevel:a,currentResolutionLevel:n,canBeCalculated:!1}}},Oo=Jn;var Xn=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:n,isALinkedParent:i}=t;if(i)return;let a=n.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(ct.avoidSubproject).forEach(t=>{this.activitiesWaitingForCalculation.add(t.id)})}catch(t){throw t}}identifyParentsWithAndWithoutLinks(){try{let{parentsWithFullProgress:t,pendingParentsWithNoLinks:r,pendingParentsWithLinks:n}=Be.identifyParentsWithAndWithoutLinks({gantt:this.gantt,direction:this.direction,linkProperty:this.linkProperty});this.parentsWithFullProgress=t,this.pendingParentsWithNoLinks=r,this.pendingParentsWithLinks=n}catch(t){throw t}}identifyForbiddenActivitiesLinkedToParentsWithLinks(){try{this.forbiddenActivitiesLinkedToParentsWithLinks=Be.identifyForbiddenActivities({pendingParentsWithLinks:this.pendingParentsWithLinks,gantt:this.gantt,direction:this.direction})}catch(t){throw t}}getArrayOfIdOfLinkedActivities(t,r=!1){return t.map(n=>{let a=this.gantt.getLink(n)[r||this.linkDirection];return Number(a)})}async identifyThirdLevelActivities(){try{let{structureOfParents:t,singleParents:r}=new Oo({gantt:this.gantt,linkProperty:this.linkProperty}).identifyThirdLevelActivities();this.structureOfParents=t,this.singleParents=r}catch(t){throw t}}processEachActivity(t){let r=new Set,n=new Set,i=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(n.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),i.has(c.$level)||i.set(c.$level,new Map);let d=i.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:n,activitiesByLevel:i,singleParents:a})})}identifySecondLevelActivities(){try{let t=Be.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}=Be.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:n,ef:i}=r;this.calculations.set(t.id,{es:n,ef:i,text:t.text}),this.activitiesWaitingForCalculation.delete(t.id)}else{let{ls:n,lf:i}=r;this.calculations.set(t.id,{ls:n,lf:i,text:t.text}),this.activitiesWaitingForCalculation.delete(t.id)}})}catch(t){throw t}}buildDependencyGraph(t){let r=new Map,n=new Set(this.calculations.keys()),i=new Map;return t.forEach(a=>{a&&i.set(a.id,a)}),i.forEach((a,s)=>{if(n.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=>i.has(l)||n.has(l)),r.set(s,o)}),{graph:r,activityMap:i,calculatedActivities:n}}topologicalSort(t,r){let n=new Set,i=new Set,a=[],s=o=>{if(i.has(o))throw new Error("Cyclical dependency detected",{cause:{nodeId:o}});if(!n.has(o)&&!r.has(o)){i.add(o);let c=t.get(o)||[];for(let l of c)s(l);i.delete(o),n.add(o),a.push(o)}};for(let o of t.keys())!n.has(o)&&!r.has(o)&&s(o);return a.reverse()}calculateStartAndFinishOfChainOrigin(t=null,r=null){try{let n=t,i=Number(n.progress);i==="0.00"&&(i=0);let a=this.gantt.getCalendar(n.calendar_id);if(!a)throw new Error(`Error trying to get calendar with id: ${n.calendar_id}`);if((r||this.direction)==="forward"){let o=n.start_date,c=n.end_date;return{es:o,ef:c}}else{if(i>=100)return{ls:gt(n.start_date).clone(),lf:gt(n.end_date).clone()};if(i===0)return this.calculateBackwardWhenZeroProgress(n,a);if(i<100&&i>0)return this.calculateWhenProgressIsBetweenZeroAndOneHundred(n,a)}}catch(n){throw n}}calculateBackwardWhenZeroProgress(t,r){let n=gt(t.start_date).clone(),i=gt(t.end_date).clone(),a=t.duration,s=[y.ASAP,y.ALAP,y.SNET,y.FNET],o=t.constraint_type||y.ASAP;if(s.includes(o))i=this.projectDates.end_date,n=k(r,i,-a,t);else{let c=[y.SNLT,y.MSO],l=[y.FNLT,y.MFO];c.includes(o)&&(n=t.constraint_date,i=k(r,n,a,t)),l.includes(o)&&(i=t.constraint_date,n=k(r,i,-a,t))}return{ls:n,lf:i}}calculateWhenProgressIsBetweenZeroAndOneHundred(t){let r=t.start_date,n=null,i=t.constraint_type||y.ASAP,a=this.projectDates.end_date,s=[y.ASAP,y.ALAP,y.SNET,y.FNET],o=[y.SNLT,y.FNLT];if(s.includes(i))n=Math.max(t.end_date,a);else if(i===y.MSO)n=t.end_date;else if(i===y.MFO||o.includes(i)){let c=Math.min(a,t.constraint_date);n=Math.max(c,t.end_date)}return{ls:r,lf:new Date(n)}}initializeActivitiesWithFullProgress(){try{Array.from(this.activitiesWaitingForCalculation).filter(n=>Number(this.gantt.getTask(n).progress)===100).map(n=>this.gantt.getTask(n)).forEach(n=>{let i=n.type==="project";this.setDatesForActivityWithFullProgress(n),this.activitiesWaitingForCalculation.delete(n.id),i&&this.pendingParentsWithLinks.has(n.id)&&(this.parentCalculationFromChildren.add(n.id),this.calculationsOfParentThatImpactChildrens.set(n.id,{[this.direction==="forward"?"es":"ls"]:n.start_date,[this.direction==="forward"?"ef":"lf"]:n.end_date}),this.calculationOfParentsFromLinks.add(n.id))})}catch(t){throw t}}doCalculationForParentType(t){let r=new wo({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()}},Gt=Xn;function Jp(e,t,r){let n={es:null,ef:null};if(!e)return n;if([y.SNET,y.SNLT].includes(t)){let i=new Date(e.constraint_date);n.es=i,n.ef=k(r,i,e.duration,e)}else if([y.FNLT,y.FNET].includes(t)){let i=new Date(e.constraint_date);n.es=k(r,i,-e.duration,e),n.ef=i}else if(t===y.MSO){let i=new Date(e.constraint_date);n.es=i,n.ef=k(r,i,e.duration,e)}else if(t===y.MFO){let i=new Date(e.constraint_date);n.es=k(r,i,-e.duration,e),n.ef=i}return n}var wr=Jp;var Zn=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,n=0,i,a=H.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===H.FS&&i===0?o=ht({dateBaseToCalculate:o,activityCalendar:s,direction:"future",activity:this.referenceActivity}):o=this.mutateTheDateToFutureOrPastInBaseRestriction(t,a,s)),[H.FF,H.SF].includes(a)?(l=k(s,o,n,this.referenceActivity),c=k(s,l,r,this.referenceActivity),!d&&i>0&&(c=this.mutateTheDateToFutureOrPastInBaseRestriction(c,a,s))):(c=k(s,o,r,this.referenceActivity),!d&&i>0&&(c=this.mutateTheDateToFutureOrPastInBaseRestriction(c,a,s)),l=k(s,c,n,this.referenceActivity)),{es:c,ef:l}}calculateSS(t){let r=this.getEsAndEfFromPreviousCalculatedActivities(Number(t.source)),n=t.lag||0,a=this.referenceActivity.duration,s=t.lag||0;return this.calculateSucessorTimes(r.es,n,a,s,H.SS)}calculateFF(t){let r=this.getEsAndEfFromPreviousCalculatedActivities(Number(t.source)),i=-this.referenceActivity.duration,a=t.lag||0,s=t.lag||0;return this.calculateSucessorTimes(r.ef,i,a,s,H.FF)}calculateFS(t){let r=this.getEsAndEfFromPreviousCalculatedActivities(Number(t.source)),n=t.lag||0,a=this.referenceActivity.duration,s=t.lag||0;return this.calculateSucessorTimes(r.ef,n,a,s,H.FS)}calculateSF(t){let r=this.getEsAndEfFromPreviousCalculatedActivities(Number(t.source)),i=-this.referenceActivity.duration,a=t.lag||0,s=t.lag||0;return this.calculateSucessorTimes(r.es,i,a,s,H.SF)}mutateTheDateToFutureOrPastInBaseRestriction(t,r,n){if(![H.FS,H.SS,H.FF].includes(r))return t;let a=[H.FS,H.SS].includes(r)?"future":"past";return ht({dateBaseToCalculate:t,activityCalendar:n,direction:a,activity:this.referenceActivity})}},xo=Zn;var je=class extends xo{constructor(t){super(t)}calculate(){if(this.links.length===0)return new Gt(this.gantt,"forward").calculateStartAndFinishOfChainOrigin(this.referenceActivity);let t=this.links.map(n=>{let i=this.gantt.getLink(n);if(!i)throw new Error("Link data not found",{cause:{linkId:n}});return this.calculateLink(i)}),r=Number(this.referenceActivity.parent);if(this.parentsWithLinks.has(r)){let n=this.gantt.getCalendar(this.referenceActivity.calendar_id),i=this.parentsCalculations.get(r).es,a=k(n,i,this.referenceActivity.duration,this.referenceActivity);t.push({es:i,ef:a})}return Lr(t)}calculateLink(t){return{0:()=>this.calculateFS(t),1:()=>this.calculateSS(t),2:()=>this.calculateFF(t),3:()=>this.calculateSF(t)}[t.type]()}};var Qn=class{constructor(t){this.gantt=t.gantt,this.direction=t.direction,this.pendingParentsWithNoLinks=t.pendingParentsWithNoLinks,this.pendingParentsWithLinks=t.pendingParentsWithLinks,this.calculationOfParentsFromLinks=t.calculationOfParentsFromLinks,this.singleParents=t.singleParents,this.calculations=t.calculations,this.activitiesStartChainButChildrenOfLinkedParents=t.activitiesStartChainButChildrenOfLinkedParents,this.linkProperty=t.linkProperty,this.linkDirection=t.linkDirection}checkActivitiesThatNowCanBeCalculated(t){let r=new Set,n=new Set(t);for(let i of t){let a=this.gantt.getTask(i);a.type==="project"?this.handleProjectActivity(i,a,r,n):this.handleNonProjectActivity(i,a,r,n)}return{activitiesThatCanBeCalculated:r,pendingActivities:n}}handleProjectActivity(t,r,n,i){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))&&(n.add(t),i.delete(t));return}if(s&&o){let c=this.singleParents.get(t)?.childrens;if(!c)return;c.every(d=>this.calculations.has(d))&&(n.add(t),i.delete(t));return}s&&!o&&this.canCalculateParentActivity(r)&&(n.add(t),i.delete(t))}canCalculateParentActivity(t){let r=(t[this.linkProperty]||[]).length===0,n=t.constraint_type;return(this.direction==="forward"?n==="fnlt"||n==="snlt":n==="fnlt")&&r?!0:this.getArrayOfLinkedActivities(t[this.linkProperty]).every(s=>this.calculations.has(s))}handleNonProjectActivity(t,r,n,i){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){n.add(t),i.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){n.add(t),i.delete(t);return}l&&(n.add(t),i.delete(t))}getLinkedActivities(t){if(!Array.isArray(t))return[];let r=[];for(let n of t){let i=this.gantt.getLink(n);if(!i)continue;let a=i[this.linkDirection],s=this.gantt.getTask(a);s&&r.push(s)}return r}getArrayOfLinkedActivities(t){if(!Array.isArray(t))return[];let r=[];for(let n of t){let i=this.gantt.getLink(n);i&&r.push(Number(i[this.linkDirection]))}return r}},Or=Qn;var ti=(e,t)=>()=>t()===e;var ei=e=>!e?.fullyParsed||typeof window<"u"&&window.to_use_react_gantt?.conversionMode?.isActive;var Xp=16,He=async e=>performance.now()-e>Xp?(await Z(),performance.now()):e;var Ve=async({pending:e,activityCalculator:t,calculateFn:r,shouldKeepPending:n,isCalculated:i,onActivityProcessed:a,isCurrent:s})=>{let o=new Set(e),c=performance.now();for(;o.size>0;){if(!s())return;c=await He(c);let{activitiesThatCanBeCalculated:l,pendingActivities:d}=t.checkActivitiesThatNowCanBeCalculated(o);if(l.size===0)break;for(let u of l){if(!s())return;c=await He(c),r([u])}for(let u of l){if(!s())return;n(u)&&d.add(u),a(u),i(u)&&d.delete(u)}o=d}};var ri=class extends Gt{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 Or({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 Ve({pending:this.activitiesWaitingForCalculation,activityCalculator:r,calculateFn:n=>this.calculateStartAndFinishTimes(n),shouldKeepPending:n=>this.calculationOfParentsFromLinks.has(n)&&!this.calculations.has(n),isCalculated:n=>this.calculations.has(n),onActivityProcessed:n=>this.activitiesWaitingForCalculation.delete(n),isCurrent:t})}calculateStartAndFinishTimes(t){t.forEach(r=>{let n=this.gantt.getTask(r);if(n.type==="project")return this.doCalculationForParentType(n);if(!n)throw new Error("Error trying to get activity",{cause:{activityId:r}});let i=n.$target,a=n.constraint_type||y.ASAP,s=[y.SNET,y.SNLT,y.FNLT,y.FNET],o=[y.ASAP,y.ALAP,y.SNET,y.FNET,y.SNLT,y.FNLT],c=this.gantt.getCalendar(n.calendar_id);if(!c)throw new Error(`Error trying to get calendar with id: ${n.calendar_id}`);let l=Number(n.progress),d=null,u=null,f=null;if(l===100){this.setDatesForActivityWithFullProgress(n);return}l>0&&o.includes(a)?({es:d,ef:u}=this.getDatesForActivityWithZeroProgress(n),f=new je({links:i,activity:n,calculatedActivitiesMap:this.calculations,calculatedAlapsMap:this.alapMap,constraint:a,parentsWithLinks:this.pendingParentsWithLinks,parentsCalculations:this.calculationsOfParentThatImpactChildrens,ganttInstance:this.gantt}).calculate(),a===y.ASAP&&this.totalFloatForAsap.set(r,{es:f.es,ef:f.ef,text:n.text})):{es:d,ef:u}=new je({links:i,activity:n,calculatedActivitiesMap:this.calculations,calculatedAlapsMap:this.alapMap,constraint:a,parentsWithLinks:this.pendingParentsWithLinks,parentsCalculations:this.calculationsOfParentThatImpactChildrens,ganttInstance:this.gantt}).calculate(),a===y.ALAP&&this.alapMap.set(r,{es:n.start_date,ef:n.end_date,text:n.text});let p=wr(n,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})),[y.MSO,y.MFO].includes(a))if(this.totalFloatForMsoMfo.set(r,{es:d,ef:u}),this.constraintsMap.set(r,p),n.progress===0)d=p.es,u=p.ef;else{let m=n.end_date;a===y.MFO&&(m=Math.max(p.ef,n.end_date)),d=n.start_date,u=m}this.calculations.set(r,{es:d,ef:u}),this.activitiesWaitingForCalculation.delete(r)})}getTheGreatesDateBetweenRestrictionAndEsEf(t,r,n="greater"){if(n==="greater")return r.ef>t.ef?r:t;if(n==="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,n){let i=[y.SNET,y.FNET].includes(t)?"greater":"less",{es:a,ef:s}=this.getTheGreatesDateBetweenRestrictionAndEsEf(r,n,i);return{es:a,ef:s}}cleanAllActivityParentsFromLinks(t){return t.map(r=>{let n=this.gantt.getLink(r);if(!n)throw new Error("Error trying to get link",{cause:{linkId:r}});let i=n.source,a=n.target;if(!(!this.gantt.getTask(i)||this.gantt.getTask(i)?.type==="project")&&!(!this.gantt.getTask(a)||this.gantt.getTask(a)?.type==="project"))return r}).filter(Boolean)}},Fo=ri;var ni=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===y.ALAP?this.forwardPathCalculations.get(t):this.calculatedActivities.get(t)}calculateSuccessorTimes(t,r,n=0,i,a=H.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&&i===0){let d=k(s,o,r,this.activity),u=k(s,d,n,this.activity);return{ls:d,lf:u}}let l={lag:i,workTime:o,activityCalendar:s,lsDataCalculation:r,lfDataCalculation:n,isMilestone:c};if(a===H.FS){let{ls:d,lf:u}=this.calculateFsLink(l);return{ls:d,lf:u}}if(a===H.FF){let{ls:d,lf:u}=this.calculateFFLink(l);return{ls:d,lf:u}}if(a===H.SS){let{ls:d,lf:u}=this.calculateSSlink(l);return{ls:d,lf:u}}if(a===H.SF){let{ls:d,lf:u}=this.calculateSFLink(l);return{ls:d,lf:u}}}calculateSS(t,r=!1){let n=this.getValueForSS(t,r),i=-t.lag||0,a=this.activity.duration,s=t.lag;return this.calculateSuccessorTimes(n,i,a,s,H.SS)}calculateFF(t,r){let n=this.getForwardOrBackwardCalculations(Number(t.target)),i=r===y.ALAP?"ef":"lf",a=n[i],s=-this.activity.duration,o=-t.lag||0,c=t.lag;return this.calculateSuccessorTimes(a,s,o,c,H.FF)}calculateFS(t,r){let n="ls";n=r===y.ALAP?"es":"ls";let i=this.getForwardOrBackwardCalculations(Number(t.target),r),a=-this.activity.duration,s=t.lag||0,o=-t.lag||0;return this.calculateSuccessorTimes(i[n],a,o,s,H.FS)}calculateSF(t,r=!1){let n=r?this.getEarlyStartFromForwardPath(Number(t.target)).ef:this.getForwardOrBackwardCalculations(Number(t.target)).lf,i=-t.lag||0,a=this.activity.duration,s=t.lag;return this.calculateSuccessorTimes(n,i,a,s,H.SF)}getEarlyStartFromForwardPath(t){return this.forwardPathCalculations.get(t)}getValueForSS(t,r){return r?this.getEarlyStartFromForwardPath(Number(t.target)).es:this.getForwardOrBackwardCalculations(Number(t.target))["ls"]}calculateDate(t,r,n){let i=gt(r).clone();return k(t,new Date(i),n,this.activity)}getLastWorkingHour(t,r,n="past"){let i=t instanceof Date?t:new Date(t),a=gt(i).clone();return this.isActivityInInitHour(r,i)&&n==="past"&&(a=a.hours(0).minutes(0).seconds(0).milliseconds(0)),ht({dateBaseToCalculate:new Date(a),direction:n,activityCalendar:r,activity:this.activity})}isActivityInInitHour(t,r){let n=r instanceof Date?r:new Date(r),a=t.getWorkHours(n)[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),gt.isMoment(r)?r.hours()===s:n.getUTCHours()===s)}calculateFsLink({lag:t,workTime:r,activityCalendar:n,lsDataCalculation:i,lfDataCalculation:a,isMilestone:s=!1}){let o=null,c=null;if(t===0){let d=this.getLastWorkingHour(r,n,"past");return o=k(n,d,a,this.activity),o=this.getLastWorkingHour(o,n,"past"),c=k(n,o,i,this.activity),{ls:c,lf:o}}let l=r;return s||(l=this.getLastWorkingHour(r,n)),o=k(n,l,a,this.activity),c=k(n,o,i,this.activity),s||(o=this.getLastWorkingHour(o,n,"past",!0)),{ls:c,lf:o}}calculateFFLink({lag:t,workTime:r,activityCalendar:n,lsDataCalculation:i,lfDataCalculation:a}){let s=null,o=null;if(t===0)return s=k(n,r,a,this.activity),o=k(n,s,i,this.activity),{ls:o,lf:s};let c=r;return t>0&&(c=this.getLastWorkingHour(c,n,"past")),s=k(n,c,a,this.activity),o=k(n,s,i,this.activity),{ls:o,lf:s}}calculateSSlink({lag:t,workTime:r,activityCalendar:n,lsDataCalculation:i,lfDataCalculation:a,isMilestone:s=!1}){let o=null,c=null;if(t===0)return c=k(n,r,i,this.activity),o=k(n,c,a,this.activity),{ls:c,lf:o};let l=r;return t<0&&!s&&(l=this.getLastWorkingHour(l,n,"future")),c=k(n,l,i,this.activity),o=k(n,c,a,this.activity),{ls:c,lf:o}}calculateSFLink({lag:t,workTime:r,activityCalendar:n,lsDataCalculation:i,lfDataCalculation:a}){let s=null,o=null;return t===0?(o=k(n,r,i),s=k(n,o,a,this.activity),{ls:o,lf:s}):(o=k(n,r,i,this.activity),s=k(n,o,a,this.activity),{ls:o,lf:s})}},No=ni;var ii=class extends No{constructor(t){super(t),this.constraint=t.constraint||y.ASAP,this.parentsWithFullProgress=t.parentsWithFullProgress,this.parentsThatImpactChildrens=t.parentsThatImpactChildrens,this.projectDates=this.gantt.getSubtaskDates()}calculate(){if(this.links.length===0)return new Gt(this.gantt,"backward").calculateStartAndFinishOfChainOrigin(this.activity);let t=this.activity.progress>0&&this.activity.progress<100,r=this.gantt.getTask(this.activity.parent),n=!1;r&&(n=this.parentsThatImpactChildrens.has(Number(this.activity.parent)));let i=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(i.length!==0){let s=this.getMinLfFromLinks(i);if(i.push(this.calculateTheLsAndLfForTheActivity()),n){let d=this.parentsThatImpactChildrens.get(Number(this.activity.parent));i.push(this.calculateTheLsAndLfForTheActivity(d))}let o=this.getMinDateFromLinks(i),c=o.ls,l=o.lf;return t&&(c=this.activity.start_date,l=this.getMinCalculationLogic(o)),{ls:c,lf:l,minFromLinks:s}}if(n){i.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);i.push({ls:c,lf:o});let l=this.getMinDateFromLinks(i);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,n=this.gantt.getCalendar(this.activity.calendar_id);if(!n)throw new Error(`Calendar not found with id ${this.activity.calendar_id}`);let i=t?t.lf:this.projectDates.end_date;if(!i)throw new Error("End date not found for activity",{cause:{activityId:this.activity.id}});return{ls:k(n,i,-r,this.activity),lf:i}}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 n=this.getSpecialCalculationParamForConstraintLink(),i=this.getSpecialParamForSf(),a=this.getSpecialParamForFF();return{0:()=>this.calculateFS(t,n),1:()=>this.calculateSS(t),2:()=>this.calculateFF(t,a),3:()=>this.calculateSF(t,i)}[t.type]()}getSpecialCalculationParamForConstraintLink(){if(this.constraint===y.ALAP)return y.ALAP;if(this.constraint===y.FNET||this.constraint===y.SNET)return"snet-fnet";if(this.constraint===y.FNLT)return y.FNLT}getSpecialParamForSf(){return!![y.ALAP].includes(this.constraint)}getSpecialParamForFF(){return!![y.MFO,y.MSO].includes(this.constraint)}getMinCalculationLogic(t){if(this.constraint===y.ALAP)return this.getMinDateBasedOnConstraint(t);if(this.constraint===y.FNET)return this.getMinDateBasedOnConstraint(t);if(this.constraint===y.FNLT)return this.getMinDateBasedOnConstraint(t);if(this.constraint===y.MFO)return this.getMinDateBasedOnConstraint(t);if(this.constraint===y.SNET||this.constraint===y.SNLT||this.constraint===y.MSO)return this.SnetSnltMsoMinDate(t);if(this.constraint===y.ASAP)return this.getMinDateBasedOnConstraint(t)}getMinDateFromLinks(t){try{return this.constraint===y.ALAP||this.constraint===y.ASAP?t.reduce((n,i)=>i.lf<n.lf?i:n):t.reduce((r,n)=>n.ls<r.ls?n:r)}catch(r){throw new Error(`Function: getMinDateFromLinks in LinksConstraintCalculator - ${r.message}`)}}getMinLfFromLinks(t){return t.reduce((r,n)=>n.lf<r.lf?n:r)}getMinDateBasedOnConstraint(t,r=this.constraint){let n=Math.min(t.lf,this.projectDates.end_date),i=this.activity.end_date,a=this.activity.constraint_date;if(r===y.ASAP)return new Date(Math.max(n,i));if(r===y.FNET||r===y.FNLT){let s=Math.min(n,a);return new Date(Math.max(n,s))}if(r===y.ALAP)return new Date(Math.min(n,i))}},Mo=ii;function Zp(e,t,r){let n={ls:null,lf:null};return r===y.MSO&&(n.ls=t.constraint_date,n.lf=k(e,n.ls,t.duration,t)),r===y.MFO&&(n.lf=t.constraint_date,n.ls=k(e,n.lf,-t.duration,t)),n}var Wo=Zp;var ai=class extends Gt{constructor(t,r,n){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=n,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 Or({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 Ve({pending:this.activitiesWaitingForCalculation,activityCalculator:r,calculateFn:n=>this.calculateStartAndFinishTimes(n),shouldKeepPending:n=>this.calculationOfParentsFromLinks.has(n)&&!this.calculations.has(n),isCalculated:n=>this.calculations.has(n),onActivityProcessed:n=>this.activitiesWaitingForCalculation.delete(n),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,i=Array.from(this.calculations).filter(o=>r.includes(o[0])).map(o=>o[1]),{minLs:a,maxLf:s}=i.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(i[0].ls),maxLf:new Date(i[0].lf)});this.calculations.set(t.id,{ls:a,lf:s})}calculateStartAndFinishTimes(t){t.forEach(r=>{let n=this.gantt.getTask(r);if(!n)throw new Error("Activity not found",{cause:{activityId:r}});let i=n.$source,a=n.constraint_type||y.ASAP,s=Number(n.progress);if(this.activitiesStartChainButChildrenOfLinkedParents.has(r)){if(this.calculationsOfParentThatImpactChildrens.has(Number(n.parent))&&this.calculationsOfParentThatImpactChildrens.get(Number(n.parent))===!1){let{ls:d,lf:u}=this.calculateStartAndFinishOfChainOrigin(n,this.direction);this.setCalculations(n,d,u);return}return this.doCalculationForActivitiesThatStartLinkButHisParentIsLinked(n)}if(n.type==="project")return this.doCalculationForParentType(n);if(s===100){this.setDatesForActivityWithFullProgress(n);return}if(this.allLinkedActivitiesHasProgress(i,n)){this.setWhenAllLinkedActivitiesHasProgress(n);return}if(s>0&&s<100&&(a===y.MSO||a===y.MFO)){this.setWhenActivitiesHasProgressButLessThanOneHundred(n,a);return}if(a===y.MSO||a===y.MFO){this.recalculateInBaseRestriction(n,a);return}let{ls:o,lf:c,minFromLinks:l}=this.calculateLfandLsFromLinks(i,n,a,this.parentsWithFullProgress,this.calculationsOfParentThatImpactChildrens);(a===y.SNLT||a===y.FNLT)&&({ls:o,lf:c}=this.getTheLessLateInBasEsEfConstraint(n.id,{ls:o,lf:c},a)),this.setCalculations(n,o,c),this.minFromLinks.set(n.id,{ls:l.ls,lf:l.lf})})}getTheLessLateInBasEsEfConstraint(t,r,n){let i=this.forwardConstraintsMap.get(t);if(!i){let a=this.gantt.getTask(t),s=this.gantt.getCalendar(a.calendar_id);i=wr(a,n,s)}return r.lf<i.ef?r:{ls:i.es,lf:i.ef}}allLinkedActivitiesHasProgress(t){try{let r=!0;for(let n of t){let i=this.gantt.getLink(n);if(!i)continue;let a=this.gantt.getTask(i.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:n,lf:i}=this.calculateStartAndFinishOfChainOrigin(t,"backward");if(this.calculationsOfParentThatImpactChildrens.has(r)){n=t.start_date;let a=this.calculationsOfParentThatImpactChildrens.get(r);a&&typeof a=="object"&&a.lf!=null&&(i=new Date(Math.min(i,a.lf)))}this.setCalculations(t,n,i)}setWhenActivitiesHasProgressButLessThanOneHundred(t,r){if(r===y.MSO){this.setCalculations(t,t.start_date,t.end_date);return}if(r===y.MFO){let n=Math.min(t.constraint_date,this.projectDates.end_date),i=new Date(Math.max(n,t.end_date));this.setCalculations(t,t.start_date,i);return}}setCalculations(t,r,n){this.calculations.set(t.id,{ls:r,lf:n,text:t.text})}calculateLfandLsFromLinks(t,r,n,i,a){return new Mo({links:t,activity:r,calculatedActivitiesMap:this.calculations,calculatedForwardActivitiesMap:this.forwardPathCalculations,constraint:n,parentsWithFullProgress:i,parentsThatImpactChildrens:a,ganttInstance:this.gantt}).calculate()}recalculateInBaseRestriction(t,r){try{let n=this.gantt.getCalendar(t.calendar_id);if(!n)throw new Error(`Error trying to get calendar with id: ${t.calendar_id}`);let i=Wo(n,t,r);this.constraintMap.set(t,i),this.setCalculations(t,i.ls,i.lf)}catch(n){throw new Error(n.message)}}cleanAllActivityParentsFromLinks(t){return t.map(r=>{let n=this.gantt.getLink(r).source,i=this.gantt.getLink(r).target;if(!(!this.gantt.getTask(n)||this.gantt.getTask(n)?.type==="project")&&!(!this.gantt.getTask(i)||this.gantt.getTask(i)?.type==="project"))return r}).filter(Boolean)}doCalculationForActivitiesThatStartLinkButHisParentIsLinked(t){let r=Number(t.parent),n=this.calculationsOfParentThatImpactChildrens.get(r),i=0,a=0;if([y.ASAP,y.ALAP,y.SNET,y.FNET].includes(t.constraint_type))if(Number(t.progress)>0){let l=this.projectDates.end_date;a=new Date(Math.min(l,n.lf)),i=t.start_date}else a=n.lf,i=k(this.gantt.getCalendar(t.calendar_id),a,-t.duration,t);if([y.SNLT].includes(t.constraint_type)){let l=t.constraint_date,d=this.calculationsOfParentThatImpactChildrens.get(r),u=k(this.gantt.getCalendar(t.calendar_id),d.lf,-t.duration,t);i=new Date(Math.min(l.getTime(),u.getTime())),a=k(this.gantt.getCalendar(t.calendar_id),i,t.duration,t)}if([y.FNLT].includes(t.constraint_type)){let l=t.constraint_date,d=this.calculationsOfParentThatImpactChildrens.get(r);i=new Date(Math.min(l.getTime(),d.lf.getTime())),a=k(this.gantt.getCalendar(t.calendar_id),i,t.duration,t)}[y.MSO].includes(t.constraint_type)&&(i=t.constraint_date,a=k(this.gantt.getCalendar(t.calendar_id),i,t.duration,t)),[y.MFO].includes(t.constraint_type)&&(a=t.constraint_date,i=k(this.gantt.getCalendar(t.calendar_id),a,-t.duration,t));let s=this.projectDates.end_date,o=[{ls:i,lf:a}];o.push({ls:k(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,n)=>n.lf<r.lf?n:r):!1}},Bo=ai;function Uo(){return null}var jo=({forward:e,backward:t,id:r,activity:n,gantt:i,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:n,gantt:i},freeFloat:{forwardMap:e.calculations||new Map,backwardMap:t.calculations||new Map,activity:n,projectDates:a,gantt:i}});var si=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=y.ASAP),t===y.ASAP||!t)return r===0?this.calculateAsap():this.calculateAsapWithProgress();if(t===y.ALAP)return r===0?this.calculateAlap():this.calculateAlapWithProgress();if(t===y.SNET||t===y.FNET)return r===0?this.calculateSnetFet():this.calculateSnetFnetSnltWithProgress();if(t===y.SNLT)return r===0?this.calculateSnltFnlt():this.calculateSnetFnetSnltWithProgress();if(t===y.FNLT)return r===0?this.calculateSnltFnlt():this.calculateFnltWithProgress();if(t===y.MSO||t===y.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),n=this.getMinValue(t,r),i=this.calculationWithCalendar(this.lf,this.activity.end_date);return this.getMinValue(n,i)/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 n=this.calculationWithCalendar(this.minFromLinks.lf,this.ef);return this.getMinValue(t,r,n)/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),n=this.getMinValue(t,r);if(!this.totalFloatSnltFnlt&&!this.constrainstMap)return this.getMinValue(t,r)/this.gantt.config.hoursPerDay;let i=0;return this.activity.constraint_type===y.SNLT?i=this.calculationWithCalendar(this.constrainstMap.es,this.totalFloatSnltFnlt.es):i=this.calculationWithCalendar(this.constrainstMap.ef,this.totalFloatSnltFnlt.ef),this.getMinValue(i,n)/this.gantt.config.hoursPerDay}calculateMsoMfo(){let t=this.calculationWithCalendar(this.ls,this.es),r=this.calculationWithCalendar(this.lf,this.ef),n=this.getMinValue(t,r);if(!this.totalFloatForMsoMfo&&!this.constrainstMap)return this.getMinValue(t,r)/this.gantt.config.hoursPerDay;let i=0;return this.activity.constraint_type===y.MSO?i=this.calculationWithCalendar(this.constrainstMap.es,this.totalFloatForMsoMfo.es):i=this.calculationWithCalendar(this.constrainstMap.ef,this.totalFloatForMsoMfo.ef),this.getMinValue(i,n)/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)})}},Ho=si;var oi=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===y.MSO||t===y.MFO?this.calculateMsoMfo(t):this.calculateGeneral(t)}calculateFreeFloatOfLink(t=y.ASAP){let r=this.activity.$source.map(n=>{let{LINK:i,LINK_TYPE:a}=this.getLinkData(n),s=this.gantt.getTask(i.target);if(!s)return{linkId:i.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(i.lag),f=Math.max(0,u);return this.linksFreeFloatObject[i.id]=f,{linkId:i.id,freeFloat:f,hasProgress:o}}).filter(n=>n.freeFloat!==null&&n.freeFloat!==void 0);return this.linksFreeFloatArray=r,r}calculateGeneral(t=y.ASAP){let r=this.getMinFloat(this.linksFreeFloatArray),n=this.calculateFreeFloatForEndOfProject(t),i=0;return[y.SNLT,y.FNLT].includes(t)?i=this.doCalculationForSnltFnlt(t,n,r):i=this.doGeneralCalculation(n,r),Math.max(0,i)}getConstraintType(){let{constraint_type:t}=this.activity;return t||(t=y.ASAP),t}getDatesFromSucessorAndPredecessor(t,r,n){let i=n.constraint_type===y.ALAP,a=this.getSucessorAndPredecessorDates({constraint:r,isSuscessorAlap:i,sucessorId:n.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,n){let i=this.calculateFreeFloatOfRestriction(t);return this.getMinValue(n,r,i)}calculateFreeFloatForEndOfProject(t){return this.parseHoursToDays(this.calculationWithCalendar(this.gantt.getSubtaskDates().end_date,t===y.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===y.FNLT?this.forwardMap.get(this.activity.id).ef:this.forwardMap.get(this.activity.id).es))}getLinkData(t){let r=this.gantt.getLink(t)||{},n=ee(r.type);return{LINK:r,LINK_TYPE:n}}getSucessorAndPredecessorDates({constraint:t,isSuscessorAlap:r,sucessorId:n,predecessorId:i}){let a=({direction:s,constraint:o=y.ASAP})=>o===y.ALAP?this.backwardMap.get(i)[s]:this.forwardMap.get(i)[s];if(t===y.ASAP||t===y.SNET||t===y.FNET||t===y.MSO||t===y.MFO)return{fs:{sucessor:r?this.backwardMap.get(n).ls:this.forwardMap.get(n).es,predecessor:a({direction:"ef"})},ss:{sucessor:r?this.backwardMap.get(n).ls:this.forwardMap.get(n).es,predecessor:a({direction:"es"})},ff:{sucessor:r?this.backwardMap.get(n).lf:this.forwardMap.get(n).ef,predecessor:a({direction:"ef"})},sf:{sucessor:r?this.backwardMap.get(n).lf:this.forwardMap.get(n).ef,predecessor:a({direction:"es"})}};if(t===y.ALAP)return{fs:{sucessor:r?this.backwardMap.get(n).ls:this.forwardMap.get(n).es,predecessor:a({constraint:y.ALAP,direction:"lf"})},ss:{sucessor:r?this.backwardMap.get(n).ls:this.forwardMap.get(n).es,predecessor:a({constraint:y.ALAP,direction:"ls"})},ff:{sucessor:r?this.backwardMap.get(n).lf:this.forwardMap.get(n).ef,predecessor:a({constraint:y.ALAP,direction:"lf"})},sf:{sucessor:r?this.backwardMap.get(n).lf:this.forwardMap.get(n).ef,predecessor:a({constraint:y.ALAP,direction:"ls"})}};if(t===y.SNLT)return{fs:{sucessor:r?this.backwardMap.get(n).ls:this.forwardMap.get(n).es,predecessor:a({direction:"ef"})},ss:{sucessor:r?this.backwardMap.get(n).ls:this.forwardMap.get(n).es,predecessor:a({direction:"es"})},ff:{sucessor:r?this.backwardMap.get(n).lf:this.forwardMap.get(n).ef,predecessor:a({direction:"ef"})},sf:{sucessor:r?this.backwardMap.get(n).lf:this.forwardMap.get(n).ef,predecessor:a({direction:"es"})}};if(t===y.FNLT)return{fs:{sucessor:r?this.backwardMap.get(n).ls:this.forwardMap.get(n).es,predecessor:a({direction:"ef"})},ss:{sucessor:r?this.backwardMap.get(n).ls:this.forwardMap.get(n).es,predecessor:a({direction:"es"})},ff:{sucessor:r?this.backwardMap.get(n).lf:this.forwardMap.get(n).ef,predecessor:a({direction:"ef"})},sf:{sucessor:r?this.backwardMap.get(n).lf:this.forwardMap.get(n).ef,predecessor:a({direction:"es"})}}}calculateMsoMfo(t){let r=this.activity.constraint_date||new Date,n=t===y.MSO?this.forwardMap.get(this.activity.id).es:this.forwardMap.get(this.activity.id).ef,i=this.calculationWithCalendar(r,n);return Math.max(0,this.parseHoursToDays(i))}getMinValue(...t){let r=t.filter(n=>n!=null);return r.length?Math.min(...r):0}calculationWithCalendar(t,r){let n=`${r.getTime()}_${t.getTime()}`;if(this.durationCache.has(n))return this.durationCache.get(n);let a=this.gantt.getCalendar(this.activity.calendar_id).calculateDuration({start_date:new Date(r),end_date:new Date(t)});return this.durationCache.set(n,a),a}parseHoursToDays(t){return t?t/this.gantt.config.hoursPerDay:0}getMinFloat(t){if(!t?.length)return null;let r=t.filter(n=>!n.hasProgress).map(n=>n.freeFloat);return r.length===0?null:Math.min(...r)}},Vo=oi;var Yo=e=>({totalFloat:new Ho(e.totalFloat).getTotalFloat(),freeFloat:new Vo(e.freeFloat).getFreeFloat()});var ci=async({activityIds:e,forward:t,backward:r,gantt:n,projectDates:i,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=n.getTask(l);if(!d)continue;let u=jo({forward:t,backward:r,id:l,activity:d,gantt:n,projectDates:i}),{totalFloat:f,freeFloat:p}=Yo(u);o.set(l,f),c.set(l,p),s=await He(s)}return{totalFloatMap:o,freeFloatMap:c}};var li=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,r=()=>!0){let n=++this.currentCalculationId,i=ti(n,this.getCurrentCalculationId),a=()=>i()&&r();try{let s=t||this.gantt;if(this.gantt=s||Uo(),ei(this.gantt))return!1;let o=new Fo(this.gantt);if(await o.calculateAsync(a),!a())return!1;let c=o.calculations,l=o.constraintsMap,d=new Bo(this.gantt,c,l);if(await d.calculateAsync(a),!a())return!1;this.forwardPathCalculations=c,this.backwardPathCalculations=d.calculations;let{totalFloatMap:u,freeFloatMap:f}=await this.calculateFloatsAsync(o,d,a);return a()?(this.totalFloat=u,this.freeFloat=f,this.gantt.refreshData(),!0):!1}catch(s){throw this.forwardPathCalculations?.size,s}}async calculateFloatsAsync(t,r,n){try{let i=this.gantt.getSubtaskDates(),a=Array.from(this.forwardPathCalculations.keys());return await ci({activityIds:a,forward:t,backward:r,gantt:this.gantt,projectDates:i,isCurrent:n})}catch(i){throw this.forwardPathCalculations?.size,i}}},Ko=li;var Qp=e=>e==="fnet"||e==="fnlt"||e==="mfo",th=e=>new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()));function eh(e,t){let r=e.constraintDate;if(!r||!Qp(e.constraintType))return r;let n=th(r);if(r.getTime()!==n.getTime())return r;let i=t.getClosestWorkTime({date:n,dir:"future",task:e});return i.getUTCFullYear()===r.getUTCFullYear()&&i.getUTCMonth()===r.getUTCMonth()&&i.getUTCDate()===r.getUTCDate()?Dn(e,t):r}function rh(e){let t=new Map,r=new Map,n=new Map;return{calculateEndDate:({start_date:i,duration:a})=>{let s=`${i.getTime()}|${a}`,o=t.get(s);if(o!==void 0)return new Date(o);let c=e.calculateEndDate(i,a);return t.set(s,c.getTime()),c},calculateDuration:({start_date:i,end_date:a})=>{let s=`${i.getTime()}|${a.getTime()}`,o=r.get(s);if(o!==void 0)return o;let c=e.calculateDuration(i,a);return r.set(s,c),c},getWorkHours:i=>e.getWorkHours(i),$gantt:{getClosestWorkTime:({date:i,dir:a,unit:s})=>{let o=s??"hour",c=`${i.getTime()}|${a}|${o}`,l=n.get(c);if(l!==void 0)return new Date(l);let d=e.getClosestWorkTime({date:i,direction:a,unit:o});return n.set(c,d.getTime()),d}}}}function nh(e){let t=new Map;e.forEachActivity((i,a)=>t.set(String(a),i));let r=new Map,n=(i,a)=>{let s=r.get(i);if(s!=null)return s;let c=t.get(i)?.parentId??null,l=0;return c!==null&&!a.has(i)&&(a.add(i),l=n(String(c),a)+1),r.set(i,l),l};for(let i of t.keys())n(i,new Set);return r}function ih(e){let t=nh(e),r=new Map;return e.forEachActivity((n,i)=>{let a=String(i);r.set(a,{id:Number(i),parent:n.parentId===null?0:Number(n.parentId),$level:t.get(a)??0,$source:e.getOutgoingLinkIds(a),$target:e.getIncomingLinkIds(a),start_date:n.startDate,end_date:n.endDate,duration:n.durationHours,progress:n.progress,type:n.type,calendar_id:n.calendarId,constraint_type:n.constraintType,constraint_date:eh(n,e)})}),r}function ah(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=[],n=new Set,i=[],a=s=>{if(s)for(let o=s.length-1;o>=0;o-=1)i.push(s[o])};for(a(t.get(0));i.length>0;){let s=i.pop();n.has(s)||(n.add(s),r.push(s),a(t.get(s.id)))}if(r.length<e.size)for(let s of e.values())n.has(s)||r.push(s);return r}function sh(e){let t=null,r=null;return e.forEachActivity(n=>{if(n.startDate){let i=n.startDate.getTime();t=t==null?i:Math.min(t,i)}if(n.endDate){let i=n.endDate.getTime();r=r==null?i:Math.max(r,i)}}),{start_date:new Date(t??0),end_date:new Date(r??0)}}async function Go(e,t){let r=new Map,n=c=>{let l=c==null?"__default__":String(c),d=r.get(l);if(d)return d;let u=e.calendarReader.getCalendar(String(c)),f=rh(u);return r.set(l,f),f},i=sh(e);await Z();let a=ih(e);await Z();let s=[...a.values()].sort((c,l)=>(c.start_date?.getTime()??0)-(l.start_date?.getTime()??0));await Z();let o=ah(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:n,getChildren:c=>e.getChildren(c).map(l=>Number(l)),eachTask:c=>{for(let l of o)c(l)},getTaskByTime:()=>s,getSubtaskDates:()=>i,refreshData:()=>{}}}var oh=1e3;function ch(e,t,r){let n=o=>o==null?null:new Date(o),i=r.forward?.get(e),a=r.backward?.get(e),s=r.totalFloat.get(e)??null;return{criticalPath:{earlyStart:n(i?.es),earlyFinish:n(i?.ef),lateStart:n(a?.ls),lateFinish:n(a?.lf),totalSlackHours:s},isCritical:t<100&&s!=null&&s<=0,freeSlackHours:r.freeFloat.get(e)?.activityFreeFloat??null}}var xr=(e,t)=>e===t||e!==null&&t!==null&&e.getTime()===t.getTime();function di(e,t,r){let n=e.getActivity(t),i=n?.criticalPath,a=r.criticalPath;n&&i&&xr(i.earlyStart,a.earlyStart)&&xr(i.earlyFinish,a.earlyFinish)&&xr(i.lateStart,a.lateStart)&&xr(i.lateFinish,a.lateFinish)&&Object.is(i.totalSlackHours,a.totalSlackHours)&&Object.is(n.isCritical,r.isCritical)&&Object.is(n.freeSlackHours,r.freeSlackHours)||e.setActivityFields(t,r)}async function ui(e,t,r=()=>!0){if(!r())return null;let n=await Go(e,t);if(!r())return null;let i=new Ko(n);if(!await i.calculate(n,r)){if(!r())return null;throw new Error("critical path calculation aborted")}if(!r())return null;let s={forward:i.forwardPathCalculations,backward:i.backwardPathCalculations,totalFloat:i.totalFloat,freeFloat:i.freeFloat},o=new Set([...s.forward?.keys()??[]]),c=new Map,l=0;for(let d of o){if(++l>=oh&&(l=0,await Z(),!r()))return null;let u=e.getActivity(d);if(!u)continue;let f=Number(u.progress??0);c.set(d,ch(d,f,s))}return r()?c:null}async function Fr(e,t,r=()=>!0){let n=await ui(e,t,r);if(!n||!r())return!1;for(let[i,a]of n){if(!r())return!1;di(e,i,a)}return!0}var b={ID:"id",PROPLANNER_ID:"proplannerId",PARENT:"parentId",NAME:"name",DESCRIPTION:"description",TYPE:"type",START_DATE:"startDate",END_DATE:"endDate",DURATION_HOURS:"durationHours",CONSTRAINT_TYPE:"constraintType",CONSTRAINT_DATE:"constraintDate",AUTO_SCHEDULING:"autoScheduling",CALENDAR_ID:"calendarId",ASSIGNED_DEFAULT_CALENDAR:"assignedDefaultCalendar",DATE_ORIGIN:"dateOrigin",PROGRESS:"progress",COST:"cost",USED_COST:"usedCost",REAL_COST:"realCost",WORK_HOURS:"workHours",REAL_WORK_HOURS:"realWorkHours",PONDERATOR:"ponderator",HAS_CUSTOM_PONDERATOR:"hasCustomPonderator",CORRELATIVE_ID:"correlativeId",UNIQUE_CORRELATIVE_ID:"uniqueCorrelativeId",CUSTOM_ID:"customId",SUBCONTRACT_ID:"subcontractId",IS_LOOKAHEAD:"isLookahead",HAS_LOOKAHEAD_TASKS:"hasLookaheadTasks",NEW_ACTIVITIES_ARRAY:"newActivityIds",HAS_NEW_ACTIVITIES:"hasNewActivities",IS_NEW_ACTIVITY:"isNewActivity",PENDING_REQUEST_IDS:"pendingRequestIds",RESPONSABLE_IDS:"responsableIds",TAG_IDS:"tagIds",BASELINE_POINTS:"baselinePoints",BASELINE_SNAPSHOT:"baselineSnapshot",SUM_OF_DURATION_RECURSIVELY:"recursiveDurationHours",IS_CRITICAL:"isCritical",FREE_SLACK_HOURS:"freeSlackHours",EXPECTED_PROGRESS:"expectedProgress",EXPECTED_PROGRESS_BASELINE:"expectedProgressBaseline",STATUS:"status",CRITICAL_PATH:"criticalPath"},fi={ID:"id",SOURCE:"source",TARGET:"target",TYPE:"type",LAG:"lag",SOURCE_LAG:"_sourceLag",TARGET_LAG:"_targetLag",TRUE_LAG:"_trueLag",SUMMARY_SOURCE_ID:"_summarySourceId",SUMMARY_TARGET_ID:"_summaryTargetId",GANTT_ID:"ganttId",SECTOR_ID:"sectorId",PROPLANNER_ID:"proplannerId"};function ke(e){let t=[],r=[];e.forEachActivity((i,a)=>{i.parentId===null&&t.push(String(a))});let n=i=>{let a=e.getActivity(String(i));if(!a)return 0;let s=[...e.getChildren(String(i))],o;if(s.length===0){let c=ut(a),l=c&&Number(c.cost)||0;o=(Number(a.progress)||0)/100*l}else{let c=0;for(let l of s)c+=n(String(l));o=c}return e.setActivityField(String(i),b.REAL_COST,o),r.push(String(i)),o};for(let i of t)n(i);return r}var $o=new Set;var zo=new Set(["activity-outdent","activity-indent"]);var Ye=new Set([E.TEXT,E.DESCRIPTION,E.COST,E.USED_COST,E.CUSTOM_ID,E.RESPONSABLES,E.SUBCONTRACT_ID,E.TAGS]),lh=new Set(["selection-toggle","selection-replace","visibility-set","filter-set","sort-set","sir-sync","activity-lookahead-sync","persistence-acknowledge","baseline-apply","ponderator-criterion-set","status-criteria-set"]),dh=new Set(["selection-toggle","selection-replace","visibility-set","filter-set","sort-set"]);function Jo(e){return!dh.has(e.kind)}var uh=new Set;function fh(e){return e.kind==="inline-edit"?Ye.has(e.column):e.kind==="bulk-edit"?e.edits.every(t=>Ye.has(t.column)):!1}function pi(e,t){return!(lh.has(e.kind)||t.has(e.kind)||fh(e))}function hi(e){return pi(e,uh)}function re(e){return pi(e,$o)}function Xo(e){return pi(e,zo)}function yi(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 ph(e){return Xo(e)&&yi(e)}var qo=new Set([E.PROGRESS,E.HH_WORK_TIME,E.DURATION,E.COST,E.USED_COST,E.REAL_COST]);function hh(e){return e.kind==="activity-set-progress"?!0:e.kind==="inline-edit"?qo.has(e.column):e.kind==="bulk-edit"?e.edits.some(t=>qo.has(t.column)):!1}var at={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 Zo(e,t,r){let n=new Set;t.ran&&n.add(at.AUTOSCHEDULE),n.add(at.PARENT_BOUNDS),hh(e)&&n.add(at.PARENT_PROGRESS),yi(e)&&n.add(at.REAL_WORK);let i=!r.skipAutoSchedule;return i&&Xo(e)&&n.add(at.EXPECTED_PROGRESS),i&&ph(e)&&n.add(at.REAL_COST),i&&re(e)&&!r.skipCriticalPath&&n.add(at.CRITICAL_PATH),n}async function G(e,t){let r=yh(t);r.has(at.AUTOSCHEDULE)&&await Ah(e.adapter,t);let n=r.has(at.AUTOSCHEDULE)?await mh(e,t.autoscheduleFrom):vh();return await Ch(e.adapter,t,n.scheduledIds,r),await Ih(e,r,t.now),n}function yh(e){let t=e.autoscheduleFrom!==null,r=!e.options.skipAutoSchedule&&t,n=new Set(Zo(e.action,{requested:t,ran:r},e.options));return e.recomputeParentProgress&&n.add(at.PARENT_PROGRESS),n}async function mh(e,t){let r=t==="roots"?{}:{triggerId:t},n=await e.scheduler.schedule(r),i=gh(e.adapter,n.updatedIds);return Ne(e.adapter,n),i}function gh(e,t){let r=[];for(let n of t){let i=String(n);r.push(i);let a=e.getActivity(i);a&&e.noteScheduledBefore(i,a)}return{scheduledIds:r}}function vh(){return{scheduledIds:[]}}async function Ah(e,t){let r=t.collectDirty?t.collectDirty([]):Hn(t.recomputeParentsFrom,[]);r.size!==0&&await fe(e,r,!1)}async function Ch(e,t,r,n){let i=t.collectDirty?t.collectDirty(r):Hn(t.recomputeParentsFrom,r);await fe(e,i,n.has(at.PARENT_PROGRESS),{recomputeRealWork:n.has(at.REAL_WORK),progressMode:t.recomputeParentProgress?"zero-when-no-contribution":"freeze-when-no-contribution"})}async function Ih(e,t,r){t.has(at.EXPECTED_PROGRESS)&&r!==null&&(Sh(e.adapter)&&Se(e.adapter,r,e.defaultBaseCalendarId??null),te(e.adapter,r),Ft(e.adapter,e.sector.statusCriteria)),t.has(at.REAL_COST)&&ke(e.adapter),t.has(at.CRITICAL_PATH)&&await Fr(e.adapter,e.sector.hoursPerDay)}function Sh(e){let t=!1;return e.forEachActivity(r=>{ut(r)&&(t=!0)}),t}var kh=new Set([E.CONSTRAINT_TYPE,E.CONSTRAINT_DATE]),Dh=new Set(["mso","mfo"]);function Nr(e){return kh.has(e)}function Mr(e){return e===E.CONSTRAINT_DATE}function Wr(e,t,r,n){let i=r.getActivity(e);if(!i)return!1;let a=i.constraintType;if(!a||jt.has(a)||Dh.has(a))return!1;let s=mi(i.startDate),o=mi(r.getLastStartDate(e));if(!o||!s||s.getTime()!==o.getTime())return!1;let c=Th(t,a,String(i.calendarId??""),n),l=mi(i.constraintDate);return _h(l,c)?!1:(r.setActivityField(e,"constraintDate",c),!0)}function Th(e,t,r,n){if(e===null)return null;let i=n.getCalendar(r);return i?wt(e,i,t):e}function mi(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 _h(e,t){return e===null&&t===null?!0:e===null||t===null?!1:e.getTime()===t.getTime()}async function Br(e,{postMutationArgs:t,revertTargets:r,revert:n}){let{scheduledIds:i}=await G(e,Qo(t)),a=!1;for(let{activityId:s,priorConstraintDate:o}of r){let c=n(s,o);a=a||c}if(a){let s=await G(e,Qo(t));i=Eh(i,s.scheduledIds)}return re(t.action)&&await G(e,Ph(t)),{scheduledIds:i}}function Qo(e){return{...e,options:{...e.options,skipCriticalPath:!0}}}function Ph(e){return{action:e.action,autoscheduleFrom:null,recomputeParentsFrom:[],now:null,options:e.options}}function Eh(e,t){let r=new Set(e);for(let n of t)r.add(n);return[...r]}function Rh(e,t){let r=n=>n.getTime();return r(e.startDate)!==r(t.startDate)||r(e.endDate)!==r(t.endDate)||e.durationHours!==t.durationHours}function gi(e,t,r){let n=[];for(let i of r){let a=e.get(i);if(!a)continue;let s=a.pendingRequestIds??[];if(!oe({pendingRequestIds:s}))continue;let o=t.getActivity(i),c=o==null;if(!c&&!Rh(a,o))continue;let l=c?"activity_deleted":"date_changed";for(let d of s)n.push({kind:"sir-auto-reject",activityId:i,sirId:d,reason:l});c||t.setActivityField(i,"pendingRequestIds",[])}return n}async function B(e,t){let r=Lh(e,t),n=new Map(t.beforeSnap),i=e.peekWriteCapture();if(i){let d=Oh(i);wh(e,i,d,n,r)}let a=t.sirDetection==="before-diff"?gi(n,e,r):[],s=bh(t.correlativeShifts,r),o=await vo(e,n,r,s),c=t.sirDetection==="after-diff"?gi(n,e,r):a,l=t.warnings??[];return{source:t.source,activities:o,links:t.links??[],calendars:[],trackingEvents:t.trackingEvents??[],...c.length>0?{effects:c}:{},...l.length>0?{warnings:l}:{}}}function bh(e,t){if(!e||e.length===0)return;let r=new Map;for(let n of e)r.set(n.activityId,n.before),t.add(n.activityId);return r}function Lh(e,t){let r=new Set;for(let n of t.touchedIds)r.add(n);for(let n of t.scheduledIds)r.add(n);if(t.includeAllIds)for(let n of e.getAllIds())r.add(n);return r}function wh(e,t,r,n,i){for(let a of t.dirty){if(r.has(a)||n.has(a))continue;let s=t.before.get(a),o=e.getActivity(a);!s||!o||Object.keys(jn(s,o)).length!==0&&(n.set(a,s),i.add(a))}}function Oh(e){return new Set(e.ops.filter(t=>t.kind==="insert").map(t=>t.activityId))}function vt(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 De(e,t,r){let n=[];for(let{op:i,finalLinkId:a,rejected:s}of e){if(s!==null)continue;if(i.kind==="create"){if(!a)continue;let d=r.getLink(a);if(!d)continue;let u=t.get(a);if(u){let f={};String(u.source)!==String(d.source)&&(f.source={before:String(u.source),after:String(d.source)}),String(u.target)!==String(d.target)&&(f.target={before:String(u.target),after:String(d.target)}),u.type!==d.type&&(f.type={before:u.type,after:d.type}),Number(u.lag)!==Number(d.lag)&&(f.lag={before:Number(u.lag),after:Number(d.lag)}),Object.keys(f).length>0&&n.push({id:String(a),kind:"updated",fields:f,after:vt(d)});continue}n.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:vt(d)});continue}if(i.kind==="delete"){if(r.getLink(i.linkId))continue;let d=t.get(i.linkId);n.push({id:String(i.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(i.linkId),c=r.getLink(i.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)}),n.push({id:String(i.linkId),kind:"updated",fields:l,after:vt(c)})}return n}function Te(e,t){let r=new Map;if(!e.getActivity(t))return r;for(let n of e.getIncomingLinkIds(t)){let i=e.getLink(n);i&&r.set(String(i.id),Number(i.lag))}return r}function _e(e,t,r){let n=[];if(!t.getActivity(r))return n;for(let i of t.getIncomingLinkIds(r)){let a=t.getLink(i);if(!a)continue;let s=e.get(String(a.id));s===void 0||s===Number(a.lag)||n.push({id:String(a.id),kind:"updated",fields:{lag:{before:s,after:Number(a.lag)}},after:vt(a)})}return n}function Ur(e,t){typeof e=="string"&&e.length>0&&t.releaseCustomId(e)}async function tc(e,t,r){let{adapter:n,ctx:i,scheduler:a,sector:s}=r,o=Vt(e.column);if(!o)return{ok:!1,reason:D.NO_PIPELINE_FOR_COLUMN};e.column===E.DURATION&&a.invalidateExpandedLinksCache();let c=i.activityReader.getActivity(e.activityId);if(!c)return{ok:!1,reason:D.ACTIVITY_NOT_FOUND};let l=o.canEdit(c,i.hierarchy);if(!l.allowed)return{ok:!1,reason:l.reason??D.CANNOT_EDIT,alertKey:l.alertKey};let d=o.parseInput(e.newValue,c,i);if(!d.ok)return{ok:!1,reason:d.reason??D.PARSE_ERROR};let u=Reflect.get(c,o.targetField),f=o.validate(c,u,d.value,i);if(!f.valid)return{ok:!1,reason:f.reason??D.INVALID,alertKey:f.notification?.messageKey};if(e.column===E.CUSTOM_ID&&d.value!==null){let T=n.getActivity(e.activityId),R=T?T.customId:null,x=typeof R=="string"?R:null;if(r.customIdTracker.isCustomIdInUse(String(d.value),x))return{ok:!1,reason:D.CUSTOM_ID_DUPLICATE}}let p=o.transform(c,d.value,i,d.raw),m=Yt(e.activityId,p),I=await q(n,m),C=Te(n,String(e.activityId)),_=c.constraintDate;Kt(n,e.activityId,p),Ut(e.activityId,p.postProcessors??[],n,I.get(String(e.activityId))??null);let S=_e(C,n,String(e.activityId));if(e.column===E.CUSTOM_ID){let T=I.get(String(e.activityId)),R=T?T.customId:null,x=typeof R=="string"?R:null,O=typeof d.value=="string"?d.value:null;x!==O&&r.customIdTracker.trackCustomIdChange(x,O)}let P=()=>({action:e,autoscheduleFrom:p.needsAutoSchedule?String(e.activityId):null,recomputeParentsFrom:[],collectDirty:T=>Rr(e.activityId,m,T),now:r.now,options:t}),g=Nr(e.column),{scheduledIds:h}=await(g?Br({adapter:n,scheduler:a,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{postMutationArgs:P(),revertTargets:Mr(e.column)?[]:[{activityId:e.activityId,priorConstraintDate:_}],revert:(T,R)=>Wr(T,R,n,i.calendars)}):G({adapter:n,scheduler:a,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},P())),v=(p.trackingEvents??[]).map(T=>({name:T.name,properties:T.properties??{}})),A=Ae(e.activityId,p.constraintWarning);return{ok:!0,changes:await B(n,{source:e,beforeSnap:I,touchedIds:m,scheduledIds:h,sirDetection:"before-diff",links:S,trackingEvents:v,...A?{warnings:[A]}:{},hoursPerDay:s.hoursPerDay})}}function xh(e,t){let r=new Set,n=new Map;for(let i of e){if(i.kind==="create"){r.add(String(i.source)),r.add(String(i.target));continue}let a=t.getLink(i.linkId);a&&(r.add(String(a.source)),r.add(String(a.target)),n.set(i.linkId,{...a}))}return{activityIds:r,links:n}}function Fh(e,t,r,n){return e.map((i,a)=>{let s=i.kind==="create"?n?.get(a):void 0,o=Pt(i,{port:t,newLinkId:s?()=>s:r.next});return{op:i,finalLinkId:o.applied?o.linkId:null,rejected:o.applied?null:o.rejected??"link_op_rejected"}})}function Nh(e){return new Map([...e].map(([t,r])=>[String(t),r]))}async function ec(e,t,r){if(e.kind==="link-create"||e.kind==="link-update"){let n=e.type;if(n!==void 0&&!Object.values(M).some(a=>a===n))return{ok:!1,reason:D.INVALID_LINK_TYPE};let i=e.lag;if(i!==void 0&&!Number.isFinite(i))return{ok:!1,reason:D.INVALID_LINK_LAG}}return vi([jh(e,r.sector.hoursPerDay)],e,t,r,e.kind==="link-create"&&e.linkId?new Map([[0,e.linkId]]):void 0)}async function rc(e,t,r){let{hoursPerDay:n}=r.sector,i=e.operations.map(s=>Wh(s,n)),a=Mh(e.operations);return vi(i,e,t,r,a)}function Mh(e){let t=new Map;return e.forEach((r,n)=>{r.kind==="create"&&r.linkId&&t.set(n,r.linkId)}),t.size>0?t:void 0}function Wh(e,t){return e.kind==="create"?{kind:"create",source:e.source,target:e.target,type:e.type,lag:dt(e.lag??0,t)}:e.kind==="update"?{kind:"update",linkId:e.linkId,type:e.type,lag:e.lag===void 0?void 0:dt(e.lag,t)}:{kind:"delete",linkId:e.linkId}}async function vi(e,t,r,n,i){let{adapter:a,scheduler:s,sector:o,linkIdGen:c}=n;s.invalidateAllCaches();let{activityIds:l,links:d}=xh(e,a),u=await q(a,l),f=Fh(e,a,c,i);if(e.length===1&&f[0]&&f[0].rejected!==null&&t.kind!=="inline-edit")return{ok:!1,reason:f[0].rejected};let p=Bh(f,d,a),{scheduledIds:m}=await G({adapter:a,scheduler:s,sector:n.sector,defaultBaseCalendarId:n.defaultBaseCalendarId},{action:t,autoscheduleFrom:p,recomputeParentsFrom:l,now:n.now,options:r}),I=De(f,d,a);return{ok:!0,linkVerdicts:f.map((C,_)=>C.rejected===null?{operationIndex:_,kind:C.op.kind,ok:!0,linkId:String(C.finalLinkId)}:{operationIndex:_,kind:C.op.kind,ok:!1,reason:C.rejected}),__beforeLinks:Nh(d),changes:await B(a,{source:t,beforeSnap:u,touchedIds:l,scheduledIds:m,links:I,hoursPerDay:o.hoursPerDay})}}function Bh(e,t,r){for(let n of e){if(n.rejected!==null)continue;let i=Uh(n.op,t,r);if(i!==null)return r.hasChildren(i)?"roots":String(i)}return null}function Uh(e,t,r){return e.kind==="create"?e.target:e.kind==="delete"?t.get(e.linkId)?.target??null:r.getLink(e.linkId)?.target??null}function jh(e,t){return e.kind==="link-create"?{kind:"create",source:e.source,target:e.target,type:e.type,lag:dt(e.lag,t)}:e.kind==="link-update"?{kind:"update",linkId:e.linkId,type:e.type,lag:e.lag===void 0?void 0:dt(e.lag,t)}:{kind:"delete",linkId:e.linkId}}async function nc(e,t,r){let{adapter:n,sector:i}=r;if(typeof e.newValue!="string")return{ok:!1,reason:D.INVALID_VALUE};if(!n.getActivity(e.activityId))return{ok:!1,reason:D.ACTIVITY_NOT_FOUND};let s=e.column===E.CUSTOM_PREDECESSORS,{specs:o}=hr(e.newValue),c=o.map(m=>({...m,lag:dt(m.lag,i.hoursPerDay)})),l=new Map;n.forEachActivity(m=>{m.correlativeId!=null&&l.set(String(m.correlativeId),m.id)});let d=m=>l.get(m)??null,u=s?n.getIncomingLinkIds(e.activityId):n.getOutgoingLinkIds(e.activityId),f=[];for(let m of u){let I=n.getLink(m);I&&f.push(I)}let p=s?mr({targetActivityId:e.activityId,currentLinks:f,desiredSpecs:c,resolveActivityByCorrelative:d}):gr({sourceActivityId:e.activityId,currentLinks:f,desiredSpecs:c,resolveActivityByCorrelative:d});return vi(p.operations,e,t,r)}var At={ACTIVITY_CREATION:"schedule_activity_creation",ACTIVITY_DELETION:"schedule_activity_deletion",ACTIVITY_MOVE:"schedule_activity_move",ACTIVITY_INDENT:"schedule_activity_indent",ACTIVITY_OUTDENT:"schedule_activity_outdent"};function st(e){e.invalidateVisualOrderIds?.();let t=[];e.forEachActivity(a=>{L(a.parentId)&&t.push(a)}),t.sort(sc);let r=[];ic(r,t);let n=[],i=0;for(;r.length>0;){let a=r.pop();if(a.correlativeId!==i){let o=typeof a.correlativeId=="number"?a.correlativeId:void 0;n.push({activityId:String(a.id),before:o}),o!==void 0&&e.noteCorrelativeBefore?.(String(a.id),o),Hh(a,i)}i+=1;let s=we(String(a.id),e);s.sort(sc),ic(r,s)}return n}function ic(e,t){for(let r=t.length-1;r>=0;r-=1)e.push(t[r])}function ac(e){let t=e.correlativeId,r=typeof t=="number"?t:Number(t);return Number.isFinite(r)?r:Cn}var sc=(e,t)=>ac(e)-ac(t);function Hh(e,t){e.correlativeId=t}function Ci(e,t){if(!e||e==="0")return;let r=String(e);for(;r!==null;){let n=t.getChildren(r),i=0,a=0;for(let c of n){let l=t.getActivity(c);if(!l)continue;let d=Ai(l,b.WORK_HOURS),u=Vh(c,l,d,t);i+=d,a+=u}t.setActivityField(r,b.WORK_HOURS,i),t.setActivityField(r,b.REAL_WORK_HOURS,a);let s=t.getActivity(r);if(!s)break;let o=s.parentId;if(!o||L(o))break;r=o}}function oc(e,t){let r=t.getActivity(e);if(!r)return;let n=r.parentId;!n||L(n)||Ci(n,t)}function Ai(e,t){let r=e[t];return typeof r=="number"&&Number.isFinite(r)?r:0}function Vh(e,t,r,n){return n.hasChildren(e)?Ai(t,b.REAL_WORK_HOURS):pt(r,Ai(t,b.PROGRESS))}function Ii(e,t){if(!e||e==="0")return;let r=String(e);for(;r!==null;){let n=t.getChildren(r),i=0;for(let o of n){let c=t.getActivity(o);c&&(i+=Yh(c,b.USED_COST))}t.setActivityField(r,b.USED_COST,i);let a=t.getActivity(r);if(!a)break;let s=a.parentId;if(!s||L(s))break;r=s}}function cc(e,t){let r=t.getActivity(e);if(!r)return;let n=r.parentId;!n||L(n)||Ii(n,t)}function Yh(e,t){let r=e[t];return typeof r=="number"&&Number.isFinite(r)?r:0}function Si(e,t){if(!e||e==="0")return;let r=String(e);for(;r!==null;){let n=t.getChildren(r),i=0;for(let o of n){let c=t.getActivity(o);c&&(i+=Kh(c,b.COST))}t.setActivityField(r,b.COST,i);let a=t.getActivity(r);if(!a)break;let s=a.parentId;if(!s||L(s))break;r=s}}function lc(e,t){let r=t.getActivity(e);if(!r)return;let n=r.parentId;!n||L(n)||Si(n,t)}function Kh(e,t){let r=e[t];return typeof r=="number"&&Number.isFinite(r)?r:0}var jr=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}),dc="New Master Plan",uc="New Activity";var Gh=["name","description","type","startDate","durationHours","constraintType","constraintDate","calendarId","assignedDefaultCalendar","autoScheduling","progress","cost","usedCost","realCost","workHours","realWorkHours","ponderator","hasCustomPonderator","customId","subcontractId","responsableIds","tagIds","isLookahead"],fc=new Set(Gh);function $h(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"||!fc.has(r))throw new Error(`activity-create: rejected override key "${String(r)}" \u2014 not a creation-writable canonical field`);return e}function pc(e,t){let r=e.parentId!=null?t.getActivity(e.parentId):null,n=$h(e.activityOverrides??{}),i=e.numTasksInGantt===0?dc:uc,a=n.name??i,s=n.durationHours??e.sector.hoursPerDay,o=n.calendarId??e.sector.defaultCalendar,c=zh(r,e.fallbackStartDate,n.startDate),l={...jr,...n,id:e.id,parentId:e.parentId,uniqueCorrelativeId:e.nextUniqueCorrelativeId,name:a,durationHours:s,calendarId:o,startDate:c,endDate:c},d=n.startDate?new Date(l.startDate):t.getClosestWorkTime({date:l.startDate,dir:J.FUTURE,task:l});if(!n.startDate&&r&&bt(r.type)){let p=new Date(r.startDate);p.setUTCHours(0,0,0,0);let m=new Date(d);m.setUTCHours(0,0,0,0),m.getTime()!==p.getTime()&&(d=t.getClosestWorkTime({date:p,dir:J.FUTURE,task:l}))}let u=t.calculateEndDate({startDate:d,durationHours:l.durationHours,task:l});return{newTask:{...l,startDate:d,endDate:u,newActivityIds:[...l.newActivityIds],pendingRequestIds:[...l.pendingRequestIds],responsableIds:[...l.responsableIds],tagIds:[...l.tagIds],baselinePoints:[...l.baselinePoints]}}}function zh(e,t,r){return r?new Date(r):e?new Date(e.startDate):t?new Date(t):new Date}function qh(e){let t=e.type;if(t!=="task"&&t!=="milestone")return null;let r=e.startDate,n=e.endDate;return!(r instanceof Date)||!(n instanceof Date)?null:{type:t,startDate:new Date(r),endDate:new Date(n),durationHours:Number(e.durationHours??0),expectedProgressBaseline:typeof e.expectedProgressBaseline=="number"?e.expectedProgressBaseline:null,constraintType:e.constraintType??null,constraintDate:e.constraintDate instanceof Date?new Date(e.constraintDate):null,progress:Number(e.progress??0)}}function Pe(e){let t=e.getParent(e.parentId);if(!t)return null;let r=e.isCurrentlyLeaf!==void 0?e.isCurrentlyLeaf&&Wt(t.type):Jh(t),n=Array.isArray(t.newActivityIds)?t.newActivityIds:[],a={isLookahead:!1,hasNewActivities:!0,newActivityIds:n.some(s=>String(s)===String(e.newChildId))?[...n]:[...n,e.newChildId]};return t.customId!=null&&t.customId!==""&&(a.customId=null),r&&(a.type=Rn,(e.promotionSource??"create")==="create"&&(a.constraintType=K.ASAP,a.constraintDate=null,a.progress=0)),{parentId:e.parentId,fields:a,promotionSnapshot:qh(t)}}function Jh(e){return Wt(e.type)&&(!Array.isArray(e.newActivityIds)||e.newActivityIds.length===0)}function Hr(e,t,r,n){let i=t,a=i==="0",s=Ke(e,i);if(n!==void 0){let c=s.find(l=>l.id===n);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 ne=Number.MAX_SAFE_INTEGER,hc=Number.MAX_SAFE_INTEGER-1;function nt(e){let t=e.correlativeId,r=typeof t=="number"?t:Number(t);return Number.isFinite(r)?r:ne}function Ke(e,t){return we(t,e)}function yc(e,t,r){let n=e,i=$t(e,r);for(;i!=null&&t.has(i);)n=i,i=$t(i,r);return n}function Vr(e,t,r){let n=new Set([e]),i=Mt(r.getActivity(e)?.parentId);for(;i!=="0"&&!n.has(i);){if(t.has(i))return!0;n.add(i),i=Mt(r.getActivity(i)?.parentId)}return!1}function $t(e,t){let r=t.getActivity(e);if(!r)return null;let n=Mt(r.parentId),i=mt(n,t),a=i.findIndex(s=>String(s)===String(e));return a<=0?null:i[a-1]??null}function mc(e,t,r,n){let i=mt(t,e).filter(c=>String(c)!==String(n)).map(c=>e.getActivity(c)).filter(c=>c!==null);if(i.length===0)return 0;let a=i.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}async function Ge(e,t,r={}){let{adapter:n,scheduler:i,sector:a,calendars:s,activityIdGen:o,uidGen:c}=t;r.skipCacheInvalidation||i.invalidateAllCaches();let l=Xh(e,n);if(!l.ok)return l;let{parent:d,anchorSiblingId:u,isRoot:f}=l,p=Qh(e.activityId,n,o),m=c.next(),I={id:p,parentId:f?null:e.parentId,sector:{id:a.id,hoursPerDay:a.hoursPerDay,defaultCalendar:ay(s)},numTasksInGantt:n.activityCount(),nextUniqueCorrelativeId:m,activityOverrides:e.overrides??{}},_=pc(I,{getActivity:A=>n.getActivity(A),calculateEndDate:A=>n.calculateEndDate(A),getClosestWorkTime:A=>n.getClosestWorkTime(A)}).newTask;_.realWorkHours=pt(_.workHours,_.progress),ey(_,e,t,u,d,r);let S=r.insertionCorrelativeId??Hr(n,f?"0":e.parentId,e.afterSiblingId,e.beforeSiblingId);_.correlativeId=S;let P=new Set([p]);d&&P.add(d.id);let g=d!==null&&n.getChildren(d.id).length===0,h=g?d?.customId:null,v=r.skipBeforeSnap?new Map:await q(n,P);return n.addActivity(_),ry(e,p,d,n,g),h&&t.customIdTracker.releaseCustomId(h),r.skipRollupCascades||(oc(p,n),cc(p,n),lc(p,n)),ny(n,p,v,P,r),{ok:!0,newId:p,parent:d,newActivity:_,beforeSnap:v,initialTouched:P}}function Xh(e,t){let r=L(e.parentId),n=r?null:t.getActivity(e.parentId);if(!r&&!n)return{ok:!1,reason:D.PARENT_NOT_FOUND};if(n!==null&&oe(n))return{ok:!1,reason:D.PARENT_FROZEN_BY_SIR};if(e.afterSiblingId!==void 0&&e.beforeSiblingId!==void 0)return{ok:!1,reason:D.ANCHOR_SIBLING_CONFLICT};let s=e.afterSiblingId??e.beforeSiblingId,o=Zh(e,t,r,s);return o||{ok:!0,parent:n,anchorSiblingId:s,isRoot:r}}function Zh(e,t,r,n){if(n===void 0)return null;let i=t.getActivity(n);if(!i)return{ok:!1,reason:D.ANCHOR_SIBLING_NOT_FOUND};let a=r?"0":e.parentId;return(i.parentId==null?"0":String(i.parentId))!==a?{ok:!1,reason:D.ANCHOR_SIBLING_WRONG_PARENT}:null}function Qh(e,t,r){return e===void 0||t.activityExists(e)?r.next():(r.bump(e),e)}function ty(e){let t=e.overrides?.customId;return typeof t=="string"?t:void 0}function ey(e,t,r,n,i,a){let{adapter:s,customIdTracker:o}=r,c=ty(t);if(c!==void 0){if(c.length===0)return;if(!o.isCustomIdInUse(c)){o.registerCustomId(c);return}}let l=a.customIdReferenceId??n,d=l!==void 0,u=d?s.getActivity(l):i;e.customId=o.generateCustomIdForNewChild({activity:u??{},useActivityCustomIdAsReference:d})}function ry(e,t,r,n,i){if(!r)return;let a=Pe({parentId:e.parentId,newChildId:t,isCurrentlyLeaf:i,getParent:s=>n.getActivity(s)??null});if(a){for(let[s,o]of Object.entries(a.fields))rt(n,a.parentId,s,o);a.promotionSnapshot&&n.setPromotionSnapshot(a.parentId,a.promotionSnapshot)}}function ny(e,t,r,n,i){if(i.skipCorrelativeRecompute)return;let a=st(e);i.skipBeforeSnap||Ce(e,a,new Set([String(t)]),r,n)}async function iy(e,t,r,n,i){let{newId:a,newActivity:s,beforeSnap:o,initialTouched:c}=r,l={name:At.ACTIVITY_CREATION,properties:{parent_id:t.parentId,activity_id:a,created_duration:s.durationHours}};return t.eventSource!==void 0&&(l.properties.event_source=t.eventSource),B(e,{source:t,beforeSnap:o,touchedIds:c,scheduledIds:n,trackingEvents:[l],hoursPerDay:i})}async function gc(e,t,r){let{adapter:n,scheduler:i,sector:a}=r,s=await Ge(e,r);if(!s.ok)return s;let{newId:o}=s,c=s.newActivity.autoScheduling;n.setActivityField(o,"autoScheduling",!1);let l;try{l=await G({adapter:n,scheduler:i,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:"roots",recomputeParentsFrom:[o],now:r.now,options:t})}finally{n.setActivityField(o,"autoScheduling",c)}let{scheduledIds:d}=l;return{ok:!0,changes:await iy(n,e,s,d,a.hoursPerDay)}}function ay(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 Dt(e,t){Ci(e,t),Ii(e,t),Si(e,t)}function vc(e,t){let r=new Set,n=[];for(let i of e){let a=String(i);r.has(a)||(r.add(a),n.push(a))}for(;n.length>0;){let i=n.pop(),a=t.getChildren(i);for(let s of a){let o=String(s);r.has(o)||(r.add(o),n.push(o))}}return r}function Ac(e,t){let r=new Set;for(let n of e){for(let i of t.getOutgoingLinkIds(n))r.add(String(i));for(let i of t.getIncomingLinkIds(n))r.add(String(i))}return[...r]}function sy(e){return e?{type:e.type,startDate:new Date(e.startDate),endDate:new Date(e.endDate),durationHours:e.durationHours,expectedProgressBaseline:e.expectedProgressBaseline,constraintType:e.constraintType,constraintDate:e.constraintDate?new Date(e.constraintDate):null,progress:e.progress}:null}function oy(e,t,r){let n=e.startDate;return!r||!(n instanceof Date)?{}:{endDate:r(n,t)}}function Ee(e){if(e.remainingChildIds.length>0)return null;let t=e.parent,r=e.defaultDurationHours,n=Number.isFinite(r),i=sy(e.promotionSnapshot)??(n?{type:le,durationHours:r,progress:0,autoScheduling:!0,constraintType:"asap",constraintDate:null,hasNewActivities:!1,...oy(t,r,e.computeEndDate)}:{type:le});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&&(i.newActivityIds=s)}}return t.hasLookaheadTasks&&(i.isLookahead=!0),{parentId:String(t.id),fields:i}}function Cc(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,n=r.filter(i=>!e.idsRemoved.has(i)&&!e.idsRemoved.has(String(i)));return n.length===r.length?null:{parentId:String(e.parent.id),fields:{newActivityIds:[...n],hasNewActivities:n.length>0}}}var Ic=200;async function Sc(e,t,r){let{adapter:n,scheduler:i,customIdTracker:a,sector:s}=r;if(i.invalidateAllCaches(),e.activityIds.length===0)return{ok:!1,reason:D.ACTIVITY_IDS_EMPTY};for(let A of e.activityIds)if(!n.getActivity(A))return{ok:!1,reason:D.ACTIVITY_NOT_FOUND};let o=vc(e.activityIds,n),c=Ac(o,n),l=new Set;for(let A of e.activityIds){let T=n.getActivity(A);if(!T)continue;let R=T.parentId;if(L(R))continue;let x=String(R);o.has(x)||l.add(x)}let d=new Set([...o,...l]),u=await q(n,d),f=new Map;for(let A of c){let T=n.getLink(A);T&&f.set(A,{...T})}let p=new Set,m=0;for(let A of o){m+=1,m%Ic===0&&await Z();let T=n.getActivity(A);if(!T)continue;let R=L(T.parentId)?null:n.getActivity(String(T.parentId)),x=R?.hasNewActivities===!0&&R.newActivityIds.some(V=>String(V)===String(A));(T.isNewActivity===!0||x)&&p.add(A);let O=T.customId;typeof O=="string"&&O.length>0&&a.releaseCustomId(O)}for(let A of c)n.removeLink(A);let I=ki(n,o),C=0;for(let A of o)C+=1,C%Ic===0&&await Z(),n.removeActivity(A);for(let A of l){let T=n.getActivity(A);if(!T)continue;cy(T,p,n);let R=n.getChildren(A),x=Ee({parent:T,remainingChildIds:R.map(String),defaultDurationHours:s.hoursPerDay,promotionSnapshot:n.getPromotionSnapshot(A),computeEndDate:(O,V)=>n.calculateEndDate({startDate:O,durationHours:V,task:T}),idsRemoved:o});if(!x){Cr(A,n);continue}for(let[O,V]of Object.entries(x.fields))rt(n,A,O,V);if(T.customId==null||T.customId===""){let O=$t(A,n),V=O?n.getActivity(O)?.customId:null,Y=a.generateCustomIdForRestoredChild(typeof V=="string"&&V?V:null);n.setActivityField(A,b.CUSTOM_ID,Y)}}for(let A of l)Dt(A,n);let _=st(n),{scheduledIds:S}=await G({adapter:n,scheduler:i,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:"roots",recomputeParentsFrom:l,now:r.now,options:t}),P={name:At.ACTIVITY_DELETION,properties:{activity_ids:[...e.activityIds],cascade_count:o.size}};e.eventSource!==void 0&&(P.properties.event_source=e.eventSource);let g=new Map;for(let[A,T]of f)g.set(A,T);let h=new Map;for(let A of o){let T=u.get(String(A));T&&h.set(String(A),T)}let v=await B(n,{source:e,beforeSnap:u,touchedIds:d,scheduledIds:S,sirDetection:"after-diff",links:ly(f),trackingEvents:[P],hoursPerDay:s.hoursPerDay,correlativeShifts:_});return{ok:!0,changes:I.length>0?{...v,viewState:I}:v,__beforeSnap:h,__beforeLinks:g}}function cy(e,t,r){let n=Cc({parent:e,idsRemoved:t});if(n)for(let[i,a]of Object.entries(n.fields))rt(r,n.parentId,i,a)}function ki(e,t){let r=[];for(let n of t){let i=e.isChecked(n),a=e.isVisible(n);!i&&a||r.push({activityId:String(n),...i?{checked:{before:!0,after:!1}}:{},...a?{}:{visible:{before:!1,after:!0}}})}return r}function ly(e){let t=[];for(let[r,n]of e.entries())t.push({id:r,kind:"deleted",fields:{source:{before:String(n.source),after:void 0},target:{before:String(n.target),after:void 0},type:{before:n.type,after:void 0},lag:{before:Number(n.lag),after:void 0}},after:null});return t}async function Tc(e,t,r){let n=dy(e,r);if(n)return{ok:!1,reason:n};let i=fy(e,r);if(!i.ok)return i;let a=e.mode==="replace"?new Set(r.adapter.getAllIds().map(g=>String(g))):new Set,s=e.mode==="replace"?await q(r.adapter,a):new Map,o=e.mode==="replace"?my(r):new Map,c=e.mode==="replace"?ki(r.adapter,a):[];r.scheduler.invalidateAllCaches();let l=[];if(e.mode==="replace"){for(let g of o.keys()){let h=Pt({kind:"delete",linkId:g},{port:r.adapter});if(!h.applied)return{ok:!1,reason:h.rejected??D.INVALID};l.push({op:{kind:"delete",linkId:g},finalLinkId:g,rejected:null})}for(let g of a){let h=r.adapter.getActivity(g)?.customId;typeof h=="string"&&h.length>0&&r.customIdTracker.releaseCustomId(h),r.adapter.removeActivity(g)}}let d=await yy(e,i.plan.items,r);if(!d.ok)return d;let u=_c(e)?[]:st(r.adapter),f=new Set(i.plan.items.map(g=>String(g.activityId))),p=u.filter(g=>!f.has(g.activityId)),m=e.mode==="replace"?new Set(a):new Set;Ce(r.adapter,u,f,s,m);for(let g of i.plan.items)m.add(String(g.activityId));let I=i.plan.links.map(g=>({operation:{kind:"create",source:g.source,target:g.target,type:g.type,lag:t.inputUnit==="hours"?g.lag:dt(g.lag,r.sector.hoursPerDay)},linkId:g.linkId})),C=pr(I,{port:r.adapter,preserved:o});if(!C.applied)return{ok:!1,reason:C.rejected??D.INVALID};for(let{operation:g,linkId:h}of I)l.push({op:g,finalLinkId:h,rejected:null});let _=i.plan.items.map(g=>g.activityId),{scheduledIds:S}=await G({adapter:r.adapter,scheduler:r.scheduler,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:e.items.length>0||e.links.length>0?"roots":null,recomputeParentsFrom:_,now:r.now,options:t}),P=await B(r.adapter,{source:e,beforeSnap:s,touchedIds:m,scheduledIds:S,links:De(l,o,r.adapter),hoursPerDay:r.sector.hoursPerDay,correlativeShifts:p,...e.mode==="replace"?{sirDetection:"after-diff"}:{}});return{ok:!0,changes:c.length>0?{...P,viewState:c}:P,...e.mode==="replace"?{__beforeSnap:s,__beforeLinks:gy(o)}:{}}}function dy(e,t){if(e.mode!=="append"&&e.mode!=="replace")return D.INVALID;let r=new Set,n=new Set;for(let a of e.items){if(a.batchId.length===0||r.has(a.batchId))return D.INVALID;if(r.add(a.batchId),a.index!==void 0&&(!Number.isInteger(a.index)||a.index<0))return D.INVALID;if(a.activityId!==void 0){let s=String(a.activityId);if(s.length===0||s==="0"||n.has(s)||e.mode==="append"&&t.adapter.getActivity(s)!==null)return D.INVALID;n.add(s)}}for(let a of e.items)if(!Di(a.parent,!0,e.mode,r,t))return D.PARENT_NOT_FOUND;if(uy(e.items))return D.INVALID;let i=new Set;for(let a of e.links){if(!Object.values(M).includes(a.type)||!Number.isFinite(a.lag))return Number.isFinite(a.lag)?D.INVALID_LINK_TYPE:D.INVALID_LINK_LAG;if(!Di(a.source,!1,e.mode,r,t)||!Di(a.target,!1,e.mode,r,t))return D.ACTIVITY_NOT_FOUND;if(a.linkId!==void 0){let s=String(a.linkId);if(s.length===0||i.has(s)||e.mode==="append"&&t.adapter.getLink(s)!==null)return D.INVALID;i.add(s)}}return null}function Di(e,t,r,n,i){return typeof e=="string"?e==="0"?t:r==="append"&&i.adapter.getActivity(String(e))!==null:e!==null&&e.batchId.length>0&&n.has(e.batchId)}function uy(e){let t=new Map;for(let n of e)typeof n.parent!="string"&&t.set(n.batchId,n.parent.batchId);let r=new Set;for(let n of e){let i=new Set,a=n.batchId;for(;a!==void 0&&!r.has(a);){if(i.has(a))return!0;i.add(a),a=t.get(a)}for(let s of i)r.add(s)}return!1}function fy(e,t){for(let o of e.items)o.activityId!==void 0&&t.activityIdGen.bump(o.activityId);let r=new Map;for(let o of e.items)r.set(o.batchId,o.activityId??t.activityIdGen.next());for(let o of e.links)o.linkId!==void 0&&t.linkIdGen.bump(o.linkId);let n=e.links.map(o=>o.linkId??t.linkIdGen.next()),i=py(e,r,t),a=[];for(let o of e.items){let c=r.get(o.batchId),l=i.get(o.batchId);if(c===void 0||l===void 0)return{ok:!1,reason:D.INVALID};let d=typeof o.parent=="string"?null:o.parent.batchId,u=typeof o.parent=="string"?o.parent:r.get(o.parent.batchId);if(u===void 0)return{ok:!1,reason:D.PARENT_NOT_FOUND};a.push({input:o,activityId:c,parentId:u,parentBatchId:d,insertionCorrelativeId:l})}let s=[];for(let[o,c]of e.links.entries()){let l=Dc(c.source,r),d=Dc(c.target,r),u=n[o];if(l===null||d===null||u===void 0)return{ok:!1,reason:D.ACTIVITY_NOT_FOUND};s.push({source:l,target:d,type:c.type,lag:c.lag,linkId:u})}return{ok:!0,plan:{items:a,links:s}}}function py(e,t,r){if(_c(e)){let o=r.adapter.activityCount();return new Map(e.items.map((c,l)=>[c.batchId,o+l]))}let n=new Set(Array.from(t.values(),o=>String(o))),i=new Map;for(let o of e.items){let c=t.get(o.batchId);if(c===void 0)continue;let l=typeof o.parent=="string"?o.parent:t.get(o.parent.batchId);if(l===void 0)continue;let d=String(l),u=i.get(d);u||(u={existing:e.mode==="replace"||typeof o.parent!="string"&&t.has(o.parent.batchId)?[]:Ke(r.adapter,d).sort((I,C)=>nt(I)-nt(C)||String(I.id).localeCompare(String(C.id))).map(I=>String(I.id)),newIdsByTarget:new Map},i.set(d,u));let f=o.index===void 0?u.existing.length:Math.min(o.index,u.existing.length),p=u.newIdsByTarget.get(f)??[];p.push(String(c)),u.newIdsByTarget.set(f,p)}let a=new Map,s=new Map(Array.from(t,([o,c])=>[String(c),o]));for(let o of i.values()){let c=[];for(let d=0;d<=o.existing.length;d+=1){for(let f of o.newIdsByTarget.get(d)??[])c.push(f);let u=o.existing[d];u!==void 0&&c.push(u)}let l=0;for(;l<c.length;){if(!n.has(c[l])){l+=1;continue}let d=l;for(;l<c.length&&n.has(c[l]);)l+=1;let u=l-d,f=d>0?kc(c[d-1],r):null,p=l<c.length?kc(c[l],r):null;for(let m=0;m<u;m+=1){let I=c[d+m],C=s.get(I);C!==void 0&&a.set(C,hy(f,p,m+1,u))}}}return a}function _c(e){return e.mode==="append"&&e.items.every(t=>t.parent==="0"&&t.index===void 0)}function kc(e,t){let r=t.adapter.getActivity(e);return r?nt(r):0}function hy(e,t,r,n){return e!==null&&t!==null&&t>e?e+(t-e)*r/(n+1):e!==null?e+r:t!==null?t-(n-r+1):r-1}async function yy(e,t,r){let n=new Map,i=[];for(let s of t){if(s.parentBatchId===null){i.push(s);continue}let o=n.get(s.parentBatchId)??[];o.push(s),n.set(s.parentBatchId,o)}for(let s=0;s<i.length;s+=1){let o=i[s],c=await Ge({kind:"activity-create",parentId:o.parentId,activityId:o.activityId,...o.input.overrides===void 0?{}:{overrides:o.input.overrides},...e.eventSource===void 0?{}:{eventSource:e.eventSource}},r,{skipCorrelativeRecompute:!0,skipBeforeSnap:!0,skipCacheInvalidation:!0,skipRollupCascades:!0,insertionCorrelativeId:o.insertionCorrelativeId});if(!c.ok)return c;for(let l of n.get(o.input.batchId)??[])i.push(l)}if(i.length!==t.length)return{ok:!1,reason:D.INVALID};let a=new Set;for(let s=i.length-1;s>=0;s-=1){let o=i[s].parentId;o==="0"||a.has(String(o))||(a.add(String(o)),Dt(o,r.adapter))}return{ok:!0}}function Dc(e,t){return typeof e=="string"?e:t.get(e.batchId)??null}function my(e){return new Map(e.adapter.getAllLinks().map(t=>[String(t.id),{...t}]))}function gy(e){return new Map(Array.from(e,([t,r])=>[String(t),r]))}function vy(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:D.ANCHOR_SIBLING_NOT_FOUND}}let r=e.parentId,i=Ke(t,r).sort((a,s)=>nt(a)-nt(s))[e.index]?.id;return{ok:!0,parentId:r,firstBefore:i}}function Ay(e){let{customId:t,...r}=e;return{...r,progress:0,ponderator:0,usedCost:0,workHours:0,isLookahead:!1}}async function Pc(e,t,r){let{adapter:n,scheduler:i,sector:a}=r,s=vy(e.destination,n);if(!s.ok)return s;let o=await q(n,new Set),c=new Set,l=new Map,d=[],u;for(let _ of e.activities){let S=l.get(_.originalParentId),P,g,h;S!==void 0?P=S:(P=s.parentId,u===void 0?(g=s.firstAfter,h=s.firstBefore):g=u);let v=await Ge({kind:"activity-create",parentId:P,afterSiblingId:g,beforeSiblingId:h,..._.activityId?{activityId:_.activityId}:{},overrides:Ay(_.overrides),eventSource:e.eventSource},r,{skipCorrelativeRecompute:!0,skipBeforeSnap:!0,customIdReferenceId:e.referenceActivityId});if(!v.ok)return v;if(_.baselineSnapshot!==void 0){let A=_.baselineSnapshot;n.setActivityField(v.newId,"baselineSnapshot",A?{...A,startDate:A.startDate?new Date(A.startDate):null,endDate:A.endDate?new Date(A.endDate):null}:null)}l.set(_.originalId,v.newId),d.push(v.newId),S===void 0&&(u=v.newId)}let f=st(n),p=new Set(d.map(String));Ce(n,f,p,o,c);for(let _ of d)c.add(String(_));let m=[];for(let _ of e.links){let S=l.get(_.source),P=l.get(_.target);if(S===void 0||P===void 0)continue;let g={kind:"create",source:S,target:P,type:_.type,lag:dt(_.lag,a.hoursPerDay)},h=Pt(g,{port:n,newLinkId:_.linkId?()=>_.linkId:r.linkIdGen.next});m.push({op:g,finalLinkId:h.applied?h.linkId:null,rejected:h.applied?null:h.rejected??"link_op_rejected"})}let{scheduledIds:I}=await G({adapter:n,scheduler:i,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:d[0]??null,recomputeParentsFrom:d,now:r.now,options:t}),C=De(m,new Map,n);return{ok:!0,changes:await B(n,{source:e,beforeSnap:o,touchedIds:c,scheduledIds:I,links:C,hoursPerDay:a.hoursPerDay})}}function Ec(e,t){let{adapter:r}=t,n=e.activityId,i=r.getActivity(n);if(!i)return{ok:!1,reason:D.ACTIVITY_NOT_FOUND};let a=i.pendingRequestIds??[],s=e.pendingRequests.map(c=>c.id);return r.setActivityField(e.activityId,"pendingRequestIds",s),{ok:!0,changes:{source:e,activities:[{id:n,kind:"updated",fields:{pendingRequestIds:{before:a,after:s}},after:{id:n,pendingRequestIds:s}}],links:[],calendars:[],trackingEvents:[]}}}function Rc(e,t){let r=[...new Set(e.activityIds.map(String))],n=r.map(a=>t.adapter.getActivity(a));if(n.some(a=>!a))return{ok:!1,reason:D.ACTIVITY_NOT_FOUND};let i=[];for(let[a,s]of r.entries()){let o=n[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&&i.push({id:s,kind:"updated",fields:c,after:{...o,isLookahead:e.isLookahead,hasLookaheadTasks:e.hasLookaheadTasks}})}return{ok:!0,changes:{source:e,activities:i,links:[],calendars:[],trackingEvents:[]}}}function Yr(e,t){let r=new Set;for(let i of e)r.add(String(i));let n=[];for(let i of t.getAllLinks()){let a=String(i.source),s=String(i.target);!r.has(a)&&!r.has(s)||(bc(s,a,t)||bc(a,s,t))&&n.push(String(i.id))}return n}function bc(e,t,r){let n=String(e),i=new Set;for(;n!=null;){if(i.has(n))return!1;i.add(n);let a=r.getActivity(n);if(!a)return!1;let s=a.parentId;if(s===null||L(s))return!1;let o=s;if(o===t)return!0;n=o}return!1}async function Lc(e,t,r){let{adapter:n,scheduler:i,sector:a}=r;i.invalidateAllCaches();let s=n.getActivity(e.activityId);if(!s)return{ok:!1,reason:D.ACTIVITY_NOT_FOUND};let o=L(e.parentId);if(!o&&!n.getActivity(e.parentId))return{ok:!1,reason:D.PARENT_NOT_FOUND};if(!o&&(e.parentId===e.activityId||n.isChildOf(e.parentId,e.activityId)))return{ok:!1,reason:D.CANNOT_MOVE_INTO_OWN_DESCENDANT};if(e.afterSiblingId!==void 0&&e.beforeSiblingId!==void 0)return{ok:!1,reason:D.ANCHOR_SIBLING_CONFLICT};let c=e.afterSiblingId??e.beforeSiblingId;if(c!==void 0){let h=n.getActivity(c);if(!h)return{ok:!1,reason:D.ANCHOR_SIBLING_NOT_FOUND};if((h.parentId===null?"0":String(h.parentId))!==e.parentId)return{ok:!1,reason:D.ANCHOR_SIBLING_WRONG_PARENT}}let l=s.parentId,d=Mt(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 m=await q(n,p);f&&n.setActivityField(e.activityId,b.PARENT,u);let I=Hr(n,e.parentId,e.afterSiblingId,e.beforeSiblingId);if(n.setActivityField(e.activityId,b.CORRELATIVE_ID,I),f){if(!o){let h=n.getActivity(e.parentId);if(h){let v=h.customId,A=Wt(h.type)&&n.getChildren(e.parentId).filter(R=>R!==e.activityId).length===0,T=Pe({parentId:e.parentId,newChildId:e.activityId,getParent:R=>n.getActivity(R)??null,isCurrentlyLeaf:A,promotionSource:"reparent"});if(T){for(let[R,x]of Object.entries(T.fields))rt(n,T.parentId,R,x);T.promotionSnapshot&&n.setPromotionSnapshot(T.parentId,T.promotionSnapshot),T.fields.customId===null&&Ur(v,r.customIdTracker)}}}if(d!=="0"){let h=n.getActivity(d);if(h){let v=n.getChildren(d),A=Ee({parent:h,remainingChildIds:v.map(String),defaultDurationHours:a.hoursPerDay,promotionSnapshot:n.getPromotionSnapshot(d),computeEndDate:(T,R)=>n.calculateEndDate({startDate:T,durationHours:R,task:h}),idsRemoved:new Set([e.activityId])});if(A){for(let[V,Y]of Object.entries(A.fields))rt(n,d,V,Y);let T=$t(d,n),R=T?n.getActivity(T)?.customId:null,x=typeof R=="string"&&R?R:null,O=r.customIdTracker.generateCustomIdForRestoredChild(x);n.setActivityField(d,b.CUSTOM_ID,O)}}}}f&&(d!=="0"&&Dt(d,n),o||Dt(e.parentId,n));let C=st(n);for(let h of C){if(p.add(h.activityId),m.has(h.activityId))continue;let v=n.getActivity(h.activityId);if(!v)continue;let A=X(v);h.before!==void 0&&(A.correlativeId=h.before),m.set(h.activityId,A)}let _=f&&d!=="0"?n.getChildren(d).map(String):[],{scheduledIds:S}=await G({adapter:n,scheduler:i,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:e.activityId,recomputeParentsFrom:[e.activityId,e.parentId,..._],now:r.now,options:t,recomputeParentProgress:f}),P=f?Yr([e.activityId],n):[],g={name:At.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:P.map(String)}};return e.eventSource!==void 0&&(g.properties.event_source=e.eventSource),{ok:!0,changes:await B(n,{source:e,beforeSnap:m,touchedIds:p,scheduledIds:S,sirDetection:"before-diff",trackingEvents:[g],hoursPerDay:a.hoursPerDay})}}async function wc(e,t,r){let{adapter:n,scheduler:i,sector:a}=r;if(i.invalidateAllCaches(),e.activityIds.length===0)return{ok:!1,reason:D.ACTIVITY_IDS_EMPTY};let s=new Set(e.activityIds),o=new Set,c=[],l=[],d=[],u=new Set,f=new Set(s),p=[...e.activityIds].sort((h,v)=>{let A=n.getActivity(h),T=n.getActivity(v),R=A?nt(A):ne,x=T?nt(T):ne;return R-x});for(let h of p){if(!n.getActivity(h)){c.push({activityId:h,reason:D.ACTIVITY_NOT_FOUND}),f.delete(h);continue}if(Vr(h,u,n))continue;let A=ha(h,f,n);if(A==null){c.push({activityId:h,reason:D.INDENT_NO_ELIGIBLE_SIBLING}),f.delete(h);continue}let T=n.getActivity(h)?.parentId,R=L(T)?"0":String(T);d.push({activityId:h,newParentId:A,oldParentId:R}),u.add(h),o.add(h),o.add(A),R!=="0"&&o.add(R)}let m=await q(n,o);for(let{activityId:h,newParentId:v}of d)n.setActivityField(h,b.PARENT,v),n.setActivityField(h,b.CORRELATIVE_ID,hc),l.push(h);let I=new Set;for(let{activityId:h,newParentId:v}of d){if(I.has(v))continue;I.add(v);let A=n.getActivity(v);if(!A)continue;let T=A.customId,R=Wt(A.type)&&n.getChildren(v).filter(V=>!l.includes(V)).length===0,x=A.hasNewActivities&&A.newActivityIds.some(V=>String(V)===String(h)),O=Pe({parentId:v,newChildId:h,getParent:V=>n.getActivity(V)??null,isCurrentlyLeaf:R,promotionSource:"reparent"});if(O){for(let[V,Y]of Object.entries(O.fields))rt(n,O.parentId,V,Y);O.promotionSnapshot&&n.setPromotionSnapshot(O.parentId,O.promotionSnapshot),x||(n.setActivityField(v,b.HAS_NEW_ACTIVITIES,!1),n.setActivityField(v,b.NEW_ACTIVITIES_ARRAY,[]))}n.setActivityField(v,b.CONSTRAINT_TYPE,"asap"),n.setActivityField(v,b.CONSTRAINT_DATE,null),n.setActivityField(v,b.CUSTOM_ID,null),Ur(T,r.customIdTracker)}let C=new Set;for(let h of d)h.oldParentId!=="0"&&C.add(h.oldParentId),C.add(h.newParentId);for(let h of C)Dt(h,n);let _=st(n);for(let h of _){if(o.add(h.activityId),m.has(h.activityId))continue;let v=n.getActivity(h.activityId);if(!v)continue;let A=X(v);h.before!==void 0&&(A.correlativeId=h.before),m.set(h.activityId,A)}let{scheduledIds:S}=await G({adapter:n,scheduler:i,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:null,recomputeParentsFrom:l,now:r.now,options:t}),P=Yr(l,n),g={name:At.ACTIVITY_INDENT,properties:{activity_ids:l,failed:c.map(h=>({activity_id:h.activityId,reason:h.reason})),invalid_link_ids:P}};return e.eventSource!==void 0&&(g.properties.event_source=e.eventSource),{ok:!0,activityVerdicts:e.activityIds.map(h=>{let v=c.find(A=>String(A.activityId)===String(h));return v?{activityId:String(h),ok:!1,reason:v.reason}:{activityId:String(h),ok:!0}}),changes:await B(n,{source:e,beforeSnap:m,touchedIds:o,scheduledIds:S,trackingEvents:[g],hoursPerDay:a.hoursPerDay})}}async function Oc(e,t,r){let{adapter:n,scheduler:i,sector:a}=r;if(i.invalidateAllCaches(),e.activityIds.length===0)return{ok:!1,reason:D.ACTIVITY_IDS_EMPTY};let s=new Set(e.activityIds),o=new Map,c=new Map;for(let h of e.activityIds){let v=h;n.getActivity(v)&&(o.set(v,In(v,n)),c.set(v,yc(v,s,n)))}let l=new Set,d=[],u=[],f=new Set,p=[],m=new Set,I=[...e.activityIds].sort((h,v)=>{let A=n.getActivity(h),T=n.getActivity(v),R=A?nt(A):ne,x=T?nt(T):ne;return R-x});for(let h of I){let v=h,A=n.getActivity(v);if(!A){d.push({activityId:v,reason:D.ACTIVITY_NOT_FOUND});continue}if(Vr(v,m,n))continue;let T=A.parentId;if(L(T)){d.push({activityId:v,reason:D.OUTDENT_ROOT_LEVEL_NOT_EDITABLE});continue}let R=String(T),x=n.getActivity(R);if(!x){d.push({activityId:v,reason:D.ACTIVITY_NOT_FOUND});continue}let O=x.parentId;if(L(O)){d.push({activityId:v,reason:D.OUTDENT_ROOT_LEVEL_NOT_EDITABLE});continue}let V=String(O),Y=In(R,n)+1,it=c.get(v);if(it!=null&&s.has(it)){let Le=o.get(it)??-1,lt=o.get(v)??-1;Le>=0&<>=0&&(Y+=lt-Le)}p.push({activityId:v,grandparentKey:V,oldParentKey:R,targetIndexInGrandparent:Y}),m.add(v),l.add(String(v)),l.add(String(R)),V!=="0"&&l.add(String(V)),f.add(R)}let C=await q(n,l);for(let h of p){n.setActivityField(h.activityId,b.PARENT,h.grandparentKey);let v=mc(n,h.grandparentKey,h.targetIndexInGrandparent,h.activityId);n.setActivityField(h.activityId,b.CORRELATIVE_ID,v),u.push(h.activityId)}for(let h of f){let v=n.getActivity(h);if(!v)continue;let A=n.getChildren(h),T=Ee({parent:v,remainingChildIds:A.map(String),defaultDurationHours:a.hoursPerDay,promotionSnapshot:n.getPromotionSnapshot(h),computeEndDate:(Y,it)=>n.calculateEndDate({startDate:Y,durationHours:it,task:v}),idsRemoved:new Set(p.filter(Y=>Y.oldParentKey===h).map(Y=>Y.activityId))});if(!T){Cr(h,n);continue}for(let[Y,it]of Object.entries(T.fields))rt(n,h,Y,it);let R=$t(h,n),x=R?n.getActivity(R)?.customId:null,O=typeof x=="string"&&x?x:null,V=r.customIdTracker.generateCustomIdForRestoredChild(O);n.setActivityField(h,b.CUSTOM_ID,V)}let _=new Set;for(let h of f)_.add(String(h));for(let h of p)h.grandparentKey!=="0"&&_.add(String(h.grandparentKey));for(let h of _)Dt(h,n);let S=st(n);for(let h of S){if(l.add(h.activityId),C.has(h.activityId))continue;let v=n.getActivity(h.activityId);if(!v)continue;let A=X(v);h.before!==void 0&&(A.correlativeId=h.before),C.set(h.activityId,A)}let{scheduledIds:P}=await G({adapter:n,scheduler:i,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:u.length>0?"roots":null,recomputeParentsFrom:u,now:r.now,options:t}),g={name:At.ACTIVITY_OUTDENT,properties:{activity_ids:u.map(String),failed:d.map(h=>({activity_id:String(h.activityId),reason:h.reason}))}};return e.eventSource!==void 0&&(g.properties.event_source=e.eventSource),{ok:!0,activityVerdicts:e.activityIds.map(h=>{let v=d.find(A=>String(A.activityId)===String(h));return v?{activityId:String(h),ok:!1,reason:v.reason}:{activityId:String(h),ok:!0}}),changes:await B(n,{source:e,beforeSnap:C,touchedIds:l,scheduledIds:P,trackingEvents:[g],hoursPerDay:a.hoursPerDay})}}async function xc(e,t,r){let{adapter:n,ctx:i,scheduler:a,sector:s}=r;if(e.newValue!==0&&e.newValue!==100)return{ok:!1,reason:D.INVALID_PROGRESS_VALUE};let o=i.activityReader.getActivity(e.activityId);if(!o)return{ok:!1,reason:D.ACTIVITY_NOT_FOUND};let c=Vt(E.PROGRESS);if(!c)throw new Error("[ScheduleCore] progressPipeline not registered \u2014 cannot dispatch activity-set-progress");let l=c.transform(o,e.newValue,i,e.newValue),d=Yt(e.activityId,l),u=await q(n,d);Kt(n,e.activityId,l),Ut(e.activityId,l.postProcessors??[],n);let{scheduledIds:f}=await G({adapter:n,scheduler:a,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:l.needsAutoSchedule?e.activityId:null,recomputeParentsFrom:[],collectDirty:m=>Rr(e.activityId,d,m),now:r.now,options:t}),p=(l.trackingEvents??[]).map(m=>({name:m.name,properties:m.properties??{}}));return{ok:!0,changes:await B(n,{source:e,beforeSnap:u,touchedIds:d,scheduledIds:f,trackingEvents:p,hoursPerDay:s.hoursPerDay})}}async function Fc(e,t,r){let{adapter:n,scheduler:i,sector:a}=r,s=[],o=new Map,c=new Set,l=[],d=[],u=[],f=!1;for(let m of e.edits){let I=Cy(m,r);if(s.push(I.verdict),!I.verdict.ok||!I.changes)continue;let C=Yt(m.activityId,I.changes);Iy(o,C,r);for(let g of C)c.add(g);let _=Te(n,m.activityId),S=Er(n,String(m.activityId));Kt(n,m.activityId,I.changes),Ut(m.activityId,I.changes.postProcessors??[],n,S),d.push(..._e(_,n,m.activityId)),f||=!!I.changes.needsAutoSchedule;for(let g of I.changes.trackingEvents??[])l.push({name:g.name,properties:g.properties??{}});let P=Ae(m.activityId,I.changes.constraintWarning);P&&u.push(P)}let{scheduledIds:p}=await G({adapter:n,scheduler:i,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:await B(n,{source:e,beforeSnap:o,touchedIds:c,scheduledIds:p,sirDetection:"before-diff",links:d,trackingEvents:l,warnings:u,hoursPerDay:a.hoursPerDay})}}function Cy(e,t){let{ctx:r}=t,n=e.activityId,i=Vt(e.column);if(!i)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=i.canEdit(a,r.hierarchy);if(!s.allowed)return{verdict:{activityId:n,ok:!1,reason:s.reason??D.CANNOT_EDIT,...s.alertKey?{alertKey:s.alertKey}:{}},changes:null};let o=i.parseInput(e.newValue,a,r);if(!o.ok)return{verdict:{activityId:n,ok:!1,reason:o.reason??D.PARSE_ERROR},changes:null};let c=Reflect.get(a,i.targetField),l=i.validate(a,c,o.value,r);if(!l.valid)return{verdict:{activityId:n,ok:!1,reason:l.reason??D.INVALID,...l.notification?.messageKey?{alertKey:l.notification.messageKey}:{}},changes:null};let d=i.transform(a,o.value,r,o.raw);return{verdict:{activityId:n,ok:!0},changes:d}}function Iy(e,t,r){let n=new Set;for(let i of t)e.has(i)||n.add(i);if(n.size!==0)for(let i of n){let a=r.adapter.getActivity(i);a&&e.set(i,X(a))}}var Ti=E.CUSTOM_ID;async function Nc(e,t,r){let{adapter:n,scheduler:i,sector:a}=r;e.edits.some(P=>P.column===E.DURATION)&&i.invalidateExpandedLinksCache();let o=[],c=new Map,l=new Map,d=new Set,u=new Set,f=[],p=[],m=[],I=!1;for(let P of e.edits){let g=Sy(P,r);if(o.push(g.verdict),!g.verdict.ok||!g.changes)continue;let h=Ae(P.activityId,g.changes.constraintWarning);h&&m.push(h);let v=Yt(P.activityId,g.changes);_y(c,v,r);for(let O of v)u.add(O);Ty(l,P,c),Mr(P.column)&&d.add(String(P.activityId));let A=Te(n,P.activityId),T=Er(n,String(P.activityId)),R=ky(P,r),x=g.changes;Kt(n,P.activityId,x),Ut(P.activityId,g.changes.postProcessors??[],n,T),Dy(P,R,r),p.push(..._e(A,n,P.activityId)),I||=!!g.changes.needsAutoSchedule;for(let O of g.changes.trackingEvents??[])f.push({name:O.name,properties:O.properties??{}})}let C={action:e,autoscheduleFrom:I?"roots":null,recomputeParentsFrom:u,now:r.now,options:t},_=l.size>0,{scheduledIds:S}=await(_?Br({adapter:n,scheduler:i,sector:a,defaultBaseCalendarId:r.defaultBaseCalendarId},{postMutationArgs:C,revertTargets:[...l].filter(([P])=>!d.has(P)).map(([P,g])=>({activityId:P,priorConstraintDate:g})),revert:(P,g)=>Wr(P,g,n,r.ctx.calendars)}):G({adapter:n,scheduler:i,sector:a,defaultBaseCalendarId:r.defaultBaseCalendarId},C));return{ok:!0,verdicts:o,changes:await B(n,{source:e,beforeSnap:c,touchedIds:u,scheduledIds:S,sirDetection:"before-diff",links:p,trackingEvents:f,warnings:m,hoursPerDay:a.hoursPerDay})}}function Sy(e,t){let{ctx:r}=t,n=e.activityId,i=Vt(e.column);if(!i)return{verdict:{activityId:n,ok:!1,reason:D.NO_PIPELINE_FOR_COLUMN},changes:null};let a=r.activityReader.getActivity(e.activityId);if(!a)return{verdict:{activityId:n,ok:!1,reason:D.ACTIVITY_NOT_FOUND},changes:null};let s=i.canEdit(a,r.hierarchy);if(!s.allowed)return{verdict:{activityId:n,ok:!1,reason:s.reason??D.CANNOT_EDIT,...s.alertKey?{alertKey:s.alertKey}:{}},changes:null};let o=i.parseInput(e.newValue,a,r);if(!o.ok)return{verdict:{activityId:n,ok:!1,reason:o.reason??D.PARSE_ERROR},changes:null};let c=Reflect.get(a,i.targetField),l=i.validate(a,c,o.value,r);if(!l.valid)return{verdict:{activityId:n,ok:!1,reason:l.reason??D.INVALID,...l.notification?.messageKey?{alertKey:l.notification.messageKey}:{}},changes:null};if(e.column===Ti&&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:n,ok:!1,reason:D.CUSTOM_ID_DUPLICATE},changes:null}}let d=i.transform(a,o.value,r,o.raw);return{verdict:{activityId:n,ok:!0},changes:d}}function ky(e,t){if(e.column!==Ti)return null;let r=t.adapter.getActivity(e.activityId),n=r?r.customId:null;return typeof n=="string"?n:null}function Dy(e,t,r){if(e.column!==Ti)return;let n=r.adapter.getActivity(e.activityId),i=n?n.customId:null,a=typeof i=="string"?i:null;t!==a&&r.customIdTracker.trackCustomIdChange(t,a)}function Ty(e,t,r){if(!Nr(t.column))return;let n=String(t.activityId);if(e.has(n))return;let i=r.get(n);i&&e.set(n,i.constraintDate??null)}function _y(e,t,r){let n=new Set;for(let i of t)e.has(i)||n.add(i);if(n.size!==0)for(let i of n){let a=r.adapter.getActivity(i);a&&e.set(i,X(a))}}function Py(e,t,r,n,i,a){let s=String(e.id);if(s.length===0||i.has(s))throw new Error(`persistence-acknowledge: duplicate or empty ${t} id "${s}"`);if(!Number.isSafeInteger(e.proplannerId)||e.proplannerId<=0)throw new Error(`persistence-acknowledge: invalid ${t} proplannerId ${String(e.proplannerId)}`);if(a.has(e.proplannerId))throw new Error(`persistence-acknowledge: duplicate ${t} proplannerId ${String(e.proplannerId)}`);let o=r(s);if(!o.exists)throw new Error(`persistence-acknowledge: unknown ${t} id "${s}"`);if(o.current!==null&&o.current!==e.proplannerId)throw new Error(`persistence-acknowledge: ${t} "${s}" already has proplannerId ${String(o.current)}`);let c=n.get(e.proplannerId);if(c!==void 0&&c!==s)throw new Error(`persistence-acknowledge: ${t} proplannerId ${String(e.proplannerId)} already belongs to "${c}"`);i.add(s),a.add(e.proplannerId)}function Mc(e,t,r,n){let i=new Set,a=new Set;for(let s of e)Py(s,t,r,n,i,a)}function Wc(e,t){let r=e.activities??[],n=e.links??[],i=new Map;for(let c of t.adapter.getAllActivities())c.proplannerId!=null&&i.set(c.proplannerId,String(c.id));let a=new Map;for(let c of t.adapter.getAllLinks())c.proplannerId!=null&&a.set(c.proplannerId,String(c.id));Mc(r,"activity",c=>{let l=t.adapter.getActivity(c);return{exists:l!==null,current:l?.proplannerId??null}},i),Mc(n,"link",c=>{let l=t.adapter.getLink(c);return{exists:l!==null,current:l?.proplannerId??null}},a);let s=[],o=[];return t.adapter.batchUpdate(()=>{for(let c of r){let l=t.adapter.getActivity(c.id);if(!l||l.proplannerId===c.proplannerId)continue;let d=l.proplannerId;t.adapter.setActivityField(c.id,"proplannerId",c.proplannerId),s.push({id:c.id,kind:"updated",fields:{proplannerId:{before:d,after:c.proplannerId}},after:{...l,proplannerId:c.proplannerId}})}for(let c of n){let l=t.adapter.getLink(c.id);if(!l||l.proplannerId===c.proplannerId)continue;let d=l.proplannerId;t.adapter.setLinkProplannerId(c.id,c.proplannerId),o.push({id:c.id,kind:"updated",fields:{proplannerId:{before:d,after:c.proplannerId}},after:{...l,proplannerId:c.proplannerId}})}}),{ok:!0,changes:{source:e,activities:s,links:o,calendars:[],trackingEvents:[]}}}function Bc(e){return typeof e=="string"&&e.length>0?xt(e):e instanceof Date?e:null}function _i(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 Kr(e,t){let r=_i(e.duration),n=_i(e.cost),i=_i(e.hh_work);return r===null||n===null||i===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:Bc(e.start_date),endDate:Bc(e.end_date),durationDays:r,cost:n,workHours:i,versionId:typeof e.sectorbaselineversionId=="number"?e.sectorbaselineversionId:null,isActiveVersion:!!e.sectorbaselineversion?.active,isVisibleVersion:!!e.sectorbaselineversion?.visible,baseCalendarId:e.baseCalendarId!=null?String(e.baseCalendarId):null,hoursPerDay:typeof e.hoursPerDay=="number"?e.hoursPerDay:null,hoursPerWeek:typeof e.hoursPerWeek=="number"?e.hoursPerWeek:null}}function Uc(e,t,r){let n=new Map;e.forEachActivity((s,o)=>{let c=s.proplannerId;typeof c=="number"&&n.set(c,o)});let i=new Map;for(let s of t){let o=s.activityId;if(typeof o!="number")continue;let c=n.get(o);if(c===void 0)continue;let l=i.get(c);l?l.push(s):i.set(c,[s])}let a=[];for(let[s,o]of i)e.setActivityField(s,"baselinePoints",o.map(c=>Kr(c,r)).filter(c=>c!==null)),a.push(s);return e.forEachActivity((s,o)=>{if(i.has(o))return;let c=s.baselinePoints;Array.isArray(c)&&c.length>0&&(e.setActivityField(o,"baselinePoints",[]),a.push(o))}),a}function Ey(e){let t=ut(e);return t?{startDate:t.startDate,endDate:t.endDate,durationDays:t.durationDays,cost:t.cost,workHours:t.workHours}:null}function jc(e){let t=[];return e.forEachActivity((r,n)=>{let i=Ey(r);if(!i){r.baselineSnapshot!==null&&(e.setActivityField(n,"baselineSnapshot",null),t.push(n));return}e.setActivityField(n,"baselineSnapshot",i),t.push(n)}),t}function Gr(e,t,r,n,i=null){let a=new Set;for(let s of Uc(e,t,n))a.add(s);if(r)for(let s of Se(e,r,i))a.add(s);for(let s of jc(e))a.add(s);for(let s of ke(e))a.add(s);return[...a]}function Hc(e,t,r){if(!e||e==="0")return;let n=r.getChildren(e);if(n.length===0)return;let i=new Map,a=0;for(let o of n){let c=Ry(String(o),t,r);i.set(String(o),c),a+=c}let s=a?100/a:0;for(let o of n){let c=r.getActivity(o);if(!c)continue;let l=c.baselinePoints;if(ut(c)){let u=i.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 Ry(e,t,r){let n=r.getActivity(e);if(!n)return 0;let i=ut(n);if(!i)return 0;if(t==="COST")return $r(i.cost);if(t==="HH")return $r(i.workHours);let a=n.type;return a==="project"?Vc(e,r):a==="milestone"?0:$r(i.durationDays)}function Vc(e,t){let r=0;for(let n of t.getChildren(e)){let i=t.getActivity(n);if(!i)continue;let a=ut(i);if(!a)continue;let s=i.type;s==="project"?r+=Vc(String(n),t):s!=="milestone"&&(r+=$r(a.durationDays))}return r}function $r(e){let t=typeof e=="string"?parseFloat(e):e;return typeof t=="number"&&Number.isFinite(t)?t:0}function Yc(e,t){t.forEachActivity((r,n)=>{t.setActivityField(n,E.PONDERATOR,0)}),t.forEachActivity((r,n)=>{t.getChildren(n).length>0&&Hc(String(n),e,t)})}function Kc(e){for(let t of by(e))wy(t,e)}function by(e){let t=new Set;e.forEachActivity((n,i)=>{e.getChildren(i).length>0&&t.add(i)});let r=new Map;for(let n of t)r.set(n,Ly(n,e));return[...t].sort((n,i)=>(r.get(i)??0)-(r.get(n)??0))}function Ly(e,t){let r=0,n=e;for(;n&&n!=="0"&&t.getActivity(n);)r+=1,n=t.getParentId(n);return r}function wy(e,t){let r=t.getChildren(e);if(r.length===0)return;let n=[];for(let a of r){let s=t.getActivity(a);s&&n.push({progress:Number(s.progress??0),ponderator:Number(s.ponderator??0)})}let i=ue(n);i!==null&&t.setActivityField(e,E.PROGRESS,Ar(i))}function zr(e,t){Yc(t,e.adapter),Kc(e.adapter),e.now&&(Se(e.adapter,e.now,e.defaultBaseCalendarId??null),te(e.adapter,e.now)),ke(e.adapter),e.now&&Ft(e.adapter,e.sector.statusCriteria)}function Gc(e){return JSON.stringify(e.adapter.getAllIds().map(t=>{let r=e.adapter.getActivity(t)?.baselinePoints.find(n=>n.isActiveVersion);return r?[String(t),r.versionId,r.startDate?.getTime()??null,r.endDate?.getTime()??null,r.durationDays,r.cost,r.workHours,r.baseCalendarId,r.hoursPerDay,r.hoursPerWeek]:[String(t),null]}))}async function $c(e,t){let r=await q(t.adapter,new Set(t.adapter.getAllIds())),n=Gc(t),i=Gr(t.adapter,e.points,t.now,t.reporter,t.defaultBaseCalendarId??null);return Gc(t)!==n&&zr(t,t.sector.activityCreter??"DURATION"),{ok:!0,changes:await B(t.adapter,{source:e,beforeSnap:r,touchedIds:i,scheduledIds:[],hoursPerDay:t.sector.hoursPerDay})}}function Oy(e){if(!(e==="DURATION"||e==="COST"||e==="HH"))throw new Error(`ponderator-criterion-set: invalid criterion "${String(e)}"`)}async function zc(e,t){Oy(e.criterion);let r=new Set(t.adapter.getAllIds()),n=await q(t.adapter,r);return zr(t,e.criterion),t.sector.activityCreter=e.criterion,{ok:!0,changes:await B(t.adapter,{source:e,beforeSnap:n,touchedIds:r,scheduledIds:[],hoursPerDay:t.sector.hoursPerDay})}}async function qc(e,t){let r=nr(e.criteria),n=new Set(t.adapter.getAllIds()),i=await q(t.adapter,n),a=Ft(t.adapter,r);return t.sector.statusCriteria=r,{ok:!0,changes:await B(t.adapter,{source:e,beforeSnap:i,touchedIds:a,scheduledIds:[],hoursPerDay:t.sector.hoursPerDay})}}async function Jc(e,t,r){return e.kind==="activity-batch"?Tc(e,t,r):e.kind==="persistence-acknowledge"?Wc(e,r):e.kind==="baseline-apply"?$c(e,r):e.kind==="ponderator-criterion-set"?zc(e,r):e.kind==="status-criteria-set"?qc(e,r):e.kind==="link-create"||e.kind==="link-update"||e.kind==="link-delete"?ec(e,t,r):e.kind==="links-batch"?rc(e,t,r):e.kind==="activity-create"?gc(e,t,r):e.kind==="activity-paste"?Pc(e,t,r):e.kind==="activity-delete"?Sc(e,t,r):e.kind==="activity-move"?Lc(e,t,r):e.kind==="activity-indent"?wc(e,t,r):e.kind==="activity-outdent"?Oc(e,t,r):e.kind==="activity-set-progress"?xc(e,t,r):e.kind==="dates-batch"?Fc(e,t,r):e.kind==="bulk-edit"?Nc(e,t,r):e.kind==="selection-toggle"?ra(e,Pi(r)):e.kind==="selection-replace"?na(e,Pi(r)):e.kind==="visibility-set"?ia(e,Pi(r)):e.kind==="filter-set"?ua(e,{adapter:r.adapter,hoursPerDay:r.sector.hoursPerDay}):e.kind==="sort-set"?ma(e,{adapter:r.adapter}):e.kind==="sir-sync"?Ec(e,r):e.kind==="activity-lookahead-sync"?Rc(e,r):e.kind==="inline-edit"&&(e.column===E.CUSTOM_PREDECESSORS||e.column===E.CUSTOM_SUCESSORS)?nc(e,t,r):e.kind!=="inline-edit"?es(e,`[ScheduleCore] dispatch kind "${e.kind}" not supported yet`):tc(e,t,r)}function Pi(e){return{adapter:e.adapter}}var xy=new Set(["startDate","endDate","constraintDate"]);function Xc(e,t){return xy.has(e)&&typeof t=="string"?new Date(t):t}function Zc(e,t={}){let r=t.defaultUnit??"hour";return{getCalendar(n){let i=e.getCalendar(String(n));return i?Fy(i,r):null}}}function Fy(e,t){return{getClosestWorkTime(r){return e.getClosestWorkTime({date:r.date,dir:r.direction,unit:r.unit})},calculateEndDate(r,n){return e.calculateEndDate({start_date:r,duration:n,unit:t})},calculateDuration(r,n){return e.calculateDuration({start_date:r,end_date:n,unit:t})},isWorkTime(r,n){return e.isWorkTime({date:r,unit:n})},getWorkHours(r){return e.getWorkHours(r)}}}function Ny(e){return Array.isArray?Array.isArray(e):e&&e.length!==void 0&&e.pop&&e.push}function ie(e){return e&&typeof e=="object"?!!(e.getFullYear&&e.getMonth&&e.getDate):!1}function ae(e){return ie(e)&&!isNaN(e.getTime())}var My={}.constructor.toString();function Wy(e){var t=e.constructor.toString();return t!==My}function By(e){return e.$$typeof&&e.$$typeof.toString().includes("react.")}function Tt(e){var t,r;if(e&&typeof e=="object")switch(!0){case ie(e):r=new Date(e);break;case Ny(e):for(r=new Array(e.length),t=0;t<e.length;t++)r[t]=Tt(e[t]);break;default:if(Wy(e))r=Object.create(e);else{if(By(e))return r=e,r;r={}}for(t in e)Object.prototype.hasOwnProperty.apply(e,[t])&&(r[t]=Tt(e[t]));break}return r||e}function Re(e,t,r){for(var n in t)(e[n]===void 0||r)&&(e[n]=t[n]);return e}function Qc(e){return typeof e<"u"}var qr;function Ei(){return qr||(qr=new Date().valueOf()),qr++,qr}function yt(e,t){return e.bind?e.bind(t):function(){return e.apply(t,arguments)}}var jy=(e,t,r)=>{e=e.replace(/%[a-zA-Z]/g,i=>{switch(i){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 i}});let n=new Function("date","to_fixed","locale","getISOWeek","getWeek",`return "${e}";`);return i=>n(i,r.date.to_fixed,r.locale,r.date.getISOWeek,r.date.getWeek)},Hy=(e,t,r)=>{let n="var temp=date.match(/[a-zA-Z]+|[0-9]+/g);",i=e.match(/%[a-zA-Z]/g);for(let o=0;o<i.length;o++)switch(i[o]){case"%j":case"%d":n+=`set[2]=temp[${o}]||1;`;break;case"%n":case"%m":n+=`set[1]=(temp[${o}]||1)-1;`;break;case"%y":n+=`set[0]=temp[${o}]*1+(temp[${o}]>50?1900:2000);`;break;case"%g":case"%G":case"%h":case"%H":n+=`set[3]=temp[${o}]||0;`;break;case"%i":n+=`set[4]=temp[${o}]||0;`;break;case"%Y":n+=`set[0]=temp[${o}]||0;`;break;case"%a":case"%A":n+=`set[3]=set[3]%12+((temp[${o}]||'').toLowerCase()=='am'?0:12);`;break;case"%s":n+=`set[5]=temp[${o}]||0;`;break;case"%M":n+=`set[1]=locale.date.month_short_hash[temp[${o}]]||0;`;break;case"%F":n+=`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]; ${n} return new Date(${a});`);return o=>s(o,r.locale)},tl={date_to_str:jy,str_to_date:Hy},Vy=(e,t,r)=>n=>e.replace(/%[a-zA-Z]/g,i=>{switch(i){case"%d":return t?r.date.to_fixed(n.getUTCDate()):r.date.to_fixed(n.getDate());case"%m":return t?r.date.to_fixed(n.getUTCMonth()+1):r.date.to_fixed(n.getMonth()+1);case"%j":return t?n.getUTCDate():n.getDate();case"%n":return t?n.getUTCMonth()+1:n.getMonth()+1;case"%y":return t?r.date.to_fixed(n.getUTCFullYear()%100):r.date.to_fixed(n.getFullYear()%100);case"%Y":return t?n.getUTCFullYear():n.getFullYear();case"%D":return t?r.locale.date.day_short[n.getUTCDay()]:r.locale.date.day_short[n.getDay()];case"%l":return t?r.locale.date.day_full[n.getUTCDay()]:r.locale.date.day_full[n.getDay()];case"%M":return t?r.locale.date.month_short[n.getUTCMonth()]:r.locale.date.month_short[n.getMonth()];case"%F":return t?r.locale.date.month_full[n.getUTCMonth()]:r.locale.date.month_full[n.getMonth()];case"%h":return t?r.date.to_fixed((n.getUTCHours()+11)%12+1):r.date.to_fixed((n.getHours()+11)%12+1);case"%g":return t?(n.getUTCHours()+11)%12+1:(n.getHours()+11)%12+1;case"%G":return t?n.getUTCHours():n.getHours();case"%H":return t?r.date.to_fixed(n.getUTCHours()):r.date.to_fixed(n.getHours());case"%i":return t?r.date.to_fixed(n.getUTCMinutes()):r.date.to_fixed(n.getMinutes());case"%a":return t?n.getUTCHours()>11?"pm":"am":n.getHours()>11?"pm":"am";case"%A":return t?n.getUTCHours()>11?"PM":"AM":n.getHours()>11?"PM":"AM";case"%s":return t?r.date.to_fixed(n.getUTCSeconds()):r.date.to_fixed(n.getSeconds());case"%W":return t?r.date.to_fixed(r.date.getUTCISOWeek(n)):r.date.to_fixed(r.date.getISOWeek(n));case"%w":return r.date.to_fixed(r.date.getWeek(n));default:return i}}),Yy=(e,t,r)=>n=>{let i=[0,0,1,0,0,0],a=n.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":i[2]=a[o]||1;break;case"%n":case"%m":i[1]=(a[o]||1)-1;break;case"%y":i[0]=a[o]*1+(a[o]>50?1900:2e3);break;case"%g":case"%G":case"%h":case"%H":i[3]=a[o]||0;break;case"%i":i[4]=a[o]||0;break;case"%Y":i[0]=a[o]||0;break;case"%a":case"%A":i[3]=i[3]%12+((a[o]||"").toLowerCase()==="am"?0:12);break;case"%s":i[5]=a[o]||0;break;case"%M":i[1]=r.locale.date.month_short_hash[a[o]]||0;break;case"%F":i[1]=r.locale.date.month_full_hash[a[o]]||0;break}return t?new Date(Date.UTC(i[0],i[1],i[2],i[3],i[4],i[5])):new Date(i[0],i[1],i[2],i[3],i[4],i[5])},el={date_to_str:Vy,str_to_date:Yy};function rl(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 n=null;function i(){try{new Function("canUseCsp = false;")}catch{n=!0}}function a(){var o=!1;return e.config.csp==="auto"?(n===null&&i(),o=n):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=tl;return a()&&(l=el),l.date_to_str(o,c,e)},str_to_date:function(o,c){var l=tl;return a()&&(l=el),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 Ri(e,t,r,n,i){return this.date=e,this.unit=t,this.task=r,this.id=n,this.calendar=i,this}function bi(e,t,r,n,i,a){return this.date=e,this.dir=t,this.unit=r,this.task=n,this.id=i,this.calendar=a,this}function Li(e,t,r,n,i,a,s){return this.start_date=e,this.duration=t,this.unit=r,this.step=n,this.task=i,this.id=a,this.calendar=s,this}function Ky(e,t,r,n){return this.start_date=e,this.end_date=t,this.task=r,this.calendar=n,this.unit=null,this.step=null,this}var nl=function(e){return{getWorkHoursArguments:function(){var t=arguments[0];if(ie(t)?t={date:t}:t=Re({},t),!ae(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 Ri)return t;var r;if(t.date?r=new Ri(t.date,t.unit,t.task,null,t.calendar):r=new Ri(arguments[0],arguments[1],arguments[2],null,arguments[3]),r.unit=r.unit||e.config.duration_unit,!ae(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 bi)return r;var n;if(ie(r)?n=new bi(r):n=new bi(r.date,r.dir,r.unit,r.task,null,r.calendar),r.id&&(n.task=r),n.dir=r.dir||"any",n.unit=r.unit||e.config.duration_unit,!ae(n.date))throw e.assert(!1,"Invalid date argument for getClosestWorkTime method"),new Error("Invalid date argument for getClosestWorkTime method");return n},_getStartEndConfig:function(t){var r=Ky,n;if(t instanceof r)return t;if(ie(t)?n=new r(arguments[0],arguments[1],arguments[2],arguments[3]):(n=new r(t.start_date,t.end_date,t.task),t.id!==null&&t.id!==void 0&&(n.task=t)),n.unit=n.unit||e.config.duration_unit,n.step=n.step||e.config.duration_step,n.start_date=n.start_date||n.start||n.date,!ae(n.start_date))throw e.assert(!1,"Invalid start_date argument for getDuration method"),new Error("Invalid start_date argument for getDuration method");if(!ae(n.end_date))throw e.assert(!1,"Invalid end_date argument for getDuration method"),new Error("Invalid end_date argument for getDuration method");return n},getDurationArguments:function(t,r,n,i){return this._getStartEndConfig.apply(this,arguments)},hasDurationArguments:function(t,r,n,i){return this._getStartEndConfig.apply(this,arguments)},calculateEndDateArguments:function(t,r,n,i){var a=arguments[0];if(a instanceof Li)return a;var s;if(ie(a)?s=new Li(arguments[0],arguments[1],arguments[2],void 0,arguments[3],void 0,arguments[4]):s=new Li(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,!ae(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 il(){}il.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 n(a){var s=Math.floor(a/3600),o=a-s*60*60,c=Math.floor(o/60);return s+":"+r(c)}for(var i=0;i<e.length;i++)t.push(n(e[i].start)+"-"+n(e[i].end));return t},_intersectHourRanges:function(e,t){var i=[],r=e.length>t.length?e:t,n=e===r?t:e;r=r.slice(),n=n.slice();for(var i=[],a=0;a<r.length;a++)for(var s=r[a],o=0;o<n.length;o++){var c=n[o];c.start<s.end&&c.end>s.start&&(i.push({start:Math.max(s.start,c.start),end:Math.min(s.end,c.end)}),s.end>c.end&&(n.splice(o,1),o--,a--))}return i},_mergeAdjacentIntervals:function(e){var t=e.slice();t.sort(function(a,s){return a.start-s.start});for(var r=t[0],n=1;n<t.length;n++){var i=t[n];i.start<=r.end?(i.end>r.end&&(r.end=i.end),t.splice(n,1),n--):r=i}return t},_mergeHoursConfig:function(e,t){return this._mergeAdjacentIntervals(this._intersectHourRanges(e,t))},merge:function(e,t){let r=Tt(e.getConfig()),n=Tt(t.getConfig()),i=r.parsed,a=n.parsed;i.customWeeks=r.customWeeks,a.customWeeks=n.customWeeks;var s={hours:this._toHoursArray(this._mergeHoursConfig(i.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 m=d.dates[p];if(p==u&&(s.dates[u]=!!(f&&m)),Array.isArray(f)){let I=Array.isArray(m)?m:d.hours;s.dates[u]=this._toHoursArray(this._mergeHoursConfig(f,I))}}}};if(o(i,a),o(a,i),i.customWeeks)for(var c in i.customWeeks)s.customWeeks[c]=i.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 wi=class{constructor(){this.clear()}getItem(t,r,n){if(this._cache.has(t)){let a=this._cache.get(t)[n.getUTCFullYear()];if(a&&a.has(r))return a.get(r)}return-1}setItem(t,r,n,i){if(!t||!r)return;let a=this._cache,s=i.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,n)}clear(){this._cache=new Map}},Oi=class{constructor(){this.clear()}getItem(t,r,n){let i=this._cache;if(i&&i[t]){let a=i[t];if(a===void 0)return-1;let s=a[n.getUTCFullYear()];if(s&&s[r]!==void 0)return s[r]}return-1}setItem(t,r,n,i){if(!t||!r)return;let a=this._cache;if(!a)return;a[t]||(a[t]=[]);let s=a[t],o=i.getUTCFullYear(),c=s[o];c||(c=s[o]={}),c[r]=n}clear(){this._cache={}}},xi=class{constructor(t){this.getMinutesPerWeek=r=>{let n=r.valueOf();if(this._weekCache.has(n))return this._weekCache.get(n);let i=this._calendar,a=this._calendar.$gantt,s=0,o=a.date.week_start(new Date(r));for(let c=0;c<7;c++)s+=i.getHoursPerDay(o)*60,o=a.date.add(o,1,"day");return this._weekCache.set(n,s),s},this.getMinutesPerMonth=r=>{let n=r.valueOf();if(this._monthCache.has(n))return this._monthCache.get(n);let i=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+=i.getHoursPerDay(o)*60,o=a.date.add(o,1,"day");return this._monthCache.set(n,s),s},this.clear=()=>{this._weekCache=new Map,this._monthCache=new Map},this.clear(),this._calendar=t}};function Gy(){return typeof Map<"u"?new wi:new Oi}var Fi=class{constructor(){this.clear()}_getCacheObject(t,r,n){let i=this._cache;i[r]||(i[r]=[]);let a=i[r];a||(a=i[r]={});let s=a[n];s||(s=a[n]={});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,n,i,a){let s=this._getCacheObject(t,n,i),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,n,i,a){let s=this._getCacheObject(t,n,i),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 Ni(e,t){this.argumentsHelper=t,this.$gantt=e,this._workingUnitsCache=Gy(),this._largeUnitsCache=new xi(this),this._dateDurationCache=new Fi,this._worktime=null,this._cached_timestamps={},this._cached_timestamps_count=0}Ni.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)),n=this.$gantt.date.add(r,1,t);return this.hasDuration(r,n)}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(),n=0;n<t.length;n++)if(r>=t[n].startHour&&r<t[n].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),n=0;n<t.length;n++)if(r>=t[n].start&&r<t[n].end)return!0;return!1},_nextDate:function(e,t,r){return this.$gantt.date.add(e,r,t)},_getWorkUnitsBetweenGeneric:function(e,t,r,n){var i=this.$gantt.date,a=new Date(e),s=new Date(t);n=n||1;var o=0,c=null,l,d,u=!1;l=i[r+"_start"](new Date(a)),l.valueOf()!=a.valueOf()&&(u=!0);var f=!1;d=i[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,n),p=c.valueOf()>s.valueOf(),this._isWorkTime(a,r))(u||f&&p)&&(l=i[r+"_start"](new Date(a)),d=i.add(l,n,r)),u?(u=!1,c=this._nextDate(l,r,n),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 m=this._getUnitOrder(r),I=this.units[m-1];I&&!this._isWorkTime(a,I)&&(c=this._getClosestWorkTimeFuture(a,I))}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 n=this._getWorkHours(e),i=0;i<n.length;i++){var a=n[i];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(n){r+=n.durationMinutes}),r},getHoursPerDay:function(e){var t=this._getWorkHours(e),r=0;return t.forEach(function(n){r+=n.durationHours}),r},_getWorkUnitsForRange:function(e,t,r,n){var i=0,a=new Date(e),s=new Date(t),o;for(r=="minute"?o=yt(this._getMinutesPerDay,this):o=yt(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),i+=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),i+=c,a=this.$gantt.date.add(a,7,"day");continue}}i+=o(a),a=this._nextDate(a,"day",1)}return i/n},_getMinutesBetweenSingleDay:function(e,t){for(var r=this._getIntervalTimestamp(e,t),n=this._getWorkHours(e),i=0,a=0;a<n.length;a++){var s=n[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);i+=(c-o)/60,r.start=c}}return Math.floor(i)},_getMinutesBetween:function(e,t,r,n){var i=new Date(e),a=new Date(t);n=n||1;var s=new Date(i),o=this.$gantt.date.add(this.$gantt.date.day_start(new Date(i)),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,n),p=d+f+u;return p},_getHoursBetween:function(e,t,r,n){var i=new Date(e),a=new Date(t);n=n||1;var s=new Date(i),o=this.$gantt.date.add(this.$gantt.date.day_start(new Date(i)),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,n)/60,u=this._getMinutesBetweenSingleDay(c,l,r,n)/60,f=this._getWorkUnitsForRange(o,c,r,n),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,n=null;for(var t in e.customWeeks){var i=e.customWeeks[t];if(i.from&&i.to){var a=i.from,s=i.to;(!r||r>a.valueOf())&&(r=a.valueOf()),(!n||n<s.valueOf())&&(n=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:i.from,to:i.to,hours:this._parseHours(i.hours),dates:{}};if(i.days&&!i.dates){i.dates=i.dates||{};for(var t=0;t<i.days.length;t++)i.dates[t]=i.days[t],i.days[t]instanceof Array||(i.dates[t]=!!i.days[t]);delete i.days}for(var c in i.dates)o.dates[c]=this._parseHours(i.dates[c])}}e.parsed.customWeeksRangeStart=r,e.parsed.customWeeksRangeEnd=n}},_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),n=Object.keys(t.dates);if(r.sort(),n.sort(),!this._arraysEqual(r,n))return!1;for(var i=0;i<r.length;i++){var a=r[i],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 Ni))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 n in t.parsed.customWeeks){var i=t.parsed.customWeeks[n],a=r.parsed.customWeeks[n];if(!a||!this._compareSettings(i,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 n=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()));var i=this._timestamp({date:n});if(r.haveCustomWeeks&&r.customWeeksRangeStart<=i&&r.customWeeksRangeEnd>i){for(var a=0;a<r.customWeeksBoundaries.length;a++)if(r.customWeeksBoundaries[a].from<=i&&r.customWeeksBoundaries[a].to>i){r=r.customWeeks[r.customWeeksBoundaries[a].name];break}}var s=!0;return r.dates[i]!==void 0?s=r.dates[i]: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 n=t.getUTCHours();return!n&&!t.getUTCMinutes()&&!t.getUTCSeconds()&&e.valueOf()<t.valueOf()&&(n=24),r.end=n*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=[],n=0;n<t.length;n+=2){var i=t[n],a=t[n+1],s=a-i;r.push({start:i,end:a,startHour:Math.floor(i/3600),startMinute:Math.floor(i/60),endHour:Math.ceil(a/3600),endMinute:Math.ceil(a/60),durationSeconds:s,durationMinutes:s/60,durationHours:s/3600})}return r}else return e},setWorkTime:function(e){return this._tryChangeCalendarSettings(yt(function(){var t=e.hours!==void 0?e.hours:!0,r=this._timestamp(e),n=this.getConfig();if(r!==null?n.dates[r]=t:e.customWeeks||(n.hours=t),e.customWeeks){if(n.customWeeks||(n.customWeeks={}),typeof e.customWeeks=="string")r!==null?n.customWeeks[e.customWeeks].dates[r]=t:e.customWeeks||(n.customWeeks[e.customWeeks].hours=t);else if(typeof e.customWeeks=="object"&&e.customWeeks.constructor===Object)for(var i in e.customWeeks)n.customWeeks[i]=e.customWeeks[i]}this._parseSettings(),this._clearCaches()},this))},unsetWorkTime:function(e){return this._tryChangeCalendarSettings(yt(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,n=null;return n=String(e.valueOf()),r=this._workingUnitsCache.getItem(t,n,e),r==-1&&(r=this._checkIfWorkingUnit(e,t),this._workingUnitsCache.setItem(t,n,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,n){var i=0,a=1;if(e.valueOf()>t.valueOf()){var s=t;t=e,e=s,a=-1}return r=="hour"&&n==1?i=this._getHoursBetween(e,t,r,n):r=="minute"&&n==1?i=this._getMinutesBetween(e,t,r,n):i=this._getWorkUnitsBetweenGeneric(e,t,r,n),a*Math.round(i)},hasDuration:function(){var e=this.argumentsHelper.getDurationArguments.apply(this.argumentsHelper,arguments),t=e.start_date,r=e.end_date,n=e.unit,i=e.step;if(!n)return!1;var a=new Date(t),s=new Date(r);for(i=i||1;a.valueOf()<s.valueOf();){if(this._isWorkTime(a,n))return!0;a=this._nextDate(a,n,i)}return!1},calculateEndDate:function(){var e=this.argumentsHelper.calculateEndDateArguments.apply(this.argumentsHelper,arguments),t=e.start_date,r=e.duration,n=e.unit,i=e.step;if(!n)return!1;var a=e.duration>=0?1:-1;r=Math.abs(r*1);var s=this;return this._dateDurationCache.getEndDate(t,r,n,i*a,function(){return s._calculateEndDate(t,r,n,i*a)})},_calculateEndDate:function(e,t,r,n){if(!r)return!1;if(n==1&&r=="minute")return this._calculateMinuteEndDate(e,t,n);if(n==-1&&r=="minute")return this._subtractMinuteDate(e,t,n);if(n==1&&r=="hour")return this._calculateHourEndDate(e,t,n);var i=this._addInterval(e,t,r,n,null);return i.end},_addInterval:function(e,t,r,n,i){for(var a=0,s=e;a<t&&!(i&&i(s));){var o=this._nextDate(s,r,n),c=new Date(o.valueOf()+1);n>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"),n=0,i=t,a=this._getIntervalTimestamp(e,r),s=this._getWorkHours(e),o=0;o<s.length&&n<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>i&&(u=i,d=l+i*60*60);var f=Math.round((d-l)/3600);n+=f,i-=f,a.start=d}}var p=r;return n===t&&(p=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate(),0,0,a.start))),{added:n,end:p}},_calculateHourEndDate:function(e,t,r){var n=new Date(e),i=0;r=r||1,t=Math.abs(t*1);var a=this._addHoursUntilDayEnd(n,t);i=a.added,n=a.end;var s=t-i;if(s){for(var o=n;i<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)),i+l>=t)break;i+=l,o=c}n=o}if(i<t){var s=t-i;a=this._addHoursUntilDayEnd(n,s),n=a.end}return n},_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"),n=0,i=t,a=this._getIntervalTimestamp(e,r),s=this._getWorkHours(e),o=0;o<s.length&&n<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>i&&(u=i,d=l+i*60);var f=Math.round((d-l)/60);i-=f,n+=f,a.start=d}}var p=r;return n===t&&(p=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate(),0,0,a.start))),{added:n,end:p}},_subtractMinutesUntilHourStart:function(e,t){for(var r=this.$gantt.date.hour_start(new Date(e)),n=0,i=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&&n<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>i&&(f=i,u=d-i*60);var p=Math.abs(Math.round((d-u)/60));i-=p,n+=p,s=u}}var m=r;return n===t&&(m=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate(),0,0,s))),{added:n,end:m}},_subtractMinuteDate:function(e,t,r){var n=this.getClosestWorkTime({date:e,dir:"past",unit:"minute"}),i=0;r=r||-1,t=Math.abs(t*1),t=Math.round(t);let a=this._isMinutePrecision(n),s=this._subtractMinutesUntilHourStart(n,t);i+=s.added,n=s.end;for(var o=0,c=[],l=0;i<t;){var d=this.$gantt.date.day_start(new Date(n)),u=!1;n.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-i,m=this._getTimeOfDayStamp(n,u);if(!c.length||!l){n=this.$gantt.date.add(n,-1,"day");continue}if(c[c.length-1].end<=m&&p>l){i+=l,n=this.$gantt.date.add(n,-1,"day");continue}for(var I=!1,C=null,_=null,S=c.length-1;S>=0;S--)if(c[S].start<m-1&&c[S].end>=m-1){I=!0,C=c[S],_=c[S-1];break}if(I)if(m===C.end&&p>=C.durationMinutes)i+=C.durationMinutes,n=this.$gantt.date.add(n,-C.durationMinutes,"minute");else if(!a&&p<=m/60-C.startMinute)i+=p,n=this.$gantt.date.add(n,-p,"minute");else if(a)p<=m/60-C.startMinute?(i+=p,n=this.$gantt.date.add(n,-p,"minute")):(i+=m/60-C.startMinute,_?n=new Date(Date.UTC(n.getUTCFullYear(),n.getUTCMonth(),n.getUTCDate(),0,0,_.end)):n=this.$gantt.date.day_start(n));else{var P=this._getMinutesPerHour(n);P<=p?(i+=P,n=this._nextDate(n,"hour",r)):(s=this._subtractMinutesUntilHourStart(n,p),i+=s.added,n=s.end)}else if(n.getUTCHours()===0&&n.getUTCMinutes()===0&&n.getUTCSeconds()===0){var g=this._getClosestWorkTimePast(n,"hour");if(g.valueOf()===n.valueOf()){var g=this.$gantt.date.add(n,-1,"day"),h=this._getWorkHours(g);if(h.length){var v=h[h.length-1];g.setUTCSeconds(v.durationSeconds)}}n=g}else n=this._getClosestWorkTimePast(new Date(n-1),"hour")}if(i<t){var A=t-i;s=this._subtractMinutesUntilHourStart(n,A),i+=s.added,n=s.end}return n},_calculateMinuteEndDate:function(e,t,r){var n=new Date(e),i=0;r=r||1,t=Math.abs(t*1),t=Math.round(t);var a=this._addMinutesUntilHourEnd(n,t);i+=a.added,n=a.end;for(var s=0,o=[],c=0,l=this._isMinutePrecision(n);i<t;){var d=this.$gantt.date.day_start(new Date(n)).valueOf();d!==s&&(o=this._getWorkHours(n),c=this._getMinutesPerDay(n),s=d);var u=t-i,f=this._getTimeOfDayStamp(n);if(!o.length||!c){n=this.$gantt.date.add(this.$gantt.date.day_start(n),1,"day");continue}if(o[0].start>=f&&u>=c){if(i+=c,u==c){n=new Date(Date.UTC(n.getUTCFullYear(),n.getUTCMonth(),n.getUTCDate(),0,0,o[o.length-1].end));break}else n=this.$gantt.date.add(n,1,"day"),n=this.$gantt.date.day_start(n);continue}for(var p=!1,m=null,I=0;I<o.length;I++)if(o[I].start<=f&&o[I].end>f){p=!0,m=o[I];break}if(p)if(f===m.start&&u>=m.durationMinutes)i+=m.durationMinutes,n=this.$gantt.date.add(n,m.durationMinutes,"minute");else if(u<=m.endMinute-f/60)i+=u,n=this.$gantt.date.add(n,u,"minute");else{var C=this._getMinutesPerHour(n);C<=u?(i+=C,l?n=this.$gantt.date.add(n,C,"minute"):n=this._nextDate(n,"hour",r)):(a=this._addMinutesUntilHourEnd(n,u),i+=a.added,n=a.end)}else n=this._getClosestWorkTimeFuture(n,"hour")}if(i<t){var _=t-i;a=this._addMinutesUntilHourEnd(n,_),i+=a.added,n=a.end}return n},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 n=new Date(e);if(this._isWorkTime(n,t))return n;if(n=this.$gantt.date[t+"_start"](n),r=="any"||!r){var i=this._getClosestWorkTimeFuture(n,t),a=this._getClosestWorkTimePast(n,t);Math.abs(i-e)<=Math.abs(e-a)?n=i:n=a}else r=="past"?n=this._getClosestWorkTimePast(n,t):n=this._getClosestWorkTimeFuture(n,t);return n},_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 n=new Date(e),i=null,a=!1;this._getWorkHours(n).length||(n=this._getClosestWorkTime(n,"day",t<0?"past":"future"),t<0&&(n=new Date(n.valueOf()-1),a=!0),r=this._getWorkHours(n));var s=this._getTimeOfDayStamp(n);if(a&&(s=this._getTimeOfDayStamp(new Date(n.valueOf()+1),a)),t>0){for(var o=0;o<r.length;o++)if(r[o].start>=s){i=new Date(Date.UTC(n.getUTCFullYear(),n.getUTCMonth(),n.getUTCDate(),0,0,r[o].start));break}}else for(var o=r.length-1;o>=0;o--)if(r[o].end<=s){i=new Date(Date.UTC(n.getUTCFullYear(),n.getUTCMonth(),n.getUTCDate(),0,0,r[o].end));break}else if(r[o].end>s&&r[o].start<=s){i=new Date(Date.UTC(n.getUTCFullYear(),n.getUTCMonth(),n.getUTCDate(),0,0,s));break}return i},_getClosestWorkMinute:function(e,t,r){var n=new Date(e),i=this._getWorkHours(n),a=this._findClosestTimeInDay(n,r,i);return a||(r>0?(n=this.calculateEndDate(n,r,t),n=this.$gantt.date.day_start(n)):(n=this.calculateEndDate(n,r,"day"),n=this.$gantt.date.day_start(n),n=this.$gantt.date.add(n,1,"day"),n=new Date(n.valueOf()-1)),i=this._getWorkHours(n),a=this._findClosestTimeInDay(n,r,i)),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 n=this._getUnitOrder(t),i=this.units[n-1],a=e,s=3e3,o=0;!this._isWorkTime(a,t)&&!(i&&!this._isWorkTime(a,i)&&(r>0?a=this._getClosestWorkTimeFuture(a,i):a=this._getClosestWorkTimePast(a,i),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 n in e.dates);var i=this._checkWorkHours(e.hours),a=!1;return r.forEach((function(s){if(!a){var o=t[s];o===!0?a=i: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 $e={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 n in e){r=n;break}return r},getCalendarIdFromLegacyConfig:function(e,t){if(t)for(var r in t){var n=t[r];if(e[r]){var i=n[e[r]];if(i)return i}}return null}};function $y(){function e(i){return i.map(function(a){return a&&a.resource_id?a.resource_id:a}).sort().join("-")}var t={};function r(i,a){return a.mergeCalendars(i.map(function(s){var o=s&&s.resource_id?s.resource_id:s;return a.getResourceCalendar(o)}))}function n(i,a){var s=e(i);if(i.length){if(i.length===1)return a.getResourceCalendar(s).id;if(t[s])return t[s].id;var o=r(i,a);return t[s]=o,a.addCalendar(o)}else return null}return{getCalendarIdFromMultipleResources:n}}var zy=$y();function al(e){this.$gantt=e,this._calendars={},this._legacyConfig=void 0,this.$gantt.attachEvent("onGanttReady",(function(){this.$gantt.config.resource_calendars&&(this._isLegacyConfig=$e.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))}al.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 n=0;n<7;n++)r[n]=t.weekdays[n];t?.dates&&Object.entries(t.dates).forEach(([n,i])=>{r[new Date(n).valueOf()]=i}),Object.entries(r).forEach(([n,i])=>{i instanceof Array||(r[n]=!!i)}),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 n=new il,i;return e.forEach((function(a){i?i=this._createCalendarFromConfig(n.merge(i,a)):i=a}).bind(this)),this.createCalendar(i)},_createCalendarFromConfig:function(e){var t=new Ni(this.$gantt,nl(this.$gantt));t.id=String(Ei());var r=this._convertWorkTimeSettings(e);if(r.customWeeks)for(var n in r.customWeeks)r.customWeeks[n]=this._convertWorkTimeSettings(r.customWeeks[n]);return t._setConfig(r),t},createCalendar:function(e){var t;e||(e={}),e.getConfig?t=Tt(e.getConfig()):e.worktime?t=Tt(e.worktime):t=Tt(e);var r=Tt(this.defaults.fulltime.worktime);return Re(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,n,i;if(this._legacyConfig===!1?i=t.resource_property:i=$e.getResourceProperty(t),Array.isArray(e[i])&&e[i].length)t.dynamic_resource_calendars?n=zy.getCalendarIdFromMultipleResources(e[i],this):r=this.getResourceCalendar(e[i]);else if(this._legacyConfig===void 0&&(this._legacyConfig=$e.isLegacyResourceCalendarFormat(t.resource_calendars)),this._legacyConfig)var n=$e.getCalendarIdFromLegacyConfig(e,t.resource_calendars);else if(i&&e[i]&&t.resource_calendars[e[i]])var r=this.getResourceCalendar(e[i]);if(n&&(r=this.getCalendar(n)),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,n=r.resource_calendars,i=null;if(Array.isArray(e)&&e.length===1&&(typeof e[0]=="object"?t=e[0].resource_id:t=e[0]),n){if(this._legacyConfig===void 0&&(this._legacyConfig=$e.isLegacyResourceCalendarFormat(r.resource_calendars)),this._legacyConfig){for(var a in n)if(n[a][t]){i=n[a][t];break}}else var i=n[t];if(i)return this.getCalendar(i)}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 n=this._getOwnCalendar(r),i=!!t.getState().group_mode;if(!n&&t.config.inherit_calendar&&t.isTaskExists(r.parent)){for(var a=r;t.isTaskExists(a.parent)&&(a=t.getTask(a.parent),!(t.isSummaryTask(a)&&(n=this._getOwnCalendar(a),n))););i&&!n&&e.$effective_calendar&&(n=this.getCalendar(e.$effective_calendar))}return n||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||Ei(),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],n=this.createCalendar(r);n.id=t,this.addCalendar(n)}},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 Mi(e,t){this.argumentsHelper=t,this.$gantt=e}Mi.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,n=e.unit,i=e.step;return this._calculateDuration(t,r,n,i)},_calculateDuration:function(e,t,r,n){var i=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)/(n*a[r]));else{for(var o=new Date(e),c=new Date(t);o.valueOf()<c.valueOf();)s+=1,o=i.add(o,n,r);o.valueOf()!=t.valueOf()&&(s+=(c-o)/(i.add(o,n,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,n=e.unit;return n?(t=new Date(t),r=new Date(r),t.valueOf()<r.valueOf()):!1},hasWorkTime:function(){return!0},equals:function(e){return e instanceof Mi},calculateEndDate:function(){var e=this.argumentsHelper.calculateEndDateArguments.apply(this.argumentsHelper,arguments),t=e.start_date,r=e.duration,n=e.unit,i=e.step;return this.$gantt.date.add(t,i*r,n)}};function sl(e){this.$gantt=e.$gantt,this.argumentsHelper=nl(this.$gantt),this.calendarManager=e,this.$disabledCalendar=new Mi(this.$gantt,this.argumentsHelper)}sl.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,n){var i=this.argumentsHelper.isWorkTimeArguments.apply(this.argumentsHelper,arguments);return n=this._getCalendar(i),n.isWorkTime(i)},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 qy=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,n,i){return t.isWorkTime(r,n,i)},getClosestWorkTime:function(r){return t.getClosestWorkTime(r)},calculateDuration:function(r,n,i){return t.calculateDuration(r,n,i)},_hasDuration:function(r,n,i){return t.hasDuration(r,n,i)},calculateEndDate:function(r,n,i,a){return t.calculateEndDate(r,n,i,a)},mergeCalendars:yt(e.mergeCalendars,e),createCalendar:yt(e.createCalendar,e),addCalendar:yt(e.addCalendar,e),getCalendar:yt(e.getCalendar,e),getCalendars:yt(e.getCalendars,e),getResourceCalendar:yt(e.getResourceCalendar,e),getTaskCalendar:yt(e.getTaskCalendar,e),deleteCalendar:yt(e.deleteCalendar,e)}},Jy={create:qy};function ol(e){var t=new al(e),r=new sl(t),n=Jy.create(t,r);Re(e,n)}var cl={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 ll(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||cl,templates:e.templates||{},getTask:e.getTask||function(n){return null},isTaskExists:e.isTaskExists||function(n){return!1},isSummaryTask:e.isSummaryTask||function(n){return!1},getState:function(){return{group_mode:!1}},callEvent:function(n,i){let a=e.onEvent;return a&&a(n,i),!0},attachEvent:function(){return 0},checkEvent:function(){return!1},detachEvent:function(){},defined:Qc,mixin:Re,copy:Tt,assert:function(n,i){if(!n){if(e.throwOnAssert)throw new Error("[calendar] "+i);e.silent!==!0&&console.error("[calendar]",i)}},$services:{getService:function(){return null}},$ui:{getView:function(){return null}}};return r._correct_dst_change=function(n){return n},r.date=rl(r),r.date.init(),ol(r),r}function Xy(e={}){let t=ll(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 dl={createCalendar:Xy};var cO=3600*1e3;function hl(e){return{getActivity(t){return e.getActivity(t)}}}var{createCalendar:Zy}=dl,ze="__replay_default__";function Qy(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],n=t[t.length-1];return t.every((a,s)=>a===r+s)?[`${r}:00-${n+1}:00`]:e}var ul={hours:["8:00-16:00"],days:[!1,!0,!0,!0,!0,!0,!1]},fl="__main_global__",tm={hours:["8:00-12:00","13:00-17:00"],days:[!1,!0,!0,!0,!0,!0,!1]};function pl(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 em(e){let t={};if(Array.isArray(e.days))for(let n=0;n<e.days.length;n+=1)t[n]=e.days[n];if(e.dates)for(let[n,i]of Object.entries(e.dates))t[n]=i;let r={hours:Qy(e.hours),dates:t};return e.customWeeks&&(r.customWeeks=e.customWeeks),r}function yl(e){let t=Zy({config:{work_time:!0}});t.addCalendar({id:ze,worktime:ul}),t.addCalendar({id:fl,worktime:tm});let r=new Set(e.filter(d=>!pl(d.worktime)).map(d=>String(d.id))),n=e.filter(d=>pl(d.worktime));for(let d of n)t.addCalendar({id:d.id,worktime:d.worktime?em(d.worktime):ul});let i=Zc(t),a=i.getCalendar(ze),s=i.getCalendar(fl);if(!a||!s)throw new Error("[replay-calendar] fallback calendars failed to register in work-calendar instance");let o=new Set([ze]);for(let d of n)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=i.getCalendar(d)??a:r.has(u)&&(p=s),c.set(u,p),p}}}}function ml(e){return{hasChildren(t){return e.hasChildren(t)},getParentStartDateIfHasPredecessors(t){let r=e.getActivity(t);if(!r)return null;let n=e.getParent(r.id);return!n||e.getIncomingLinkIds(n.id).length===0?null:n.startDate},getDescendantIds(t){return rm(e,t).map(r=>String(r))},getAncestorIds(t){let r=[],n=e.getActivity(t);for(;n;){let i=n.parentId;if(i===null)break;let a=e.getActivity(i);if(!a)break;r.push(String(i)),n=a}return r},getChildProgressInfo(t){return e.getChildren(t).map(n=>{let i=e.getActivity(n);return{id:n,progress:Number(i?.progress??0),ponderator:Number(i?.ponderator??0)}})},getChildHhInfo(t){return e.getChildren(t).map(n=>{let i=e.getActivity(n);return{id:n,workHours:Number(i?.workHours??0),progress:Number(i?.progress??0),realWorkHours:Number(i?.realWorkHours??0)}})},getChildUsedCostInfo(t){return e.getChildren(t).map(n=>{let i=e.getActivity(n);return{id:n,usedCost:Number(i?.usedCost??0)}})},getChildCostInfo(t){return e.getChildren(t).map(n=>{let i=e.getActivity(n);return{id:n,cost:Number(i?.cost??0)}})}}}function rm(e,t){let r=[],n=new ft;for(let i of e.getChildren(t))n.enqueue(i);for(;!n.isEmpty();){let i=n.dequeue();r.push(i);for(let a of e.getChildren(i))n.enqueue(a)}return r}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 n=this._journal;n&&(n.before.has(t)||n.before.set(t,Qt(r)),n.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:Qt(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:gl(r)})}noteCorrelativeBefore(t,r){let n=this._journal;!n||n.correlativeBefore.has(t)||n.correlativeBefore.set(t,r)}noteScheduledBefore(t,r){let n=this._journal;if(!n)return;let i=Qt(r);n.scheduledBefore.has(t)||n.scheduledBefore.set(t,i),n.before.has(t)||n.before.set(t,i),n.dirty.add(t)}noteLinkField(t,r){let n=this._journal;!n||n.linkFieldCaptured.has(t)||(n.linkFieldCaptured.add(t),n.ops.push({kind:"link-field",linkId:t,before:gl(r)}))}};function gl(e){return{...e}}var Xr=class{_cache={closestWorkTime:new Map,endDate:new Map,duration:new Map};reader;constructor(t){this.reader=t.reader}resolveCalendar(t){let r=vl(t);return this.reader.getCalendar(r??ze)}getClosestWorkTime(t){let r=`${Bi(t.task)}|${t.dir}|${t.date.getTime()}`;return Wi(this._cache.closestWorkTime,r,()=>this.resolveCalendar(t.task).getClosestWorkTime({direction:t.dir,date:t.date,unit:ot.HOUR}))}calculateEndDate(t){let r=`${Bi(t.task)}|${t.startDate.getTime()}|${t.durationHours}`;return Wi(this._cache.endDate,r,()=>this.resolveCalendar(t.task).calculateEndDate(t.startDate,t.durationHours))}calculateDuration(t){let r=`${Bi(t.task)}|${t.startDate.getTime()}|${t.endDate.getTime()}`;return Wi(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 Wi(e,t,r){let n=e.get(t);if(n!==void 0)return n;let i=r();return e.set(t,i),i}var nm="__default__";function vl(e){if(!e)return null;let t=e.calendarId;return t==null?null:String(t)}function Bi(e){return vl(e)??nm}var Zr=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 n=this.activities.get(t)?.parentId,i=0,a=this.activities.size;for(;n&&!L(n);){if(n===r)return!0;if(++i>a)return!1;n=this.activities.get(n)?.parentId}return!1}getParent(t){let r=this.activities.get(t)?.parentId;return!r||L(r)?null:this.activities.get(r)??null}getParentId(t){return this.activities.get(t)?.parentId??null}addChild(t,r){if(this._dirty)return;if(L(t)){this._roots.push(r);return}let n=String(t),i=this._childrenByParent.get(n);i?i.push(r):this._childrenByParent.set(n,[r])}rebuild(){this._childrenByParent.clear(),this._roots=[];for(let r of this.activities.values()){if(L(r.parentId)){this._roots.push(r.id);continue}let n=String(r.parentId),i=this._childrenByParent.get(n)??[];i.push(r.id),this._childrenByParent.set(n,i)}let t=(r,n)=>{let i=this.activities.get(r),a=this.activities.get(n);return i&&a?er(i,a):String(r).localeCompare(String(n))};this._roots.sort(t);for(let r of this._childrenByParent.values())r.sort(t)}};var Qr=class{checkedSet=new Set;hiddenSet=new Set;activeFilter=null;activeOrder=null;isChecked(t){return this.checkedSet.has(t)}isVisible(t){return!this.hiddenSet.has(t)}hiddenIds(){return[...this.hiddenSet]}getActiveFilter(){return this.activeFilter}setActiveFilter(t){this.activeFilter=t}getActiveOrder(){return this.activeOrder}setActiveOrder(t){this.activeOrder=t}checkedIds(){return[...this.checkedSet]}checkedCount(){return this.checkedSet.size}setChecked(t,r){return r===this.checkedSet.has(t)?!1:(r?this.checkedSet.add(t):this.checkedSet.delete(t),!0)}setVisible(t,r){return r===!this.hiddenSet.has(t)?!1:(r?this.hiddenSet.delete(t):this.hiddenSet.add(t),!0)}forget(t){this.checkedSet.delete(t),this.hiddenSet.delete(t)}hydrate(t){this.checkedSet=new Set(t.checkedIds??[]),this.hiddenSet=new Set(t.hiddenIds??[]),this.activeFilter=null,this.activeOrder=null}snapshot(){return{checked:new Set(this.checkedSet),hidden:new Set(this.hiddenSet),activeFilter:this.activeFilter,activeOrder:this.activeOrder}}restore(t){this.checkedSet=new Set(t.checked),this.hiddenSet=new Set(t.hidden),this.activeFilter=t.activeFilter,this.activeOrder=t.activeOrder}};var be=class{_activities=new Map;_lastStartDate=new Map;_promotionSnapshot=new Map;_links=new Map;_outgoing=new Map;_incoming=new Map;_hierarchy;_buildOrderComparator;_cache={ids:null,visualOrderIds:null,orderComparator:null};_writeCapture=new Jr;_viewState=new Qr;_filterProjection=null;_viewStateBefore=null;_lastStartDateBefore=null;_promotionSnapshotBefore=null;_calendar;_flags;constructor(t,r=()=>null){this._buildOrderComparator=r;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._indexLink(n);this._calendar=new Xr(yl(t.calendars)),this._flags=am(t),this._hierarchy=new Zr(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=pa(this).map(t=>String(t.id)),this._cache.visualOrderIds)}invalidateVisualOrderIds(){this._cache.visualOrderIds=null}forEachActivity(t){for(let[r,n]of this._activities)t(n,r)}getParentId(t){return this._hierarchy.getParentId(t)}getActivity(t){return this._activities.get(String(t))??null}getLastStartDate(t){return this._lastStartDate.get(String(t))??null}setLastStartDate(t,r){this._captureLastStartDateOnce(),this._lastStartDate.set(String(t),r)}getPromotionSnapshot(t){return this._promotionSnapshot.get(String(t))??null}setPromotionSnapshot(t,r){this._capturePromotionSnapshotOnce(),this._promotionSnapshot.set(String(t),r)}_capturePromotionSnapshotOnce(){this._writeCapture.peek()!==null&&this._promotionSnapshotBefore===null&&(this._promotionSnapshotBefore=new Map(this._promotionSnapshot))}_captureLastStartDateOnce(){this._writeCapture.peek()!==null&&this._lastStartDateBefore===null&&(this._lastStartDateBefore=new Map(this._lastStartDate))}getLink(t){return this._links.get(String(t))??null}activityExists(t){return this._activities.has(String(t))}isChecked(t){return this._viewState.isChecked(String(t))}isVisible(t){return this._viewState.isVisible(String(t))}checkedIds(){return this._viewState.checkedIds()}hiddenIds(){return this._viewState.hiddenIds()}setChecked(t,r){return this._captureViewStateOnce(),this._viewState.setChecked(String(t),r)}setVisible(t,r){return this._captureViewStateOnce(),this._viewState.setVisible(String(t),r)}getActiveFilter(){return this._viewState.getActiveFilter()}setActiveFilter(t){this._captureViewStateOnce(),this._viewState.setActiveFilter(t),this._filterProjection=null}getFilterProjection(){return this._filterProjection}setFilterProjection(t){this._filterProjection=t}getActiveOrder(){return this._viewState.getActiveOrder()}setActiveOrder(t){this._captureViewStateOnce(),this._viewState.setActiveOrder(t),this.invalidateDerivedOrder()}getOrderComparator(){let t=this._viewState.getActiveOrder();return t===null?(this._cache.orderComparator=null,null):this._cache.orderComparator?this._cache.orderComparator:(this._cache.orderComparator=this._buildOrderComparator(t),this._cache.orderComparator)}invalidateDerivedOrder(){this._cache.orderComparator=null,this._cache.visualOrderIds=null}hydrateViewState(t){this._viewState.hydrate(t),this._filterProjection=null,this.invalidateDerivedOrder()}_captureViewStateOnce(){this._writeCapture.peek()!==null&&this._viewStateBefore===null&&(this._viewStateBefore=this._viewState.snapshot())}getOutgoingLinkIds(t){return this._outgoing.get(String(t))??Al}getIncomingLinkIds(t){return this._incoming.get(String(t))??Al}getChildren(t){return this._hierarchy.getChildren(t)}hasChildren(t){return this._hierarchy.hasChildren(t)}isChildOf(t,r){return this._hierarchy.isChildOf(t,r)}getParent(t){return this._hierarchy.getParent(t)}getRootIds(){return this._hierarchy.getRootIds()}getClosestWorkTime(t){return this._calendar.getClosestWorkTime(t)}calculateEndDate(t){return this._calendar.calculateEndDate(t)}calculateDuration(t){return this._calendar.calculateDuration(t)}clearCalendarCache(){this._calendar.clearCache()}get calendarReader(){return this._calendar.reader}batchUpdate(t){t()}updateActivity(t){}getLiveActivity(t){return this.getActivity(t)}getFlags(){return{...this._flags,allCheckedTaskIds:this._viewState.checkedIds()}}getProjectEnd(){return null}beginWriteCapture(){this._writeCapture.begin(),this._viewStateBefore=null,this._lastStartDateBefore=null,this._promotionSnapshotBefore=null}peekWriteCapture(){return this._writeCapture.peek()}endWriteCapture(){this._writeCapture.end(),this._viewStateBefore=null,this._lastStartDateBefore=null,this._promotionSnapshotBefore=null}setActivityField(t,r,n){let i=this.getActivity(t);i&&(this._writeCapture.note(String(t),i),i[r]=n,r===b.PARENT&&this._hierarchy.markDirty(),Ui(r)&&(this._cache.visualOrderIds=null))}setActivityFieldDynamic(t,r,n){let i=this.getActivity(t);if(i){if(!Object.hasOwn(i,r))throw new Error(`setActivityFieldDynamic: unknown CoreActivity field "${r}"`);this._writeCapture.note(String(t),i),Reflect.set(i,r,Xc(r,n)),r===b.PARENT&&this._hierarchy.markDirty(),Ui(r)&&(this._cache.visualOrderIds=null)}}setActivityFields(t,r){let n=this.getActivity(t);if(!n)return;this._writeCapture.note(String(t),n);let i=!1;for(let a of Object.keys(r))Reflect.set(n,a,Reflect.get(r,a)),a===b.PARENT&&(i=!0),Ui(a)&&(this._cache.visualOrderIds=null);i&&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){Il(this._outgoing,String(t.source),t.id),Il(this._incoming,String(t.target),t.id)}_deindexLink(t){let r=this._outgoing.get(String(t.source));r&&this._outgoing.set(String(t.source),Cl(r,t.id));let n=this._incoming.get(String(t.target));n&&this._incoming.set(String(t.target),Cl(n,t.id))}setLinkField(t,r,n){let i=this.getLink(t);i&&(this._writeCapture.noteLinkField(String(t),i),i[r]=n)}setLinkFieldDynamic(t,r,n){if(!im(r))return;let i=this.getLink(t);i&&(this._writeCapture.noteLinkField(String(t),i),Reflect.set(i,r,n))}setLinkProplannerId(t,r){let n=this.getLink(t);n&&(this._writeCapture.noteLinkField(String(t),n),n.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 n=String(t);(this._viewState.isChecked(n)||!this._viewState.isVisible(n))&&(this._captureViewStateOnce(),this._viewState.forget(n)),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:n,correlativeBefore:i,scheduledBefore:a}=t;this._undoLinkAdds(r),this._undoInserts(r),this._reInsertRemovedActivities(r),this._reAddRemovedLinks(r),this._restoreLinkFields(r),this._restoreCorrelatives(i),this._restoreActivityFields(a),this._restoreActivityFields(n),this._viewStateBefore!==null&&(this._viewState.restore(this._viewStateBefore),this._filterProjection=null,this.invalidateDerivedOrder()),this._promotionSnapshotBefore!==null&&(this._promotionSnapshot=this._promotionSnapshotBefore),this._lastStartDateBefore!==null&&(this._lastStartDate=this._lastStartDateBefore),this._cache.ids=null,this._cache.visualOrderIds=null,this._hierarchy.markDirty()}_restoreCorrelatives(t){for(let[r,n]of t){let i=this._activities.get(r);i&&(i.correlativeId=n)}}_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,n]of t){let i=this._activities.get(r);i&&this._restoreScalarFields(i,n)}}_restoreScalarFields(t,r){for(let n of Object.keys(t))Object.hasOwn(r,n)||Reflect.deleteProperty(t,n);for(let n of Object.keys(r))Reflect.set(t,n,Reflect.get(r,n))}_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))}},Al=[];function im(e){return e===fi.LAG||e===fi.TYPE}function Ui(e){return e===b.PARENT||e===b.CORRELATIVE_ID}function Cl(e,t){return e.filter(r=>String(r)!==String(t))}function Il(e,t,r){let n=e.get(t);n?n.push(r):e.set(t,[r])}function am(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 Sl(e,t){let r=e.getActivity(t);return r?Q(r):null}function kl(e){return e.getAllActivities().map(Q)}function Dl(e){return e.getAllIds().map(String)}function Tl(e,t){e.forEachActivity((r,n)=>t(n))}function _l(e,t){let r=t==="0"?ji(e,"0"):e.getChildren(t),n=[];for(let i of r){let a=e.getActivity(i);a&&n.push(Q(a))}return n.sort((i,a)=>(i.correlativeId??0)-(a.correlativeId??0)),n}function ji(e,t){let r=t;if(r==="0"){let n=[];return e.forEachActivity((i,a)=>{L(i.parentId)&&n.push(a)}),n}return mt(r,e)}function Pl(e){return e.checkedIds().map(String)}function El(e,t){if(t==="0"){let r=!1;return e.forEachActivity(n=>{r||=L(n.parentId)}),r}return e.getChildren(t).length>0}function Rl(e,t){let r=e.getLink(t);return r?vt(r):null}function bl(e){return e.getAllLinks().map(t=>vt(t))}function tn(e){let[t,r]=e.split(":");return Number(t)*60+Number(r??0)}function sm(e){return e.reduce((t,r)=>tn(r)<tn(t)?r:t)}function om(e){return e.reduce((t,r)=>tn(r)>tn(t)?r:t)}function cm(e){return e.worktime.days.flatMap(t=>Array.isArray(t)?t:t===!0?e.worktime.hours:[])}function Ll(e){let t=[...e].find(a=>a.is_default);if(!t)return null;let r=cm(t);if(r.length===0)return null;let n=r.map(a=>a.split("-")[0]),i=r.map(a=>a.split("-")[1]);return{startHour:sm(n),endHour:om(i)}}function wl(e,t){return{calendars:e.calendarReader,hierarchy:ml(e),activityReader:hl(e),dateFormat:t.dateFormat??"YYYY-MM-DD",customHours:t.customHours??{},hoursPerDay:t.hoursPerDay,inputUnit:t.inputUnit??"days"}}function Ol(e){return re(e)}function Nl(e){let t=e.activities.map(i=>({...i,after:null})),r=e.links.map(i=>({...i,after:null})),n=e.source.kind==="activity-batch"?{...e.source,items:[],links:[]}:e.source;return Q({...e,source:n,activities:t,links:r})}function Hi(e,t,r,n,i){return{changeSet:e,beforeSnap:t,beforeLinks:r,afterSnap:n,afterLinks:i}}function Ml(e,t){let r=new Map,n=new Map;for(let i of t.activities){if(i.kind!=="created")continue;let a=e.getActivity(String(i.id));a&&r.set(String(i.id),X(a))}for(let i of t.links){if(i.kind==="deleted")continue;let a=e.getLink(String(i.id));a&&n.set(String(i.id),{...a})}return{afterSnap:r,afterLinks:n}}function Wl(e){return e.kind!=="inline-edit"||!Ye.has(e.column)?null:`inline-edit:${String(e.activityId)}:${e.column}`}function xl(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 Bl(e,t){if(!xl(e)||!xl(t))return!1;let r=e.changeSet.activities[0],n=t.changeSet.activities[0];return!!r&&!!n&&String(r.id)===String(n.id)}function Ul(e,t){let r=e.changeSet.activities[0],n=t.changeSet.activities[0];if(!r||!n)return t;let i=r.fields??{},a=n.fields??{},s={};for(let c of new Set([...Object.keys(i),...Object.keys(a)])){let l=i[c],d=a[c];s[c]={before:l?l.before:d?.before,after:d?d.after:l?.after}}let o={...t.changeSet,activities:[{...n,fields:s}]};return Hi(o)}function jl(e){return e.kind==="persistence-acknowledge"?"clear-on-success":e.kind==="sir-sync"||e.kind==="activity-lookahead-sync"||e.kind==="baseline-apply"||e.kind==="ponderator-criterion-set"||e.kind==="status-criteria-set"||e.kind==="selection-toggle"||e.kind==="selection-replace"||e.kind==="visibility-set"||e.kind==="filter-set"||e.kind==="sort-set"?"skip":"record"}function Vi(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 Yi(e,t,r){let n=[],i=[];for(let s of t.changeSet.activities){let o=String(s.id);if(s.kind==="updated"){let c=e.getActivity(o);n.push({id:o,kind:"updated",fields:Fl(s.fields,r),after:c?X(c):null})}else if(s.kind==="deleted")if(r==="before"){let c=e.getActivity(o);n.push({id:o,kind:"created",after:c?X(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.getActivity(o);n.push({id:o,kind:"created",after:c?X(c):null})}}for(let s of t.changeSet.links){let o=String(s.id);if(s.kind==="updated"){let c=e.getLink(o);i.push({id:o,kind:"updated",fields:Fl(s.fields,r),after:c?vt(c):null})}else if(s.kind==="deleted")if(r==="before"){let c=e.getLink(o);i.push({id:o,kind:"created",after:c?vt(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.getLink(o);i.push({id:o,kind:"created",after:c?vt(c):null})}}let a=(t.changeSet.viewState??[]).map(s=>r==="before"?lm(s):s);return{source:{kind:r==="before"?"undo":"redo"},activities:n,links:i,calendars:[],trackingEvents:[],effects:[],viewState:a}}function Fl(e,t){if(e!=null)return Object.fromEntries(Object.entries(e).map(([r,n])=>[r,t==="before"?{before:Q(n.after),after:Q(n.before)}:{before:Q(n.before),after:Q(n.after)}]))}function lm(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 Ki(e){return e.activities.length>0||e.links.length>0||(e.viewState?.length??0)>0||(e.effects?.length??0)>0}function Hl(e,t){Yl(e,t,"before")}function Vl(e,t){Yl(e,t,"after")}function Yl(e,t,r){let n=t.changeSet;for(let i of n.activities)if(i.kind==="updated"){if(!i.fields)continue;for(let[a,s]of Object.entries(i.fields))rt(e,i.id,a,r==="before"?s.before:s.after)}else if(i.kind==="deleted")if(r==="before"){let a=t.beforeSnap?.get(String(i.id));if(!a)throw new Error(`undo: missing beforeSnap for resurrecting activity ${i.id}`);e.addActivity(X(a))}else e.removeActivity(String(i.id));else if(r==="before")e.removeActivity(String(i.id));else{let a=t.afterSnap?.get(String(i.id));if(!a)throw new Error(`redo: missing afterSnap for re-creating activity ${i.id}`);e.addActivity(X(a))}for(let i of n.links)if(i.kind==="updated"){if(!i.fields)continue;if(Object.hasOwn(i.fields,"source")||Object.hasOwn(i.fields,"target")){let a=r==="before"?t.beforeLinks?.get(String(i.id)):t.afterLinks?.get(String(i.id));if(!a)throw new Error(`${r==="before"?"undo":"redo"}: missing link snapshot for ${i.id}`);e.removeLink(String(i.id)),e.addLink({...a});continue}for(let[a,s]of Object.entries(i.fields))ho(e,String(i.id),a,r==="before"?s.before:s.after)}else if(i.kind==="deleted")if(r==="before"){let a=t.beforeLinks?.get(String(i.id));if(!a)throw new Error(`undo: missing beforeLinks for re-adding link ${i.id}`);e.addLink(a)}else e.removeLink(String(i.id));else if(r==="before")e.removeLink(String(i.id));else{let a=t.afterLinks?.get(String(i.id));if(!a)throw new Error(`redo: missing afterLinks for re-creating link ${i.id}`);e.addLink(a)}for(let i of n.viewState??[])i.checked&&e.setChecked(i.activityId,r==="before"?i.checked.before:i.checked.after),i.visible&&e.setVisible(i.activityId,r==="before"?i.visible.before:i.visible.after)}var dm=100,um=600,en=class{constructor(t=dm){this.maxDepth=t}maxDepth;undoStack=[];redoStack=[];_lastKey=null;_lastTime=0;record(t,r=null,n=0){let i=this.undoStack[this.undoStack.length-1];r!=null&&r===this._lastKey&&n-this._lastTime<=um&&i!==void 0&&Bl(i,t)?this.undoStack[this.undoStack.length-1]=Ul(i,t):(this.undoStack.push(t),this.undoStack.length>this.maxDepth&&this.undoStack.splice(0,this.undoStack.length-this.maxDepth)),this._lastKey=r,this._lastTime=n,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,this.resetCoalesce()}};var fm=["parentId","correlativeId"];function Gl(e,t){let r=new Set,n=i=>{let a=t(i);r.add(a===null?"0":String(a))};for(let i of e.activities){let a=String(i.id);if(i.kind==="created"){n(a);continue}if(i.kind==="deleted"){let c=i.fields;c&&"parentId"in c&&r.add(Kl(c.parentId?.before));continue}let s=i.fields;!s||!fm.some(c=>c in s)||(n(a),"parentId"in s&&r.add(Kl(s.parentId?.before)))}return r}function Kl(e){return e==null?"0":String(e)}function pm(e){return{...e,id:String(e.id),source:String(e.source),target:String(e.target),type:e.type,lag:Number(e.lag)}}function hm(e){return{days:e.days,hours:e.hours,...e.dates?{dates:e.dates}:{},...e.customWeeks?{customWeeks:e.customWeeks}:{}}}function $l(e){return{id:String(e.id),worktime:hm(e.worktime)}}function rn(e,t,r,n=[]){let i=t.map(pm),a=[...r.map($l),...n.map($l)];return{activities:[...e],links:i,calendars:a}}var zl=["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","responsableIds","tagIds"],ql=new Set(["startDate","endDate","constraintDate","dateOrigin"]),Jl=new Set(["newActivityIds","responsableIds","tagIds"]);function Xl(e){let t=zl.map(r=>[r,ym(r,e[r])]);return Object.fromEntries(t)}function ym(e,t){return ql.has(e)?t instanceof Date?new Date(t):null:Jl.has(e)?Array.isArray(t)?[...t]:[]:t}function qe(e,t){if(e.assignedDefaultCalendar)return!0;for(let r of zl)if(!mm(r,e[r],t[r]))return!0;return!1}function mm(e,t,r){return ql.has(e)?gm(t,r):Jl.has(e)?vm(t,r):(t??null)===(r??null)}function gm(e,t){let r=e instanceof Date?e.getTime():null,n=t instanceof Date?t.getTime():null;return r===n}function vm(e,t){let r=Array.isArray(e)?[...e].map(String).sort():[],n=Array.isArray(t)?[...t].map(String).sort():[];return r.length!==n.length?!1:r.every((i,a)=>i===n[a])}function nn(e,t){return e.source!==t.source||e.target!==t.target||e.lag!==t.lag||e.type!==t.type}function Zl(e,t){let r=new Map(e.map(n=>[String(n.id),n]));return t.filter(n=>{let i=r.get(String(n.id));return i?nn(i,n):!1})}var an=class{initialized=!1;dirtyActivityIds=new Set;dirtyLinkIds=new Set;linksAtLastSave=new Map;activitiesAtLastSave=new Map;init(t,r){this.snapshotActivities(t),this.snapshotLinks(r),this.initialized=!0}snapshotActivities(t){this.activitiesAtLastSave.clear(),this.dirtyActivityIds.clear();for(let r of t){let n=String(r.id);if(r.proplannerId==null){this.dirtyActivityIds.add(n);continue}let i=Xl(r);this.activitiesAtLastSave.set(String(r.id),{persistable:i,deletedSnapshot:{id:r.id,proplannerId:r.proplannerId,parentId:r.parentId,hadBaseline:r.baselineSnapshot!==null||r.baselinePoints.length>0}}),qe(r,i)&&this.dirtyActivityIds.add(n)}}snapshotLinks(t){this.linksAtLastSave.clear(),this.dirtyLinkIds.clear();for(let r of t){let n=String(r.id);if(r.proplannerId==null){this.dirtyLinkIds.add(n);continue}this.linksAtLastSave.set(String(r.id),{id:r.id,proplannerId:r.proplannerId,source:r.source,target:r.target,lag:r.lag,type:r.type})}}recordChanges(t,r,n,i){if(this.initialized){for(let a of t){let s=String(a.id),o=n(s),c=this.activitiesAtLastSave.get(s);(o===null?c!==void 0:o.proplannerId==null||c===void 0||qe(o,c.persistable))?this.dirtyActivityIds.add(s):this.dirtyActivityIds.delete(s)}for(let a of r){let s=String(a.id),o=i(s),c=this.linksAtLastSave.get(s);(o===null?c!==void 0:o.proplannerId==null||c===void 0||nn(c,o))?this.dirtyLinkIds.add(s):this.dirtyLinkIds.delete(s)}}}acknowledgePersistedLookahead(t,r){if(this.initialized)for(let n of t){let i=r(n),a=this.activitiesAtLastSave.get(n);if(i===null||a===void 0)continue;let s={...a.persistable,isLookahead:i.isLookahead};this.activitiesAtLastSave.set(n,{...a,persistable:s}),i.proplannerId==null||qe(i,s)?this.dirtyActivityIds.add(n):this.dirtyActivityIds.delete(n)}}hasUnsavedChanges(){return this.initialized&&(this.dirtyActivityIds.size>0||this.dirtyLinkIds.size>0)}deletedActivities(t){if(!this.initialized)return[];let r=new Set(t.map(i=>String(i.id))),n=[];for(let[i,a]of this.activitiesAtLastSave)r.has(i)||n.push({...a.deletedSnapshot});return n}deletedLinks(t){if(!this.initialized)return[];let r=new Set(t.map(n=>String(n.id)));return Array.from(this.linksAtLastSave.entries(),([n,i])=>r.has(n)?null:{...i}).filter(n=>n!==null)}modifiedActivities(t){return this.initialized?t.filter(r=>{if(r.proplannerId==null)return!1;if(r.assignedDefaultCalendar)return!0;let n=this.activitiesAtLastSave.get(String(r.id));return n?qe(r,n.persistable):!0}):[]}modifiedLinks(t){return this.initialized?t.filter(r=>{if(r.proplannerId==null)return!1;let n=this.linksAtLastSave.get(String(r.id));return n?nn(n,r):!0}):[]}clear(){this.initialized=!1,this.dirtyActivityIds.clear(),this.dirtyLinkIds.clear(),this.linksAtLastSave.clear(),this.activitiesAtLastSave.clear()}};var Ql=/^(\d{4})[/-](\d{1,2})[/-](\d{1,2})/;var Gi=[!1,!0,!0,!0,!0,!0,!1],td=new Set(["1","true"]),$i="DURATION",ed="asap",rd={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 nd(e,t){let r=[],n=e.map(a=>{let s=Pm(a,t);return a.should_be_showed===!1&&r.push(s.id),s});Rm(n);let i=new Set(n.map(a=>a.id));return bm(n,i,t.reporter),{activities:n,activityIds:i,hiddenIds:r}}function Am(e){return e===0}function Cm(e,t){if(!e)return null;let r=rd[e.toUpperCase()];return r===void 0?(t.warn(`[parseFromBackend] unknown constraint label "${e}" \u2014 defaulting to "asap"`),ed):r}function Im(e,t){let r=Cm(e.constraint,t),i=r!=="asap"&&r!=="alap"&&e.constraint_date?xt(e.constraint_date):null;return{constraintType:r,constraintDate:i}}function Sm(e,t,r){if(e==null)return r;let n=String(e);return t.has(n)?n:r}function km(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 Dm(e){if(typeof e!="object"||e===null||!("id"in e))return!1;let t=e.id;return typeof t=="string"||typeof t=="number"}function zi(e){if(!Array.isArray(e))return[];let t=[];for(let r of e)Dm(r)&&t.push(String(r.id));return t}function Tm(e){return e==="0"?null:String(e)}function _m(e,t){return Array.isArray(e)?e.map(r=>Kr(r,t)).filter(r=>r!==null):[]}function Pm(e,t){let r=Sm(e.calendarId,t.knownCalendarIds,t.defaultCalendarId),n=e.calendarId==null||!t.knownCalendarIds.has(String(e.calendarId)),i=Number(e.progress),{constraintType:a,constraintDate:s}=Im(e,t.reporter),o=e.type==="milestone",c=xt(e.start_date),l=o?c:xt(e.end_date),d=o?0:Number(e.duration);return{id:String(e.unique_id),proplannerId:typeof e.id=="number"?e.id:null,parentId:Tm(e.parent_id),name:e.name,description:e.description??"",type:e.type,startDate:c,endDate:l,durationHours:Me(d,t.hoursPerDay),constraintType:a,constraintDate:s,autoScheduling:Am(i),calendarId:r,assignedDefaultCalendar:r!=null&&n,dateOrigin:e.date_origin==null?null:xt(e.date_origin),progress:i,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:Em(e),subcontractId:e.subcontractId,isLookahead:e.isOnLookahead,hasLookaheadTasks:Array.isArray(e.tasks)&&e.tasks.length>0,newActivityIds:km(e.newActivitiesArray),hasNewActivities:e.hasNewActivities??!1,...e.isNewActivity===!0?{isNewActivity:!0}:{},pendingRequestIds:zi(e.pendingRequests),responsableIds:zi(e.responsables),tagIds:zi(e.tags),baselinePoints:_m(e.baseline_points,t.reporter),baselineSnapshot:null,recursiveDurationHours:Me(Number(e.sumOfDurationRecursively??0),t.hoursPerDay),isCritical:!!e.is_critical,freeSlackHours:null,expectedProgress:null,expectedProgressBaseline:null,status:null,criticalPath:null}}function Em(e){return e.has_childs?null:e.custom_id}function Rm(e){let t=e.find(r=>r.correlativeId===0&&r.type==="project");t&&(t.parentId=null)}function bm(e,t,r){for(let n of e)n.parentId!==null&&(t.has(n.parentId)||(r.warn(`[parseFromBackend] activity "${n.id}" references unknown parent "${n.parentId}" \u2014 re-parenting to root (null)`),n.parentId=null))}function od(e,t,r,n=null){let s=(e!==void 0&&e.length>0?e:t??[]).map(c=>Om(c,n)),o=(r??[]).map(c=>xm(c,n));return{calendars:s,baseCalendars:o,knownCalendarIds:new Set(s.map(c=>c.id)),defaultCalendarId:wm(s)}}function wm(e){let t=e.find(n=>n.is_default);if(t)return t.id;let r=e[0];return r?r.id:null}function cd(e,t){let r=Um(e.working_days),{days:n,hours:i}=Bm(e,r),a=Fm(t.exceptionsSource,t.exceptionRange),s={days:n,hours:i};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 Om(e,t){let r=e.baseDefault,n=typeof r=="boolean"?r:void 0;return cd(e,{idSuffix:"",isDefault:!!e.is_default,baseDefault:n,exceptionsSource:e.exceptiondays,exceptionRange:t})}function xm(e,t){return cd(e,{idSuffix:"-base",isDefault:!1,baseDefault:!!e.is_default,exceptionsSource:e.baseexceptiondays??e.exceptiondays,exceptionRange:t})}function Fm(e,t){if(!Array.isArray(e)||e.length===0)return null;let r={};for(let n of e){if(!n)continue;let i=Nm(n.from_date,n.to_date,t);if(i.length===0)continue;let a=Mm(n);if(a!==void 0)for(let s of i)r[s]=a}return Object.keys(r).length>0?r:null}function Nm(e,t,r){let n=id(e),i=id(t);if(n===null||i===null)return[];if(r&&(i<r.start||n>r.end))return[];let a=[],s=r?Math.max(n,r.start):n,o=r?Math.min(i,r.end):i;for(;s<=o;)a.push(String(s)),s+=864e5;return a}function id(e){if(typeof e!="string")return null;let t=Ql.exec(e.trim());if(!t)return null;let r=Number(t[1]),n=Number(t[2]),i=Number(t[3]);return Number.isFinite(r)&&Number.isFinite(n)&&Number.isFinite(i)?Date.UTC(r,n-1,i):null}function Mm(e){if(e.workable===!1)return!1;let t=e.shifts;if(Array.isArray(t)&&t.length>0){let r=Wm(t);if(r.length>0)return r}}var ad=/^\d{1,2}:\d{2}$/;function Wm(e){let t=[];for(let r of e){let n=ud(r?.shift_string);if(!n)continue;if(!n.startsCsv.includes(",")&&!n.endsCsv.includes(",")){let o=n.startsCsv.trim(),c=n.endsCsv.trim();!sn(o)&&!sn(c)&&ad.test(o)&&ad.test(c)&&t.push(`${o}-${c}`);continue}let s=dd(n.startsCsv,n.endsCsv).find(o=>o!==null);s&&t.push(s)}return t.sort(ld),t}function sd(e){let t=e.indexOf("-"),r=t>0?e.slice(0,t):e,[n,i]=r.split(":");return(Number(n)||0)*60+(Number(i)||0)}function ld(e,t){return sd(e)-sd(t)}function Bm(e,t){let r=Array.from({length:7},()=>[]),n=(l,d)=>{let u=dd(l,d);for(let f=0;f<7;f+=1){let p=u[f],m=r[f];p&&m&&m.push(p)}},i=Array.isArray(e.shifts)&&e.shifts.length>0,a=typeof e.shift_start=="string"&&typeof e.shift_end=="string";if(i)for(let l of e.shifts){let d=ud(l?.shift_string);d&&n(d.startsCsv,d.endsCsv)}else a&&n(e.shift_start,e.shift_end);for(let l of r)l.sort(ld);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 dd(e,t){let r=Array.from({length:7},()=>null);if(typeof e!="string"||typeof t!="string")return r;let n=e.split(",").map(o=>o.trim()),i=t.split(",").map(o=>o.trim());if(!(n.length===i.length&&n.length>0&&n.length<=7))return r;let s=[...r];for(let o=0;o<n.length;o+=1){let c=n[o],l=i[o];sn(c)||sn(l)||(s[o]=`${c}-${l}`)}return s}function ud(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 Um(e){if(typeof e!="string")return[...Gi];let t=e.split(",").map(r=>r.trim());return t.length!==7?[...Gi]:t.map(r=>td.has(r))}var jm=new Set(["false","null"]);function sn(e){return!e||jm.has(e)}function Hm(e){return e==="0"||e==="1"||e==="2"||e==="3"}function Vm(e){if(typeof e!="string")return null;let t=Rs(e);return t||(Hm(e)?e:null)}function pd(e,t){let r=[];for(let n of e)try{r.push(Ym(n,t.knownActivityIds,t.hoursPerDay))}catch(i){t.reporter.warn("[parseFromBackend] dropping invalid link",i)}return Km(r)}function Ym(e,t,r){let n=String(e.unique_id??e.id),i=String(e.source_id??e.source??""),a=String(e.target_id??e.target??"");if(!t.has(i))throw new Error(`[parseFromBackend] link "${n}" source "${i}" does not exist`);if(!t.has(a))throw new Error(`[parseFromBackend] link "${n}" target "${a}" does not exist`);let s=Vm(e.type);if(s===null)throw new Error(`[parseFromBackend] link "${n}" has invalid type "${String(e.type)}"`);let o=e.ganttId,c=e.sectorId,l=e.id;return{id:n,source:i,target:a,type:s,lag:dt(Number(e.lag??0),r),...typeof o=="number"?{ganttId:o}:{},...typeof c=="number"?{sectorId:c}:{},...typeof l=="number"?{proplannerId:l}:{}}}function Km(e){let t=new Map;for(let r of e){let n=`${r.source}-${r.target}-${r.type}`,i=t.get(n);(!i||fd(r)>fd(i))&&t.set(n,r)}return[...t.values()]}function fd(e){let t=Number(e.id);return Number.isFinite(t)?t:-1/0}function Gm(e){if(typeof e!="string")return $i;switch(e.toUpperCase()){case"DURATION":return"DURATION";case"COST":return"COST";case"HH":return"HH";default:return $i}}function $m(e){let t=e.custom_id_prefix;return typeof t=="string"&&t.length>0?t:void 0}function zm(e){let t=e.custom_id_increment;return typeof t=="string"?t:typeof t=="number"&&Number.isFinite(t)?String(t):void 0}function hd(e){let t=$m(e),r=zm(e),n=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}:{},...n?{updateDurationForPrimaveraEndDate:!0}:{},activityCreter:Gm(e.activity_creter),statusCriteria:kn}}function on(e,t=de){let r=hd(e.sector),{calendars:n,baseCalendars:i,knownCalendarIds:a,defaultCalendarId:s}=od(e.calendars,e.sector.calendars,e.baseCalendars,qm(e.activities)),{activities:o,activityIds:c,hiddenIds:l}=nd(e.activities,{knownCalendarIds:a,defaultCalendarId:s,hoursPerDay:r.hoursPerDay,reporter:t}),d=pd(e.links,{knownActivityIds:c,hoursPerDay:r.hoursPerDay,reporter:t});return{sector:r,activities:o,links:d,calendars:n,baseCalendars:i,viewStateSeed:{hiddenIds:l}}}function qm(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 n=new Date(t),i=new Date(r);return n.setFullYear(n.getFullYear()-1),i.setFullYear(i.getFullYear()+1),{start:n.getTime(),end:i.getTime()}}function yd(e={}){let t=e.seed??0,r=n=>{n>t&&(t=n)};if(e.knownIds)for(let n of e.knownIds){let i=typeof n=="number"?n:Number(n);Number.isFinite(i)&&r(i)}return{next(){return t+=1,String(t)},bump(n){let i=typeof n=="number"?n:Number(n);Number.isFinite(i)&&r(i)},snapshot(){return t},restore(n){t=n}}}function md(e={}){let t=e.seed??0,r=n=>{n>t&&(t=n)};if(e.knownIds)for(let n of e.knownIds){let i=typeof n=="number"?n:Number(n);Number.isFinite(i)&&r(i)}return{next(){return t+=1,String(t)},bump(n){let i=typeof n=="number"?n:Number(n);Number.isFinite(i)&&r(i)},snapshot(){return t},restore(n){t=n}}}function gd(e={}){let t=e.seed??0,r=n=>{Number.isFinite(n)&&n>0&&n<=9999999&&n>t&&(t=n)};if(e.knownIds)for(let n of e.knownIds){if(n==null)continue;let i=typeof n=="number"?n:Number(n);r(i)}return{next(){return t+=1,String(t)},bump(n){if(n==null)return;let i=typeof n=="number"?n:Number(n);r(i)},snapshot(){return t},restore(n){t=n}}}function vd(e){return!!e&&typeof e=="string"&&e.trim().length>0}function cn(e){if(!e||typeof e!="string"||e.trim().length===0)return"";let t=e.match(/^(.*?)(\d+)$/);return t?t[1]??"":e}function ln(e){if(!e||typeof e!="string"||e.trim().length===0)return"";let t=e.match(/(\d+)$/);return t?t[1]??"":""}function Ad(e){if(!e||typeof e!="object")return"";let t=e.customId;return typeof t=="string"?t:""}function Cd(e,t){return!t&&vd(e)}function Id(e,t){return t&&vd(e)}function Xe(e){return typeof e=="string"&&e.length>0&&/^\d+$/.test(e)}function Je(e){if(!Xe(e))return 0n;try{return BigInt(e)}catch{return 0n}}function Jm(e,t){if(typeof e!="bigint")return"";let r=e.toString();if(!Xe(t))return r;let n=t.length;return r.padStart(n,"0")}function Ct(e,t){let r=Je(e),n=Je(t),i=r+n;return Jm(i,e)}function dn(e,t){let r=Je(e),n=Je(t);return r<n?-1:r>n?1:0}function un(e,t){return dn(e,t)<=0?e:t}function fn(e,t){return dn(e,t)>=0?e:t}function Sd(e){if(!e||e.length===0)throw new Error("minSuffixFromArray requires non-empty array");return e.reduce((t,r)=>un(t,r))}function kd(e){if(!e||e.length===0)throw new Error("maxSuffixFromArray requires non-empty array");return e.reduce((t,r)=>fn(t,r))}function Dd(e){return{prefix:e,baseSuffix:null}}function Td(e,t){let r=ln(e);return{prefix:cn(e),baseSuffix:Ct(r,t)}}function _d(e){return{prefix:e,baseSuffix:null}}function Pd(e,t){return Cd(e,t)?"parentConversion":Id(e,t)?"pasteReference":"noContext"}function Xm(e){return{...e,usedSuffixes:new Set(e.usedSuffixes)}}var pn=class{prefixMap=new Map;processedIds=new Set;_journalPrefixBefore=null;_journalIds=null;beginCustomIdTransaction(){this._journalPrefixBefore=new Map,this._journalIds=[]}commitCustomIdTransaction(){this._journalPrefixBefore=null,this._journalIds=null}rollbackCustomIdTransaction(){let t=this._journalPrefixBefore,r=this._journalIds;if(!(t===null||r===null)){for(let[n,i]of t)i===null?this.prefixMap.delete(n):this.prefixMap.set(n,i);for(let n of[...r].reverse())n.hadId?this.processedIds.add(n.customId):this.processedIds.delete(n.customId);this._journalPrefixBefore=null,this._journalIds=null}}_noteCustomIdBefore(t){if(this._journalPrefixBefore===null||this._journalIds===null)return;let{prefix:r}=this.analyzeCustomId(t);if(!this._journalPrefixBefore.has(r)){let n=this.prefixMap.get(r);this._journalPrefixBefore.set(r,n?Xm(n):null)}this._journalIds.push({customId:t,hadId:this.processedIds.has(t)})}_ensureFreshBounds(t){let r=this.prefixMap.get(t);if(!r?.boundsDirty)return;r.boundsDirty=!1;let n=Array.from(r.usedSuffixes);r.min=Sd(n),r.max=kd(n),r.quantity=n.length,this._recalculateNext(t)}defaultPrefix;suffixIncrement;constructor(t={}){this.defaultPrefix=t.defaultPrefix??"A",this.suffixIncrement=t.suffixIncrement??"10"}extractPrefix(t){return cn(t)}extractSuffix(t){return ln(t)}analyzeCustomId(t){return{prefix:this.extractPrefix(t),suffix:this.extractSuffix(t)}}_updatePrefixStats(t,r){if(this._ensureFreshBounds(t),!this.prefixMap.has(t)){this.prefixMap.set(t,{min:r,max:r,next:r,quantity:1,usedSuffixes:new Set([r])}),this._recalculateNext(t);return}let n=this.prefixMap.get(t);n.usedSuffixes.has(r)||(n.usedSuffixes.add(r),n.min=un(r,n.min),n.max=fn(r,n.max),n.quantity+=1,this._recalculateNext(t))}_recalculateNext(t){let r=this.prefixMap.get(t);if(!r)return;let n=this.getNextAvailableSuffix(t);r.next=n??this.suffixIncrement}getPrefixStats(t){this._ensureFreshBounds(t);let r=this.prefixMap.get(t);return r?{min:r.min,max:r.max,next:r.next,quantity:r.quantity}:null}getNextSuffix(t){this._ensureFreshBounds(t);let r=this.prefixMap.get(t);return r?r.next:this.suffixIncrement}getAllPrefixes(){return Array.from(this.prefixMap.keys())}registerCustomId(t){if(!t||typeof t!="string")return{prefix:"",suffix:""};let{prefix:r,suffix:n}=this.analyzeCustomId(t);if(!r&&!n)return{prefix:r,suffix:n};if(this._noteCustomIdBefore(t),this._ensureFreshBounds(r),this.prefixMap.has(r)){let i=this.prefixMap.get(r);i.usedSuffixes.has(n)||(i.usedSuffixes.add(n),i.min=un(n,i.min),i.max=fn(n,i.max),i.quantity+=1,this._recalculateNext(r))}else this.prefixMap.set(r,{min:n,max:n,next:Ct(n,this.suffixIncrement),quantity:1,usedSuffixes:new Set([n])});return this.processedIds.add(t),{prefix:r,suffix:n}}releaseCustomId(t=null){if(!t||typeof t!="string")return{prefix:"",suffix:""};let{prefix:r,suffix:n}=this.analyzeCustomId(t);if(!this.prefixMap.has(r))return{prefix:r,suffix:n};this._noteCustomIdBefore(t);let i=this.prefixMap.get(r);return i.usedSuffixes.has(n)&&(i.usedSuffixes.delete(n),i.quantity-=1,i.usedSuffixes.size===0?this.prefixMap.delete(r):i.boundsDirty=!0),this.processedIds.delete(t),{prefix:r,suffix:n}}trackCustomIdChange(t,r){let n=this.releaseCustomId(t),i=this.registerCustomId(r);return{oldPrefix:n.prefix,oldSuffix:n.suffix,newPrefix:i.prefix,newSuffix:i.suffix}}_exceedsMaxLength(t){return t.length>20}_shouldSearchForGaps(t){if(this._ensureFreshBounds(t),!this.prefixMap.has(t))return!1;let r=this.prefixMap.get(t);return`${t}${Ct(r.max,this.suffixIncrement)}`.length>20}_suffixForUnknownPrefix(t,r){let n=r&&Xe(r)?r:this.suffixIncrement;return`${t}${n}`.length>20?null:n}_findFirstAvailableGap(t){if(this._ensureFreshBounds(t),!this.prefixMap.has(t))return null;let r=this.prefixMap.get(t),n=this.suffixIncrement;for(;dn(n,r.max)<0;){if(`${t}${n}`.length>20)return null;if(!r.usedSuffixes.has(n))return n;n=Ct(n,this.suffixIncrement)}return null}_generateDefaultCustomId(){let t=this.getNextAvailableSuffix(this.defaultPrefix);if(t===null){if(this._shouldSearchForGaps(this.defaultPrefix)){let r=this._findFirstAvailableGap(this.defaultPrefix);if(r!==null)return`${this.defaultPrefix}${r}`}return`${this.defaultPrefix}${this.suffixIncrement}`}return`${this.defaultPrefix}${t}`}getNextAvailableSuffix(t,r=null){if(this._ensureFreshBounds(t),!this.prefixMap.has(t))return this._suffixForUnknownPrefix(t,r);let n=this.prefixMap.get(t),i=this.suffixIncrement;if(!r||!Xe(r)){let o=Ct(n.max,i);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(!n.usedSuffixes.has(a))return a;a=Ct(a,i)}let s=Ct(n.max,i);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 i=this.prefixMap.get(t),a=0;for(;i.usedSuffixes.has(r)&&a<1e4;){let s=this.getNextAvailableSuffix(t,Ct(r,this.suffixIncrement));if(s===null)return this._generateDefaultCustomId();r=s,a++}}let n=`${t}${r}`;return this._exceedsMaxLength(n)&&(n=this._generateDefaultCustomId()),n}populateFromActivities(t){if(!Array.isArray(t))return this;let r=[...new Set(t.filter(n=>n&&typeof n.customId=="string"&&n.customId).map(n=>n.customId))];for(let n of r){if(this.processedIds.has(n))continue;let{prefix:i,suffix:a}=this.analyzeCustomId(n);(i||a)&&(this._updatePrefixStats(i,a),this.processedIds.add(n))}return this}getDefaults(){return{prefix:this.defaultPrefix,increment:this.suffixIncrement}}generateCustomIdForNewChild(t){let{activity:r,useActivityCustomIdAsReference:n=!1}=t,i=Ad(r),a=Pd(i,n),{prefix:s,baseSuffix:o}=this._applyGenerationStrategy(a,i),c=null;if(a==="parentConversion"&&this.prefixMap.has(s)){this._ensureFreshBounds(s);let f=this.prefixMap.get(s).max;c=Ct(f,this.suffixIncrement)}a==="parentConversion"&&this.releaseCustomId(i);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 Dd(this.defaultPrefix);case"pasteReference":return Td(r,this.suffixIncrement);default:return _d(this.defaultPrefix)}}generateCustomIdForRestoredChild(t=null){if(t){let n=t.trim();if(n.length>0){let i=this.extractPrefix(n),a=this.extractSuffix(n),s=Ct(a,this.suffixIncrement),o=this.getNextAvailableSuffix(i,s);if(o===null){let l=this._generateDefaultCustomId();return this.registerCustomId(l),l}let c=`${i}${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 n=t.trim();return r&&n===r.trim()?!1:this.processedIds.has(n)}};var Zm=1,Qm=-1;function tg(e,t){return!e&&!t?null:e&&t?0:e?Zm:Qm}function Ed(e){return e==null}function Rd(e,t){let r=t.indexOf(String(e));return r===-1?t.length:r}function eg(e,t,r){return e instanceof Date&&t instanceof Date?e.getTime()-t.getTime():typeof e=="number"&&typeof t=="number"?e-t:typeof e=="boolean"&&typeof t=="boolean"?Number(e)-Number(t):Array.isArray(e)&&Array.isArray(t)?e.length-t.length:String(e).localeCompare(String(t),r,{sensitivity:"base",numeric:!0})}function rg(e,t){let r=Nt(e.field);return r===null?null:(n,i)=>{let a=r.extract(n,t),s=r.extract(i,t),o=tg(Ed(a),Ed(s));if(o!==null)return o;let c=r.valueKind==="enum"?Rd(a,r.order)-Rd(s,r.order):eg(a,s,t.locale);return e.direction==="desc"?-c:c}}function bd(e,t){let r=e.rules.map(n=>rg(n,t)).filter(n=>n!==null);return r.length===0?null:(n,i)=>{for(let a of r){let s=a(n,i);if(s!==0)return s}return 0}}function Ld(e){let t=[];e.forEachActivity((r,n)=>{r.type==="project"&&e.getChildren(String(n)).length===0&&t.push(String(n))});for(let r of t)e.setActivityField(r,b.TYPE,le),ng(e,r)}function ng(e,t){let r=e.getActivity(t);if(!r||!r.startDate||r.durationHours==null)return;let n=new Date(r.startDate);n.setUTCHours(0,0,0,0);let i=e.getClosestWorkTime({date:n,dir:J.FUTURE,task:r});if(i.getTime()===r.startDate.getTime())return;let a=e.calculateEndDate({startDate:i,durationHours:r.durationHours,task:r});e.setActivityField(t,b.START_DATE,i),e.setActivityField(t,b.END_DATE,a)}function wd(e){let t=[],r=[];e.forEachActivity((i,a)=>{i.parentId===null&&t.push(String(a))});let n=i=>{let a=e.getActivity(i);if(!a)return 0;let s=[...e.getChildren(i)],o=s.length===0?pt(a.workHours,a.progress):s.reduce((c,l)=>c+n(String(l)),0);return e.setActivityField(i,b.REAL_WORK_HOURS,o),r.push(i),o};for(let i of t)n(i);return r}async function Od(e){let{state:t,sector:r,scheduler:n,skipAutoSchedule:i,now:a}=e;if(st(t),r.updateDurationForPrimaveraEndDate&&ag(t),sg(t),wd(t),i){a&&(te(t,a),Ft(t,r.statusCriteria));return}let s=await n.schedule({});Ne(t,s),og(t),ig(t),await fe(t,void 0,!1),a&&(te(t,a),Ft(t,r.statusCriteria))}function ig(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 ag(e){e.forEachActivity(t=>{!t.startDate||!t.endDate||(t.durationHours=e.calculateDuration({startDate:t.startDate,endDate:t.endDate,task:t}))})}function sg(e){e.forEachActivity(t=>{let r=t.constraintType;if(!r||!t.constraintDate)return;let n=t.constraintDate;if(t.type==="milestone"&&(n.getUTCHours()!==0||n.getUTCMinutes()!==0))return;let i=e.calendarReader.getCalendar(String(t.calendarId));i&&(t.constraintDate=wt(t.constraintDate,i,r))})}function og(e){e.forEachActivity(t=>{if(t.type!=="milestone")return;let r=t.constraintType;if(!r||!t.constraintDate)return;let n=e.calendarReader.getCalendar(String(t.calendarId));n&&(t.constraintDate=wt(t.constraintDate,n,r))})}var It={READY:"ready",DESTROYED:"destroyed",POISONED:"poisoned"};function xd(e){let t=e.clock??null,r=t?.()??null,n=r?kr(r):null,i=e.reporter??de,a=on({sector:e.sector,activities:e.activities,links:e.links,calendars:e.calendars,baseCalendars:e.baseCalendars},i),s=a.sector;s.statusCriteria=nr(e.statusCriteria);let o=a.calendars,c=a.baseCalendars??[],l=rn(a.activities,a.links,a.calendars,c),d=S=>bd(S,qt(s.hoursPerDay)),u=new be(l,d);u.hydrateViewState({hiddenIds:a.viewStateSeed.hiddenIds});let f=new vr(u,i);Ld(u);let p=yd({knownIds:a.activities.map(S=>S.id)}),m=md({seed:r?.getTime()??0,knownIds:a.links.map(S=>S.id)}),I=gd({knownIds:a.activities.map(S=>S.uniqueCorrelativeId)}),C=new pn({defaultPrefix:s.customIdPrefix,suffixIncrement:s.customIdIncrement});if(C.populateFromActivities(a.activities),e.baselinePoints&&e.baselinePoints.length>0){let S=c.find(P=>P.baseDefault)?.id??null;Gr(u,e.baselinePoints,n,i,S)}let _=Od({state:u,sector:s,scheduler:f,skipAutoSchedule:e.skipInitialAutoSchedule===!0,now:n??void 0});return{sector:s,state:u,scheduler:f,activityIdGen:p,linkIdGen:m,uidGen:I,customIdTracker:C,calendars:o,baseCalendars:c,clock:t,reporter:i,initPromise:_}}var cg=()=>({constantStart:null,variableStartOffset:null,constantEnd:null,variableEndOffset:null}),Ji=(e,t)=>e===null?t:Math.min(e,t),Xi=(e,t)=>e===null?t:Math.max(e,t);function Nd(e,t,r){let n=[...new Set(t.kind==="move"?t.activityIds.map(String):[String(t.activityId)])];if(n.length===0)throw new Error("[ScheduleCore] date gesture has no participants");let i=lg(e,t,n);return dg(e,n,i),{getDates(a,s){if(r(),!Number.isFinite(s))throw new Error("[ScheduleCore] invalid date gesture edge");let o=i.get(String(a));if(!o)return null;let c=fg(o,s),l=pg(o,s);if(c===null||l===null)throw new Error(`[ScheduleCore] incomplete date gesture bounds for ${String(a)}`);return{startTimeMs:c,endTimeMs:l}}}}function lg(e,t,r){let n=new Map,i=t.kind==="move"?String(t.anchorActivityId):null,a=i===null?null:Fd(e,i);if(i!==null&&!r.includes(i))throw new Error("[ScheduleCore] move anchor is not a participant");for(let s of r){let o=Fd(e,s);if(t.kind==="move"){let c=a.startDate.getTime();n.set(s,{constantStart:null,variableStartOffset:o.startDate.getTime()-c,constantEnd:null,variableEndOffset:o.endDate.getTime()-c})}else t.kind==="resize-start"?n.set(s,{constantStart:null,variableStartOffset:0,constantEnd:o.endDate.getTime(),variableEndOffset:null}):n.set(s,{constantStart:o.startDate.getTime(),variableStartOffset:null,constantEnd:null,variableEndOffset:0})}return n}function dg(e,t,r){let n=Fn(e,new Set(t));for(let i of n){let a=cg();for(let s of e.getChildren(i)){let o=r.get(s);if(o){ug(a,o);continue}let c=e.getActivity(s);if(!c)throw new Error(`[ScheduleCore] missing child ${s} while previewing parent ${i}`);a.constantStart=Ji(a.constantStart,c.startDate.getTime()),a.constantEnd=Xi(a.constantEnd,c.endDate.getTime())}r.set(i,a)}}function Fd(e,t){let r=e.getActivity(t);if(!r)throw new Error(`[ScheduleCore] missing date gesture activity ${t}`);if(e.hasChildren(t))throw new Error(`[ScheduleCore] summary activity ${t} cannot be dragged directly`);return r}function ug(e,t){t.constantStart!==null&&(e.constantStart=Ji(e.constantStart,t.constantStart)),t.variableStartOffset!==null&&(e.variableStartOffset=Ji(e.variableStartOffset,t.variableStartOffset)),t.constantEnd!==null&&(e.constantEnd=Xi(e.constantEnd,t.constantEnd)),t.variableEndOffset!==null&&(e.variableEndOffset=Xi(e.variableEndOffset,t.variableEndOffset))}function fg(e,t){if(e.variableStartOffset===null)return e.constantStart;let r=t+e.variableStartOffset;return e.constantStart===null?r:Math.min(e.constantStart,r)}function pg(e,t){if(e.variableEndOffset===null)return e.constantEnd;let r=t+e.variableEndOffset;return e.constantEnd===null?r:Math.max(e.constantEnd,r)}function hg(e){for(let t of e.activities)if(t.kind==="deleted"||t.kind==="updated"&&t.fields!==void 0&&"parentId"in t.fields)return!0;return!1}function yg(e,t){let r=[];for(let n of e.activities){let i=t.getActivity(n.id);if(i===null)return null;r.push(i)}return r}function mg(e,t,r){if(e===null||e.filter!==t)return!1;let n=e.context.hoursPerDay===r.hoursPerDay,i=e.context.locale===r.locale;return n&&i}var hn=class{_status=It.READY;coreRuntime;_undo=new en;_opQueue=Promise.resolve();_scheduleRevision=0;_pendingScheduleRevision=0;_criticalPathRevision=-1;_activeCriticalPath=null;constructor(t){let r=xd(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(i=>[i.id,i])),baseCalendars:r.baseCalendars,reporter:r.reporter},this._initPromise=r.initPromise.then(()=>{this._status!==It.DESTROYED&&this._saveTracker.init(this.coreRuntime.state.getAllActivities(),this.getAllLinksView())}),this._criticalPathReady=this._initPromise.then(()=>this._enqueue(async()=>{let i=await this._runCriticalPathAndCapture();return this._criticalPathRevision=this._scheduleRevision,i}));let n=t.criticalPathOnLoad===!0;this._ready=n?this._criticalPathReady.then(()=>{}):this._initPromise}get ready(){return this._ready}get criticalPathReady(){return this._criticalPathReady}get status(){return this._status}getSector(){return Q(this.coreRuntime.sector)}getActivityView(t){return this.assertReady(),Sl(this.coreRuntime.state,t)}createDateGesturePreview(t){this.assertReady();let r=this._scheduleRevision;return Nd(this.coreRuntime.state,t,()=>{if(this.assertReady(),this._scheduleRevision!==r)throw new Error("[ScheduleCore] date gesture preview is stale")})}getAllActivitiesView(){return this.assertReady(),kl(this.coreRuntime.state)}getChildrenView(t){return this.assertReady(),_l(this.coreRuntime.state,t)}getLinkView(t){return this.assertReady(),Rl(this.coreRuntime.state,t)}getAllLinksView(){return this.assertReady(),bl(this.coreRuntime.state)}getProperty(t,r){this.assertReady();let n=this.coreRuntime.state.getActivity(t);return n?Q(n[r]):null}getAllIds(){return this.assertReady(),Dl(this.coreRuntime.state)}forEachActivityId(t){this.assertReady(),Tl(this.coreRuntime.state,t)}getChildrenIds(t){return this.assertReady(),ji(this.coreRuntime.state,t)}getSelectedActivityIds(){return this.assertReady(),Pl(this.coreRuntime.state)}getHiddenActivityIds(){return this.assertReady(),this.coreRuntime.state.hiddenIds().map(String)}getActiveFilter(){return this.assertReady(),this.coreRuntime.state.getActiveFilter()}getActiveOrder(){return this.assertReady(),this.coreRuntime.state.getActiveOrder()}getVisualOrderIds(){return this.assertReady(),[...this.coreRuntime.state.getVisualOrderIds()]}hasChild(t){return this.assertReady(),El(this.coreRuntime.state,t)}getCalendar(t){this.assertReady();let r=this.coreRuntime.calendars.get(t);return r?Q(r):null}getAllCalendars(){return this.assertReady(),Array.from(this.coreRuntime.calendars.values(),t=>Q(t))}getBaseCalendars(){return this.assertReady(),this.coreRuntime.baseCalendars.map(t=>Q(t))}isCustomIdInUse(t,r=null){return this.assertReady(),this.coreRuntime.customIdTracker.isCustomIdInUse(t,r)}getProjectWorkHours(){return this.assertReady(),Ll(this.coreRuntime.calendars.values())}getModifiedLinks(){return this.assertReady(),this._saveTracker.modifiedLinks(this.getAllLinksView())}getModifiedActivities(){return this.assertReady(),this._saveTracker.modifiedActivities(this.coreRuntime.state.getAllActivities()).map(Q)}hasUnsavedChanges(){return this.assertReady(),this._saveTracker.hasUnsavedChanges()}getDeletedActivitiesSinceLastSave(){return this.assertReady(),this._saveTracker.deletedActivities(this.coreRuntime.state.getAllActivities()).map(Q)}getDeletedLinksSinceLastSave(){return this.assertReady(),this._saveTracker.deletedLinks(this.getAllLinksView()).map(Q)}_enqueue(t){let r=this._opQueue.then(t,t);return this._opQueue=r.then(()=>{},()=>{}),r}_beginScheduleMutation(t){return hi(t)?this._admitScheduleMutation():!1}_admitScheduleMutation(){return this._pendingScheduleRevision++,this._activeCriticalPath&&(this._activeCriticalPath.cancellation.cancelled=!0),!0}_settleScheduleMutation(t,r){t&&(r||(this._pendingScheduleRevision=Math.max(this._pendingScheduleRevision-1,this._scheduleRevision),this._pendingScheduleRevision===this._scheduleRevision&&this._criticalPathRevision!==this._scheduleRevision&&this.recomputeCriticalPath().catch(n=>{this.coreRuntime.reporter.error("[ScheduleCore] Critical Path re-arm after a barren mutation failed",n)})))}async dispatch(t,r={}){let n=this._beginScheduleMutation(t);return this._enqueue(()=>this._dispatchInner(t,r,n))}async applyActivityBatch(t,r={}){let n=this._beginScheduleMutation(t);return this._enqueue(()=>this._dispatchInner(t,r,n))}async _dispatchInner(t,r={},n=!1){let i=!1;try{let a=await this._runDispatch(t,r);return i=a.changedState,a.result}finally{this._settleScheduleMutation(n,i)}}async _runDispatch(t,r){this.assertReady();let n=wl(this.coreRuntime.state,{hoursPerDay:this.coreRuntime.sector.hoursPerDay,dateFormat:this.coreRuntime.sector.dateFormat,inputUnit:r.inputUnit??"days"}),i=jl(t),a=[this.coreRuntime.activityIdGenerator.snapshot(),this.coreRuntime.linkIdGenerator.snapshot(),this.coreRuntime.uniqueCorrelativeIdGenerator.snapshot()];this.coreRuntime.state.beginWriteCapture(),this.coreRuntime.customIdTracker.beginCustomIdTransaction();let s;try{s=await Jc(t,r,{adapter:this.coreRuntime.state,ctx:n,scheduler:this.coreRuntime.scheduler,sector:this.coreRuntime.sector,calendars:this.coreRuntime.calendars,activityIdGen:this.coreRuntime.activityIdGenerator,linkIdGen:this.coreRuntime.linkIdGenerator,uidGen:this.coreRuntime.uniqueCorrelativeIdGenerator,customIdTracker:this.coreRuntime.customIdTracker,reporter:this.coreRuntime.reporter,defaultBaseCalendarId:this.coreRuntime.baseCalendars.find(o=>o.baseDefault)?.id??null,now:this.coreRuntime.clock?kr(this.coreRuntime.clock()):null}),s.ok||this._rollback(a)}catch(o){throw this._rollback(a),o}finally{this.coreRuntime.state.endWriteCapture(),this.coreRuntime.customIdTracker.commitCustomIdTransaction()}if(s.ok&&i==="record"&&Ki(s.changes)){let o=Ml(this.coreRuntime.state,s.changes);this._undo.record(Hi(Nl(s.changes),s.__beforeSnap,s.__beforeLinks,o.afterSnap,o.afterLinks),Wl(t),Date.now())}return s.ok&&(i==="clear-on-success"?(this._saveTracker.snapshotActivities(this.coreRuntime.state.getAllActivities()),this._saveTracker.snapshotLinks(this.getAllLinksView()),this._undo.clear()):t.kind==="activity-lookahead-sync"&&t.acknowledgePersistedLookahead===!0?this._saveTracker.acknowledgePersistedLookahead(t.activityIds,o=>this.coreRuntime.state.getActivity(o)):this._saveTracker.recordChanges(s.changes.activities,s.changes.links,o=>this.coreRuntime.state.getActivity(o),o=>this.coreRuntime.state.getLink(o))),s=this._withReappliedViewState(t,s),s.ok?hi(t)&&Ki(s.changes)?(this._recordScheduleMutation(r.skipAutoSchedule!==!0&&r.skipCriticalPath!==!0&&re(t)),{result:Md(s),changedState:!0}):{result:Md(s),changedState:!1}:{result:s,changedState:!1}}recomputeCriticalPath(){let t=this._enqueue(async()=>({job:this._startCriticalPathForCurrentRevision()})).then(({job:r})=>r);return this._criticalPathReady=t,t}isCriticalPathSettled(){return this._criticalPathRevision===this._scheduleRevision&&this._pendingScheduleRevision===this._scheduleRevision&&this._activeCriticalPath===null}async whenCriticalPathSettled(){for(;!this.isCriticalPathSettled();)await this.recomputeCriticalPath()}_withReappliedViewState(t,r){if(!r.ok||(t.kind==="visibility-set"&&this.coreRuntime.state.setFilterProjection(null),!Jo(t)))return r;let n=this._reapplyViewState(r.changes);return n===null?r:{...r,changes:n}}_reapplyViewState(t){let r=this._reapplyActiveFilter(t),n=this._emitTouchedBranchOrder(r??t),a=this._reapplyActiveOrder(n.changes??r??t,n.touchedParents)??n.changes??r,s=a??t,o=s.activities.filter(u=>u.kind==="created").map(u=>String(u.id));if(o.length===0)return a;let c=new Set(o),l=this.coreRuntime.state.getFilterProjection();for(let u of o){l!==null&&l.pinnedVisibleIds.add(u);let f=u;for(;f!==null&&f!=="0";)c.add(f),l!==null&&(l.visibleIds.add(f),l.visibleReferenceCounts.set(f,(l.visibleReferenceCounts.get(f)??0)+1)),f=this.coreRuntime.state.getParentId(f)}let d=zt(this.coreRuntime.state,c,c);return d.length===0?a:{...s,viewState:[...s.viewState??[],...d]}}_emitTouchedBranchOrder(t){let r=this.coreRuntime.state,n=Gl(t,a=>r.getParentId(a));if(r.getActiveOrder()!==null)return{changes:null,touchedParents:n};if(n.size===0)return{changes:null,touchedParents:n};let i=Sn(r,n);return i.length===0?{changes:null,touchedParents:n}:{changes:{...t,order:i},touchedParents:n}}_reapplyActiveOrder(t,r){let n=this.coreRuntime.state;if(n.getActiveOrder()===null)return null;if(n.invalidateDerivedOrder(),t.links.length>0||t.calendars.length>0)return{...t,order:Oe(n)};let a=new Set(r);for(let o of t.activities){if(o.kind==="deleted")return{...t,order:Oe(n)};let c=n.getParentId(o.id);a.add(c===null?"0":String(c))}let s=Sn(n,a);return s.length===0?null:{...t,order:s}}_reapplyActiveFilter(t){let r=this.coreRuntime.state,n=r.getActiveFilter();if(n===null)return null;let i=qt(this.coreRuntime.sector.hoursPerDay),a=r.getFilterProjection(),s=mg(a,n,i),o=hg(t)?null:yg(t,r),c,l;if(o===null||!s){let f=tr({activities:r.getAllActivities(),parentOf:p=>r.getParentId(p),filter:n,context:i,...s?{pinnedVisibleIds:a.pinnedVisibleIds}:{}});r.setFilterProjection(f),l=f.visibleIds,c=r.getAllIds()}else c=ca(a,o,f=>r.getParentId(f)),l=a.visibleIds;let u=zt(r,l,c);return u.length===0?null:{...t,viewState:[...t.viewState??[],...u]}}_recordScheduleMutation(t){this._scheduleRevision++,this._pendingScheduleRevision=Math.max(this._pendingScheduleRevision,this._scheduleRevision),this._activeCriticalPath&&(this._activeCriticalPath.cancellation.cancelled=!0),t&&(this._criticalPathRevision=this._scheduleRevision)}_startCriticalPathForCurrentRevision(){if(this._status===It.DESTROYED)return Promise.resolve(null);let t=this._scheduleRevision;if(this._criticalPathRevision===t)return Promise.resolve(null);if(this._activeCriticalPath?.revision===t)return this._activeCriticalPath.promise;this._activeCriticalPath&&(this._activeCriticalPath.cancellation.cancelled=!0);let r={cancelled:!1},n=new be(rn(this.coreRuntime.state.getAllActivities().map(o=>X(o)),this.coreRuntime.state.getAllLinks().map(o=>({...o})),Array.from(this.coreRuntime.calendars.values()),this.coreRuntime.baseCalendars)),i=()=>!r.cancelled&&this._status!==It.DESTROYED&&this._scheduleRevision===t&&this._pendingScheduleRevision===this._scheduleRevision,a=(async()=>{let o=await ui(n,this.coreRuntime.sector.hoursPerDay,i);return!i()||o===null?null:this._enqueue(async()=>{if(!i())return null;this.coreRuntime.state.beginWriteCapture(),this.coreRuntime.customIdTracker.beginCustomIdTransaction();let c;try{for(let[l,d]of o)di(this.coreRuntime.state,l,d);c=await B(this.coreRuntime.state,{source:{kind:"init"},beforeSnap:new Map,touchedIds:[],scheduledIds:[],hoursPerDay:this.coreRuntime.sector.hoursPerDay}),this._criticalPathRevision=t}catch(l){throw this._rollback(),l}finally{this.coreRuntime.state.endWriteCapture(),this.coreRuntime.customIdTracker.commitCustomIdTransaction()}return{changes:c}})})();this._activeCriticalPath={revision:t,cancellation:r,promise:a};let s=()=>{this._activeCriticalPath?.promise===a&&(this._activeCriticalPath=null)};return a.then(s,s),a}async _runCriticalPathAndCapture(){if(this._status===It.DESTROYED)return{changes:{source:{kind:"init"},activities:[],links:[],calendars:[],trackingEvents:[]}};this.coreRuntime.state.beginWriteCapture(),this.coreRuntime.customIdTracker.beginCustomIdTransaction();let t;try{await Fr(this.coreRuntime.state,this.coreRuntime.sector.hoursPerDay),t=await B(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(t={}){let r=this._admitScheduleMutation(),n=!1,i=this._enqueue(async()=>{try{return await this._runUndo(t,a=>{n=a})}finally{this._settleScheduleMutation(r,n)}});return i.then(a=>{a&&t.skipCriticalPath!==!0&&this.recomputeCriticalPath().catch(s=>{this.coreRuntime.reporter.error("[ScheduleCore] Critical Path recompute after undo failed",s)})},()=>{}),i}async _runUndo(t,r){{if(this.assertReady(),t.expectedUndoDepth!==void 0&&this._undo.undoDepth()!==t.expectedUndoDepth)return null;let n=this._undo.takeUndo();if(!n)return null;Hl(this.coreRuntime.state,n),this._recordScheduleMutation(!1),r(!0),Vi(n)&&this._resyncCustomIdTrackerFromModel(),this._undo.pushRedo(n),this._undo.resetCoalesce();let i=Yi(this.coreRuntime.state,n,"before");return this._saveTracker.recordChanges(i.activities,i.links,a=>this.coreRuntime.state.getActivity(a),a=>this.coreRuntime.state.getLink(a)),this._reapplyViewState(i)??i}}redo(t={}){let r=this._admitScheduleMutation(),n=!1,i=this._enqueue(async()=>{try{return await this._runRedo(a=>{n=a})}finally{this._settleScheduleMutation(r,n)}});return i.then(a=>{a&&t.skipCriticalPath!==!0&&this.recomputeCriticalPath().catch(s=>{this.coreRuntime.reporter.error("[ScheduleCore] Critical Path recompute after redo failed",s)})},()=>{}),i}async _runRedo(t){this.assertReady();let r=this._undo.takeRedo();if(!r)return null;Vl(this.coreRuntime.state,r),this._recordScheduleMutation(!1),t(!0),Vi(r)&&this._resyncCustomIdTrackerFromModel(),this._undo.pushUndo(r),this._undo.resetCoalesce();let n=Yi(this.coreRuntime.state,r,"after");return this._saveTracker.recordChanges(n.activities,n.links,i=>this.coreRuntime.state.getActivity(i),i=>this.coreRuntime.state.getLink(i)),this._reapplyViewState(n)??n}canUndo(){return this._undo.canUndo()}canRedo(){return this._undo.canRedo()}clearHistory(){this._undo.clear()}undoDepth(){return this._undo.undoDepth()}_resyncCustomIdTrackerFromModel(){this.coreRuntime.customIdTracker.clear(),this.coreRuntime.customIdTracker.populateFromActivities(this.coreRuntime.state.getAllActivities())}destroy(){this._activeCriticalPath&&(this._activeCriticalPath.cancellation.cancelled=!0),this.coreRuntime.calendars.clear(),this._saveTracker.clear(),this._status=It.DESTROYED}_initPromise;_criticalPathReady;_ready;_saveTracker=new an;assertReady(){if(this._status===It.DESTROYED)throw new Error("[ScheduleCore] instance is destroyed");if(this._status===It.POISONED)throw new Error("[ScheduleCore] instance is poisoned (a rollback failed) \u2014 reload from backend")}_rollback(t){try{this.coreRuntime.state.restoreFromCapture(),this.coreRuntime.customIdTracker.rollbackCustomIdTransaction(),t&&(this.coreRuntime.activityIdGenerator.restore(t[0]),this.coreRuntime.linkIdGenerator.restore(t[1]),this.coreRuntime.uniqueCorrelativeIdGenerator.restore(t[2]))}catch(r){throw this._status=It.POISONED,this.coreRuntime.reporter.error("[ScheduleCore] rollback failed \u2014 core poisoned",r),r}}};function Md(e){let{__beforeSnap:t,__beforeLinks:r,...n}=e;return n}var Wd=(e=[])=>(e??[]).filter(t=>!t.proplannerId);var Bd={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 Ud=8;var $={PERSISTENCE_ACKNOWLEDGE:"persistence-acknowledge",BASELINE_APPLY:"baseline-apply",PONDERATOR_CRITERION_SET:"ponderator-criterion-set",STATUS_CRITERIA_SET:"status-criteria-set",INLINE_EDIT:"inline-edit",DATES_BATCH:"dates-batch",BULK_EDIT:"bulk-edit",LINK_CREATE:"link-create",LINK_UPDATE:"link-update",LINK_DELETE:"link-delete",LINKS_BATCH:"links-batch",ACTIVITY_CREATE:"activity-create",ACTIVITY_DELETE:"activity-delete",ACTIVITY_MOVE:"activity-move",ACTIVITY_INDENT:"activity-indent",ACTIVITY_OUTDENT:"activity-outdent",ACTIVITY_SET_PROGRESS:"activity-set-progress",ACTIVITY_PASTE:"activity-paste",SELECTION_TOGGLE:"selection-toggle",SELECTION_REPLACE:"selection-replace",VISIBILITY_SET:"visibility-set",FILTER_SET:"filter-set",SORT_SET:"sort-set",SIR_SYNC:"sir-sync",ACTIVITY_LOOKAHEAD_SYNC:"activity-lookahead-sync"},gg={[$.PERSISTENCE_ACKNOWLEDGE]:!0,[$.BASELINE_APPLY]:!0,[$.PONDERATOR_CRITERION_SET]:!0,[$.STATUS_CRITERIA_SET]:!0,[$.INLINE_EDIT]:!0,[$.DATES_BATCH]:!0,[$.BULK_EDIT]:!0,[$.LINK_CREATE]:!0,[$.LINK_UPDATE]:!0,[$.LINK_DELETE]:!0,[$.LINKS_BATCH]:!0,[$.ACTIVITY_CREATE]:!0,[$.ACTIVITY_DELETE]:!0,[$.ACTIVITY_MOVE]:!0,[$.ACTIVITY_INDENT]:!0,[$.ACTIVITY_OUTDENT]:!0,[$.ACTIVITY_SET_PROGRESS]:!0,[$.ACTIVITY_PASTE]:!0,[$.SELECTION_TOGGLE]:!0,[$.SELECTION_REPLACE]:!0,[$.VISIBILITY_SET]:!0,[$.FILTER_SET]:!0,[$.SORT_SET]:!0,[$.SIR_SYNC]:!0,[$.ACTIVITY_LOOKAHEAD_SYNC]:!0},jd=Object.keys(gg);var Hd={CHILD:"child",CHILD_CONFIRMED:"child-confirmed",LINE:"line",ROOT:"root"};return qd(vg);})();
|
|
2
2
|
//# sourceMappingURL=schedule-core.global.js.map
|