@outbuild-company/schedule-core 1.8.0 → 1.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- "use strict";var ScheduleCore=(()=>{var Bn=Object.defineProperty;var Lu=Object.getOwnPropertyDescriptor;var wu=Object.getOwnPropertyNames;var Ou=Object.prototype.hasOwnProperty;var xu=(e,t)=>{for(var r in t)Bn(e,r,{get:t[r],enumerable:!0})},Fu=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of wu(t))!Ou.call(e,i)&&i!==r&&Bn(e,i,{get:()=>t[i],enumerable:!(n=Lu(t,i))||n.enumerable});return e};var Nu=e=>Fu(Bn({},"__esModule",{value:!0}),e);var Ev={};xu(Ev,{ACTIVITY_TYPE:()=>Ar,CALENDAR_UNIT:()=>ot,COLUMN:()=>_,CONSTRAINT_TYPE:()=>K,CONSTRAINT_TYPE_TO_LABEL:()=>_u,CREATION_KIND:()=>bu,DEFAULT_HOURS_PER_DAY:()=>Pu,DISPATCH_ACTION_KIND:()=>G,DISPATCH_ACTION_KINDS:()=>Ru,DISPATCH_TRACK_EVENT:()=>Ct,LINK_CODE_TO_TYPE:()=>te,LINK_TYPE:()=>W,LINK_TYPE_CODE:()=>no,NEW_ACTIVITY_DEFAULTS:()=>on,REJECTION_REASON:()=>S,ROOT_PARENT_ID:()=>F,SCHEDULE_CORE_STATUS:()=>St,STATUS:()=>Rt,ScheduleCore:()=>Wn,WORK_TIME_DIRECTION:()=>X,checkNoUpdatedLinks:()=>Bd,computeExpectedProgress:()=>ui,expectedProgressFromBaseline:()=>Le,getActiveBaseline:()=>ut,getUnsavedActivities:()=>Tu,isRootParent:()=>L,normalizeParentKey:()=>Bt,parseFromBackend:()=>Ln,willRunCriticalPath:()=>gd,yieldToBrowser:()=>Z});var ht=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 fr=e=>String(e);function ba(e){let{clickedId:t,isChecked:r,currentSelection:n,hierarchy:i,isFrozen:a,exists:s,autoCheckParents:o}=e,c=fr(t),l=new Set([...n].map(String)),d=new Set(l),u=Mu(c,i).filter(s),f=u.filter(h=>!a(h)),p=r&&f.length<u.length;r&&!p?d.add(c):d.delete(c);for(let h of f)r?d.add(h):d.delete(h);return p||Wu({id:c,isChecked:r,autoCheckParents:o,hierarchy:i,isFrozen:a,exists:s,next:d}),{nextSelection:d,changed:Bu(l,d),parentBlocked:p}}function Mu(e,t){let r=[],n=new ht;n.enqueue(e);let i=new Set([e]);for(;!n.isEmpty();){let a=n.dequeue();for(let s of t.getChildrenIds(a)){let o=fr(s);i.has(o)||(i.add(o),r.push(o),n.enqueue(o))}}return r}function Wu(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=fr(c);if(a(l))return;let d=i.getChildrenIds(l).map(fr).filter(s),u=d.some(a),f=d.filter(A=>!a(A)),h=f.length>0&&f.every(A=>o.has(A))&&!u;if(r){if(!n||!h||o.has(l))return;o.add(l)}else{if(h||!o.has(l))return;o.delete(l)}c=i.getParentId(l)}}function Bu(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 ye(e){return(e.pendingRequestIds?.length??0)>0}var S={CANNOT_EDIT:"cannot_edit",PARSE_ERROR:"parse_error",INVALID:"invalid",CUSTOM_ID_DUPLICATE:"custom_id_duplicate",INVALID_LINK_TYPE:"invalid_link_type",INVALID_LINK_LAG:"invalid_link_lag",INVALID_VALUE:"invalid_value",NO_PIPELINE_FOR_COLUMN:"no_pipeline_for_column",ACTIVITY_NOT_FOUND:"activity_not_found",PARENT_NOT_FOUND:"parent_not_found",ACTIVITY_IDS_EMPTY:"activity_ids_empty",NO_ACTIVITY_SELECTION:"no_activity_selection",CLIPBOARD_EMPTY:"clipboard_empty",ACTIVITY_PASTE_INVARIANT_FAILED:"activity_paste_invariant_failed",ANCHOR_SIBLING_CONFLICT:"anchor_sibling_conflict",ANCHOR_SIBLING_NOT_FOUND:"anchor_sibling_not_found",ANCHOR_SIBLING_WRONG_PARENT:"anchor_sibling_wrong_parent",PARENT_FROZEN_BY_SIR:"parent_frozen_by_sir",CANNOT_MOVE_INTO_OWN_DESCENDANT:"cannot_move_into_own_descendant",INDENT_NO_ELIGIBLE_SIBLING:"indent_no_eligible_sibling",OUTDENT_ROOT_LEVEL_NOT_EDITABLE:"outdent_root_level_not_editable",HIERARCHY_CYCLE:"hierarchy_cycle",SANDBOX_PERSISTENCE_FORBIDDEN:"sandbox_persistence_forbidden",INVALID_PROGRESS_VALUE:"invalid_progress_value_must_be_0_or_100"};var Ea=(e,t)=>{let r=e.getActivity(t);return r!=null&&ye(r)},La=(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 wa(e,t){let{adapter:r}=t,n=e.activityId;if(!r.getActivity(n))return{ok:!1,reason:S.ACTIVITY_NOT_FOUND};let i=e.frozenIds?new Set(e.frozenIds):null,a=i?o=>i.has(o):o=>Ea(r,o),s=ba({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:La(e,r,s.changed)}}function pr(e,t){let{adapter:r}=t,n=new Set(e.activityIds.map(String).filter(s=>r.activityExists(s)).filter(s=>!Ea(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:La(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 Oa(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 Uu=["Waiting","Done","Doing","Overdue","Advancement"],ju=["mfo","mso","snlt","snet","alap","asap","fnet","fnlt"];function Un(e,t){return e===null||t<=0?null:e/t}function Hu(e,t){let r=Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()),n=Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate());return Math.floor((n-r)/864e5)+1}var Vu={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=>{let t=Number(e.uniqueCorrelativeId);return Number.isFinite(t)?t:null}},progress:{valueKind:"number",extract:e=>e.progress},durationDays:{valueKind:"number",extract:(e,t)=>Un(e.durationHours,t.hoursPerDay)},calendarDuration:{valueKind:"number",extract:e=>e.type==="milestone"?0:Hu(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)=>Un(e.freeSlackHours,t.hoursPerDay)},totalSlackDays:{valueKind:"number",extract:(e,t)=>Un(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:Uu,extract:e=>e.status},constraintType:{valueKind:"enum",order:ju,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 Wt(e){return Vu[e]??null}function Yu(e){return e instanceof Date?e:typeof e=="string"||typeof e=="number"?new Date(e):new Date(Number.NaN)}function Ku(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 Gu(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 $u(e,t,r){return e instanceof Date?r==="after"?e.getTime()>t.getTime():r==="before"?e.getTime()<t.getTime():!1:!1}function zu(e,t,r){let i=(Array.isArray(e)?e:[]).some(a=>t.has(String(a)));return r==="someOf"?i:r==="notSomeOf"?!i:!1}function qu(e,t,r){let n=e!==null&&t.has(String(e));return r==="someOf"?n:r==="notSomeOf"?!n:!1}function xa(e){let t=Array.isArray(e)?e:[e];return new Set(t.map(r=>String(r)))}function Fa(e,t,r){let n=Wt(t.field);if(n===null)return!1;let i=n.extract(e,r),{operator:a}=t;return n.valueKind==="string"?Ku(i,String(t.value),a):n.valueKind==="number"?Gu(i,Number(t.value),a):n.valueKind==="date"?$u(i,Yu(t.value),a):n.valueKind==="id-array"?zu(i,xa(t.value),a):qu(i,xa(t.value),a)}function Ju(e,t,r){return t.criteria.length===0?!0:t.logic==="or"?t.criteria.some(n=>Fa(e,n,r)):t.criteria.every(n=>Fa(e,n,r))}function Xu(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 jn(e,t,r){let n=Ju(e,t,r),i=t.dateRange,a=i===void 0||Xu(e,i);return n&&a}function Zu(e,t,r){let n=t(e);for(;n!==null&&!r.has(String(n));)r.add(String(n)),n=t(n)}function Na(e){let{activities:t,parentOf:r,filter:n,context:i}=e,a=new Set,s=[];for(let o of t)jn(o,n,i)&&(a.add(String(o.id)),s.push(o.id));for(let o of s)Zu(o,r,a);return a}function Qu(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=jn(d,n,i),h=e.pinnedVisibleIds?.has(u)===!0;o.set(u,(p?1:0)+(h?1:0)),p&&a.add(u),h&&s.add(u)}return{matchedIds:a,pinnedVisibleIds:s,visibleReferenceCounts:o,parentIds:c,remainingChildren:l}}function tf(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 ef(e){let t=new Set;for(let[r,n]of e)n>0&&t.add(r);return t}function hr(e){let t=Qu(e);tf(t);let r=ef(t.visibleReferenceCounts);return{filter:e.filter,context:e.context,matchedIds:t.matchedIds,pinnedVisibleIds:t.pinnedVisibleIds,visibleIds:r,visibleReferenceCounts:t.visibleReferenceCounts}}function Ma(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=jn(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 rf={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 Wa(e){if(e===void 0)return{ok:!0,dateRange:void 0};if(typeof e!="object"||e===null)return{ok:!1,reason:"invalid_value"};let{start:t,end:r}=e;if(!(t instanceof Date)||!(r instanceof Date))return{ok:!1,reason:"invalid_value"};let n=t.getTime(),i=r.getTime();return!Number.isFinite(n)||!Number.isFinite(i)||n>i?{ok:!1,reason:"invalid_value"}:{ok:!0,dateRange:{start:new Date(n),end:new Date(i)}}}function Ba(e){let t=Wt(e.field);if(t===null)return{ok:!1,reason:"unknown_field"};if(!rf[t.valueKind].has(e.operator))return{ok:!1,reason:"unknown_operator"};if(t.valueKind==="number"){let n=af(e.value);return n===null?{ok:!1,reason:"invalid_value"}:{ok:!0,criterion:{...e,value:n}}}if(t.valueKind==="date"){let n=sf(e.value);return n===null?{ok:!1,reason:"invalid_value"}:{ok:!0,criterion:{...e,value:n}}}let r=nf(e,t.valueKind);return r!==null?{ok:!1,reason:r}:t.valueKind==="boolean"?{ok:!0,criterion:{...e,value:[...new Set(e.value)]}}:t.valueKind==="id-array"||t.valueKind==="enum"||t.valueKind==="reference"?{ok:!0,criterion:{...e,value:[...new Set(e.value.map(String))]}}:{ok:!0,criterion:e}}function nf(e,t){let{value:r}=e;return t==="boolean"?Array.isArray(r)&&r.every(n=>typeof n=="boolean")?null:"invalid_value":t==="id-array"||t==="enum"||t==="reference"?Array.isArray(r)&&r.every(n=>typeof n=="string"||typeof n=="number")?null:"invalid_value":Array.isArray(r)?"invalid_value":null}function af(e){if(typeof e=="string"&&e.trim()===""||typeof e!="string"&&typeof e!="number")return null;let t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?t:null}function sf(e){let t;if(e instanceof Date)t=new Date(e.getTime());else if(typeof e=="string")t=new Date(e);else if(typeof e=="number")t=new Date(e);else return null;return Number.isFinite(t.getTime())?t:null}function b(e){return structuredClone(e)}function Ua(e){return e.criteria.length===0&&e.dateRange===void 0}function of(e,t,r){let n=e.getAllActivities();if(Ua(t))return{visibleIds:Na({activities:n,parentOf:a=>e.getParentId(a),filter:t,context:Qt(r)}),projection:null};let i=hr({activities:n,parentOf:a=>e.getParentId(a),filter:t,context:Qt(r)});return{visibleIds:i.visibleIds,projection:i}}function ja(e,t){let{adapter:r,hoursPerDay:n}=t,i=[];for(let u of e.criteria){let f=Ba(u);if(!f.ok)return{ok:!1,reason:f.reason};i.push(f.criterion)}let a=Wa(e.dateRange);if(!a.ok)return{ok:!1,reason:a.reason};let s=b(a.dateRange===void 0?{criteria:i,logic:e.logic}:{criteria:i,logic:e.logic,dateRange:a.dateRange});r.setActiveFilter(Ua(s)?null:s);let{visibleIds:o,projection:c}=of(r,s,n);r.setFilterProjection(c);let l=Zt(r,o);return{ok:!0,changes:{source:e,activities:[],links:[],calendars:[],trackingEvents:[],viewState:l}}}var F="0";function L(e){return e==null||e===0||e==="0"}function Bt(e){return L(e)?"0":String(e)}var Hn=Number.MAX_SAFE_INTEGER;function gt(e,t){let r=He(e,t),n=t.getOrderComparator?.()??null;return r.sort(n===null?yr:(i,a)=>n(i,a)||yr(i,a)),r.map(i=>String(i.id))}function Va(e){let t=[],r=i=>{t.push(i);let a=gt(String(i.id),e);for(let s of a){let o=e.getActivity(s);o&&r(o)}},n=gt("0",e);for(let i of n){let a=e.getActivity(i);a&&r(a)}return t}function Ya(e,t,r){let n=r.getActivity(e);if(!n)return null;let i=Ka(n),a=gt(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&&!cf(t,c))return c}return null}function Vn(e,t){let r=t.getActivity(e);if(!r)return-1;let n=Ka(r);return gt(n,t).findIndex(a=>String(a)===String(e))}function He(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 yr(e,t){let r=Ha(e),n=Ha(t);return r!==n?r-n:String(e.id).localeCompare(String(t.id))}function Ha(e){let t=e.correlativeId,r=typeof t=="number"?t:Number(t);return Number.isFinite(r)?r:Hn}function Ka(e){let t=e.parentId;return t===null?"0":t}function cf(e,t){return e.has(t)?!0:e.has(String(t))}function me(e){let t=[],r=n=>{let i=gt(n,e);i.length>1&&t.push({parentId:n,childIds:i});for(let a of i)r(a)};return r("0"),t}function Yn(e,t){let r=[];for(let n of t){let i=gt(n,e);i.length>1&&r.push({parentId:n,childIds:i})}return r}function lf(e){return Wt(e.field)===null?"unknown_field":e.direction!=="asc"&&e.direction!=="desc"?"unknown_operator":null}function Ga(e,t){let{adapter:r}=t;for(let a of e.rules){let s=lf(a);if(s!==null)return{ok:!1,reason:s}}let n=e.rules.length===0?null:b({rules:e.rules});return r.setActiveOrder(n),{ok:!0,changes:{source:e,activities:[],links:[],calendars:[],trackingEvents:[],order:me(r)}}}var $a="text";var za="description";var qa="duration";var Ja="progress";var Xa="cost";var Za="used_cost";var Qa="hhWorkTime";var ts="start_date";var es="end_date";var rs="constraint_type";var ns="constraint_date";var is="calendar_id";var as="custom_id";var ss="subcontractId";var os="responsables";var cs="tags";var ls="custom_predecessors";var ds="custom_sucessors";var us="real_work";var fs="real_cost";var ps="expected_progress";var hs="expected_progress_base";var ys="start_base";var ms="end_base";var gs="duration_base";var vs="cost_base";var As="work_base";var Cs="calendarDuration";var Is="is_critical",Ss="earlyStart",ks="earlyFinish",Ds="lateStart",Ts="lateFinish",_s="freeSlack",Ps="totalSlack";var Rs="correlative_id";var bs="unique_correlative_id";var Es="ponderator";var X={FUTURE:"future",PAST:"past"},ot={HOUR:"hour",DAY:"day"},Rt={DONE:"Done",OVERDUE:"Overdue",ADVANCEMENT:"Advancement",WAITING:"Waiting",DOING:"Doing"};var mr="status";var Kn="Baseline";function gr(e){return e==="Actual"?"Actual":Kn}var df={TEXT:$a,DESCRIPTION:za,DURATION:qa,PROGRESS:Ja,COST:Xa,USED_COST:Za,HH_WORK_TIME:Qa,START_DATE:ts,END_DATE:es,CONSTRAINT_TYPE:rs,CONSTRAINT_DATE:ns,CALENDAR_ID:is,CUSTOM_ID:as,SUBCONTRACT_ID:ss,RESPONSABLES:os,TAGS:cs,CUSTOM_PREDECESSORS:ls,CUSTOM_SUCESSORS:ds},uf={REAL_WORK:us,REAL_COST:fs,EXPECTED_PROGRESS:ps,EXPECTED_PROGRESS_BASE:hs,START_BASE:ys,END_BASE:ms,DURATION_BASE:gs,COST_BASE:vs,WORK_BASE:As,CALENDAR_DURATION:Cs,IS_CRITICAL:Is,EARLY_START:Ss,EARLY_FINISH:ks,LATE_START:Ds,LATE_FINISH:Ts,FREE_SLACK:_s,TOTAL_SLACK:Ps,CORRELATIVE_ID:Rs,UNIQUE_CORRELATIVE_ID:bs,PONDERATOR:Es,STATUS:mr},_={...df,...uf};function Ls(e,t){throw new Error(t)}function ws(e,t){return()=>t()===e}var K={ASAP:"asap",ALAP:"alap",SNET:"snet",SNLT:"snlt",FNET:"fnet",FNLT:"fnlt",MSO:"mso",MFO:"mfo"},ff={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 xs(e,t,r){if(!t)return{violated:!1};let n=ff[e];return n?n(t,r)?{violated:!0,constraintType:e,constraintDate:t}:{violated:!1}:{violated:!1}}var pf=new Set(["mso","snet","snlt"]);function Ve(e,t,r){return pf.has(e)?t:r}function Fs(e,t,r){return{type:"constraint",messageKey:"constraint_violation",data:{constraintType:e,constraintDate:t,...r?{projectedDate:r}:{}}}}var hf={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}},vr=e=>new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate())),Os=(e,t)=>new Date(e.getTime()+t*864e5),yf=(e,t)=>e.getUTCFullYear()===t.getUTCFullYear()&&e.getUTCMonth()===t.getUTCMonth()&&e.getUTCDate()===t.getUTCDate();function Gn(e,t){if(!e.constraintDate||!e.constraintType)return null;let r=hf[e.constraintType];if(!r)return e.constraintDate;let n=e.constraintDate,i=t.getClosestWorkTime({date:vr(n),dir:X.FUTURE,task:e});if(yf(i,n))return n.getTime()!==vr(n).getTime()?n:r.startOfDay?i:t.getClosestWorkTime({date:Os(vr(n),1),dir:X.PAST,task:e});let a=vr(t.getClosestWorkTime({date:n,dir:r.direction,task:e}));return r.startOfDay?t.getClosestWorkTime({date:a,dir:X.FUTURE,task:e}):t.getClosestWorkTime({date:Os(a,1),dir:X.PAST,task:e})}function Ns(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=Gn(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 Ms(e,t){return!(t.earliestStart&&e<t.earliestStart||t.latestStart&&e>t.latestStart)}function $n(e,t){return t.latestStart&&e>t.latestStart?t.latestStart:t.earliestStart&&e<t.earliestStart?t.earliestStart:e}var W={FINISH_TO_START:"0",START_TO_START:"1",FINISH_TO_FINISH:"2",START_TO_FINISH:"3"};var Ar={TASK:"task",PROJECT:"project",MILESTONE:"milestone"},Ws={ALAP_DEBOUNCE_MS:1e3,CRITICAL_PATH_DEBOUNCE_MS:1e3,YIELD_SLICE_MS:8};var zn=typeof window>"u",mf=!zn&&typeof MessageChannel<"u";function Z(){return mf?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 Cr(e,t){return performance.now()-e<Ws.YIELD_SLICE_MS?{aborted:!1,newSliceStart:e}:(await Z(),t()?{aborted:!1,newSliceStart:performance.now()}:{aborted:!0,newSliceStart:performance.now()})}async function ge(e){return zn||await Z(),e()?{aborted:!1}:{aborted:!0}}function Ir(e,t){let{inDegree:r,successors:n}=gf(e,t),i=vf(r),a=Af(i,r,n),s=a.length<e.length,o=s?Cf(e,a):[],c=[...a].reverse();return{ordered:a,reversed:c,hasCycles:s,cycleNodes:o}}function gf(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 vf(e){let t=new ht;for(let[r,n]of e)n===0&&t.enqueue(r);return t}function Af(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 Cf(e,t){let r=new Set(t);return e.filter(n=>!r.has(n))}var Sr=class{cached=null;invalidate(){this.cached=null}get(t,r){return this.cached?this.cached:(this.cached=Ir(t,r),this.cached)}};function Bs(e,t){let r=[];for(let n of e)t.has(n)&&r.push(n);return r}var qn={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 Jn(e){return e==="project"||e==="task"||e==="milestone"}function Lt(e,t){return t||Jn(e)&&qn[e].alwaysSummary}function wt(e){return e==="milestone"}function Ut(e){return Jn(e)&&qn[e].promotesToProjectOnFirstChild}var Xn="project",ve="task";function Ye(e,t){return t===0?"milestone":e===0&&t>0?"task":null}function kr(e,t){let r=t.getActivity(e);return r?Lt(r.type,t.getChildren(e).length>0):!1}function Dr(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 Zn(e,t,r){let n=kr(e,r);return kr(t,r)&&Dr(e,t,r)||n&&Dr(t,e,r)}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 If(e){let t=new Map;for(let r of e)Us(t,String(r.source),r),Us(t,String(r.target),r);return t}function Us(e,t,r){let n=e.get(t);if(n){n.push(r);return}e.set(t,[r])}function Sf(e,t,r,n){if(e.length<=1)return e;let i=new Set(e.map(String)),a=[];for(let s of e)kf(s,i,t,r,n)||a.push(s);return a.length>0?a:e}function kf(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(Df(c,a,s,t,r,i))return!0;return!1}function Df(e,t,r,n,i,a){if(Tf(e)||!(a?String(e.source)===t:String(e.target)===t))return!1;let o=_f(e,t);if(!n.has(String(o)))return!1;let c=i.getActivity(o);return!!(c?.autoScheduling!==!1&&c&&Pf(e,r,c))}function Tf(e){return e.source===e.target}function _f(e,t){return String(e.source)===t?e.target:e.source}function Pf(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 _r(e,t){let r=[],n=If(e),i=0;for(let a of e){let s=kr(a.source,t),o=kr(a.target,t);if(Rf(a,s,o,t))continue;if(!s&&!o){r.push(a);continue}let c=js(a.source,s,t,n,!0),l=js(a.target,o,t,n,!1);i=Ff(r,c,l,a,t,i,n)}return r}function Rf(e,t,r,n){return r&&Dr(e.source,e.target,n)||t&&Dr(e.target,e.source,n)}function js(e,t,r,n,i){return t?Sf(Hs(e,r),r,n,i):[e]}function bf(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 Tr(e,t){return bf(e,t,r=>{let n=t.getActivity(r);return n?{startDate:n.startDate,endDate:n.endDate}:null})}function Ef(e,t,r){return e?t?r.calculateDuration({startDate:t.startDate,endDate:t.endDate,task:e}):e.durationHours:0}function Lf(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 wf(e,t){let r=String(e);return(t.get(r)??[]).some(i=>String(i.target)===r)}function Of(e,t,r,n,i){if(wf(e,i))return 0;let a=n.getActivity(e);return!t||!a||!r?0:n.calculateDuration({startDate:t,endDate:a.startDate,task:r})}function xf(e,t){let r=t.getActivity(e.source),n=t.getActivity(e.target),i=Tr(e.source,t),a=Tr(e.target,t),s=e.type===W.START_TO_START||e.type===W.START_TO_FINISH,o=e.type===W.FINISH_TO_FINISH||e.type===W.START_TO_FINISH;return{source:r,sourceBounds:i,targetStart:a?.startDate??n?.startDate,userLag:e.lag??0,sourceEndpointIsStart:s,targetLag:o?-Ef(n,a,t):0,summarySourceId:e.type===W.START_TO_START&&i?e.source:void 0}}function Ff(e,t,r,n,i,a,s){let o=xf(n,i),{source:c,sourceBounds:l,targetStart:d,userLag:u}=o,{sourceEndpointIsStart:f,targetLag:p,summarySourceId:h}=o,A=a;for(let C of t){let T=f?Lf(C,c,l,i):0;for(let g of r){if(String(C)===String(g))continue;let k=Of(g,d,c,i,s);e.push(Nf(n,C,g,A,T,p,u+k,h,k!==0&&p===0?n.target:void 0)),A+=1}}return A}function Nf(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,freeSlackHours:null,isCritical:!1,_sourceLag:i,_targetLag:a,_trueLag:s,...o===void 0?{}:{_summarySourceId:o},...c===void 0?{}:{_summaryTargetId:c}}}var Pr=class{invalidate(){}get(t,r){return _r(t,r)}};function Mf(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 Wf(e,t,r){let n=new Set,i=new Map,a=new ht;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 Vs(e,t){let r=new Map;for(let s of t)r.set(s.id,s);let n=Mf(t),i=Wf(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 Ys(e,t,r){let n=r.type===W.FINISH_TO_START,i=r.type===W.FINISH_TO_FINISH;if(r._targetLag!==void 0)return{sourceLag:r._sourceLag??0,targetLag:r._targetLag,trueLag:r._trueLag??r.lag??0,isFS:n,isFF:i,isZeroDurationCase:!1};let a=r.lag??0;switch(r.type){case W.FINISH_TO_START:return{sourceLag:0,targetLag:0,trueLag:a,isFS:n,isFF:i,isZeroDurationCase:!1};case W.START_TO_START:return{sourceLag:-e.durationHours,targetLag:0,trueLag:a,isFS:n,isFF:i,isZeroDurationCase:!1};case W.FINISH_TO_FINISH:return{sourceLag:0,targetLag:-t.durationHours,trueLag:a,isFS:n,isFF:i,isZeroDurationCase:!1};case W.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 Bf(e,t,r){if(e._summarySourceId===void 0)return null;let n=r.getActivity(e._summarySourceId);if(!n)return null;let i=Tr(e._summarySourceId,r);return i?-r.calculateDuration({startDate:i.startDate,endDate:t.endDate,task:n}):null}function Uf(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 Ks(e,t,r,n){let{sourceLag:i,targetLag:a,trueLag:s,isFS:o,isFF:c}=Ys(e,t,r),l=Bf(r,e,n)??i,d=l+a+s;if(!(t.durationHours===0?d!==0:l!==0||a!==0||s!==0))return Uf(e,t,r,n,o||c);let p=o?t:e,h=n.getClosestWorkTime({date:e.endDate,dir:"future",task:p});if(l!==0&&(h=n.calculateEndDate({startDate:h,durationHours:l,task:e})),a!==0&&(h=n.calculateEndDate({startDate:h,durationHours:a,task:t})),s!==0&&(h=n.calculateEndDate({startDate:h,durationHours:s,task:t})),t.durationHours===0){if(o||c)return{successorStart:n.getClosestWorkTime({date:h,dir:"past",task:t}),link:r};let A=new Date(Date.UTC(h.getUTCFullYear(),h.getUTCMonth(),h.getUTCDate()));return{successorStart:n.getClosestWorkTime({date:A,dir:"future",task:t}),link:r}}return{successorStart:n.getClosestWorkTime({date:h,dir:"future",task:t}),link:r}}function Gs(e,t,r,n){let{sourceLag:i,targetLag:a,trueLag:s}=Ys(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 $s(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=Ns(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 Rr(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=$n(e.startDate,n):Ms(i,n)?a=i:a=$n(i,n),t.startDate=a,t.endDate=r.calculateEndDate({startDate:a,durationHours:e.durationHours,task:e})}function zs(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 jf(e,t){return t.length?t.some(r=>String(r)===String(e)):!1}function qs(e,t,r){return Qn(e.id,t,r)?{startDate:e.startDate,endDate:e.endDate}:{startDate:e.startDate,endDate:e.endDate}}function Qn(e,t,r){return t.dragWithMultiple&&jf(e,r)}async function Xs(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 Cr(d,i);if(f.aborted)return a;d=f.newSliceStart;let p=r.getActivity(u);if(!p||!p.autoScheduling||p.progress===100||Hf(p,r))continue;let h=s.get(String(u))??[],A=null,C=null,T=!1;for(let w of h){let v=r.getActivity(w.source);if(!v)continue;let I=o(w.source),R=I.startDate.getTime()!==v.startDate.getTime()||I.endDate.getTime()!==v.endDate.getTime(),N={...v,startDate:I.startDate,endDate:I.endDate},x=qs(N,c,l),z={...N,startDate:x.startDate,endDate:x.endDate},Q=Qn(w.source,c,l)?{...w,lag:0}:w,lt=Ks(z,p,Q,r);(!A||lt.successorStart>A)&&(A=lt.successorStart,C=String(w.id),T=w._summaryTargetId!==void 0&&!R)}A!==null&&T&&A<p.startDate&&(A=new Date(p.startDate));let k=a.get(u),m=k?{...k}:{activityId:u,startDate:p.startDate,endDate:p.endDate,drivingLinkId:null,kind:"asap",conflict:!1},P=m.earliestStart||m.latestStart||m.earliestEnd||m.latestEnd;if(!(!A&&!P)){if(A){let w=A;p.type===Ar.MILESTONE&&(w=zs(p,A)),m.drivingLinkId=C,m.startDate=w,m.endDate=r.calculateEndDate({startDate:w,durationHours:p.durationHours,task:p}),m.earliestSchedulingStart=w,m.earliestSchedulingEnd=m.endDate}else p.constraintType===K.MSO?m.earliestStart&&(m.startDate=m.earliestStart,m.endDate=m.earliestEnd??r.calculateEndDate({startDate:m.earliestStart,durationHours:p.durationHours,task:p})):p.constraintType===K.MFO&&m.latestStart&&(m.startDate=m.latestStart,m.endDate=m.latestEnd??r.calculateEndDate({startDate:m.latestStart,durationHours:p.durationHours,task:p}));Rr(p,m,r),a.set(u,m)}}return a}function Hf(e,t){return Lt(e.type,t.getChildren(e.id).length>0)}async function Zs(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 T=String(C.source);d.has(T)||d.set(T,[]),d.get(T).push(C);let g=String(C.target);u.has(g)||u.set(g,[]),u.get(g).push(C)}let f=C=>{let T=s.get(C);if(T)return{startDate:T.startDate,endDate:T.endDate};let g=n.getActivity(C);return g?{startDate:g.startDate,endDate:g.endDate}:{startDate:new Date,endDate:new Date}},p=C=>!C.parentId||L(C.parentId)?n.getProjectEnd():f(C.parentId).endDate,h=(C,T)=>{let g=C,k=0;for(;g&&!L(g)&&k++<c+1;){if(String(g)===String(T))return!0;let m=n.getActivity(g);if(!m||!m.parentId)break;g=m.parentId}return!1},A=performance.now();for(let C of e){let T=await Cr(A,a);if(T.aborted)return s;A=T.newSliceStart;let g=n.getActivity(C);if(!g||g.constraintType!==K.ALAP||!g.autoScheduling||g.progress===100||Lt(g.type,n.getChildren(C).length>0))continue;let k=p(g);if(!k)continue;let m=k,P=null,w=!1,v=d.get(String(C))??[];for(let kt of v){if((kt.lag??0)<0)continue;let he=n.getActivity(kt.target);if(!he||he.autoScheduling===!1)continue;let Ra=f(kt.target),Eu={...he,startDate:Ra.startDate,endDate:Ra.endDate},ur=Gs(Eu,g,kt,n);ur<m&&(m=ur),(P===null||ur<P)&&(P=ur,w=g.parentId&&!L(g.parentId)?h(kt.target,g.parentId):!1)}if(P!==null)if(w)m=P;else{let kt=f(C).endDate,he=kt.getTime()>k.getTime()?kt:k;m=P<he?P:he}else m>k&&(m=k);let R=(u.get(String(C))??[]).some(kt=>kt.type===W.FINISH_TO_START||kt.type===W.FINISH_TO_FINISH),N=new Date(Date.UTC(m.getUTCFullYear(),m.getUTCMonth(),m.getUTCDate())),x=()=>n.getClosestWorkTime({date:N,dir:"past",task:g}),z=n.getClosestWorkTime({date:m,dir:"future",task:g}).getTime()===m.getTime(),Q;g.durationHours===0&&P===null?Q=R&&z?x():n.getClosestWorkTime({date:m,dir:"past",task:g}):g.durationHours===0?R?Q=x():Q=n.getClosestWorkTime({date:m,dir:"future",task:g}):Q=n.getClosestWorkTime({date:m,dir:"future",task:g});let lt=n.calculateEndDate({startDate:Q,durationHours:-g.durationHours,task:g}),pt=s.get(C),nt=pt?{...pt}:{activityId:C,startDate:lt,endDate:Q,drivingLinkId:null,kind:"alap",conflict:!1};nt.startDate=lt,nt.endDate=Q,nt.drivingLinkId=null,nt.kind="alap";let fe=nt.earliestSchedulingStart??null;nt.earliestSchedulingStart=null,nt.earliestSchedulingEnd=null;let pe=fe!==null&&fe.getTime()>lt.getTime()?fe:lt;nt.latestSchedulingStart=pe,nt.latestSchedulingEnd=pe===lt?Q:n.calculateEndDate({startDate:pe,durationHours:g.durationHours,task:g}),Rr(g,nt,n),s.set(C,nt)}return s}var Ae={warn(){},error(){}};function bt(e){if(e.type==="milestone")return 0;let t=e.startDate?.getTime(),r=e.endDate?.getTime();return t==null||r==null||Number.isNaN(t)||Number.isNaN(r)?null:Math.floor((r-t)/864e5)+1}function Ke(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,i.calendarDuration=bt(i),e.updateActivity(r))}})}function ti(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 Vf(i,n,r)}function Ge(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 ht;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 Vf(e,t,r){if(t===r)return!0;let n=new Set([t]),i=new ht;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 br(e){let t=Yf(e);for(let r of t.adjacency.keys())t.records.has(r)||Kf(r,t);return t.components}function Yf(e){let t=new Map,r=new Set;for(let n of e){let i=String(n.source),a=String(n.target),s=Qs(t,i);if(Qs(t,a),i===a){r.add(i);continue}s.push(a)}return{adjacency:t,selfLooped:r,records:new Map,componentStack:[],nextIndex:0,components:[]}}function Qs(e,t){let r=e.get(t);if(r)return r;let n=[];return e.set(t,n),n}function Kf(e,t){let r=[];for(r.push({node:e,record:to(e,t),neighborCursor:0});r.length>0;){let n=r[r.length-1];if(n===void 0)break;let i=t.adjacency.get(n.node)??[];if(n.neighborCursor<i.length){let o=i[n.neighborCursor];if(n.neighborCursor+=1,o===void 0)continue;Gf(n,o,r,t);continue}r.pop();let a=r[r.length-1];a&&n.record.lowLink<a.record.lowLink&&(a.record.lowLink=n.record.lowLink),n.record.lowLink===n.record.visitIndex&&$f(n.node,t)}}function Gf(e,t,r,n){let i=n.records.get(t);if(!i){r.push({node:t,record:to(t,n),neighborCursor:0});return}i.onStack&&i.visitIndex<e.record.lowLink&&(e.record.lowLink=i.visitIndex)}function to(e,t){let r={visitIndex:t.nextIndex,lowLink:t.nextIndex,onStack:!0};return t.nextIndex+=1,t.records.set(e,r),t.componentStack.push({node:e,record:r}),r}function $f(e,t){let r=[];for(;;){let s=t.componentStack.pop();if(s===void 0||(s.record.onStack=!1,r.push(s.node),s.node===e))break}let n=r[0],i=r.length===1&&n!==void 0&&t.selfLooped.has(n);(r.length>1||i)&&t.components.push(r)}function $e(e,t,r){let n=r?new ei(e,r):e;return _r([...t],n)}var ei=class{constructor(t,r){this.base=t;for(let[n,i]of r.reparented){let a=String(n),s=i===null||L(i)?null:i,o=t.getActivity(n)?.parentId??null,c=o===null||L(o)?null:String(o),l=s===null?null:String(s);if(c!==l){if(this.reparented.set(a,s),c!==null){let d=this.movedOutByParent.get(c)??new Set;d.add(a),this.movedOutByParent.set(c,d)}if(l!==null){let d=this.movedInByParent.get(l)??[];d.push(n),this.movedInByParent.set(l,d)}}}}base;reparented=new Map;movedOutByParent=new Map;movedInByParent=new Map;withOverride(t){if(!t)return null;let r=this.reparented.get(String(t.id));return r===void 0?t:{...t,parentId:r}}getActivity(t){return this.withOverride(this.base.getActivity(t))}getLiveActivity(t){return this.withOverride(this.base.getLiveActivity(t))}getAllActivities(){return this.base.getAllActivities().map(t=>this.withOverride(t)??t)}getChildren(t){let r=String(t),n=this.movedOutByParent.get(r),i=this.base.getChildren(t),a=n?i.filter(o=>!n.has(String(o))):[...i],s=this.movedInByParent.get(r);return s&&a.push(...s),a}getParent(t){let r=this.reparented.get(String(t));return r===void 0?this.base.getParent(t):r===null?null:this.getActivity(r)}isChildOf(t,r){let n=String(r),i=new Set,a=this.getActivity(t);for(;a;){let s=a.parentId;if(s===null||L(s))return!1;let o=String(s);if(o===n)return!0;if(i.has(o))return!1;i.add(o),a=this.getActivity(s)}return!1}getAllLinks(){return this.base.getAllLinks()}getAllIds(){return this.base.getAllIds()}getLink(t){return this.base.getLink(t)}activityExists(t){return this.base.activityExists(t)}getOutgoingLinkIds(t){return this.base.getOutgoingLinkIds(t)}getIncomingLinkIds(t){return this.base.getIncomingLinkIds(t)}getClosestWorkTime(t){return this.base.getClosestWorkTime(t)}calculateEndDate(t){return this.base.calculateEndDate(t)}calculateDuration(t){return this.base.calculateDuration(t)}batchUpdate(t){this.base.batchUpdate(t)}updateActivity(t){this.base.updateActivity(t)}getFlags(){return this.base.getFlags()}getProjectEnd(){return this.base.getProjectEnd()}};function ze(e){let{port:t,currentLinks:r,proposedLinks:n,proposal:i}=e,a=$e(t,n,i);if(!Ge(a))return{ok:!0};let s=$e(t,r),o=eo(s),l=[...eo(a)].filter(d=>!o.has(d));return l.length===0?{ok:!0}:{ok:!1,newlyCyclicActivityIds:l}}function eo(e){let t=new Set;for(let r of br(e))for(let n of r)t.add(n);return t}function jt(e,t){switch(e.kind){case"create":return zf(e,t);case"update":return qe(e,t.port);case"delete":return qf(e,t)}}function Lr(e,t){if(e.length===0)return{applied:!0};let r=t.port.getAllLinks(),n=new Map,i=[];for(let l of r){let d=ro(l);n.has(d)||n.set(d,l.id),i.push({source:l.source,target:l.target})}let a=Ge(i),s=null;for(let{operation:l,linkId:d}of e){if(String(l.source)===String(l.target)){s={applied:!1,rejected:"self-link"};break}if(!t.port.getActivity(l.source)||!t.port.getActivity(l.target)){s={applied:!1,rejected:"activity-missing"};break}if(Zn(l.source,l.target,t.port)){s={applied:!1,rejected:"hierarchy-link"};break}let u=ro(l),f=n.get(u);if(f!==void 0){s={applied:!1,rejected:"duplicate",linkId:f};break}if(n.set(u,d),a&&ti(i,{source:l.source,target:l.target}))return{applied:!1,rejected:"cycle"};i.push({source:l.source,target:l.target})}if(!a&&Ge(i))return{applied:!1,rejected:"cycle"};if(s)return s;let o=[...r,...e.map(({operation:l,linkId:d})=>({id:d,source:l.source,target:l.target,type:l.type,lag:l.lag,freeSlackHours:null,isCritical:!1}))];if(!ze({port:t.port,currentLinks:r,proposedLinks:o}).ok)return{applied:!1,rejected:"cycle"};for(let{operation:l,linkId:d}of e){let u=t.preserved?.get(d);t.port.addLink({id:d,source:l.source,target:l.target,type:l.type,lag:l.lag,freeSlackHours:null,isCritical:!1,...u?.ganttId===void 0?{}:{ganttId:u.ganttId},...u?.sectorId===void 0?{}:{sectorId:u.sectorId},...u?.proplannerId===void 0?{}:{proplannerId:u.proplannerId}})}return{applied:!0}}function ro(e){return JSON.stringify([String(e.source),String(e.target),e.type])}function zf(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"};if(Zn(e.source,e.target,r))return{applied:!1,rejected:"hierarchy-link"};let a=r.getAllLinks();for(let d of a)if(String(d.source)===String(e.source)&&String(d.target)===String(e.target)&&d.type===e.type)return{applied:!1,rejected:"duplicate",linkId:d.id};let s=a.map(d=>({source:d.source,target:d.target}));if(ti(s,{source:e.source,target:e.target}))return{applied:!1,rejected:"cycle"};let o=(t.newLinkId??Jf)(),c={id:o,source:e.source,target:e.target,type:e.type,lag:e.lag,freeSlackHours:null,isCritical:!1};return ze({port:r,currentLinks:a,proposedLinks:[...a,c]}).ok?(r.addLink(c),{applied:!0,linkId:o}):{applied:!1,rejected:"cycle"}}function qe(e,t){return t.getLink(e.linkId)?(e.lag!==void 0&&t.setLinkField(e.linkId,"lag",e.lag),e.type!==void 0&&t.setLinkField(e.linkId,"type",e.type),{applied:!0,linkId:e.linkId}):{applied:!1,rejected:"link-missing"}}function qf(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 Er=null;function Jf(){return Er===null&&(Er=Date.now()),Er+=1,String(Er)}var no={[W.FINISH_TO_START]:"fs",[W.START_TO_START]:"ss",[W.FINISH_TO_FINISH]:"ff",[W.START_TO_FINISH]:"sf"},te={fs:W.FINISH_TO_START,ss:W.START_TO_START,ff:W.FINISH_TO_FINISH,sf:W.START_TO_FINISH},io="fs";function ao(e){if(e in te)return te[e]}var so=";",oo=/^(\d+)(fs|ss|ff|sf)?(?:([+-]?)(\d+(?:\.\d+)?)d?)?$/i;function wr(e){let t=[],r=[],n=e.replace(/\s+/g,"");if(n.length===0)return{specs:t,errors:r};for(let i of n.split(so)){if(i.length===0)continue;let a=Xf(i);a?t.push(a):r.push(i)}return{specs:t,errors:r}}function Xf(e){let t=e.toLowerCase(),r=oo.exec(t);if(!r)return null;let[,n,i,a,s]=r,o=i?te[i]:te[io],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 xr(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=Or(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(Or(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 Or(e,t){return`${String(e)}::${t}`}function Fr(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=Or(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(Or(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 Nr(e){let t=Math.sign(e)*Math.round(Math.abs(e));return Object.is(t,-0)?0:t}function vt(e,t){return Math.sign(e)*Math.round(Math.abs(e)*t)}var co={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 ri(e,t,r){switch(r){case"0":return{sourceDate:e.endDate,targetDate:t.startDate};case"1":return{sourceDate:e.startDate,targetDate:t.startDate};case"2":return{sourceDate:e.endDate,targetDate:t.endDate};case"3":return{sourceDate:e.startDate,targetDate:t.endDate}}}var ni=co;var Ce=class{adapter;reporter;currentCalculationId=0;topoCache=new Sr;expandedLinksCache=new Pr;constructor(t,r=Ae){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=ws(r,()=>this.currentCalculationId),i={plans:new Map,updatedIds:[],cycles:[],cancelled:!1};try{ep(this.adapter);let a=Ht("schedule.total"),s=Ht("schedule.expandParentLinks"),o=this.adapter.getAllLinks(),c=this.expandedLinksCache.get(o,this.adapter);Ot(s);let l=c;if((await ge(n)).aborted)return{...i,cancelled:!0};let d=Ht("schedule.scoping"),u=this.adapter.getAllIds(),f=rp(t,l,this.adapter),p=f.links,h=f.idSet;Ot(d);let A=Ht("schedule.topologicalSort"),C=ip(this.topoCache,u,l,h);if(Ot(A),C.hasCycles)return Ot(a),{...i,cycles:[C.cycleNodes]};if((await ge(n)).aborted)return{...i,cancelled:!0};let T=Ht("schedule.processConstraints"),g=new Map;if($s(C.ordered,this.adapter,g),Ot(T),(await ge(n)).aborted)return{...i,cancelled:!0};let k=Ht("schedule.asapPass"),m=await Xs(C.ordered,p,this.adapter,t,n,g);if(Ot(k),(await ge(n)).aborted)return{...i,cancelled:!0};let P=Ht("schedule.alapPass"),w=await Zs(C.reversed,p,m,this.adapter,t,n);if(Ot(P),(await ge(n)).aborted)return{...i,cancelled:!0};let v=Ht("schedule.diff"),I=[];for(let[R,N]of w){let x=this.adapter.getActivity(R);if(!x)continue;let z=x.startDate.getTime()!==N.startDate.getTime(),Q=x.endDate.getTime()!==N.endDate.getTime();(z||Q)&&I.push(R)}return Ot(v),Ot(a),{plans:w,updatedIds:I,cycles:[],cancelled:!1}}catch(a){return this.reporter.error("[AutoScheduler] Error during scheduling",a),i}}},Qf=!1;function tp(){let e=globalThis.__SCHEDULER_PHASE_LOG__;return typeof e=="boolean"?e:Qf}function Ht(e){return{name:e,startedAt:performance.now()}}function ep(e){let t=e;typeof t.clearCalendarCache=="function"&&t.clearCalendarCache()}function Ot(e){if(!tp())return;let t=performance.now()-e.startedAt;console.log(`[scheduler] ${e.name} ${t.toFixed(1)}ms`)}function rp(e,t,r){let n=e.triggerId;if(n==null)return{idSet:null,links:t};let i=Vs(n,t);return np(i,t,r)}function np(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 ip(e,t,r,n){let i=e.get(t,r);if(i.hasCycles){let s=n?Array.from(n):t;return Ir(s,r)}if(!n)return i;let a=Bs(i.ordered,n);return{ordered:a,reversed:[...a].reverse(),hasCycles:!1,cycleNodes:[]}}function lo(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"||wt(n.type)&&(o.type===W.START_TO_FINISH||o.type===W.FINISH_TO_FINISH))continue;let{sourceDate:d,targetDate:u}=ri(c,i,o.type),f=ni.computeLagBetweenTasks(d,u,a);f!==o.lag&&qe({kind:"update",linkId:o.id,lag:f},t)}}function uo(e,t){let r=t.getActivity(e);r&&wt(r.type)&&(r.durationHours=0)}function Ie(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 Mr(e){return Number(e.toFixed(2))}function dt(e,t){return(Number(e)||0)*(Number(t)||0)/100}async function Se(e,t,r=!0,n={}){let i=t?Je(e,t):dp(e),a=r?n.progressMode??"freeze-when-no-contribution":"skip";await ap(i,e,a,{recomputeRealWork:n.recomputeRealWork??!1})}function Wr(e,t){fo(e,t,"skip")}async function ap(e,t,r,n={recomputeRealWork:!1}){let a=0;for(let s of e)fo(s,t,r,n.recomputeRealWork),a+=1,a%200===0&&await Z()}function Je(e,t){let r=new Set,n=new Map;for(let s of t)sp(s,e,r,n);if(r.size===0)return[];let i=Array.from(r),a=op(i,n);return po(i,a)}function sp(e,t,r,n){let i=t.getParentId(e);for(;i&&!L(i);){if(r.has(i))return;r.add(i);let a=t.getParentId(i);n.set(i,a),i=a}}function op(e,t){let r=new Map;for(let n of e){if(r.has(n))continue;let i=[],a=new Set,s=n;for(;s&&!L(s)&&!r.has(s)&&!a.has(s);)i.push(s),a.add(s),s=t.get(s)??null;let o=s?r.get(s)??0:0;for(let c=i.length-1;c>=0;c-=1)o+=1,r.set(i[c],o)}return r}function cp(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+=lp(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 fo(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=cp(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=Ie(s.weightedChildren);r!=="skip"&&(f!==null||r==="zero-when-no-contribution")&&t.setActivityField(e,"progress",Mr(f??0)),n&&t.setActivityField(e,"realWorkHours",s.realWorkSum)}function lp(e,t){return t?Number(e.realWorkHours)||0:dt(e.workHours,e.progress)}function dp(e){let t=up(e),r=fp(t,e);return po(t,r)}function up(e){let t=new Set;return e.forEachActivity(r=>{r.parentId!==null&&t.add(r.parentId)}),Array.from(t)}function fp(e,t){let r=new Map;for(let n of e)r.set(n,pp(n,t));return r}function pp(e,t){let r=0,n=e;for(;n&&!L(n)&&t.getActivity(n);)r+=1,n=t.getParentId(n);return r}function po(e,t){return[...e].sort((r,n)=>(t.get(n)??0)-(t.get(r)??0))}var ho={updateActivityDuration:uo,updateTaskTiming:yp("updateTaskTiming"),adjustLinkLagOnTaskMove:lo,recordLastStartDate:hp};function hp(e,t){let r=t.getActivity(e);r&&t.setLastStartDate(e,r.startDate)}function Vt(e,t,r,n){for(let i of t){let a=i in ho?ho[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 yp(e){return()=>{console.debug(`[replay post-processors] ${e}: not yet ported to adapter \u2014 no-op.`)}}function O(e,t){return t!==void 0?{ok:!0,value:e,raw:t}:{ok:!0,value:e}}function M(e){return{ok:!1,reason:e}}function j(){return{valid:!0}}function tt(e,t){return t!==void 0?{valid:!1,reason:e,notification:t}:{valid:!1,reason:e}}function H(){return{allowed:!0}}function q(e,t){return t!==void 0?{allowed:!1,reason:e,alertKey:t}:{allowed:!1,reason:e}}function U(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 yo={targetField:"name",canEdit(){return H()},parseInput(e){return typeof e!="string"?M("not_a_string"):O(e)},validate(){return j()},transform(e,t){return U({name:t},{autoSchedule:!1,postProcessors:[]})},trackEvent:"activity_name_entry"};var mo={targetField:"description",canEdit(){return H()},parseInput(e){return typeof e!="string"?M("not_a_string"):O(e.trim())},validate(){return j()},transform(e,t){return U({description:t},{autoSchedule:!1,postProcessors:[]})},trackEvent:"activity_description_entry"};function Dt(e){return e.constraintType??K.ASAP}var Br=100;function ke(e){return e.progress>=Br}function et(e,t){return Lt(e.type,t.hasChildren(e.id))}function go(e){return e.progress>0}function vo(e){return e.hasLookaheadTasks}function ee(e,t){return Math.round(Math.ceil(e*t*60)/60)}var De=e=>({endDate:e});function Yt(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 jr(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 mp(e,t){let r=Yt(t,"UTC");for(;!e.isWorkTime(r,ot.DAY);)r=new Date(r),r.setUTCDate(r.getUTCDate()+1),r=Yt(r,"UTC");return r}function ii(e,t){return e.getClosestWorkTime({direction:X.FUTURE,date:t,unit:ot.HOUR})}function ai(e,t){let r=mp(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 Ur=new Set(["snet","snlt","mso"]),si=new Set(["fnet","fnlt","mfo"]),Kt=new Set(["asap","alap"]),Hr="snet";function xt(e,t,r){let n=Yt(e,"UTC");if(!Ur.has(r)&&!si.has(r))return n;let i=Ur.has(r)?ii(t,n):ai(t,n),a=new Date(n);return a.setUTCHours(i.getUTCHours(),i.getUTCMinutes(),i.getUTCSeconds(),i.getUTCMilliseconds()),a}var Gt=()=>({constraintType:Hr});var re=e=>({constraintDate:e}),Ao=e=>({constraintDate:e});var Co={UPDATE_TASK_TIMING:"updateTaskTiming",ADJUST_LINK_LAG_ON_TASK_MOVE:"adjustLinkLagOnTaskMove",RECORD_LAST_START_DATE:"recordLastStartDate"};var Io={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 Te(e,t,r){return xs(e,t,r)}function _e(e,t,r){return Fs(e,t,r)}var ko={targetField:"durationHours",canEdit(e,t){return ke(e)?q("completed","cant_edit_completed_activity"):et(e,t)?q("summary","summary_column_value"):H()},parseInput(e,t,r){let n=parseFloat(String(e));return Number.isFinite(n)?O(ee(n,r.hoursPerDay)):M("not_a_number")},validate(e,t,r){return So(r)?tt(Io.NEGATIVE_DURATION):gp(t,r)?tt("unchanged"):j()},transform(e,t,r){if(So(t))return U({},{autoSchedule:!1,postProcessors:[]});let n=vp(e,t,r),i=Ap(e,t,r,n.violated);return{...U(i,{autoSchedule:!0,postProcessors:[Co.RECORD_LAST_START_DATE]}),...n.violated?{constraintWarning:_e(n.constraintType,n.constraintDate,Do(e,t,r)??void 0)}:{}}},trackEvent:"activity_duration_entry"};function So(e){return Math.sign(e)===-1}function gp(e,t){return e===t}function vp(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 Te(i,e.constraintDate,a)}function Ap(e,t,r,n=!1){let i={};n&&Object.assign(i,Gt(),re(e.startDate));let a=Ye(e.durationHours,t);a&&(i.type=a),i.durationHours=t;let s=Do(e,t,r);return s&&Object.assign(i,De(s)),i}function Do(e,t,r){let n=r.calendars.getCalendar(e.calendarId);return n?n.calculateEndDate(e.startDate,t):null}var Pe=e=>({realWorkHours:e});var Cp=0,Ip=Br,To=0,_o={targetField:"progress",canEdit(e,t){return vo(e)?q("has_lookahead_tasks","cant_edit_actvity_with_task"):et(e,t)?q("summary","summary_column_value"):H()},parseInput(e){let t=parseFloat(String(e));return Number.isNaN(t)?M("not_a_number"):O(t)},validate(e,t,r){return Sp(r)?tt("out_of_range"):j()},transform(e,t,r){let n=kp(t),i=Dp(t),a=Pp(e,t,r.hierarchy),s={progress:t,autoScheduling:n,...Pe(a.get(e.id)??0)},o=i?Tp(e,t,n,r.hierarchy,a):[],c=i?bp(e,t,r.hierarchy):[],l=o.length+c.length>0?[...o,...c]:void 0,d=[],u=i?Lp(e,t):void 0;return U(s,{autoSchedule:!1,postProcessors:d,cascadeMutations:l,trackingEvents:u})},trackEvent:"activity_progress_entry"};function Sp(e){return e<Cp||e>Ip}function kp(e){return e===To}function Dp(e){return e===Br||e===To}function Tp(e,t,r,n,i){return n.getDescendantIds(e.id).map(s=>({activityId:s,fields:_p(t,r,i.get(s)??0)}))}function _p(e,t,r){return{progress:e,autoScheduling:t,...Pe(r)}}function Pp(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):dt(c.workHours,t);n.set(c.id,l),o+=l}return o},a=r.hasChildren(e.id)?i(e.id):dt(e.workHours,t);return n.set(e.id,a),n}function Rp(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 bp(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=[...Rp(e,r),...r.getAncestorIds(e.id)],a=[];for(let s of i){let o=Ep(s,n,r);n.set(s,o),a.push({activityId:s,fields:{progress:o}})}return a}function Ep(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((Ie(n)??0).toFixed(2))}function Lp(e,t){return[{name:"activity_progress_update_radio_button",properties:{activity_id:e.id,activity_name:e.name,progress_updated:t}}]}var Po={targetField:"cost",canEdit(e,t){return et(e,t)?q("summary","summary_column_value"):H()},parseInput(e,t){if(String(e).trim()==="")return O(t.cost);let r=parseFloat(String(e));return Number.isNaN(r)?M("not_a_number"):O(r)},validate(){return j()},transform(e,t,r){let n=wp(e,t,r.hierarchy);return U({cost:t},{autoSchedule:!1,postProcessors:[],cascadeMutations:n})},trackEvent:"activity_cost_budgeted_entry"};function wp(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 Ro={targetField:"usedCost",canEdit(e,t){return et(e,t)?q("summary","summary_column_value"):H()},parseInput(e,t){if(String(e).trim()==="")return O(t.usedCost);let r=parseFloat(String(e));return Number.isNaN(r)?M("not_a_number"):O(r)},validate(){return j()},transform(e,t,r){let n=Op(e,t,r.hierarchy);return U({usedCost:t},{autoSchedule:!1,postProcessors:[],cascadeMutations:n})},trackEvent:"activity_cost_spent_entry"};function Op(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 bo={targetField:"workHours",canEdit(e,t){return et(e,t)?q("summary","summary_column_value"):H()},parseInput(e){if(String(e).trim()==="")return O(0,e);let t=parseFloat(String(e));return Number.isNaN(t)?M("not_a_number"):O(t)},validate(){return j()},transform(e,t,r,n){let i=Eo(t,e.progress),a=String(n).trim()===""?[]:xp(e,t,i,r.hierarchy);return U({workHours:t,...Pe(i)},{autoSchedule:!1,postProcessors:[],cascadeMutations:a})},trackEvent:"activity_labor_hours_budgeted_entry"};function Eo(e,t){return dt(e,t)}function xp(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??Eo(d.workHours,d.progress);c+=u,l+=f}i.set(o,c),a.set(o,l),s.push({activityId:o,fields:{workHours:c,...Pe(l)}})}return s}function Vr(e,t){return e.getUTCFullYear()===t.getUTCFullYear()&&e.getUTCMonth()===t.getUTCMonth()&&e.getUTCDate()===t.getUTCDate()}function oi(e,t){return e.getTime()<t.getTime()}function Re(e){return e instanceof Date&&!Number.isNaN(e.getTime())}var Yr=e=>({durationHours:e});var Lo={targetField:"startDate",canEdit(e,t){return et(e,t)?q("summary","summary_column_value"):go(e)?q("has_progress","cant_edit_activity_with_progress"):H()},parseInput(e,t,r){return Re(e)?O(Yt(e,"UTC")):M("invalid_date")},validate(e,t,r,n){if(Vr(t,r))return tt("unchanged");let i=Fp(e,r,n);return i||j()},transform(e,t,r){let n=r.calendars.getCalendar(e.calendarId);if(!n)throw new Error("startDatePipeline: no calendar resolved (integrity)");let i=ii(n,t),a=e.type==="milestone",s=a?i:n.calculateEndDate(i,e.durationHours),o=i;return{...U({startDate:i,...De(s),...a?Yr(0):{},...Gt(),...re(o)},{autoSchedule:!0,postProcessors:["adjustLinkLagOnTaskMove"]}),constraintWarning:Np(e,i,n)}},trackEvent:"activity_start_date_entry"};function Fp(e,t,r){let n=r.hierarchy.getParentStartDateIfHasPredecessors(e.id);if(!n)return null;let i=Yt(n,"UTC");return t.getTime()<i.getTime()?tt("before_parent_start"):null}function Np(e,t,r){let n=r.calculateEndDate(t,e.durationHours),i=Ve(Dt(e),t,n),a=Te(Dt(e),e.constraintDate,i);if(a.violated)return _e(a.constraintType,a.constraintDate,i)}var Mp=99.999,Oo={targetField:"endDate",canEdit(e,t){return et(e,t)?q("summary","summary_column_value"):Wp(e)?q("completed","cant_edit_completed_activity"):H()},parseInput(e,t,r){if(!Re(e))return M("invalid_date");let n=Yt(e,"UTC"),i=r.calendars.getCalendar(t.calendarId);return i?i.isWorkTime(n,ot.DAY)?O(ai(i,n)):O(i.getClosestWorkTime({direction:"past",date:n,unit:ot.HOUR})):O(n)},validate(e,t,r,n){if(Vr(e.endDate,r))return tt("unchanged");if(Bp(r,e))return tt("before_date_origin");if(Up(r,e))return tt("before_start_date");let i=jp(r,e,n);return i||j()},transform(e,t,r){let n=Hp(e,t),i=Vp(e,t,r,!!n);return{...U(i,{autoSchedule:!0,postProcessors:["updateTaskTiming"]}),...n?{constraintWarning:n}:{}}},trackEvent:"activity_end_date_entry"};function Wp(e){return e.progress>=Mp}function Bp(e,t){return t.dateOrigin?oi(e,t.dateOrigin):!1}function Up(e,t){return oi(e,t.startDate)}function jp(e,t,r){let n=r.calendars.getCalendar(t.calendarId);return n?n.isWorkTime(e,ot.DAY)?null:tt("not_working_day"):null}function Hp(e,t){if(Dt(e)===K.MSO)return;let n=Ve(Dt(e),e.startDate,t),i=Te(Dt(e),e.constraintDate,n);if(i.violated)return _e(i.constraintType,i.constraintDate,n)}function Vp(e,t,r,n=!1){let i={};wt(e.type)&&!n&&wo(e)?Object.assign(i,re(e.startDate)):(n||wo(e))&&Object.assign(i,Gt(),re(e.startDate));let o=Yp(e,t,r),c=Ye(e.durationHours,o);return c&&(i.type=c),Object.assign(i,Yr(o)),i.endDate=t,i}function wo(e){return Kt.has(Dt(e))}function Yp(e,t,r){let n=r.calendars.getCalendar(e.calendarId);return n?n.calculateDuration(e.startDate,t):e.durationHours}var Kp=new Set(Object.values(K)),xo={targetField:"constraintType",canEdit(e,t){return ke(e)?q("completed","cant_edit_completed_activity"):et(e,t)?q("summary","summary_column_value"):H()},parseInput(e){let t=String(e).toLowerCase();return Gp(t)?O(t):M("invalid_constraint_type")},validate(){return j()},transform(e,t,r){let n=$p(e,t,r);return U(n,{autoSchedule:!0})}};function Gp(e){return Kp.has(e)}function $p(e,t,r){let n=qp(e,t);return{constraintType:t,...Ao(zp(e,t,n,r))}}function zp(e,t,r,n){if(e.type!=="milestone"||!r)return r;let i=n.calendars.getCalendar(String(e.calendarId));return i?xt(r,i,t):r}function qp(e,t){return Kt.has(t)?null:Ur.has(t)?e.startDate:si.has(t)?e.endDate:e.constraintDate}var Fo={targetField:"constraintDate",canEdit(e,t){return ke(e)?q("completed","cant_edit_completed_activity"):et(e,t)?q("summary","summary_column_value"):H()},parseInput(e){return Re(e)?O(e):M("invalid_date")},validate(){return j()},transform(e,t,r){let n=No(e)?Hr:Dt(e),i=r.calendars.getCalendar(e.calendarId);if(!i)throw new Error("constraintDatePipeline: no calendar resolved (integrity)");let a=xt(t,i,n),s=Jp(e,a);return U(s,{autoSchedule:!0})}};function Jp(e,t){return{constraintDate:t,...No(e)?Gt():{}}}function No(e){return Kt.has(Dt(e))||!e.constraintType}var Mo={targetField:"calendarId",canEdit(){return H()},parseInput(e){let t=String(e).trim();return Xp(t)?M("empty_calendar"):O(t)},validate(e,t,r,n){return Zp(e.calendarId,r)?tt("unchanged"):n.calendars.getCalendar(r)?j():tt("unknown_calendar")},transform(e,t,r){return U(Qp(e,t,r),{autoSchedule:!0,postProcessors:[]})},trackEvent:"activity_calendar_assignment"};function Xp(e){return e===""}function Zp(e,t){return e===t}function Qp(e,t,r){let n={calendarId:t,assignedDefaultCalendar:!1},i=r.calendars.getCalendar(t);if(i){let a=e.durationHours===0,s=a?th(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,De(i.calculateEndDate(c,e.durationHours)))}return n}function th(e){return new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()))}var Wo={targetField:"customId",canEdit(e,t){return et(e,t)?q("summary","summary_column_value"):H()},parseInput(e){if(e==null)return M("empty_custom_id");if(typeof e!="string")return M("not_a_string");let t=e.trim();return t.length===0?M("empty_custom_id"):t.length>20?M("exceeds_max_length"):O(t)},validate(){return j()},transform(e,t){return U({customId:t},{autoSchedule:!1,postProcessors:[]})},trackEvent:"schedule_custom_id_edition"};var Bo={targetField:"subcontractId",canEdit(){return H()},parseInput(e){if(e==null)return O(null);if(typeof e=="string"){let t=e.trim();if(t.length===0)return O(null);let r=Number(t);return!Number.isFinite(r)||!Number.isInteger(r)?M("not_an_integer"):O(r)}return typeof e=="number"?!Number.isFinite(e)||!Number.isInteger(e)?M("not_an_integer"):O(e):M("not_an_integer")},validate(){return j()},transform(e,t){return U({subcontractId:t},{autoSchedule:!1,postProcessors:[]})}};function Xe(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 Kr(e){return e.some(t=>Xe(t)===null)}var Uo={targetField:"responsableIds",canEdit(){return H()},parseInput(e){return e==null?O([]):Array.isArray(e)?O(e):M("not_an_array")},validate(e,t,r){return Kr(r)?tt("missing_id"):j()},transform(e,t){let r=t.map(Xe).filter(n=>n!==null);return U({responsableIds:r},{autoSchedule:!1,postProcessors:[]})}};var jo={targetField:"tagIds",canEdit(){return H()},parseInput(e){return e==null?O([]):Array.isArray(e)?O(e):M("not_an_array")},validate(e,t,r){return Kr(r)?tt("missing_id"):j()},transform(e,t){let r=t.map(Xe).filter(n=>n!==null);return U({tagIds:r},{autoSchedule:!1,postProcessors:[]})}};var eh=new Map([[_.TEXT,yo],[_.DESCRIPTION,mo],[_.DURATION,ko],[_.PROGRESS,_o],[_.COST,Po],[_.USED_COST,Ro],[_.HH_WORK_TIME,bo],[_.START_DATE,Lo],[_.END_DATE,Oo],[_.CONSTRAINT_TYPE,xo],[_.CONSTRAINT_DATE,Fo],[_.CALENDAR_ID,Mo],[_.CUSTOM_ID,Wo],[_.SUBCONTRACT_ID,Bo],[_.RESPONSABLES,Uo],[_.TAGS,jo]]);function $t(e){return eh.get(e)}function be(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 rh=["name","description","type","startDate","endDate","durationHours","constraintType","constraintDate","calendarId","assignedDefaultCalendar","autoScheduling","progress","cost","usedCost","workHours","realWorkHours","customId","subcontractId","responsableIds","tagIds"],Ho=new Set(rh);var E={ID:"id",PROPLANNER_ID:"proplannerId",PARENT:"parentId",NAME:"name",DESCRIPTION:"description",TYPE:"type",START_DATE:"startDate",END_DATE:"endDate",DURATION_HOURS:"durationHours",CONSTRAINT_TYPE:"constraintType",CONSTRAINT_DATE:"constraintDate",AUTO_SCHEDULING:"autoScheduling",CALENDAR_ID:"calendarId",ASSIGNED_DEFAULT_CALENDAR:"assignedDefaultCalendar",DATE_ORIGIN:"dateOrigin",PROGRESS:"progress",COST:"cost",USED_COST:"usedCost",REAL_COST:"realCost",WORK_HOURS:"workHours",REAL_WORK_HOURS:"realWorkHours",PONDERATOR:"ponderator",HAS_CUSTOM_PONDERATOR:"hasCustomPonderator",CORRELATIVE_ID:"correlativeId",UNIQUE_CORRELATIVE_ID:"uniqueCorrelativeId",CUSTOM_ID:"customId",SUBCONTRACT_ID:"subcontractId",IS_LOOKAHEAD:"isLookahead",HAS_LOOKAHEAD_TASKS:"hasLookaheadTasks",NEW_ACTIVITIES_ARRAY:"newActivityIds",HAS_NEW_ACTIVITIES:"hasNewActivities",IS_NEW_ACTIVITY:"isNewActivity",PENDING_REQUEST_IDS:"pendingRequestIds",RESPONSABLE_IDS:"responsableIds",TAG_IDS:"tagIds",BASELINE_POINTS:"baselinePoints",BASELINE_SNAPSHOT:"baselineSnapshot",SUM_OF_DURATION_RECURSIVELY:"recursiveDurationHours",CALENDAR_DURATION:"calendarDuration",IS_CRITICAL:"isCritical",FREE_SLACK_HOURS:"freeSlackHours",EXPECTED_PROGRESS:"expectedProgress",EXPECTED_PROGRESS_BASELINE:"expectedProgressBaseline",STATUS:"status",CRITICAL_PATH:"criticalPath"},Ze={ID:"id",SOURCE:"source",TARGET:"target",TYPE:"type",LAG:"lag",FREE_SLACK_HOURS:"freeSlackHours",IS_CRITICAL:"isCritical",SOURCE_LAG:"_sourceLag",TARGET_LAG:"_targetLag",TRUE_LAG:"_trueLag",SUMMARY_SOURCE_ID:"_summarySourceId",SUMMARY_TARGET_ID:"_summaryTargetId",GANTT_ID:"ganttId",SECTOR_ID:"sectorId",PROPLANNER_ID:"proplannerId"};function rt(e,t,r,n){e.setActivityFieldDynamic(t,r,n)}function Vo(e,t,r,n){e.setLinkFieldDynamic(t,r,n)}function Ft(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:nh(e.baselineSnapshot),criticalPath:ih(e.criticalPath)}}function Et(e){return e===null?null:new Date(e)}function nh(e){return e===null?null:{...e,startDate:Et(e.startDate),endDate:Et(e.endDate)}}function ih(e){return e===null?null:{...e,earlyStart:Et(e.earlyStart),earlyFinish:Et(e.earlyFinish),lateStart:Et(e.lateStart),lateFinish:Et(e.lateFinish)}}var Go=200;function zt(e,t){let r=new Set([String(e)]);for(let n of t.cascadeMutations??[])r.add(String(n.activityId));return r}async function $(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 Ft(e)}function Gr(e,t){let r=e.getActivity(t);return r?Ft(r):null}function qt(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(!Ho.has(n))throw new Error(`applyFieldChanges: column write to non-writable field "${n}"`);rt(e,t,n,i)}}async function $r(e,t,r,n){let i=[],a=0;for(let s of r){a+=1,a%Go===0&&await Z();let o=ah(e,t,s,n);o&&i.push(o)}return i}function ah(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 sh(r,n.get(r),i);let s=li(a,i);return oh(s,n,r,i),a&&Object.keys(s).length===0?null:{id:r,kind:a?"updated":"created",fields:s,after:J(i)}}function sh(e,t,r){return t===r.correlativeId?null:{id:e,kind:"updated",fields:{correlativeId:{before:t,after:r.correlativeId}},after:J(r)}}function oh(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 li(e,t){let r={},n=e??{},i=t,a=new Set([...Object.keys(n),...Object.keys(i)]);a.delete(E.CALENDAR_DURATION);for(let s of a)(Object.hasOwn(n,s)!==Object.hasOwn(i,s)||!ci(n[s],i[s]))&&(r[s]={before:Ko(n[s]),after:Ko(i[s])});return r}function Ko(e){return e===null||typeof e!="object"?e:b(e)}function ci(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)=>ci(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)&&ci(r[s],n[s]))}function zr(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 di(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 Ee(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 ch=/^(\d{4})\/(\d{1,2})\/(\d{1,2})\s+(\d{1,2}):(\d{2})$/;function Nt(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(ch);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 Le(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 lh=e=>e.type==="project",dh=(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:Nt(String(s));return Le(a(e.startDate),a(e.endDate),t,i)};function uh(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(!lh(o)){let d=dh(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 ie(e,t){let r=[];e.forEachActivity((n,i)=>{n.parentId===null&&r.push(i)}),uh(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 fh=e=>e.type==="project",ph=e=>ut(e),hh=(e,t,r,n)=>{let i=ph(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:Le(i.startDate,i.endDate,t,a)};function ui(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(!fh(c)){let u=hh(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),h=typeof p?.ponderator=="number"?p.ponderator:0;l+=f*h}let d=l/100;return a(o,d),d};for(let o of e)s(o);return i}function we(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)}),ui(i,t,n,r)}var $o=e=>Math.round(e*100)/100;function yh(e,t){return(t==="Baseline"?e.expectedProgressBaseline:e.expectedProgress)??void 0}function mh(e,t){let r=$o(e),n=$o(t);return r>99.99?Rt.DONE:n>r?Rt.OVERDUE:e>0&&r>n?Rt.ADVANCEMENT:e===0&&t===0?Rt.WAITING:e>0&&r<n?Rt.DOING:Rt.WAITING}function Mt(e,t){let r=[];return e.forEachActivity((n,i)=>{let a=typeof n.progress=="number"?n.progress:0,s=mh(a,yh(n,t));n.status!==s&&(rt(e,i,mr,s),r.push(i))}),r}function fi(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:()=>fi(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}fi.isMoment=e=>!!e&&typeof e=="object"&&e.__isMomentShim===!0;var At=fi;function gh(e){return e&&e.constructor===Date?!!(e.getFullYear&&e.getMonth&&e.getDate):!1}function qr(e){return gh(e)&&!isNaN(e.getTime())}function D(e,t,r,n){if(!qr(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 yt(e){if(!qr(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 vh=e=>e?e.$level===1:!1,Ah=e=>e.type==="project",Ch=e=>e.$level!==0,Ih=e=>e.type==="task",Sh=e=>e.type==="task"||e.type==="milestone",ct={byFirstLevel:vh,filterByParentType:Ah,avoidSubproject:Ch,byTaskType:Ih,byTaskTypeAndMilestone:Sh};var y=Object.freeze({MFO:"mfo",MSO:"mso",FNLT:"fnlt",FNET:"fnet",SNET:"snet",SNLT:"snlt",ALAP:"alap",ASAP:"asap"});var V=Object.freeze({FS:"fs",SS:"ss",FF:"ff",SF:"sf"});function ae(e){return{0:"fs",1:"ss",2:"ff",3:"sf"}[Number(e)]||"sf"}function zo(e){let{gantt:t,pendingParentsWithNoLinks:r,calculations:n,linkProperty:i}=e;try{let a=kh({gantt:t,pendingParentsWithNoLinks:r});if(a.length===0)return new Set;let s=Dh({gantt:t,subprojectsWithNoLinks:a}),o=Th({gantt:t,childrenIds:s,linkProperty:i,getArrayOfLinkedActivities:_h,calculations:n});return new Set(o.map(c=>c.id))}catch(a){throw a}}function kh(e){let{gantt:t,pendingParentsWithNoLinks:r}=e;return t.getTaskByTime().filter(ct.filterByParentType).filter(n=>r.has(n.id)).map(n=>n.id)}function Dh(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 Th(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 _h(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 qo({gantt:e,linkProperty:t,direction:r}){try{let n=Ph(e,t);if(r==="forward")return{chainStartActivities:n,activitiesStartChainButChildrenOfLinkedParents:null};if(r==="backward")return Rh(n,e,t)}catch(n){throw console.log("Critical Path",n),n}}function Ph(e,t){return e.getTaskByTime().filter(ct.avoidSubproject).filter(ct.byTaskTypeAndMilestone).filter(r=>!r[t].length)}function Rh(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 Jo({gantt:e,direction:t,linkProperty:r}){try{let n=bh(e),i=new Set,a=new Set,s=new Set;t==="backward"&&wh(n).forEach(d=>{i.add(d.id)});let o=Eh(n,t,r),c=Lh(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 bh(e){return e.getTaskByTime().filter(ct.filterByParentType).filter(ct.avoidSubproject)}function Eh(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 Lh(e,t){let r=new Set(t.map(n=>n.id));return e.filter(n=>!r.has(n.id))}function wh(e){return e.filter(t=>{let r=Number(t.progress);return Number.isNaN(r)?!1:r===100})}function Xo({pendingParentsWithLinks:e,gantt:t,direction:r}){try{let n=new Set;return e.forEach(i=>{let a=t.getTask(i),s=Oh(r),o=xh(r),c=a[s];if(!Array.isArray(c))return;Fh(t,c,o).forEach(d=>{n.add(d)})}),n}catch(n){throw n}}function Oh(e){return e==="forward"?"$source":"$target"}function xh(e){return e==="forward"?"target":"source"}function Fh(e,t,r){return t.map(n=>{let a=e.getLink(n)[r];return Number(a)})}var Qe={identifySecondLevelActivities:zo,identifyInitialActivities:qo,identifyParentsWithAndWithoutLinks:Jo,identifyForbiddenActivities:Xo};function Jr(e){return e.length?e.reduce((t,r)=>r.ef>t.ef?r:t):!1}function pi({linkType:e,lag:t,predecessorTime:r,activityCalendar:n,activity:i}){return e===V.FS&&t===0?yt({predecessorTime:r,activityCalendar:n,direction:"future",activity:i}):tr(r,e,n,i)}function Zo({duration:e,constraintDate:t,activityCalendar:r,activity:n}){let i=new Date(t);return{es:D(r,i,e,n),ef:i}}function Qo({duration:e,constraintDate:t,activityCalendar:r,activity:n}){let i=new Date(t),a=D(r,i,e,n);return{es:i,ef:a}}function tr(e,t,r,n){if(![V.FS,V.SS,V.FF].includes(t))return e;let a=[V.FS,V.SS].includes(t)?"future":"past";return yt({dateBaseToCalculate:e,activityCalendar:r,direction:a,activity:n})}var hi=class{constructor(t,r,n,i){if(this.linkedActivitiesData=t,this.activity=r,this.gantt=n,this.linkCandidates=i,this.activityCalendar=this.gantt.getCalendar(this.activity.calendar_id),!this.activityCalendar)throw new Error(`Error trying to get calendar with id: ${this.activity.calendar_id}`)}calculate(){let t=this.calculateLinks(),r=Jr(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=ae(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&&(this.linkCandidates?.set(r.linkId,{targetId:String(this.activity.id),...c}),t.push(c))}return t}handleSNETConstraint(t){let r=Qo({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=Zo({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=pi({linkType:"ss",lag:t,predecessorTime:r,activityCalendar:this.activityCalendar,activity:this.activity}),i=D(this.activityCalendar,n,t,this.activity);t>0&&(i=tr(i,"ss",this.activityCalendar,this.activity));let a=D(this.activityCalendar,i,this.activity.duration,this.activity);return{es:i,ef:a}}calculateFFLink({lag:t,predecessorEf:r}){let n=pi({linkType:"ff",lag:t,predecessorTime:r,activityCalendar:this.activityCalendar,activity:this.activity}),i=D(this.activityCalendar,n,t,this.activity),a=D(this.activityCalendar,i,-this.activity.duration,this.activity);return t>0&&(a=tr(a,"ff",this.activityCalendar,this.activity)),{es:a,ef:i}}calculateFSLink({lag:t,predecessorEf:r}){let n=r;t===0&&(n=yt({dateBaseToCalculate:r,activityCalendar:this.activityCalendar,direction:"future",activity:this.activity}));let i=D(this.activityCalendar,n,t,this.activity),a=D(this.activityCalendar,i,this.activity.duration,this.activity);return{es:i,ef:a}}calculateSFLink({lag:t,predecessorEs:r}){let n=D(this.activityCalendar,r,t,this.activity),i=D(this.activityCalendar,n,-this.activity.duration,this.activity);return t>0&&(i=tr(i,"sf",this.activityCalendar,this.activity)),{es:i,ef:n}}},tc=hi;var yi=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=ae(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:D(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=D(this.activityCalendar,r,i,this.activity),s=D(this.activityCalendar,a,n,this.activity),{ls:s,lf:a};let o=r;return t>0&&(o=this.getLastWorkingHour(o,this.activityCalendar,"past")),a=D(this.activityCalendar,o,i,this.activity),s=D(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=D(this.activityCalendar,l,i,this.activity),s=this.getLastWorkingHour(s,this.activityCalendar,"past"),o=D(this.activityCalendar,s,n,this.activity),{ls:o,lf:s}}let c=r;return a||(c=this.getLastWorkingHour(r,this.activityCalendar)),s=D(this.activityCalendar,c,i,this.activity),o=D(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=D(this.activityCalendar,o,n,this.activity),a=D(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=D(this.activityCalendar,r,n,this.activity),s=D(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=D(this.activityCalendar,c,n,this.activity),s=D(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:D(this.activityCalendar,t,-r,this.activity),lf:t}}getLastWorkingHour(t,r,n="past"){let i=t instanceof Date?t:new Date(t),a=At(i).clone();return this.isActivityInInitHour(r,i)&&n==="past"&&(a=a.hours(0).minutes(0).seconds(0).milliseconds(0)),yt({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),At.isMoment(r)?r.hours()===s:n.getUTCHours()===s)}},ec=yi;function rc(e){let{parent:t,linkProperty:r,linkDirection:n,calculations:i,gantt:a,direction:s,linkCandidates:o}=e,c=t[r],l=Nh(t),d=null;if(s==="forward"){let u=Mh(c,n,i,a);d=new tc(u,t,a,o),d=d.calculate()}else{let u=Wh(c,n,i,a);d=new ec({linksWithActivityData:u,activity:t,parentData:l,gantt:a}).calculate()}return d}function Nh(e){return{duration:e.duration,calendarId:e.calendar_id}}function Mh(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?{linkId:String(a.id),es:o.es,ef:o.ef,linkLag:a.lag,linkType:a.type}:(console.warn(`Calculations not found for activity: ${s}`),null)}).filter(Boolean)}function Wh(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 ac(e){let{activityData:t,calculations:r,singleParents:n,direction:i}=e;if(Bh(t.id,r))return null;let a=Uh(t.id,n),s=jh(a,r);return s.length===0?null:Hh(s,i)}function Bh(e,t){return t.has(e)}function Uh(e,t){let r=t.get(e);return r?r.childrens:[]}function jh(e,t){return e.filter(r=>t.has(r)).map(r=>t.get(r))}function Hh(e,t){if(t==="forward"){let r=nc(e,"es"),n=ic(e,"ef");return{es:r,ef:n}}else{let r=nc(e,"ls"),n=ic(e,"lf");return{ls:r,lf:n}}}function nc(e,t){return e.reduce((r,n)=>n[t]<r[t]?n:r)[t]}function ic(e,t){return e.reduce((r,n)=>n[t]>r[t]?n:r)[t]}var mi={parentWithLinks:rc,parentWithNoLinks:ac};var gi=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.linkCandidates=t.linkCandidates,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=mi.parentWithLinks({parent:t,linkProperty:this.linkProperty,linkDirection:this.linkDirection,gantt:this.gantt,calculations:this.calculations,direction:this.direction,linkCandidates:this.linkCandidates});this.calculationsOfParentThatImpactChildrens.set(t.id,r),this.calculationOfParentsFromLinks.add(t.id)}areAllLinksCalculated(t){return t.every(r=>this.calculations.has(r))}shouldSetDatesToParentsWithLinks(t){let r=t.includes(this.activity.constraint_type),n=this.calculationOfParentsFromLinks.has(this.activity.id);return r&&n}handleParentWithNoLinks(){let t=mi.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)})}},sc=gi;var vi=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}}},oc=vi;var Ai=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}=Qe.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=Qe.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 oc({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=Qe.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}=Qe.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:At(n.start_date).clone(),lf:At(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=At(t.start_date).clone(),i=At(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=D(r,i,-a,t);else{let c=[y.SNLT,y.MSO],l=[y.FNLT,y.MFO];c.includes(o)&&(n=t.constraint_date,i=D(r,n,a,t)),l.includes(o)&&(i=t.constraint_date,n=D(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 sc({activity:t,direction:this.direction,calculationsOfParentThatImpactChildrens:this.calculationsOfParentThatImpactChildrens,calculations:this.calculations,calculationOfParentsFromLinks:this.calculationOfParentsFromLinks,singleParents:this.singleParents,parentCalculationFromChildren:this.parentCalculationFromChildren,linkCandidates:this.linkCandidates,gantt:this.gantt});this.pendingParentsWithLinks.has(t.id)?r.handleParentWithLinks():r.handleParentWithNoLinks()}},Jt=Ai;function Vh(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=D(r,i,e.duration,e)}else if([y.FNLT,y.FNET].includes(t)){let i=new Date(e.constraint_date);n.es=D(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=D(r,i,e.duration,e)}else if(t===y.MFO){let i=new Date(e.constraint_date);n.es=D(r,i,-e.duration,e),n.ef=i}return n}var Xr=Vh;var Ci=class{constructor(t){this.referenceActivity=t.activity,this.activityToCalculate=null,this.links=t.links,this.calculatedActivities=t.calculatedActivitiesMap,this.alapMap=t.calculatedAlapsMap,this.parentsWithLinks=t.parentsWithLinks,this.parentsCalculations=t.parentsCalculations,this.gantt=t.ganttInstance,this.linkCandidates=t.linkCandidates}getEsAndEfFromPreviousCalculatedActivities(t){return this.alapMap.has(t)?this.alapMap.get(Number(t)):this.calculatedActivities.get(Number(t))}calculateSucessorTimes(t,r,n=0,i,a=V.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===V.FS&&i===0?o=yt({dateBaseToCalculate:o,activityCalendar:s,direction:"future",activity:this.referenceActivity}):o=this.mutateTheDateToFutureOrPastInBaseRestriction(t,a,s)),[V.FF,V.SF].includes(a)?(l=D(s,o,n,this.referenceActivity),c=D(s,l,r,this.referenceActivity),!d&&i>0&&(c=this.mutateTheDateToFutureOrPastInBaseRestriction(c,a,s))):(c=D(s,o,r,this.referenceActivity),!d&&i>0&&(c=this.mutateTheDateToFutureOrPastInBaseRestriction(c,a,s)),l=D(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,V.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,V.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,V.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,V.SF)}mutateTheDateToFutureOrPastInBaseRestriction(t,r,n){if(![V.FS,V.SS,V.FF].includes(r))return t;let a=[V.FS,V.SS].includes(r)?"future":"past";return yt({dateBaseToCalculate:t,activityCalendar:n,direction:a,activity:this.referenceActivity})}},cc=Ci;var er=class extends cc{constructor(t){super(t)}calculate(){if(this.links.length===0)return new Jt(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}});let a=this.calculateLink(i);return this.linkCandidates?.set(String(i.id),{targetId:String(this.referenceActivity.id),...a}),a}),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=D(n,i,this.referenceActivity.duration,this.referenceActivity);t.push({es:i,ef:a})}return Jr(t)}calculateLink(t){return{0:()=>this.calculateFS(t),1:()=>this.calculateSS(t),2:()=>this.calculateFF(t),3:()=>this.calculateSF(t)}[t.type]()}};var Ii=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}},Zr=Ii;var Si=(e,t)=>()=>t()===e;var ki=e=>!e?.fullyParsed||typeof window<"u"&&window.to_use_react_gantt?.conversionMode?.isActive;var Yh=16,se=async e=>performance.now()-e>Yh?(await Z(),performance.now()):e;var rr=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 se(c);let{activitiesThatCanBeCalculated:l,pendingActivities:d}=t.checkActivitiesThatNowCanBeCalculated(o);if(l.size===0)break;for(let u of l){if(!s())return;c=await se(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 Di=class extends Jt{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.linkCandidates=new Map,this.calculationOfParentsFromLinks=new Set,this.parentCalculationFromChildren=new Set,this.forbiddenActivitiesLinkedToParentsWithLinks=new Set,this.activitiesStartChainButChildrenOfLinkedParents=new Set,this.identifyInitialActivities(),this.initActivitiesWaitingForCalculation()}async calculateAsync(t){this.identifyParentsWithAndWithoutLinks(),t()&&(this.identifyForbiddenActivitiesLinkedToParentsWithLinks(),t()&&(this.initializeActivitiesWithFullProgress(),t()&&(this.calculateStartAndFinishOfActivitiesThatStartChain(),t()&&(this.identifySecondLevelActivities(),t()&&(this.identifyThirdLevelActivities(),t()&&await this.iterativeCalculateEfAndEs(t))))))}async iterativeCalculateEfAndEs(t){let r=new Zr({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 rr({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 er({links:i,activity:n,calculatedActivitiesMap:this.calculations,calculatedAlapsMap:this.alapMap,constraint:a,parentsWithLinks:this.pendingParentsWithLinks,parentsCalculations:this.calculationsOfParentThatImpactChildrens,ganttInstance:this.gantt,linkCandidates:this.linkCandidates}).calculate(),a===y.ASAP&&this.totalFloatForAsap.set(r,{es:f.es,ef:f.ef,text:n.text})):{es:d,ef:u}=new er({links:i,activity:n,calculatedActivitiesMap:this.calculations,calculatedAlapsMap:this.alapMap,constraint:a,parentsWithLinks:this.pendingParentsWithLinks,parentsCalculations:this.calculationsOfParentThatImpactChildrens,ganttInstance:this.gantt,linkCandidates:this.linkCandidates}).calculate(),a===y.ALAP&&this.alapMap.set(r,{es:n.start_date,ef:n.end_date,text:n.text});let p=Xr(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 h=n.end_date;a===y.MFO&&(h=Math.max(p.ef,n.end_date)),d=n.start_date,u=h}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)}},lc=Di;var Ti=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=V.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=D(s,o,r,this.activity),u=D(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===V.FS){let{ls:d,lf:u}=this.calculateFsLink(l);return{ls:d,lf:u}}if(a===V.FF){let{ls:d,lf:u}=this.calculateFFLink(l);return{ls:d,lf:u}}if(a===V.SS){let{ls:d,lf:u}=this.calculateSSlink(l);return{ls:d,lf:u}}if(a===V.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,V.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,V.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,V.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,V.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=At(r).clone();return D(t,new Date(i),n,this.activity)}getLastWorkingHour(t,r,n="past"){let i=t instanceof Date?t:new Date(t),a=At(i).clone();return this.isActivityInInitHour(r,i)&&n==="past"&&(a=a.hours(0).minutes(0).seconds(0).milliseconds(0)),yt({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),At.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=D(n,d,a,this.activity),o=this.getLastWorkingHour(o,n,"past"),c=D(n,o,i,this.activity),{ls:c,lf:o}}let l=r;return s||(l=this.getLastWorkingHour(r,n)),o=D(n,l,a,this.activity),c=D(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=D(n,r,a,this.activity),o=D(n,s,i,this.activity),{ls:o,lf:s};let c=r;return t>0&&(c=this.getLastWorkingHour(c,n,"past")),s=D(n,c,a,this.activity),o=D(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=D(n,r,i,this.activity),o=D(n,c,a,this.activity),{ls:c,lf:o};let l=r;return t<0&&!s&&(l=this.getLastWorkingHour(l,n,"future")),c=D(n,l,i,this.activity),o=D(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=D(n,r,i),s=D(n,o,a,this.activity),{ls:o,lf:s}):(o=D(n,r,i,this.activity),s=D(n,o,a,this.activity),{ls:o,lf:s})}},dc=Ti;var _i=class extends dc{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 Jt(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=D(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:D(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))}},uc=_i;function Kh(e,t,r){let n={ls:null,lf:null};return r===y.MSO&&(n.ls=t.constraint_date,n.lf=D(e,n.ls,t.duration,t)),r===y.MFO&&(n.lf=t.constraint_date,n.ls=D(e,n.lf,-t.duration,t)),n}var fc=Kh;var Pi=class extends Jt{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 Zr({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 rr({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=Xr(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 uc({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=fc(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=D(this.gantt.getCalendar(t.calendar_id),a,-t.duration,t);if([y.SNLT].includes(t.constraint_type)){let l=this.calculationsOfParentThatImpactChildrens.get(r),d=D(this.gantt.getCalendar(t.calendar_id),l.lf,-t.duration,t),u=t.constraint_date??d;i=new Date(Math.min(u.getTime(),d.getTime())),a=D(this.gantt.getCalendar(t.calendar_id),i,t.duration,t)}if([y.FNLT].includes(t.constraint_type)){let l=this.calculationsOfParentThatImpactChildrens.get(r),d=t.constraint_date??l.lf;i=new Date(Math.min(d.getTime(),l.lf.getTime())),a=D(this.gantt.getCalendar(t.calendar_id),i,t.duration,t)}[y.MSO].includes(t.constraint_type)&&(i=t.constraint_date,a=D(this.gantt.getCalendar(t.calendar_id),i,t.duration,t)),[y.MFO].includes(t.constraint_type)&&(a=t.constraint_date,i=D(this.gantt.getCalendar(t.calendar_id),a,-t.duration,t));let s=this.projectDates.end_date,o=[{ls:i,lf:a}];o.push({ls:D(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}},pc=Pi;function hc(){return null}var yc=({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 Ri=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)})}},mc=Ri;var bi=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){let r=t===y.ALAP?this.backwardMap.get(this.activity.id):this.forwardMap.get(this.activity.id);return this.parseHoursToDays(this.calculationWithCalendar(this.gantt.getSubtaskDates().end_date,t===y.ALAP?r?.lf:r?.ef))}calculateFreeFloatOfRestriction(t){let r=this.forwardMap.get(this.activity.id);return this.parseHoursToDays(this.calculationWithCalendar(this.activity.constraint_date,t===y.FNLT?r?.ef:r?.es))}getLinkData(t){let r=this.gantt.getLink(t)||{},n=ae(r.type);return{LINK:r,LINK_TYPE:n}}getSucessorAndPredecessorDates({constraint:t,isSuscessorAlap:r,sucessorId:n,predecessorId:i}){let a=(r?this.backwardMap:this.forwardMap).get(n),s=(t===y.ALAP?this.backwardMap:this.forwardMap).get(i),o=t===y.ALAP?s?.ls:s?.es,c=t===y.ALAP?s?.lf:s?.ef;return{fs:{sucessor:a?.ls??a?.es,predecessor:c},ss:{sucessor:a?.ls??a?.es,predecessor:o},ff:{sucessor:a?.lf??a?.ef,predecessor:c},sf:{sucessor:a?.lf??a?.ef,predecessor:o}}}calculateMsoMfo(t){let r=this.activity.constraint_date||new Date,n=this.forwardMap.get(this.activity.id),i=t===y.MSO?n?.es:n?.ef,a=this.calculationWithCalendar(r,i);return Math.max(0,this.parseHoursToDays(a))}getMinValue(...t){let r=t.filter(n=>n!=null);return r.length?Math.min(...r):0}calculationWithCalendar(t,r){if(!(t instanceof Date)||!(r instanceof Date)||!Number.isFinite(t.getTime())||!Number.isFinite(r.getTime()))return Number.NaN;let 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==null?0:t/this.gantt.config.hoursPerDay}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)}},gc=bi;var vc=e=>({totalFloat:new mc(e.totalFloat).getTotalFloat(),freeFloat:new gc(e.freeFloat).getFreeFloat()});var Ei=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=yc({forward:t,backward:r,id:l,activity:d,gantt:n,projectDates:i}),{totalFloat:f,freeFloat:p}=vc(u);o.set(l,f),c.set(l,p),s=await se(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.linkResidualHours=new Map,this.currentCalculationId=0}getCurrentCalculationId=()=>this.currentCalculationId;async calculate(t,r=()=>!0){let n=++this.currentCalculationId,i=Si(n,this.getCurrentCalculationId),a=()=>i()&&r();try{let s=t||this.gantt;if(this.gantt=s||hc(),ki(this.gantt))return!1;let o=new lc(this.gantt);if(await o.calculateAsync(a),!a())return!1;let c=o.calculations,l=o.constraintsMap,d=new pc(this.gantt,c,l);if(await d.calculateAsync(a),!a())return!1;this.forwardPathCalculations=c,this.backwardPathCalculations=d.calculations;let u=await this.calculateLinkResidualHours(o.linkCandidates,c,a);if(!u||!a())return!1;this.linkResidualHours=u;let{totalFloatMap:f,freeFloatMap:p}=await this.calculateFloatsAsync(o,d,a);return a()?(this.totalFloat=f,this.freeFloat=p,this.gantt.refreshData(),!0):!1}catch(s){throw this.forwardPathCalculations?.size,s}}async calculateLinkResidualHours(t,r,n=()=>!0){let i=new Map,a=performance.now();for(let[s,o]of t){if(a=await se(a),!n())return null;let c=Number(o.targetId),l=this.gantt.getTask(c),d=r.get(c),u=o.ef,f=d?.ef,p=l&&this.gantt.getCalendar(l.calendar_id);if(!p||!(u instanceof Date)||!(f instanceof Date)||!Number.isFinite(u.getTime())||!Number.isFinite(f.getTime())){i.set(s,null);continue}let h=u.getTime(),C=f.getTime()>=h?p.calculateDuration({start_date:u,end_date:f}):-p.calculateDuration({start_date:f,end_date:u});i.set(s,Number.isFinite(C)?Object.is(C,-0)?0:C:null)}return i}async calculateFloatsAsync(t,r,n){try{let i=this.gantt.getSubtaskDates(),a=Array.from(this.forwardPathCalculations.keys());return await Ei({activityIds:a,forward:t,backward:r,gantt:this.gantt,projectDates:i,isCurrent:n})}catch(i){throw this.forwardPathCalculations?.size,i}}},Ac=Li;var Gh=e=>e==="fnet"||e==="fnlt"||e==="mfo",$h=e=>new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()));function zh(e,t){let r=e.constraintDate;if(!r||!Gh(e.constraintType))return r;let n=$h(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()?Gn(e,t):r}function qh(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 Jh(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 Xh(e){let t=new Set;e.forEachActivity((o,c)=>{t.add(String(c)),o.parentId!==null&&t.add(String(o.parentId))});let r=new Map;for(let o of t){let c=Number(o);Number.isSafeInteger(c)&&c!==0&&r.set(c,(r.get(c)??0)+1)}let n=new Map,i=new Map;for(let o of t){let c=Number(o);Number.isSafeInteger(c)&&c!==0&&r.get(c)===1&&(n.set(o,c),i.set(c,o))}let a=1,s=o=>{let c=String(o),l=n.get(c);if(l!==void 0)return l;for(;i.has(a);)a+=1;return n.set(c,a),i.set(a,c),a++};for(let o of t)s(o);return{toLegacy:s,toCanonical:o=>typeof o=="number"?i.get(o)??null:n.has(String(o))?String(o):null}}function Zh(e,t){let r=Jh(e),n=new Map;return e.forEachActivity((i,a)=>{let s=String(a);n.set(s,{id:t.toLegacy(s),parent:i.parentId===null?0:t.toLegacy(i.parentId),$level:r.get(s)??0,$source:e.getOutgoingLinkIds(s),$target:e.getIncomingLinkIds(s),start_date:i.startDate,end_date:i.endDate,duration:i.durationHours,progress:i.progress,type:i.type,calendar_id:i.calendarId,constraint_type:i.constraintType,constraint_date:zh(i,e)})}),n}function Qh(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 ty(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 Cc(e,t){let r=new Map,n=l=>{let d=l==null?"__default__":String(l),u=r.get(d);if(u)return u;let f=e.calendarReader.getCalendar(String(l)),p=qh(f);return r.set(d,p),p},i=ty(e);await Z();let a=Xh(e),s=Zh(e,a);await Z();let o=[...s.values()].sort((l,d)=>(l.start_date?.getTime()??0)-(d.start_date?.getTime()??0));await Z();let c=Qh(s);return{fullyParsed:!0,config:{hoursPerDay:t},getTask:l=>{let d=a.toCanonical(l);return d===null?null:s.get(d)??null},getLink:l=>{let d=e.getLink(l);return d?{...d,source:a.toLegacy(d.source),target:a.toLegacy(d.target),lag:d.lag}:null},getCalendar:n,getChildren:l=>{let d=a.toCanonical(l);return d===null?[]:e.getChildren(d).map(a.toLegacy)},eachTask:l=>{for(let d of c)l(d)},getTaskByTime:()=>o,getSubtaskDates:()=>i,getCanonicalActivityId:a.toCanonical,refreshData:()=>{}}}var Sc=1e3;function ey(e,t,r,n){let i=typeof e=="number"&&Number.isFinite(e)?Object.is(e,-0)?0:e:null;return{freeSlackHours:i,isCritical:i!==null&&i<=0&&t&&r&&n===0}}async function ry(e,t,r,n,i){let a=new Map,s=0;for(let o of t.forward?.keys()??[]){if(++s>=Sc&&(s=0,await Z(),!i()))return null;let c=n(o);if(c===null)continue;let l=e.getActivity(c);l&&a.set(String(c),iy(o,Number(l.progress??0),t,r))}return i()?a:null}async function ny(e,t,r,n){let i=new Map,a=0;for(let s of e.getAllLinks()){if(++a>=Sc&&(a=0,await Z(),!n()))return null;i.set(String(s.id),ey(t.get(String(s.id)),r.get(s.source)?.isCritical===!0,r.get(s.target)?.isCritical===!0,e.getActivity(s.target)?.progress))}return n()?i:null}var Ic=(e,t)=>{if(typeof e!="number"||!Number.isFinite(e)||!Number.isFinite(t)||t<=0)return null;let r=e*t;return Number.isFinite(r)?Object.is(r,-0)?0:r:null};function iy(e,t,r,n){let i=c=>{if(c==null)return null;let l=new Date(c);return Number.isFinite(l.getTime())?l:null},a=r.forward?.get(e),s=r.backward?.get(e),o=Ic(r.totalFloat.get(e),n);return{criticalPath:{earlyStart:i(a?.es),earlyFinish:i(a?.ef),lateStart:i(s?.ls),lateFinish:i(s?.lf),totalSlackHours:o},isCritical:t<100&&o!==null&&o<=0,freeSlackHours:Ic(r.freeFloat.get(e)?.activityFreeFloat,n)}}var Qr=(e,t)=>e===t||e!==null&&t!==null&&e.getTime()===t.getTime();function wi(e,t,r){let n=e.getActivity(t),i=n?.criticalPath,a=r.criticalPath;n&&i&&Qr(i.earlyStart,a.earlyStart)&&Qr(i.earlyFinish,a.earlyFinish)&&Qr(i.lateStart,a.lateStart)&&Qr(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)}function Oi(e,t,r){let n=e.getLink(t);!n||Object.is(n.freeSlackHours,r.freeSlackHours)&&Object.is(n.isCritical,r.isCritical)||(e.setLinkField(t,"freeSlackHours",r.freeSlackHours),e.setLinkField(t,"isCritical",r.isCritical))}async function xi(e,t,r=()=>!0){if(!r())return null;let n=await Cc(e,t);if(!r())return null;let i=new Ac(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=await ry(e,s,t,n.getCanonicalActivityId,r);if(!o)return null;let c=await ny(e,i.linkResidualHours,o,r);return c?{activities:o,links:c}:null}async function tn(e,t,r=()=>!0){let n=await xi(e,t,r);if(!n||!r())return!1;for(let[i,a]of n.activities){if(!r())return!1;wi(e,i,a)}for(let[i,a]of n.links){if(!r())return!1;Oi(e,i,a)}return!0}function Oe(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),E.REAL_COST,o),r.push(String(i)),o};for(let i of t)n(i);return r}var kc=new Set;var Dc=new Set(["activity-outdent","activity-indent"]);var nr=new Set([_.TEXT,_.DESCRIPTION,_.COST,_.USED_COST,_.CUSTOM_ID,_.RESPONSABLES,_.SUBCONTRACT_ID,_.TAGS]),ay=new Set(["activity-clipboard-clear","activity-copy","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"]),sy=new Set(["activity-clipboard-clear","activity-copy","selection-toggle","selection-replace","visibility-set","filter-set","sort-set"]);function _c(e){return!sy.has(e.kind)}var oy=new Set;function cy(e){return e.kind==="inline-edit"?nr.has(e.column):e.kind==="bulk-edit"?e.edits.every(t=>nr.has(t.column)):!1}function Fi(e,t){return!(ay.has(e.kind)||t.has(e.kind)||cy(e))}function Ni(e){return e.kind==="activity-lookahead-sync"?e.persistedProgress!==void 0:Fi(e,oy)}function oe(e){return e.kind==="activity-lookahead-sync"?e.persistedProgress!==void 0:Fi(e,kc)}function Pc(e){return Fi(e,Dc)}function Mi(e){return e.kind==="activity-set-progress"?!0:e.kind==="inline-edit"?e.column===_.PROGRESS:e.kind==="bulk-edit"?e.edits.some(t=>t.column===_.PROGRESS):!1}function ly(e){return Pc(e)&&Mi(e)}var Tc=new Set([_.PROGRESS,_.HH_WORK_TIME,_.DURATION,_.COST,_.USED_COST,_.REAL_COST]);function dy(e){return e.kind==="activity-set-progress"?!0:e.kind==="inline-edit"?Tc.has(e.column):e.kind==="bulk-edit"?e.edits.some(t=>Tc.has(t.column)):!1}var it={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 Rc(e,t,r){let n=new Set;t.ran&&n.add(it.AUTOSCHEDULE),n.add(it.PARENT_BOUNDS),dy(e)&&n.add(it.PARENT_PROGRESS),Mi(e)&&n.add(it.REAL_WORK);let i=!r.skipAutoSchedule;return i&&Pc(e)&&n.add(it.EXPECTED_PROGRESS),i&&ly(e)&&n.add(it.REAL_COST),i&&oe(e)&&!r.skipCriticalPath&&n.add(it.CRITICAL_PATH),n}async function Y(e,t){let r=uy(t);r.has(it.AUTOSCHEDULE)&&await yy(e.adapter,t);let n=r.has(it.AUTOSCHEDULE)?await fy(e,t.autoscheduleFrom):hy();return await my(e.adapter,t,n.scheduledIds,r),await gy(e,r,t.now),n}function uy(e){let t=e.autoscheduleFrom!==null,r=!e.options.skipAutoSchedule&&t,n=new Set(Rc(e.action,{requested:t,ran:r},e.options));return e.recomputeParentProgress&&n.add(it.PARENT_PROGRESS),n}async function fy(e,t){let r=t==="roots"?{}:{triggerId:t},n=await e.scheduler.schedule(r),i=py(e.adapter,n.updatedIds);return Ke(e.adapter,n),i}function py(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 hy(){return{scheduledIds:[]}}async function yy(e,t){let r=t.collectDirty?t.collectDirty([]):di(t.recomputeParentsFrom,[]);r.size!==0&&await Se(e,r,!1)}async function my(e,t,r,n){let i=t.collectDirty?t.collectDirty(r):di(t.recomputeParentsFrom,r);await Se(e,i,n.has(it.PARENT_PROGRESS),{recomputeRealWork:n.has(it.REAL_WORK),progressMode:t.recomputeParentProgress?"zero-when-no-contribution":"freeze-when-no-contribution"})}async function gy(e,t,r){t.has(it.EXPECTED_PROGRESS)&&r!==null&&(vy(e.adapter)&&we(e.adapter,r,e.defaultBaseCalendarId??null),ie(e.adapter,r),Mt(e.adapter,e.sector.statusCriteria)),t.has(it.REAL_COST)&&Oe(e.adapter),t.has(it.CRITICAL_PATH)&&await tn(e.adapter,e.sector.hoursPerDay)}function vy(e){let t=!1;return e.forEachActivity(r=>{ut(r)&&(t=!0)}),t}var Ay=new Set([_.CONSTRAINT_TYPE,_.CONSTRAINT_DATE]),Cy=new Set(["mso","mfo"]);function en(e){return Ay.has(e)}function rn(e){return e===_.CONSTRAINT_DATE}function nn(e,t,r,n){let i=r.getActivity(e);if(!i)return!1;let a=i.constraintType;if(!a||Kt.has(a)||Cy.has(a))return!1;let s=Wi(i.startDate),o=Wi(r.getLastStartDate(e));if(!o||!s||s.getTime()!==o.getTime())return!1;let c=Iy(t,a,String(i.calendarId??""),n),l=Wi(i.constraintDate);return Sy(l,c)?!1:(r.setActivityField(e,"constraintDate",c),!0)}function Iy(e,t,r,n){if(e===null)return null;let i=n.getCalendar(r);return i?xt(e,i,t):e}function Wi(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 Sy(e,t){return e===null&&t===null?!0:e===null||t===null?!1:e.getTime()===t.getTime()}async function an(e,{postMutationArgs:t,revertTargets:r,revert:n}){let{scheduledIds:i}=await Y(e,bc(t)),a=!1;for(let{activityId:s,priorConstraintDate:o}of r){let c=n(s,o);a=a||c}if(a){let s=await Y(e,bc(t));i=Dy(i,s.scheduledIds)}return oe(t.action)&&await Y(e,ky(t)),{scheduledIds:i}}function bc(e){return{...e,options:{...e.options,skipCriticalPath:!0}}}function ky(e){return{action:e.action,autoscheduleFrom:null,recomputeParentsFrom:[],now:null,options:e.options}}function Dy(e,t){let r=new Set(e);for(let n of t)r.add(n);return[...r]}function Ty(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 Bi(e,t,r){let n=[];for(let i of r){let a=e.get(i);if(!a)continue;let s=a.pendingRequestIds??[];if(!ye({pendingRequestIds:s}))continue;let o=t.getActivity(i),c=o==null;if(!c&&!Ty(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}function ft(e){let t={id:String(e.id),source:String(e.source),target:String(e.target),type:e.type,lag:Number(e.lag),freeSlackHours:typeof e.freeSlackHours=="number"&&Number.isFinite(e.freeSlackHours)?e.freeSlackHours:null,isCritical:e.isCritical===!0};return e.proplannerId!=null&&(t.proplannerId=Number(e.proplannerId)),e.ganttId!=null&&(t.ganttId=Number(e.ganttId)),e.sectorId!=null&&(t.sectorId=Number(e.sectorId)),t}async function B(e,t){let r=by(e,t),n=new Map(t.beforeSnap),i=e.peekWriteCapture();if(i){let f=Ly(i);Ey(e,i,f,n,r)}let a=t.sirDetection,s=a==="before-diff"?Bi(n,e,r):[],o=Ry(t.correlativeShifts,r),c=await $r(e,n,r,o),l=a==="after-diff"?Bi(n,e,r):s,d=t.warnings??[],u=Py(t.links??[],i?_y(e,i):[]);return{source:t.source,activities:c,links:u,calendars:[],trackingEvents:t.trackingEvents??[],...l.length>0?{effects:l}:{},...d.length>0?{warnings:d}:{}}}function _y(e,t){let r=[];for(let n of t.ops){if(n.kind!=="link-field")continue;let i=e.getLink(n.linkId);if(!i)continue;let a={};for(let s of["freeSlackHours","isCritical"])Object.is(n.before[s],i[s])||(a[s]={before:n.before[s],after:i[s]});Object.keys(a).length!==0&&r.push({id:n.linkId,kind:"updated",fields:a,after:ft(i)})}return r}function Py(e,t){let r=[],n=new Map;for(let i of e){let a=n.get(i.id);if(a===void 0){n.set(i.id,r.length),r.push(i);continue}let s=r[a];if((s.kind==="updated"||s.kind==="created")&&i.kind==="updated"){r[a]={...s,fields:{...s.fields,...i.fields},after:i.after};continue}r[a]=i}for(let i of t){let a=n.get(i.id);if(a===void 0){n.set(i.id,r.length),r.push(i);continue}let s=r[a];if(s.kind==="deleted")continue;let o=s.kind==="created"?Object.fromEntries(Object.entries(i.fields??{}).map(([c,l])=>[c,{before:void 0,after:l.after}])):i.fields;r[a]={...s,fields:{...s.fields,...o},after:i.after}}return r}function Ry(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 by(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 Ey(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(li(s,o)).length!==0&&(n.set(a,s),i.add(a))}}function Ly(e){return new Set(e.ops.filter(t=>t.kind==="insert").map(t=>t.activityId))}function xe(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:ft(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:ft(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:ft(c)})}return n}function Fe(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 Ne(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:ft(a)})}return n}function sn(e,t){typeof e=="string"&&e.length>0&&t.releaseCustomId(e)}async function Ec(e,t,r){let{adapter:n,ctx:i,scheduler:a,sector:s}=r,o=$t(e.column);if(!o)return{ok:!1,reason:S.NO_PIPELINE_FOR_COLUMN};e.column===_.DURATION&&a.invalidateExpandedLinksCache();let c=i.activityReader.getActivity(e.activityId);if(!c)return{ok:!1,reason:S.ACTIVITY_NOT_FOUND};let l=o.canEdit(c,i.hierarchy);if(!l.allowed)return{ok:!1,reason:l.reason??S.CANNOT_EDIT,alertKey:l.alertKey};let d=o.parseInput(e.newValue,c,i);if(!d.ok)return{ok:!1,reason:d.reason??S.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??S.INVALID,alertKey:f.notification?.messageKey};if(e.column===_.CUSTOM_ID&&d.value!==null){let I=n.getActivity(e.activityId),R=I?I.customId:null,N=typeof R=="string"?R:null;if(r.customIdTracker.isCustomIdInUse(String(d.value),N))return{ok:!1,reason:S.CUSTOM_ID_DUPLICATE}}let p=o.transform(c,d.value,i,d.raw),h=zt(e.activityId,p),A=await $(n,h),C=Fe(n,String(e.activityId)),T=c.constraintDate;qt(n,e.activityId,p),Vt(e.activityId,p.postProcessors??[],n,A.get(String(e.activityId))??null);let g=Ne(C,n,String(e.activityId));if(e.column===_.CUSTOM_ID){let I=A.get(String(e.activityId)),R=I?I.customId:null,N=typeof R=="string"?R:null,x=typeof d.value=="string"?d.value:null;N!==x&&r.customIdTracker.trackCustomIdChange(N,x)}let k=()=>({action:e,autoscheduleFrom:p.needsAutoSchedule?String(e.activityId):null,recomputeParentsFrom:[],collectDirty:I=>zr(e.activityId,h,I),now:r.now,options:t}),m=en(e.column),{scheduledIds:P}=await(m?an({adapter:n,scheduler:a,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{postMutationArgs:k(),revertTargets:rn(e.column)?[]:[{activityId:e.activityId,priorConstraintDate:T}],revert:(I,R)=>nn(I,R,n,i.calendars)}):Y({adapter:n,scheduler:a,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},k())),w=(p.trackingEvents??[]).map(I=>({name:I.name,properties:I.properties??{}})),v=be(e.activityId,p.constraintWarning);return{ok:!0,changes:await B(n,{source:e,beforeSnap:A,touchedIds:h,scheduledIds:P,sirDetection:"before-diff",links:g,trackingEvents:w,...v?{warnings:[v]}:{},hoursPerDay:s.hoursPerDay})}}function wy(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 Oy(e,t,r,n){return e.map((i,a)=>{let s=i.kind==="create"?n?.get(a):void 0,o=jt(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 xy(e){return new Map([...e].map(([t,r])=>[String(t),r]))}async function Lc(e,t,r){if(e.kind==="link-create"||e.kind==="link-update"){let n=e.type;if(n!==void 0&&!Object.values(W).some(a=>a===n))return{ok:!1,reason:S.INVALID_LINK_TYPE};let i=e.lag;if(i!==void 0&&!Number.isFinite(i))return{ok:!1,reason:S.INVALID_LINK_LAG}}return Ui([Uy(e,r.sector.hoursPerDay)],e,t,r,e.kind==="link-create"&&e.linkId?new Map([[0,e.linkId]]):void 0)}async function wc(e,t,r){let{hoursPerDay:n}=r.sector,i=e.operations.map(s=>My(s,n)),a=Fy(e.operations);return Ui(i,e,t,r,a)}function Fy(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 Ny(e,t){if(e===void 0)return;let r=new Map,n=new Set,i=()=>{let a=t.linkIdGen.next();for(;t.adapter.getLink(a)!==null||t.isLinkIdReserved(String(a))||n.has(String(a));)a=t.linkIdGen.next();return a};for(let[a,s]of e){let o=t.adapter.getLink(s)!==null||t.isLinkIdReserved(String(s))||n.has(String(s)),c=o?i():s;o||t.linkIdGen.bump(s),n.add(String(c)),r.set(a,c)}return r}function My(e,t){return e.kind==="create"?{kind:"create",source:e.source,target:e.target,type:e.type,lag:vt(e.lag??0,t)}:e.kind==="update"?{kind:"update",linkId:e.linkId,type:e.type,lag:e.lag===void 0?void 0:vt(e.lag,t)}:{kind:"delete",linkId:e.linkId}}async function Ui(e,t,r,n,i){let{adapter:a,scheduler:s,sector:o,linkIdGen:c}=n;s.invalidateAllCaches();let{activityIds:l,links:d}=wy(e,a),u=await $(a,l),f=Oy(e,a,c,Ny(i,n));if(e.length===1&&f[0]&&f[0].rejected!==null&&t.kind!=="inline-edit")return{ok:!1,reason:f[0].rejected};let p=Wy(f,d,a),{scheduledIds:h}=await Y({adapter:a,scheduler:s,sector:n.sector,defaultBaseCalendarId:n.defaultBaseCalendarId},{action:t,autoscheduleFrom:p,recomputeParentsFrom:l,now:n.now,options:r}),A=xe(f,d,a);return{ok:!0,linkVerdicts:f.map((C,T)=>C.rejected===null?{operationIndex:T,kind:C.op.kind,ok:!0,linkId:String(C.finalLinkId)}:{operationIndex:T,kind:C.op.kind,ok:!1,reason:C.rejected}),__beforeLinks:xy(d),changes:await B(a,{source:t,beforeSnap:u,touchedIds:l,scheduledIds:h,links:A,hoursPerDay:o.hoursPerDay})}}function Wy(e,t,r){for(let n of e){if(n.rejected!==null)continue;let i=By(n.op,t,r);if(i!==null)return r.hasChildren(i)?"roots":String(i)}return null}function By(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 Uy(e,t){return e.kind==="link-create"?{kind:"create",source:e.source,target:e.target,type:e.type,lag:vt(e.lag,t)}:e.kind==="link-update"?{kind:"update",linkId:e.linkId,type:e.type,lag:e.lag===void 0?void 0:vt(e.lag,t)}:{kind:"delete",linkId:e.linkId}}async function Oc(e,t,r){let{adapter:n,sector:i}=r;if(typeof e.newValue!="string")return{ok:!1,reason:S.INVALID_VALUE};if(!n.getActivity(e.activityId))return{ok:!1,reason:S.ACTIVITY_NOT_FOUND};let s=e.column===_.CUSTOM_PREDECESSORS,{specs:o}=wr(e.newValue),c=o.map(h=>({...h,lag:vt(Nr(h.lag),i.hoursPerDay)})),l=new Map;n.forEachActivity(h=>{h.correlativeId!=null&&l.set(String(h.correlativeId),h.id)});let d=h=>l.get(h)??null,u=s?n.getIncomingLinkIds(e.activityId):n.getOutgoingLinkIds(e.activityId),f=[];for(let h of u){let A=n.getLink(h);A&&f.push(A)}let p=s?xr({targetActivityId:e.activityId,currentLinks:f,desiredSpecs:c,resolveActivityByCorrelative:d}):Fr({sourceActivityId:e.activityId,currentLinks:f,desiredSpecs:c,resolveActivityByCorrelative:d});return Ui(p.operations,e,t,r)}var Ct={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 at(e){e.invalidateVisualOrderIds?.();let t=[];e.forEachActivity(a=>{L(a.parentId)&&t.push(a)}),t.sort(Nc);let r=[];xc(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),jy(a,i)}i+=1;let s=He(String(a.id),e);s.sort(Nc),xc(r,s)}return n}function xc(e,t){for(let r=t.length-1;r>=0;r-=1)e.push(t[r])}function Fc(e){let t=e.correlativeId,r=typeof t=="number"?t:Number(t);return Number.isFinite(r)?r:Hn}var Nc=(e,t)=>Fc(e)-Fc(t);function jy(e,t){e.correlativeId=t}function ji(e,t){if(!e||e==="0")return;let r=String(e);for(;r!==null;){let{workHours:n,realWorkHours:i}=Bc(r,t);t.setActivityField(r,E.WORK_HOURS,n),t.setActivityField(r,E.REAL_WORK_HOURS,i);let a=t.getActivity(r);if(!a)break;let s=a.parentId;if(!s||L(s))break;r=s}}function Mc(e,t){let r=t.getActivity(e);if(!r)return;let n=r.parentId;!n||L(n)||ji(n,t)}function Wc(e,t,r){for(let n of e){if(r.hasChildren(n))continue;let i=r.getActivity(n);i&&r.setActivityField(n,E.REAL_WORK_HOURS,dt(ir(i,E.WORK_HOURS),ir(i,E.PROGRESS)))}for(let n of t)r.setActivityField(n,E.REAL_WORK_HOURS,Bc(n,r).realWorkHours)}function Bc(e,t){let r=0,n=0;for(let i of t.getChildren(e)){let a=t.getActivity(i);if(!a)continue;let s=ir(a,E.WORK_HOURS);r+=s,n+=Hy(i,a,s,t)}return{workHours:r,realWorkHours:n}}function ir(e,t){let r=e[t];return typeof r=="number"&&Number.isFinite(r)?r:0}function Hy(e,t,r,n){return n.hasChildren(e)?ir(t,E.REAL_WORK_HOURS):dt(r,ir(t,E.PROGRESS))}function Hi(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+=Vy(c,E.USED_COST))}t.setActivityField(r,E.USED_COST,i);let a=t.getActivity(r);if(!a)break;let s=a.parentId;if(!s||L(s))break;r=s}}function Uc(e,t){let r=t.getActivity(e);if(!r)return;let n=r.parentId;!n||L(n)||Hi(n,t)}function Vy(e,t){let r=e[t];return typeof r=="number"&&Number.isFinite(r)?r:0}function Vi(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+=Yy(c,E.COST))}t.setActivityField(r,E.COST,i);let a=t.getActivity(r);if(!a)break;let s=a.parentId;if(!s||L(s))break;r=s}}function jc(e,t){let r=t.getActivity(e);if(!r)return;let n=r.parentId;!n||L(n)||Vi(n,t)}function Yy(e,t){let r=e[t];return typeof r=="number"&&Number.isFinite(r)?r:0}var on=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}),Hc="New Master Plan",Vc="New Activity";var Ky=["name","description","type","startDate","durationHours","constraintType","constraintDate","calendarId","assignedDefaultCalendar","autoScheduling","progress","cost","usedCost","realCost","workHours","realWorkHours","ponderator","hasCustomPonderator","customId","subcontractId","responsableIds","tagIds","isLookahead"],cn=new Set(Ky);function Gy(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"||!cn.has(r))throw new Error(`activity-create: rejected override key "${String(r)}" \u2014 not a creation-writable canonical field`);return e}function Yc(e,t){let r=e.parentId!=null?t.getActivity(e.parentId):null,n=Gy(e.activityOverrides??{}),i=e.numTasksInGantt===0?Hc:Vc,a=n.name??i,s=n.durationHours??e.sector.hoursPerDay,o=n.calendarId??e.sector.defaultCalendar,c=$y(r,e.fallbackStartDate,n.startDate),l={...on,...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});if(!n.startDate&&r&&wt(r.type)){let p=new Date(r.startDate);p.setUTCHours(0,0,0,0);let h=new Date(d);h.setUTCHours(0,0,0,0),h.getTime()!==p.getTime()&&(d=t.getClosestWorkTime({date:p,dir:X.FUTURE,task:l}))}let u=t.calculateEndDate({startDate:d,durationHours:l.durationHours,task:l});return{newTask:{...l,startDate:d,endDate:u,calendarDuration:bt({type:l.type,startDate:d,endDate:u}),newActivityIds:[...l.newActivityIds],pendingRequestIds:[...l.pendingRequestIds],responsableIds:[...l.responsableIds],tagIds:[...l.tagIds],baselinePoints:[...l.baselinePoints]}}}function $y(e,t,r){return r?new Date(r):e?new Date(e.startDate):t?new Date(t):new Date}function zy(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 Me(e){let t=e.getParent(e.parentId);if(!t)return null;let r=e.isCurrentlyLeaf!==void 0?e.isCurrentlyLeaf&&Ut(t.type):qy(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=Xn,(e.promotionSource??"create")==="create"&&(a.constraintType=K.ASAP,a.constraintDate=null,a.progress=0)),{parentId:e.parentId,fields:a,promotionSnapshot:zy(t)}}function qy(e){return Ut(e.type)&&(!Array.isArray(e.newActivityIds)||e.newActivityIds.length===0)}function ln(e,t,r,n){let i=t,a=i==="0",s=Yi(e,i);if(n!==void 0){let c=s.find(l=>l.id===n);if(c){let l=st(c),d=s.map(st).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=st(c),d=s.map(st).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(st))+1}var ce=Number.MAX_SAFE_INTEGER,Kc=Number.MAX_SAFE_INTEGER-1;function st(e){let t=e.correlativeId,r=typeof t=="number"?t:Number(t);return Number.isFinite(r)?r:ce}function Yi(e,t){return He(t,e)}function Gc(e,t,r){let n=e,i=Xt(e,r);for(;i!=null&&t.has(i);)n=i,i=Xt(i,r);return n}function dn(e,t,r){let n=new Set([e]),i=Bt(r.getActivity(e)?.parentId);for(;i!=="0"&&!n.has(i);){if(t.has(i))return!0;n.add(i),i=Bt(r.getActivity(i)?.parentId)}return!1}function Xt(e,t){let r=t.getActivity(e);if(!r)return null;let n=Bt(r.parentId),i=gt(n,t),a=i.findIndex(s=>String(s)===String(e));return a<=0?null:i[a-1]??null}function $c(e,t,r,n){let i=gt(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(st);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}var Jy=new Set([...[...cn].filter(e=>e!=="durationHours"),"durationDays"]);function un(e,t){if(e===void 0)return{ok:!0,value:{}};let r=Object.getPrototypeOf(e);if(r!==null&&r!==Object.prototype)return{ok:!1,reason:S.INVALID_VALUE};for(let a of Reflect.ownKeys(e))if(typeof a=="symbol"||!Jy.has(a))return{ok:!1,reason:S.INVALID_VALUE};let{durationDays:n,...i}=e;return n!==void 0&&(!Number.isFinite(n)||n<0)?{ok:!1,reason:S.INVALID_VALUE}:{ok:!0,value:{...i,...n===0&&(i.type===void 0||i.type==="task")?{type:"milestone"}:{},...n===void 0?{}:{durationHours:ee(n,t)}}}}async function ar(e,t,r={}){let{adapter:n,scheduler:i,sector:a,calendars:s,activityIdGen:o,uidGen:c}=t;r.skipCacheInvalidation||i.invalidateAllCaches();let l=Xy(e,n);if(!l.ok)return l;let{parent:d,anchorSiblingId:u,isRoot:f}=l,p=Qy(e.activityId,n,o,t.isActivityIdReserved),h=c.next(),A={id:p,parentId:f?null:e.parentId,sector:{id:a.id,hoursPerDay:a.hoursPerDay,defaultCalendar:am(s)},numTasksInGantt:n.activityCount(),nextUniqueCorrelativeId:h,activityOverrides:e.overrides??{}},T=Yc(A,{getActivity:v=>n.getActivity(v),calculateEndDate:v=>n.calculateEndDate(v),getClosestWorkTime:v=>n.getClosestWorkTime(v)}).newTask;T.realWorkHours=dt(T.workHours,T.progress),em(T,e,t,u,d,r);let g=r.insertionCorrelativeId??ln(n,f?"0":e.parentId,e.afterSiblingId,e.beforeSiblingId);T.correlativeId=g;let k=new Set([p]);d&&k.add(d.id);let m=d!==null&&n.getChildren(d.id).length===0,P=m?d?.customId:null,w=r.skipBeforeSnap?new Map:await $(n,k);return n.addActivity(T),rm(e,p,d,n,m),P&&t.customIdTracker.releaseCustomId(P),r.skipRollupCascades||(Mc(p,n),Uc(p,n),jc(p,n)),nm(n,p,w,k,r),{ok:!0,newId:p,parent:d,newActivity:T,beforeSnap:w,initialTouched:k}}function Xy(e,t){let r=L(e.parentId),n=r?null:t.getActivity(e.parentId);if(!r&&!n)return{ok:!1,reason:S.PARENT_NOT_FOUND};if(n!==null&&ye(n))return{ok:!1,reason:S.PARENT_FROZEN_BY_SIR};if(e.afterSiblingId!==void 0&&e.beforeSiblingId!==void 0)return{ok:!1,reason:S.ANCHOR_SIBLING_CONFLICT};let s=e.afterSiblingId??e.beforeSiblingId,o=Zy(e,t,r,s);return o||{ok:!0,parent:n,anchorSiblingId:s,isRoot:r}}function Zy(e,t,r,n){if(n===void 0)return null;let i=t.getActivity(n);if(!i)return{ok:!1,reason:S.ANCHOR_SIBLING_NOT_FOUND};let a=r?"0":e.parentId;return(i.parentId==null?"0":String(i.parentId))!==a?{ok:!1,reason:S.ANCHOR_SIBLING_WRONG_PARENT}:null}function Qy(e,t,r,n){let i=()=>{let a=r.next();for(;t.activityExists(a)||n(String(a));)a=r.next();return a};return e===void 0||t.activityExists(e)||n(String(e))?i():(r.bump(e),e)}function tm(e){let t=e.overrides?.customId;return typeof t=="string"?t:void 0}function em(e,t,r,n,i,a){let{adapter:s,customIdTracker:o}=r,c=tm(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 rm(e,t,r,n,i){if(!r)return;let a=Me({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 nm(e,t,r,n,i){if(i.skipCorrelativeRecompute)return;let a=at(e);i.skipBeforeSnap||Ee(e,a,new Set([String(t)]),r,n)}async function im(e,t,r,n,i){let{newId:a,newActivity:s,beforeSnap:o,initialTouched:c}=r,l={name:Ct.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 zc(e,t,r){let{adapter:n,scheduler:i,sector:a}=r,s=un(e.overrides,a.hoursPerDay);if(!s.ok)return s;let o=await ar({...e,overrides:s.value},r);if(!o.ok)return o;let{newId:c}=o,l=o.newActivity.autoScheduling;n.setActivityField(c,"autoScheduling",!1);let d;try{d=await Y({adapter:n,scheduler:i,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:"roots",recomputeParentsFrom:[c],now:r.now,options:t})}finally{n.setActivityField(c,"autoScheduling",l)}let{scheduledIds:u}=d;return{ok:!0,changes:await im(n,e,o,u,a.hoursPerDay)}}function am(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 Tt(e,t){ji(e,t),Hi(e,t),Vi(e,t)}function qc(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 Jc(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 sm(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 om(e,t,r){let n=e.startDate;return!r||!(n instanceof Date)?{}:{endDate:r(n,t)}}function We(e){if(e.remainingChildIds.length>0)return null;let t=e.parent,r=e.defaultDurationHours,n=Number.isFinite(r),i=sm(e.promotionSnapshot)??(n?{type:ve,durationHours:r,progress:0,autoScheduling:!0,constraintType:"asap",constraintDate:null,hasNewActivities:!1,...om(t,r,e.computeEndDate)}:{type:ve});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 Xc(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 Zc=200;async function Qc(e,t,r){let{adapter:n,scheduler:i,customIdTracker:a,sector:s}=r;if(i.invalidateAllCaches(),e.activityIds.length===0)return{ok:!1,reason:S.ACTIVITY_IDS_EMPTY};for(let v of e.activityIds)if(!n.getActivity(v))return{ok:!1,reason:S.ACTIVITY_NOT_FOUND};let o=qc(e.activityIds,n),c=Jc(o,n),l=new Set;for(let v of e.activityIds){let I=n.getActivity(v);if(!I)continue;let R=I.parentId;if(L(R))continue;let N=String(R);o.has(N)||l.add(N)}let d=new Set([...o,...l]),u=await $(n,d),f=new Map;for(let v of c){let I=n.getLink(v);I&&f.set(v,{...I})}let p=new Set,h=0;for(let v of o){h+=1,h%Zc===0&&await Z();let I=n.getActivity(v);if(!I)continue;let R=L(I.parentId)?null:n.getActivity(String(I.parentId)),N=R?.hasNewActivities===!0&&R.newActivityIds.some(z=>String(z)===String(v));(I.isNewActivity===!0||N)&&p.add(v);let x=I.customId;typeof x=="string"&&x.length>0&&a.releaseCustomId(x)}for(let v of c)n.removeLink(v);let A=Ki(n,o),C=0;for(let v of o)C+=1,C%Zc===0&&await Z(),n.removeActivity(v);for(let v of l){let I=n.getActivity(v);if(!I)continue;cm(I,p,n);let R=n.getChildren(v),N=We({parent:I,remainingChildIds:R.map(String),defaultDurationHours:s.hoursPerDay,promotionSnapshot:n.getPromotionSnapshot(v),computeEndDate:(x,z)=>n.calculateEndDate({startDate:x,durationHours:z,task:I}),idsRemoved:o});if(!N){Wr(v,n);continue}for(let[x,z]of Object.entries(N.fields))rt(n,v,x,z);if(I.customId==null||I.customId===""){let x=Xt(v,n),z=x?n.getActivity(x)?.customId:null,Q=a.generateCustomIdForRestoredChild(typeof z=="string"&&z?z:null);n.setActivityField(v,E.CUSTOM_ID,Q)}}for(let v of l)Tt(v,n);let T=at(n),{scheduledIds:g}=await Y({adapter:n,scheduler:i,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:"roots",recomputeParentsFrom:l,now:r.now,options:t}),k={name:Ct.ACTIVITY_DELETION,properties:{activity_ids:[...e.activityIds],cascade_count:o.size}};e.eventSource!==void 0&&(k.properties.event_source=e.eventSource);let m=new Map;for(let[v,I]of f)m.set(v,I);let P=new Map;for(let v of o){let I=u.get(String(v));I&&P.set(String(v),I)}let w=await B(n,{source:e,beforeSnap:u,touchedIds:d,scheduledIds:g,sirDetection:"after-diff",links:lm(f),trackingEvents:[k],hoursPerDay:s.hoursPerDay,correlativeShifts:T});return{ok:!0,changes:A.length>0?{...w,viewState:A}:w,__beforeSnap:P,__beforeLinks:m}}function cm(e,t,r){let n=Xc({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 lm(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 rl(e,t,r){let n=dm(e,r);if(n)return{ok:!1,reason:n};let i=fm(e,r);if(!i.ok)return i;let a=e.mode==="replace"?new Set(r.adapter.getAllIds().map(m=>String(m))):new Set,s=e.mode==="replace"?await $(r.adapter,a):new Map,o=e.mode==="replace"?vm(r):new Map,c=e.mode==="replace"?Ki(r.adapter,a):[];r.scheduler.invalidateAllCaches();let l=[];if(e.mode==="replace"){for(let m of o.keys()){let P=jt({kind:"delete",linkId:m},{port:r.adapter});if(!P.applied)return{ok:!1,reason:P.rejected??S.INVALID};l.push({op:{kind:"delete",linkId:m},finalLinkId:m,rejected:null})}for(let m of a){let P=r.adapter.getActivity(m)?.customId;typeof P=="string"&&P.length>0&&r.customIdTracker.releaseCustomId(P),r.adapter.removeActivity(m)}}let d=await gm(e,i.plan.items,r);if(!d.ok)return d;let u=nl(e)?[]:at(r.adapter),f=new Set(i.plan.items.map(m=>String(m.activityId))),p=u.filter(m=>!f.has(m.activityId)),h=e.mode==="replace"?new Set(a):new Set;Ee(r.adapter,u,f,s,h);for(let m of i.plan.items)h.add(String(m.activityId));let A=i.plan.links.map(m=>({operation:{kind:"create",source:m.source,target:m.target,type:m.type,lag:vt(m.lag,r.sector.hoursPerDay)},linkId:m.linkId})),C=Lr(A,{port:r.adapter,preserved:o});if(!C.applied)return{ok:!1,reason:C.rejected??S.INVALID};for(let{operation:m,linkId:P}of A)l.push({op:m,finalLinkId:P,rejected:null});let T=i.plan.items.map(m=>m.activityId),{scheduledIds:g}=await Y({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:T,now:r.now,options:t}),k=await B(r.adapter,{source:e,beforeSnap:s,touchedIds:h,scheduledIds:g,links:xe(l,o,r.adapter),hoursPerDay:r.sector.hoursPerDay,correlativeShifts:p,...e.mode==="replace"?{sirDetection:"after-diff"}:{}});return{ok:!0,changes:c.length>0?{...k,viewState:c}:k,...e.mode==="replace"?{__beforeSnap:s,__beforeLinks:Am(o)}:{}}}function dm(e,t){if(e.mode!=="append"&&e.mode!=="replace")return S.INVALID;let r=new Set,n=new Set;for(let a of e.items){if(a.batchId.length===0||r.has(a.batchId))return S.INVALID;if(r.add(a.batchId),a.index!==void 0&&(!Number.isInteger(a.index)||a.index<0))return S.INVALID;if(a.activityId!==void 0){let s=String(a.activityId);if(s.length===0||s==="0"||n.has(s))return S.INVALID;n.add(s)}}for(let a of e.items)if(!Gi(a.parent,!0,e.mode,r,t))return S.PARENT_NOT_FOUND;if(um(e.items))return S.INVALID;let i=new Set;for(let a of e.links){if(!Object.values(W).includes(a.type)||!Number.isFinite(a.lag))return Number.isFinite(a.lag)?S.INVALID_LINK_TYPE:S.INVALID_LINK_LAG;if(!Gi(a.source,!1,e.mode,r,t)||!Gi(a.target,!1,e.mode,r,t))return S.ACTIVITY_NOT_FOUND;if(a.linkId!==void 0){let s=String(a.linkId);if(s.length===0||i.has(s))return S.INVALID;i.add(s)}}return null}function Gi(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 um(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 fm(e,t){let r=new Map;for(let d of e.items){let u=un(d.overrides,t.sector.hoursPerDay);if(!u.ok)return u;r.set(d.batchId,u.value)}let n=new Map,i=new Set;for(let d of e.items){let u=pm(d.activityId,e.mode,i,t);i.add(String(u)),n.set(d.batchId,u)}let a=new Set,s=e.links.map(d=>{let u=hm(d.linkId,e.mode,a,t);return a.add(String(u)),u}),o=ym(e,n,t),c=[];for(let d of e.items){let u=n.get(d.batchId),f=o.get(d.batchId);if(u===void 0||f===void 0)return{ok:!1,reason:S.INVALID};let p=typeof d.parent=="string"?null:d.parent.batchId,h=typeof d.parent=="string"?d.parent:n.get(d.parent.batchId);if(h===void 0)return{ok:!1,reason:S.PARENT_NOT_FOUND};c.push({input:d,activityId:u,parentId:h,parentBatchId:p,insertionCorrelativeId:f,overrides:r.get(d.batchId)??{}})}let l=[];for(let[d,u]of e.links.entries()){let f=el(u.source,n),p=el(u.target,n),h=s[d];if(f===null||p===null||h===void 0)return{ok:!1,reason:S.ACTIVITY_NOT_FOUND};l.push({source:f,target:p,type:u.type,lag:u.lag,linkId:h})}return{ok:!0,plan:{items:c,links:l}}}function pm(e,t,r,n){if(e!==void 0&&(t==="replace"||n.adapter.getActivity(e)===null&&!n.isActivityIdReserved(String(e)))&&!r.has(String(e)))return n.activityIdGen.bump(e),e;let a=n.activityIdGen.next();for(;r.has(String(a))||t==="append"&&(n.adapter.getActivity(a)!==null||n.isActivityIdReserved(String(a)));)a=n.activityIdGen.next();return a}function hm(e,t,r,n){if(e!==void 0&&(t==="replace"||n.adapter.getLink(e)===null&&!n.isLinkIdReserved(String(e)))&&!r.has(String(e)))return n.linkIdGen.bump(e),e;let a=n.linkIdGen.next();for(;r.has(String(a))||t==="append"&&(n.adapter.getLink(a)!==null||n.isLinkIdReserved(String(a)));)a=n.linkIdGen.next();return a}function ym(e,t,r){if(nl(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)?[]:Yi(r.adapter,d).sort((A,C)=>st(A)-st(C)||String(A.id).localeCompare(String(C.id))).map(A=>String(A.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?tl(c[d-1],r):null,p=l<c.length?tl(c[l],r):null;for(let h=0;h<u;h+=1){let A=c[d+h],C=s.get(A);C!==void 0&&a.set(C,mm(f,p,h+1,u))}}}return a}function nl(e){return e.mode==="append"&&e.items.every(t=>t.parent==="0"&&t.index===void 0)}function tl(e,t){let r=t.adapter.getActivity(e);return r?st(r):0}function mm(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 gm(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 ar({kind:"activity-create",parentId:o.parentId,activityId:o.activityId,overrides:o.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:S.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)),Tt(o,r.adapter))}return{ok:!0}}function el(e,t){return typeof e=="string"?e:t.get(e.batchId)??null}function vm(e){return new Map(e.adapter.getAllLinks().map(t=>[String(t.id),{...t}]))}function Am(e){return new Map(Array.from(e,([t,r])=>[String(t),r]))}function il(e,t){let{adapter:r}=t,n=e.activityId,i=r.getActivity(n);if(!i)return{ok:!1,reason:S.ACTIVITY_NOT_FOUND};let a=i.pendingRequestIds??[],s=e.pendingRequests.map(l=>l.id);r.setActivityField(e.activityId,"pendingRequestIds",s);let o=r.getActivity(n);if(!o)return{ok:!1,reason:S.ACTIVITY_NOT_FOUND};let c={id:n,kind:"updated",fields:{pendingRequestIds:{before:a,after:s}},after:J(o)};return{ok:!0,changes:{source:e,activities:[c],links:[],calendars:[],trackingEvents:[]}}}function al(e){for(let t of Cm(e))ol(t,e)}function sl(e,t){for(let r of e)ol(r,t)}function Cm(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,Im(n,e));return[...t].sort((n,i)=>(r.get(i)??0)-(r.get(n)??0))}function Im(e,t){let r=0,n=e;for(;n&&n!=="0"&&t.getActivity(n);)r+=1,n=t.getParentId(n);return r}function ol(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=Ie(n);i!==null&&t.setActivityField(e,_.PROGRESS,Mr(i))}function cl(e){let t=new Map;for(let r of e){let n=r.proplannerId;typeof n=="number"&&Number.isSafeInteger(n)&&n>0&&t.set(n,String(r.id))}return t}function ll(e,t,r){let n=new Set(t.map(({id:i})=>String(i)));for(let i of e)if((i.proplannerId==null||i.proplannerId===0)&&!n.has(String(i.id)))throw new Error(`persistence-acknowledge: missing ${r} proplannerId for "${String(i.id)}"`)}function Sm(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!==0&&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 dl(e,t,r,n){let i=new Set,a=new Set;for(let s of e)Sm(s,t,r,n,i,a)}function km(e,t){let r=new Set;for(let n of e){let i=String(n.activityId);if(i.length===0||r.has(i))throw new Error(`persistence-acknowledge: duplicate or empty reconciled activity id "${i}"`);if(!Number.isFinite(n.progress)||n.progress<0||n.progress>100)throw new Error(`persistence-acknowledge: invalid reconciled progress ${String(n.progress)} for "${i}"`);if(!t.adapter.getActivity(i))throw new Error(`persistence-acknowledge: unknown reconciled activity id "${i}"`);r.add(i)}}async function $i(e,t){let r=e.filter(o=>{let c=t.adapter.getActivity(String(o.activityId));return c!==null&&c.progress!==o.progress}),n=new Set(r.map(o=>String(o.activityId))),i=Je(t.adapter,n),a=new Set(n);for(let o of i)a.add(String(o));let s=await $(t.adapter,a);return t.adapter.batchUpdate(()=>{for(let o of r)t.adapter.setActivityField(String(o.activityId),"progress",o.progress);sl(i,t.adapter),Wc(n,i,t.adapter)}),[...await $r(t.adapter,s,a)]}async function ul(e,t){let r=e.activities??[],n=e.links??[],i=e.reconciledProgress??[];km(i,t);let a=t.adapter.getAllActivities(),s=t.adapter.getAllLinks(),o=cl(a),c=cl(s);dl(r,"activity",u=>{let f=t.adapter.getActivity(u);return{exists:f!==null,current:f?.proplannerId??null}},o),dl(n,"link",u=>{let f=t.adapter.getLink(u);return{exists:f!==null,current:f?.proplannerId??null}},c),ll(a,r,"activity"),ll(s,n,"link");let l=await $i(i,t),d=[];return t.adapter.batchUpdate(()=>{for(let u of r){let f=t.adapter.getActivity(u.id);if(!f||f.proplannerId===u.proplannerId)continue;let p=f.proplannerId;t.adapter.setActivityField(u.id,"proplannerId",u.proplannerId),l.push({id:u.id,kind:"updated",fields:{proplannerId:{before:p,after:u.proplannerId}},after:{...f,proplannerId:u.proplannerId}})}for(let u of n){let f=t.adapter.getLink(u.id);if(!f||f.proplannerId===u.proplannerId)continue;let p=f.proplannerId;t.adapter.setLinkProplannerId(u.id,u.proplannerId),d.push({id:u.id,kind:"updated",fields:{proplannerId:{before:p,after:u.proplannerId}},after:{...f,proplannerId:u.proplannerId}})}}),{ok:!0,changes:{source:e,activities:l,links:d,calendars:[],trackingEvents:[]}}}async function fl(e,t,r){if(Dm(e))return{ok:!1,reason:S.INVALID_VALUE};let n=[...new Set(e.activityIds.map(String))];if(e.acknowledgePersistedLookahead===!0&&n.some(o=>!r.isActivityIdReserved(o)))return{ok:!1,reason:S.INVALID};let a=n.map(o=>r.adapter.getActivity(o));if(a.some(o=>!o))return{ok:!1,reason:S.ACTIVITY_NOT_FOUND};let s=[];for(let[o,c]of n.entries()){let l=a[o];if(!l)continue;let d={};l.isLookahead!==e.isLookahead&&(d.isLookahead={before:l.isLookahead,after:e.isLookahead},r.adapter.setActivityField(c,"isLookahead",e.isLookahead)),l.hasLookaheadTasks!==e.hasLookaheadTasks&&(d.hasLookaheadTasks={before:l.hasLookaheadTasks,after:e.hasLookaheadTasks},r.adapter.setActivityField(c,"hasLookaheadTasks",e.hasLookaheadTasks)),Object.keys(d).length!==0&&s.push({id:c,kind:"updated",fields:d,after:{...l,isLookahead:e.isLookahead,hasLookaheadTasks:e.hasLookaheadTasks}})}return e.persistedProgress!==void 0&&(await $i([{activityId:n[0],progress:e.persistedProgress}],r)).length>0?(await Y({adapter:r.adapter,scheduler:r.scheduler,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:null,recomputeParentsFrom:[],now:r.now,options:t}),{ok:!0,changes:await B(r.adapter,{source:e,beforeSnap:new Map,touchedIds:[],scheduledIds:[],hoursPerDay:r.sector.hoursPerDay})}):{ok:!0,changes:{source:e,activities:s,links:[],calendars:[],trackingEvents:[]}}}function Dm(e){let t=e.persistedProgress;return t!==void 0&&(e.activityIds.length!==1||!Number.isFinite(t)||t<0||t>100)}function fn(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)||(pl(s,a,t)||pl(a,s,t))&&n.push(String(i.id))}return n}function pl(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}function pn(e,t){let r=e.getAllLinks();return!ze({port:e,currentLinks:r,proposedLinks:r,proposal:{reparented:t}}).ok}function hn(e,t){let r=new Set;if(e.length===0)return r;let n=new Map(e.map(a=>[a.activityId,a.newParentId]));if(!pn(t,n))return r;let i=new Map;for(let a of e){let s=new Map(i);if(s.set(a.activityId,a.newParentId),pn(t,s)){r.add(a.activityId);continue}i.set(a.activityId,a.newParentId)}return r}async function hl(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:S.ACTIVITY_NOT_FOUND};let o=L(e.parentId);if(!o&&!n.getActivity(e.parentId))return{ok:!1,reason:S.PARENT_NOT_FOUND};if(!o&&(e.parentId===e.activityId||n.isChildOf(e.parentId,e.activityId)))return{ok:!1,reason:S.CANNOT_MOVE_INTO_OWN_DESCENDANT};if(e.afterSiblingId!==void 0&&e.beforeSiblingId!==void 0)return{ok:!1,reason:S.ANCHOR_SIBLING_CONFLICT};let c=e.afterSiblingId??e.beforeSiblingId;if(c!==void 0){let P=n.getActivity(c);if(!P)return{ok:!1,reason:S.ANCHOR_SIBLING_NOT_FOUND};if((P.parentId===null?"0":String(P.parentId))!==e.parentId)return{ok:!1,reason:S.ANCHOR_SIBLING_WRONG_PARENT}}let l=s.parentId,d=Bt(l),u=String(e.parentId),f=d!==u;if(f){let P=new Map([[e.activityId,o?null:e.parentId]]);if(pn(n,P))return{ok:!1,reason:S.HIERARCHY_CYCLE}}let p=new Set([e.activityId]);f?(d!=="0"&&p.add(d),u!=="0"&&p.add(u)):d!=="0"&&p.add(d);let h=await $(n,p);f&&n.setActivityField(e.activityId,E.PARENT,u);let A=ln(n,e.parentId,e.afterSiblingId,e.beforeSiblingId);if(n.setActivityField(e.activityId,E.CORRELATIVE_ID,A),f){if(!o){let P=n.getActivity(e.parentId);if(P){let w=P.customId,v=Ut(P.type)&&n.getChildren(e.parentId).filter(R=>R!==e.activityId).length===0,I=Me({parentId:e.parentId,newChildId:e.activityId,getParent:R=>n.getActivity(R)??null,isCurrentlyLeaf:v,promotionSource:"reparent"});if(I){for(let[R,N]of Object.entries(I.fields))rt(n,I.parentId,R,N);I.promotionSnapshot&&n.setPromotionSnapshot(I.parentId,I.promotionSnapshot),I.fields.customId===null&&sn(w,r.customIdTracker)}}}if(d!=="0"){let P=n.getActivity(d);if(P){let w=n.getChildren(d),v=We({parent:P,remainingChildIds:w.map(String),defaultDurationHours:a.hoursPerDay,promotionSnapshot:n.getPromotionSnapshot(d),computeEndDate:(I,R)=>n.calculateEndDate({startDate:I,durationHours:R,task:P}),idsRemoved:new Set([e.activityId])});if(v){for(let[z,Q]of Object.entries(v.fields))rt(n,d,z,Q);let I=Xt(d,n),R=I?n.getActivity(I)?.customId:null,N=typeof R=="string"&&R?R:null,x=r.customIdTracker.generateCustomIdForRestoredChild(N);n.setActivityField(d,E.CUSTOM_ID,x)}}}}f&&(d!=="0"&&Tt(d,n),o||Tt(e.parentId,n));let C=at(n);for(let P of C){if(p.add(P.activityId),h.has(P.activityId))continue;let w=n.getActivity(P.activityId);if(!w)continue;let v=J(w);P.before!==void 0&&(v.correlativeId=P.before),h.set(P.activityId,v)}let T=f&&d!=="0"?n.getChildren(d).map(String):[],{scheduledIds:g}=await Y({adapter:n,scheduler:i,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:e.activityId,recomputeParentsFrom:[e.activityId,e.parentId,...T],now:r.now,options:t,recomputeParentProgress:f}),k=f?fn([e.activityId],n):[],m={name:Ct.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:k.map(String)}};return e.eventSource!==void 0&&(m.properties.event_source=e.eventSource),{ok:!0,changes:await B(n,{source:e,beforeSnap:h,touchedIds:p,scheduledIds:g,sirDetection:"before-diff",trackingEvents:[m],hoursPerDay:a.hoursPerDay})}}function yn(e,t){let r=new Set(e),n=[],i=[],a=new Set,s=new Set(r),o=[...e].sort((d,u)=>{let f=t.getActivity(d),p=t.getActivity(u),h=f?st(f):ce,A=p?st(p):ce;return h-A});for(let d of o){if(!t.getActivity(d)){n.push({activityId:d,reason:S.ACTIVITY_NOT_FOUND}),s.delete(d);continue}if(dn(d,a,t))continue;let f=Ya(d,s,t);if(f==null){n.push({activityId:d,reason:S.INDENT_NO_ELIGIBLE_SIBLING}),s.delete(d);continue}let p=t.getActivity(d)?.parentId,h=L(p)?"0":String(p);i.push({activityId:d,newParentId:f,oldParentId:h}),a.add(d)}let c=hn(i,t);for(let d of c)n.push({activityId:d,reason:S.HIERARCHY_CYCLE});let l=i.filter(d=>!c.has(d.activityId));return{moves:i,cyclicMoveIds:c,allowedMoves:l,failed:n}}async function yl(e,t,r){let{adapter:n,scheduler:i,sector:a}=r;if(i.invalidateAllCaches(),e.activityIds.length===0)return{ok:!1,reason:S.ACTIVITY_IDS_EMPTY};let s=new Set,o=[],c=yn(e.activityIds,n),l=[...c.failed];for(let g of c.moves)s.add(String(g.activityId)),s.add(String(g.newParentId)),g.oldParentId!=="0"&&s.add(String(g.oldParentId));let d=c.allowedMoves,u=await $(n,s);for(let{activityId:g,newParentId:k}of d)n.setActivityField(g,E.PARENT,k),n.setActivityField(g,E.CORRELATIVE_ID,Kc),o.push(g);let f=new Set;for(let{activityId:g,newParentId:k}of d){if(f.has(k))continue;f.add(k);let m=n.getActivity(k);if(!m)continue;let P=m.customId,w=Ut(m.type)&&n.getChildren(k).filter(R=>!o.includes(R)).length===0,v=m.hasNewActivities&&m.newActivityIds.some(R=>String(R)===String(g)),I=Me({parentId:k,newChildId:g,getParent:R=>n.getActivity(R)??null,isCurrentlyLeaf:w,promotionSource:"reparent"});if(I){for(let[R,N]of Object.entries(I.fields))rt(n,I.parentId,R,N);I.promotionSnapshot&&n.setPromotionSnapshot(I.parentId,I.promotionSnapshot),v||(n.setActivityField(k,E.HAS_NEW_ACTIVITIES,!1),n.setActivityField(k,E.NEW_ACTIVITIES_ARRAY,[]))}n.setActivityField(k,E.CONSTRAINT_TYPE,"asap"),n.setActivityField(k,E.CONSTRAINT_DATE,null),n.setActivityField(k,E.CUSTOM_ID,null),sn(P,r.customIdTracker)}let p=new Set;for(let g of d)g.oldParentId!=="0"&&p.add(g.oldParentId),p.add(g.newParentId);for(let g of p)Tt(g,n);let h=at(n);for(let g of h){if(s.add(g.activityId),u.has(g.activityId))continue;let k=n.getActivity(g.activityId);if(!k)continue;let m=J(k);g.before!==void 0&&(m.correlativeId=g.before),u.set(g.activityId,m)}let{scheduledIds:A}=await Y({adapter:n,scheduler:i,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:null,recomputeParentsFrom:o,now:r.now,options:t}),C=fn(o,n),T={name:Ct.ACTIVITY_INDENT,properties:{activity_ids:o,failed:l.map(g=>({activity_id:g.activityId,reason:g.reason})),invalid_link_ids:C}};return e.eventSource!==void 0&&(T.properties.event_source=e.eventSource),{ok:!0,activityVerdicts:e.activityIds.map(g=>{let k=l.find(m=>String(m.activityId)===String(g));return k?{activityId:String(g),ok:!1,reason:k.reason}:{activityId:String(g),ok:!0}}),changes:await B(n,{source:e,beforeSnap:u,touchedIds:s,scheduledIds:A,trackingEvents:[T],hoursPerDay:a.hoursPerDay})}}async function ml(e,t,r){let{adapter:n,scheduler:i,sector:a}=r;if(i.invalidateAllCaches(),e.activityIds.length===0)return{ok:!1,reason:S.ACTIVITY_IDS_EMPTY};let s=new Set(e.activityIds),o=new Map,c=new Map;for(let v of e.activityIds){let I=v;n.getActivity(I)&&(o.set(I,Vn(I,n)),c.set(I,Gc(I,s,n)))}let l=new Set,d=[],u=[],f=new Set,p=[],h=new Set,A=[...e.activityIds].sort((v,I)=>{let R=n.getActivity(v),N=n.getActivity(I),x=R?st(R):ce,z=N?st(N):ce;return x-z});for(let v of A){let I=v,R=n.getActivity(I);if(!R){d.push({activityId:I,reason:S.ACTIVITY_NOT_FOUND});continue}if(dn(I,h,n))continue;let N=R.parentId;if(L(N)){d.push({activityId:I,reason:S.OUTDENT_ROOT_LEVEL_NOT_EDITABLE});continue}let x=String(N),z=n.getActivity(x);if(!z){d.push({activityId:I,reason:S.ACTIVITY_NOT_FOUND});continue}let Q=z.parentId;if(L(Q)){d.push({activityId:I,reason:S.OUTDENT_ROOT_LEVEL_NOT_EDITABLE});continue}let lt=String(Q),pt=Vn(x,n)+1,nt=c.get(I);if(nt!=null&&s.has(nt)){let fe=o.get(nt)??-1,pe=o.get(I)??-1;fe>=0&&pe>=0&&(pt+=pe-fe)}p.push({activityId:I,grandparentKey:lt,oldParentKey:x,targetIndexInGrandparent:pt}),h.add(I),l.add(String(I)),l.add(String(x)),lt!=="0"&&l.add(String(lt)),f.add(x)}let C=hn(p.map(v=>({activityId:v.activityId,newParentId:v.grandparentKey})),n);for(let v of C)d.push({activityId:v,reason:S.HIERARCHY_CYCLE});let T=p.filter(v=>!C.has(v.activityId)),g=await $(n,l);for(let v of T){n.setActivityField(v.activityId,E.PARENT,v.grandparentKey);let I=$c(n,v.grandparentKey,v.targetIndexInGrandparent,v.activityId);n.setActivityField(v.activityId,E.CORRELATIVE_ID,I),u.push(v.activityId)}for(let v of f){let I=n.getActivity(v);if(!I)continue;let R=n.getChildren(v),N=We({parent:I,remainingChildIds:R.map(String),defaultDurationHours:a.hoursPerDay,promotionSnapshot:n.getPromotionSnapshot(v),computeEndDate:(pt,nt)=>n.calculateEndDate({startDate:pt,durationHours:nt,task:I}),idsRemoved:new Set(T.filter(pt=>pt.oldParentKey===v).map(pt=>pt.activityId))});if(!N){Wr(v,n);continue}for(let[pt,nt]of Object.entries(N.fields))rt(n,v,pt,nt);let x=Xt(v,n),z=x?n.getActivity(x)?.customId:null,Q=typeof z=="string"&&z?z:null,lt=r.customIdTracker.generateCustomIdForRestoredChild(Q);n.setActivityField(v,E.CUSTOM_ID,lt)}let k=new Set;for(let v of f)k.add(String(v));for(let v of T)v.grandparentKey!=="0"&&k.add(String(v.grandparentKey));for(let v of k)Tt(v,n);let m=at(n);for(let v of m){if(l.add(v.activityId),g.has(v.activityId))continue;let I=n.getActivity(v.activityId);if(!I)continue;let R=J(I);v.before!==void 0&&(R.correlativeId=v.before),g.set(v.activityId,R)}let{scheduledIds:P}=await Y({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}),w={name:Ct.ACTIVITY_OUTDENT,properties:{activity_ids:u.map(String),failed:d.map(v=>({activity_id:String(v.activityId),reason:v.reason}))}};return e.eventSource!==void 0&&(w.properties.event_source=e.eventSource),{ok:!0,activityVerdicts:e.activityIds.map(v=>{let I=d.find(R=>String(R.activityId)===String(v));return I?{activityId:String(v),ok:!1,reason:I.reason}:{activityId:String(v),ok:!0}}),changes:await B(n,{source:e,beforeSnap:g,touchedIds:l,scheduledIds:P,trackingEvents:[w],hoursPerDay:a.hoursPerDay})}}async function gl(e,t,r){let{adapter:n,ctx:i,scheduler:a,sector:s}=r;if(e.newValue!==0&&e.newValue!==100)return{ok:!1,reason:S.INVALID_PROGRESS_VALUE};let o=i.activityReader.getActivity(e.activityId);if(!o)return{ok:!1,reason:S.ACTIVITY_NOT_FOUND};let c=$t(_.PROGRESS);if(!c)throw new Error("[ScheduleCore] progressPipeline not registered \u2014 cannot dispatch activity-set-progress");let l=c.canEdit(o,i.hierarchy);if(!l.allowed&&!(e.origin==="action-button"&&(l.reason==="has_lookahead_tasks"||l.reason==="summary")))return{ok:!1,reason:l.reason,...l.alertKey?{alertKey:l.alertKey}:{}};let d=c.transform(o,e.newValue,i,e.newValue),u=zt(e.activityId,d),f=await $(n,u);qt(n,e.activityId,d),Vt(e.activityId,d.postProcessors??[],n);let{scheduledIds:p}=await Y({adapter:n,scheduler:a,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:d.needsAutoSchedule?e.activityId:null,recomputeParentsFrom:[],collectDirty:A=>zr(e.activityId,u,A),now:r.now,options:t}),h=(d.trackingEvents??[]).map(A=>({name:A.name,properties:A.properties??{}}));return{ok:!0,changes:await B(n,{source:e,beforeSnap:f,touchedIds:u,scheduledIds:p,trackingEvents:h,hoursPerDay:s.hoursPerDay})}}async function vl(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 h of e.edits){let A=Tm(h,r);if(s.push(A.verdict),!A.verdict.ok||!A.changes)continue;let C=zt(h.activityId,A.changes);_m(o,C,r);for(let m of C)c.add(m);let T=Fe(n,h.activityId),g=Gr(n,String(h.activityId));qt(n,h.activityId,A.changes),Vt(h.activityId,A.changes.postProcessors??[],n,g),d.push(...Ne(T,n,h.activityId)),f||=!!A.changes.needsAutoSchedule;for(let m of A.changes.trackingEvents??[])l.push({name:m.name,properties:m.properties??{}});let k=be(h.activityId,A.changes.constraintWarning);k&&u.push(k)}let{scheduledIds:p}=await Y({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 Tm(e,t){let{ctx:r}=t,n=e.activityId,i=$t(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??S.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??S.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??S.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 _m(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 zi=_.CUSTOM_ID;async function Al(e,t,r){let{adapter:n,scheduler:i,sector:a}=r;e.edits.some(k=>k.column===_.DURATION)&&i.invalidateExpandedLinksCache();let o=[],c=new Map,l=new Map,d=new Set,u=new Set,f=[],p=[],h=[],A=!1;for(let k of e.edits){let m=Pm(k,r);if(o.push(m.verdict),!m.verdict.ok||!m.changes)continue;let P=be(k.activityId,m.changes.constraintWarning);P&&h.push(P);let w=zt(k.activityId,m.changes);Lm(c,w,r);for(let x of w)u.add(x);Em(l,k,c),rn(k.column)&&d.add(String(k.activityId));let v=Fe(n,k.activityId),I=Gr(n,String(k.activityId)),R=Rm(k,r),N=m.changes;qt(n,k.activityId,N),Vt(k.activityId,m.changes.postProcessors??[],n,I),bm(k,R,r),p.push(...Ne(v,n,k.activityId)),A||=!!m.changes.needsAutoSchedule;for(let x of m.changes.trackingEvents??[])f.push({name:x.name,properties:x.properties??{}})}let C={action:e,autoscheduleFrom:A?"roots":null,recomputeParentsFrom:u,now:r.now,options:t},T=l.size>0,{scheduledIds:g}=await(T?an({adapter:n,scheduler:i,sector:a,defaultBaseCalendarId:r.defaultBaseCalendarId},{postMutationArgs:C,revertTargets:[...l].filter(([k])=>!d.has(k)).map(([k,m])=>({activityId:k,priorConstraintDate:m})),revert:(k,m)=>nn(k,m,n,r.ctx.calendars)}):Y({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:g,sirDetection:"before-diff",links:p,trackingEvents:f,warnings:h,hoursPerDay:a.hoursPerDay})}}function Pm(e,t){let{ctx:r}=t,n=e.activityId,i=$t(e.column);if(!i)return{verdict:{activityId:n,ok:!1,reason:S.NO_PIPELINE_FOR_COLUMN},changes:null};let a=r.activityReader.getActivity(e.activityId);if(!a)return{verdict:{activityId:n,ok:!1,reason:S.ACTIVITY_NOT_FOUND},changes:null};let s=i.canEdit(a,r.hierarchy);if(!s.allowed)return{verdict:{activityId:n,ok:!1,reason:s.reason??S.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??S.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??S.INVALID,...l.notification?.messageKey?{alertKey:l.notification.messageKey}:{}},changes:null};if(e.column===zi&&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:S.CUSTOM_ID_DUPLICATE},changes:null}}let d=i.transform(a,o.value,r,o.raw);return{verdict:{activityId:n,ok:!0},changes:d}}function Rm(e,t){if(e.column!==zi)return null;let r=t.adapter.getActivity(e.activityId),n=r?r.customId:null;return typeof n=="string"?n:null}function bm(e,t,r){if(e.column!==zi)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 Em(e,t,r){if(!en(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 Lm(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 Cl(e){return typeof e=="string"&&e.length>0?Nt(e):e instanceof Date?e:null}function qi(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 mn(e,t){let r=qi(e.duration),n=qi(e.cost),i=qi(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:Cl(e.start_date),endDate:Cl(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 Il(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=>mn(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 wm(e){let t=ut(e);return t?{startDate:t.startDate,endDate:t.endDate,durationDays:t.durationDays,cost:t.cost,workHours:t.workHours}:null}function Sl(e){let t=[];return e.forEachActivity((r,n)=>{let i=wm(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 gn(e,t,r,n,i=null){let a=new Set;for(let s of Il(e,t,n))a.add(s);if(r)for(let s of we(e,r,i))a.add(s);for(let s of Sl(e))a.add(s);for(let s of Oe(e))a.add(s);return[...a]}function kl(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=Om(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,_.PONDERATOR,s*u)}else(!Array.isArray(l)||l.length===0)&&r.setActivityField(o,_.PONDERATOR,0)}}function Om(e,t,r){let n=r.getActivity(e);if(!n)return 0;let i=ut(n);if(!i)return 0;if(t==="COST")return vn(i.cost);if(t==="HH")return vn(i.workHours);let a=n.type;return a==="project"?Dl(e,r):a==="milestone"?0:vn(i.durationDays)}function Dl(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+=Dl(String(n),t):s!=="milestone"&&(r+=vn(a.durationDays))}return r}function vn(e){let t=typeof e=="string"?parseFloat(e):e;return typeof t=="number"&&Number.isFinite(t)?t:0}function Tl(e,t){t.forEachActivity((r,n)=>{t.setActivityField(n,_.PONDERATOR,0)}),t.forEachActivity((r,n)=>{t.getChildren(n).length>0&&kl(String(n),e,t)})}function An(e,t){Tl(t,e.adapter),al(e.adapter),e.now&&(we(e.adapter,e.now,e.defaultBaseCalendarId??null),ie(e.adapter,e.now)),Oe(e.adapter),e.now&&Mt(e.adapter,e.sector.statusCriteria)}function _l(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 Pl(e,t){let r=await $(t.adapter,new Set(t.adapter.getAllIds())),n=_l(t),i=gn(t.adapter,e.points,t.now,t.reporter,t.defaultBaseCalendarId??null);return _l(t)!==n&&An(t,t.sector.activityCreter??"DURATION"),{ok:!0,changes:await B(t.adapter,{source:e,beforeSnap:r,touchedIds:i,scheduledIds:[],hoursPerDay:t.sector.hoursPerDay})}}function xm(e){if(!(e==="DURATION"||e==="COST"||e==="HH"))throw new Error(`ponderator-criterion-set: invalid criterion "${String(e)}"`)}async function Rl(e,t){xm(e.criterion);let r=new Set(t.adapter.getAllIds()),n=await $(t.adapter,r);return An(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 bl(e,t){let r=gr(e.criteria),n=new Set(t.adapter.getAllIds()),i=await $(t.adapter,n),a=Mt(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})}}var El=["name","description","type","startDate","durationHours","constraintType","constraintDate","calendarId","cost","hasCustomPonderator","subcontractId","responsableIds","tagIds"];function Fm(e){let t={};for(let r of El)Object.assign(t,{[r]:b(e[r])});return t}function Nm(e,t){let r=[],n=i=>{t.has(String(i))&&r.push(i);for(let a of e.getChildren(i))n(a)};for(let i of e.getRootIds())n(i);return r}function Ll(e,t){let r=new Set(t.adapter.checkedIds().map(String));if(r.size===0)return{ok:!1,reason:S.NO_ACTIVITY_SELECTION};let n=Nm(t.adapter,r);t.clipboard.value={activities:n.map(a=>{let s=t.adapter.getActivity(a);if(s===null)throw new Error(`Selected activity ${a} is missing`);return{originalId:a,originalParentId:s.parentId??"0",overrides:Fm(s)}}),links:t.adapter.getAllLinks().filter(a=>r.has(String(a.source))&&r.has(String(a.target))).map(a=>b(a))};let i=pr({kind:"selection-replace",activityIds:[]},{adapter:t.adapter});return i.ok?{...i,changes:{...i.changes,source:e}}:i}function wl(e,t){return t.value=null,{ok:!0,changes:{source:e,activities:[],links:[],calendars:[],trackingEvents:[]}}}function Mm(e,t){let r=t.getActivity(e);return r?{ok:!0,parentId:r.parentId==null?"0":String(r.parentId)}:{ok:!1,reason:S.ANCHOR_SIBLING_NOT_FOUND}}var Ol=()=>({ok:!1,reason:S.ACTIVITY_PASTE_INVARIANT_FAILED});async function xl(e,t,r){let n=r.activityClipboard.value;if(n===null)return{ok:!1,reason:S.CLIPBOARD_EMPTY};let i=Mm(e.destination.afterSiblingId,r.adapter);if(!i.ok)return i;let a=await $(r.adapter,new Set),s=new Set,o=new Map,c=[],l;for(let A of n.activities){let C=o.get(A.originalParentId),T=await ar({kind:"activity-create",parentId:C??i.parentId,...C===void 0?{afterSiblingId:l??e.destination.afterSiblingId}:{},overrides:b(A.overrides),eventSource:e.eventSource},r,{skipCorrelativeRecompute:!0,skipBeforeSnap:!0,customIdReferenceId:e.destination.afterSiblingId});if(!T.ok)return T;o.set(A.originalId,T.newId),c.push(T.newId),C===void 0&&(l=T.newId)}let d=at(r.adapter),u=new Set(c.map(String));Ee(r.adapter,d,u,a,s);for(let A of c)s.add(String(A));let f=[];for(let A of n.links){let C=o.get(A.source),T=o.get(A.target);if(C===void 0||T===void 0)return Ol();let g={kind:"create",source:C,target:T,type:A.type,lag:A.lag},k=jt(g,{port:r.adapter,newLinkId:r.linkIdGen.next});if(!k.applied)return Ol();f.push({op:g,finalLinkId:k.linkId,rejected:null})}let{scheduledIds:p}=await Y({adapter:r.adapter,scheduler:r.scheduler,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:c[0]??null,recomputeParentsFrom:c,now:r.now,options:t}),h=xe(f,new Map,r.adapter);return{ok:!0,changes:await B(r.adapter,{source:e,beforeSnap:a,touchedIds:s,scheduledIds:p,links:h,hoursPerDay:r.sector.hoursPerDay})}}async function Fl(e,t,r){return e.kind==="activity-copy"?Ll(e,{adapter:r.adapter,clipboard:r.activityClipboard}):e.kind==="activity-clipboard-clear"?wl(e,r.activityClipboard):e.kind==="activity-paste-copied"?xl(e,t,r):e.kind==="activity-batch"?rl(e,t,r):e.kind==="persistence-acknowledge"?ul(e,r):e.kind==="baseline-apply"?Pl(e,r):e.kind==="ponderator-criterion-set"?Rl(e,r):e.kind==="status-criteria-set"?bl(e,r):e.kind==="link-create"||e.kind==="link-update"||e.kind==="link-delete"?Lc(e,t,r):e.kind==="links-batch"?wc(e,t,r):e.kind==="activity-create"?zc(e,t,r):e.kind==="activity-delete"?Qc(e,t,r):e.kind==="activity-move"?hl(e,t,r):e.kind==="activity-indent"?yl(e,t,r):e.kind==="activity-outdent"?ml(e,t,r):e.kind==="activity-set-progress"?gl(e,t,r):e.kind==="dates-batch"?vl(e,t,r):e.kind==="bulk-edit"?Al(e,t,r):e.kind==="selection-toggle"?wa(e,Ji(r)):e.kind==="selection-replace"?pr(e,Ji(r)):e.kind==="visibility-set"?Oa(e,Ji(r)):e.kind==="filter-set"?ja(e,{adapter:r.adapter,hoursPerDay:r.sector.hoursPerDay}):e.kind==="sort-set"?Ga(e,{adapter:r.adapter}):e.kind==="sir-sync"?il(e,r):e.kind==="activity-lookahead-sync"?fl(e,t,r):e.kind==="inline-edit"&&(e.column===_.CUSTOM_PREDECESSORS||e.column===_.CUSTOM_SUCESSORS)?Oc(e,t,r):e.kind!=="inline-edit"?Ls(e,`[ScheduleCore] dispatch kind "${e.kind}" not supported yet`):Ec(e,t,r)}function Ji(e){return{adapter:e.adapter}}var Wm=new Set(["startDate","endDate","constraintDate"]);function Nl(e,t){return Wm.has(e)&&typeof t=="string"?new Date(t):t}function Ml(e,t={}){let r=t.defaultUnit??"hour";return{getCalendar(n){let i=e.getCalendar(String(n));return i?Bm(i,r):null}}}function Bm(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 Um(e){return Array.isArray?Array.isArray(e):e&&e.length!==void 0&&e.pop&&e.push}function le(e){return e&&typeof e=="object"?!!(e.getFullYear&&e.getMonth&&e.getDate):!1}function de(e){return le(e)&&!isNaN(e.getTime())}var jm={}.constructor.toString();function Hm(e){var t=e.constructor.toString();return t!==jm}function Vm(e){return e.$$typeof&&e.$$typeof.toString().includes("react.")}function _t(e){var t,r;if(e&&typeof e=="object")switch(!0){case le(e):r=new Date(e);break;case Um(e):for(r=new Array(e.length),t=0;t<e.length;t++)r[t]=_t(e[t]);break;default:if(Hm(e))r=Object.create(e);else{if(Vm(e))return r=e,r;r={}}for(t in e)Object.prototype.hasOwnProperty.apply(e,[t])&&(r[t]=_t(e[t]));break}return r||e}function Be(e,t,r){for(var n in t)(e[n]===void 0||r)&&(e[n]=t[n]);return e}function Wl(e){return typeof e<"u"}var Cn;function Xi(){return Cn||(Cn=new Date().valueOf()),Cn++,Cn}function mt(e,t){return e.bind?e.bind(t):function(){return e.apply(t,arguments)}}var Km=(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)},Gm=(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)},Bl={date_to_str:Km,str_to_date:Gm},$m=(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}}),zm=(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])},Ul={date_to_str:$m,str_to_date:zm};function jl(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=Bl;return a()&&(l=Ul),l.date_to_str(o,c,e)},str_to_date:function(o,c){var l=Bl;return a()&&(l=Ul),l.str_to_date(o,c,e)},getISOWeek:function(o){return e.date._getWeekNumber(o,!0)},_getWeekNumber:function(o,c){if(!o)return!1;var l=o.getUTCDay();c&&l===0&&(l=7);var d=new Date(o.valueOf());d.setUTCDate(o.getUTCDate()+(4-l));var u=d.getUTCFullYear(),f=Math.round((d.getTime()-Date.UTC(u,0,1))/864e5),p=1+Math.floor(f/7);return p},getWeek:function(o){return e.date._getWeekNumber(o,e.config.start_on_monday)},getUTCISOWeek:function(o){return e.date.getISOWeek(o)},parseDate:function(o,c){if(o&&!o.getFullYear){var l=!c||c==="parse_date"||c==="xml_date",d=l&&(e.defined(e.templates.xml_date)||e.templates.parse_date&&!e.templates.parse_date._ganttAuto);if(!d&&typeof o=="string"&&t.test(o)){var u=o.indexOf("T")!==-1,f=r(o);if(f)return s._isoDateDetected?u&&(s._isoDateOnly=!1):(s._isoDateDetected=!0,s._isoDateOnly=!u),f}typeof c!="function"&&(typeof c=="string"?c==="parse_date"||c==="xml_date"?c=e.defined(e.templates.xml_date)?e.templates.xml_date:e.templates.parse_date:c=e.defined(e.templates[c])?e.templates[c]:e.date.str_to_date(c,!0):c=e.defined(e.templates.xml_date)?e.templates.xml_date:e.templates.parse_date),o?o=c(o):o=null}return o}};return s}function Zi(e,t,r,n,i){return this.date=e,this.unit=t,this.task=r,this.id=n,this.calendar=i,this}function Qi(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 ta(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 qm(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 Hl=function(e){return{getWorkHoursArguments:function(){var t=arguments[0];if(le(t)?t={date:t}:t=Be({},t),!de(t.date))throw e.assert(!1,"Invalid date argument for getWorkHours method"),new Error("Invalid date argument for getWorkHours method");return t},setWorkTimeArguments:function(){return arguments[0]},unsetWorkTimeArguments:function(){return arguments[0]},isWorkTimeArguments:function(){var t=arguments[0];if(t instanceof Zi)return t;var r;if(t.date?r=new Zi(t.date,t.unit,t.task,null,t.calendar):r=new Zi(arguments[0],arguments[1],arguments[2],null,arguments[3]),r.unit=r.unit||e.config.duration_unit,!de(r.date))throw e.assert(!1,"Invalid date argument for isWorkTime method"),new Error("Invalid date argument for isWorkTime method");return r},getClosestWorkTimeArguments:function(t){var r=arguments[0];if(r instanceof Qi)return r;var n;if(le(r)?n=new Qi(r):n=new Qi(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,!de(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=qm,n;if(t instanceof r)return t;if(le(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,!de(n.start_date))throw e.assert(!1,"Invalid start_date argument for getDuration method"),new Error("Invalid start_date argument for getDuration method");if(!de(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 ta)return a;var s;if(le(a)?s=new ta(arguments[0],arguments[1],arguments[2],void 0,arguments[3],void 0,arguments[4]):s=new ta(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,!de(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 Vl(){}Vl.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=_t(e.getConfig()),n=_t(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 h=d.dates[p];if(p==u&&(s.dates[u]=!!(f&&h)),Array.isArray(f)){let A=Array.isArray(h)?h:d.hours;s.dates[u]=this._toHoursArray(this._mergeHoursConfig(f,A))}}}};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 ea=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}},ra=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={}}},na=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 Jm(){return typeof Map<"u"?new ea:new ra}var ia=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 aa(e,t){this.argumentsHelper=t,this.$gantt=e,this._workingUnitsCache=Jm(),this._largeUnitsCache=new na(this),this._dateDurationCache=new ia,this._worktime=null,this._cached_timestamps={},this._cached_timestamps_count=0}aa.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 h=this._getUnitOrder(r),A=this.units[h-1];A&&!this._isWorkTime(a,A)&&(c=this._getClosestWorkTimeFuture(a,A))}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=mt(this._getMinutesPerDay,this):o=mt(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 aa))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(mt(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(mt(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 h=r;return n===t&&(h=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate(),0,0,s))),{added:n,end:h}},_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,h=this._getTimeOfDayStamp(n,u);if(!c.length||!l){n=this.$gantt.date.add(n,-1,"day");continue}if(c[c.length-1].end<=h&&p>l){i+=l,n=this.$gantt.date.add(n,-1,"day");continue}for(var A=!1,C=null,T=null,g=c.length-1;g>=0;g--)if(c[g].start<h-1&&c[g].end>=h-1){A=!0,C=c[g],T=c[g-1];break}if(A)if(h===C.end&&p>=C.durationMinutes)i+=C.durationMinutes,n=this.$gantt.date.add(n,-C.durationMinutes,"minute");else if(!a&&p<=h/60-C.startMinute)i+=p,n=this.$gantt.date.add(n,-p,"minute");else if(a)p<=h/60-C.startMinute?(i+=p,n=this.$gantt.date.add(n,-p,"minute")):(i+=h/60-C.startMinute,T?n=new Date(Date.UTC(n.getUTCFullYear(),n.getUTCMonth(),n.getUTCDate(),0,0,T.end)):n=this.$gantt.date.day_start(n));else{var k=this._getMinutesPerHour(n);k<=p?(i+=k,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 m=this._getClosestWorkTimePast(n,"hour");if(m.valueOf()===n.valueOf()){var m=this.$gantt.date.add(n,-1,"day"),P=this._getWorkHours(m);if(P.length){var w=P[P.length-1];m.setUTCSeconds(w.durationSeconds)}}n=m}else n=this._getClosestWorkTimePast(new Date(n-1),"hour")}if(i<t){var v=t-i;s=this._subtractMinutesUntilHourStart(n,v),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,h=null,A=0;A<o.length;A++)if(o[A].start<=f&&o[A].end>f){p=!0,h=o[A];break}if(p)if(f===h.start&&u>=h.durationMinutes)i+=h.durationMinutes,n=this.$gantt.date.add(n,h.durationMinutes,"minute");else if(u<=h.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=t-i;a=this._addMinutesUntilHourEnd(n,T),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 sr={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 Xm(){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 Zm=Xm();function Yl(e){this.$gantt=e,this._calendars={},this._legacyConfig=void 0,this.$gantt.attachEvent("onGanttReady",(function(){this.$gantt.config.resource_calendars&&(this._isLegacyConfig=sr.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))}Yl.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 Vl,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 aa(this.$gantt,Hl(this.$gantt));t.id=String(Xi());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=_t(e.getConfig()):e.worktime?t=_t(e.worktime):t=_t(e);var r=_t(this.defaults.fulltime.worktime);return Be(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=sr.getResourceProperty(t),Array.isArray(e[i])&&e[i].length)t.dynamic_resource_calendars?n=Zm.getCalendarIdFromMultipleResources(e[i],this):r=this.getResourceCalendar(e[i]);else if(this._legacyConfig===void 0&&(this._legacyConfig=sr.isLegacyResourceCalendarFormat(t.resource_calendars)),this._legacyConfig)var n=sr.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=sr.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||Xi(),this._calendars[e.id]=e,r.worktimes||(r.worktimes={}),r.worktimes[e.id]=e.getConfig(),e.id}else return this.$gantt.callEvent("onCalendarError",[{message:"Invalid calendar settings, no worktime available"},e]),null},deleteCalendar:function(e){var t=this.$gantt.config;return e&&this._calendars[e]?(delete this._calendars[e],t.worktimes&&t.worktimes[e]&&delete t.worktimes[e],!0):!1},restoreConfigCalendars:function(e){for(var t in e)if(!this._calendars[t]){var r=e[t],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 sa(e,t){this.argumentsHelper=t,this.$gantt=e}sa.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 sa},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 Kl(e){this.$gantt=e.$gantt,this.argumentsHelper=Hl(this.$gantt),this.calendarManager=e,this.$disabledCalendar=new sa(this.$gantt,this.argumentsHelper)}Kl.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 Qm=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:mt(e.mergeCalendars,e),createCalendar:mt(e.createCalendar,e),addCalendar:mt(e.addCalendar,e),getCalendar:mt(e.getCalendar,e),getCalendars:mt(e.getCalendars,e),getResourceCalendar:mt(e.getResourceCalendar,e),getTaskCalendar:mt(e.getTaskCalendar,e),deleteCalendar:mt(e.deleteCalendar,e)}},tg={create:Qm};function Gl(e){var t=new Yl(e),r=new Kl(t),n=tg.create(t,r);Be(e,n)}var $l={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 zl(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||$l,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:Wl,mixin:Be,copy:_t,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=jl(r),r.date.init(),Gl(r),r}function eg(e={}){let t=zl(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 ql={createCalendar:eg};var hF=3600*1e3;function Ql(e){return{getActivity(t){return e.getActivity(t)}}}var{createCalendar:rg}=ql,or="__replay_default__";function ng(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 Jl={hours:["8:00-16:00"],days:[!1,!0,!0,!0,!0,!0,!1]},Xl="__main_global__",ig={hours:["8:00-12:00","13:00-17:00"],days:[!1,!0,!0,!0,!0,!0,!1]};function Zl(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 ag(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:ng(e.hours),dates:t};return e.customWeeks&&(r.customWeeks=e.customWeeks),r}function td(e){let t=rg({config:{work_time:!0}});t.addCalendar({id:or,worktime:Jl}),t.addCalendar({id:Xl,worktime:ig});let r=new Set(e.filter(d=>!Zl(d.worktime)).map(d=>String(d.id))),n=e.filter(d=>Zl(d.worktime));for(let d of n)t.addCalendar({id:d.id,worktime:d.worktime?ag(d.worktime):Jl});let i=Ml(t),a=i.getCalendar(or),s=i.getCalendar(Xl);if(!a||!s)throw new Error("[replay-calendar] fallback calendars failed to register in work-calendar instance");let o=new Set([or]);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 ed(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 sg(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 sg(e,t){let r=[],n=new ht;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 In=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,Ft(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:Ft(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:rd(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=Ft(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:rd(r)}))}};function rd(e){return{...e}}var Sn=class{_cache={closestWorkTime:new Map,endDate:new Map,duration:new Map};reader;constructor(t){this.reader=t.reader}resolveCalendar(t){let r=nd(t);return this.reader.getCalendar(r??or)}getClosestWorkTime(t){let r=`${ca(t.task)}|${t.dir}|${t.date.getTime()}`;return oa(this._cache.closestWorkTime,r,()=>this.resolveCalendar(t.task).getClosestWorkTime({direction:t.dir,date:t.date,unit:ot.HOUR}))}calculateEndDate(t){let r=`${ca(t.task)}|${t.startDate.getTime()}|${t.durationHours}`;return oa(this._cache.endDate,r,()=>this.resolveCalendar(t.task).calculateEndDate(t.startDate,t.durationHours))}calculateDuration(t){let r=`${ca(t.task)}|${t.startDate.getTime()}|${t.endDate.getTime()}`;return oa(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 oa(e,t,r){let n=e.get(t);if(n!==void 0)return n;let i=r();return e.set(t,i),i}var og="__default__";function nd(e){if(!e)return null;let t=e.calendarId;return t==null?null:String(t)}function ca(e){return nd(e)??og}var kn=class{constructor(t){this.activities=t}activities;_childrenByParent=new Map;_roots=[];_dirty=!1;markDirty(){this._dirty=!0}getChildren(t){return this._dirty&&(this.rebuild(),this._dirty=!1),this._childrenByParent.get(String(t))??[]}hasChildren(t){return this._dirty&&(this.rebuild(),this._dirty=!1),(this._childrenByParent.get(String(t))?.length??0)>0}getRootIds(){return this._dirty&&(this.rebuild(),this._dirty=!1),[...this._roots]}isChildOf(t,r){let 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?yr(i,a):String(r).localeCompare(String(n))};this._roots.sort(t);for(let r of this._childrenByParent.values())r.sort(t)}};var Dn=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 Ue=class e{_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 In;_viewState=new Dn;_filterProjection=null;_viewStateBefore=null;_lastStartDateBefore=null;_promotionSnapshotBefore=null;_calendar;_flags;_calendarSnapshot;constructor(t,r=()=>null){this._buildOrderComparator=r,this._calendarSnapshot=b(t.calendars);for(let n of t.activities)this._activities.set(n.id,n);for(let n of t.links){let i={...n,freeSlackHours:n.freeSlackHours??null,isCritical:n.isCritical===!0};this._links.set(String(n.id),i),this._indexLink(i)}this._calendar=new Sn(td(this._calendarSnapshot)),this._flags=lg(t),this._hierarchy=new kn(this._activities),this._hierarchy.rebuild()}fork(){let t=new e({activities:this.getAllActivities().map(Ft),links:this.getAllLinks().map(r=>({...r})),calendars:b(this._calendarSnapshot)},this._buildOrderComparator);return t._viewState.restore(b(this._viewState.snapshot())),t._lastStartDate=new Map(Array.from(this._lastStartDate,([r,n])=>[r,new Date(n)])),t._promotionSnapshot=new Map(Array.from(this._promotionSnapshot,([r,n])=>[r,b(n)])),t._flags=b(this._flags),t._filterProjection=b(this._filterProjection),t}getAllActivities(){return Array.from(this._activities.values())}getAllLinks(){return Array.from(this._links.values())}getAllIds(){return this._cache.ids?this._cache.ids:(this._cache.ids=Array.from(this._activities.keys()),this._cache.ids)}activityCount(){return this._activities.size}getVisualOrderIds(){return this._cache.visualOrderIds?this._cache.visualOrderIds:(this._cache.visualOrderIds=Va(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))??id}getIncomingLinkIds(t){return this._incoming.get(String(t))??id}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,da(i,r),r===E.PARENT&&this._hierarchy.markDirty(),la(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,Nl(r,n)),da(i,r),r===E.PARENT&&this._hierarchy.markDirty(),la(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)),da(n,a),a===E.PARENT&&(i=!0),la(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);let n={...t,freeSlackHours:t.freeSlackHours??null,isCritical:t.isCritical===!0};this._links.set(String(t.id),n),this._indexLink(n)}_indexLink(t){sd(this._outgoing,String(t.source),t.id),sd(this._incoming,String(t.target),t.id)}_deindexLink(t){let r=this._outgoing.get(String(t.source));r&&this._outgoing.set(String(t.source),ad(r,t.id));let n=this._incoming.get(String(t.target));n&&this._incoming.set(String(t.target),ad(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(!cg(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))}},id=[];function cg(e){return e===Ze.LAG||e===Ze.TYPE||e===Ze.FREE_SLACK_HOURS||e===Ze.IS_CRITICAL}function la(e){return e===E.PARENT||e===E.CORRELATIVE_ID}function da(e,t){t!==E.START_DATE&&t!==E.END_DATE&&t!==E.TYPE||(e.calendarDuration=bt(e))}function ad(e,t){return e.filter(r=>String(r)!==String(t))}function sd(e,t,r){let n=e.get(t);n?n.push(r):e.set(t,[r])}function lg(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 od(e,t){let r=e.getActivity(t);return r?b(r):null}function cd(e){return e.getAllActivities().map(b)}function ld(e){return e.getAllIds().map(String)}function dd(e,t){e.forEachActivity((r,n)=>t(n))}function ud(e,t){let r=t==="0"?ua(e,"0"):e.getChildren(t),n=[];for(let i of r){let a=e.getActivity(i);a&&n.push(b(a))}return n.sort((i,a)=>(i.correlativeId??0)-(a.correlativeId??0)),n}function ua(e,t){return gt(t,e)}function fd(e){return e.checkedIds().map(String)}function pd(e,t){if(t==="0"){let r=!1;return e.forEachActivity(n=>{r||=L(n.parentId)}),r}return e.getChildren(t).length>0}function fa(e,t){let r=e.getLink(t);return r?ft(r):null}function hd(e){return e.getAllLinks().map(t=>ft(t))}function Tn(e){let[t,r]=e.split(":");return Number(t)*60+Number(r??0)}function dg(e){return e.reduce((t,r)=>Tn(r)<Tn(t)?r:t)}function ug(e){return e.reduce((t,r)=>Tn(r)>Tn(t)?r:t)}function fg(e){return e.worktime.days.flatMap(t=>Array.isArray(t)?t:t===!0?e.worktime.hours:[])}function yd(e){let t=[...e].find(a=>a.is_default);if(!t)return null;let r=fg(t);if(r.length===0)return null;let n=r.map(a=>a.split("-")[0]),i=r.map(a=>a.split("-")[1]);return{startHour:dg(n),endHour:ug(i)}}function md(e,t){return{calendars:e.calendarReader,hierarchy:ed(e),activityReader:Ql(e),dateFormat:t.dateFormat??"YYYY-MM-DD",customHours:t.customHours??{},hoursPerDay:t.hoursPerDay}}function gd(e){return oe(e)}var pg=new Set(["freeSlackHours","isCritical"]);function hg(e,t){let r=Object.fromEntries(Object.entries(e.fields??{}).filter(([n])=>!t.has(n)));return e.kind==="updated"&&Object.keys(r).length===0?null:{...e,...e.fields===void 0?{}:{fields:r},after:null}}function Id(e){let t=e.activities.map(i=>({...i,after:null})),r=e.links.map(i=>hg(i,pg)).filter(i=>i!==null),n=e.source.kind==="activity-batch"?{...e.source,items:[],links:[]}:e.source;return b({...e,source:n,activities:t,links:r})}function pa(e,t,r,n,i){return{changeSet:e,beforeSnap:t,beforeLinks:vd(r),afterSnap:n,afterLinks:vd(i)}}function vd(e){if(e)return new Map(Array.from(e,([t,r])=>[t,{...r,freeSlackHours:null,isCritical:!1}]))}function Sd(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 kd(e){return e.kind!=="inline-edit"||!nr.has(e.column)?null:`inline-edit:${String(e.activityId)}:${e.column}`}function Ad(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 Dd(e,t){if(!Ad(e)||!Ad(t))return!1;let r=e.changeSet.activities[0],n=t.changeSet.activities[0];return!!r&&!!n&&String(r.id)===String(n.id)}function Td(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 pa(o)}function _d(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==="activity-clipboard-clear"||e.kind==="activity-copy"||e.kind==="selection-toggle"||e.kind==="selection-replace"||e.kind==="visibility-set"||e.kind==="filter-set"||e.kind==="sort-set"?"skip":"record"}function ha(e){for(let t of e.changeSet.activities)if(t.kind==="created"||t.kind==="deleted"||t.kind==="updated"&&t.fields&&_.CUSTOM_ID in t.fields)return!0;return!1}function ya(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:Cd(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:Cd(s.fields,r),after:c?ft(c):null})}else if(s.kind==="deleted")if(r==="before"){let c=e.getLink(o);i.push({id:o,kind:"created",after:c?ft(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?ft(c):null})}}let a=(t.changeSet.viewState??[]).map(s=>r==="before"?yg(s):s);return{source:{kind:r==="before"?"undo":"redo"},activities:n,links:i,calendars:[],trackingEvents:[],effects:[],viewState:a}}function Cd(e,t){if(e!=null)return Object.fromEntries(Object.entries(e).map(([r,n])=>[r,t==="before"?{before:b(n.after),after:b(n.before)}:{before:b(n.before),after:b(n.after)}]))}function yg(e){return{activityId:e.activityId,...e.checked?{checked:{before:e.checked.after,after:e.checked.before}}:{},...e.visible?{visible:{before:e.visible.after,after:e.visible.before}}:{}}}function ma(e){return e.activities.length>0||e.links.length>0||(e.viewState?.length??0)>0||(e.effects?.length??0)>0}function Pd(e,t){bd(e,t,"before")}function Rd(e,t){bd(e,t,"after")}function bd(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))Vo(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 mg=100,gg=600,_n=class e{constructor(t=mg){this.maxDepth=t}maxDepth;undoStack=[];redoStack=[];_lastKey=null;_lastTime=0;fork(){let t=new e(this.maxDepth);return t.undoStack.push(...b(this.undoStack)),t.redoStack.push(...b(this.redoStack)),t._lastKey=this._lastKey,t._lastTime=this._lastTime,t}record(t,r=null,n=0){let i=this.undoStack[this.undoStack.length-1];r!=null&&r===this._lastKey&&n-this._lastTime<=gg&&i!==void 0&&Dd(i,t)?this.undoStack[this.undoStack.length-1]=Td(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 vg=["parentId","correlativeId"];function Ld(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(Ed(c.parentId?.before));continue}let s=i.fields;!s||!vg.some(c=>c in s)||(n(a),"parentId"in s&&r.add(Ed(s.parentId?.before)))}return r}function Ed(e){return e==null?"0":String(e)}function Ag(e){return{...e,id:String(e.id),source:String(e.source),target:String(e.target),type:e.type,lag:Number(e.lag)}}function Cg(e){return{days:e.days,hours:e.hours,...e.dates?{dates:e.dates}:{},...e.customWeeks?{customWeeks:e.customWeeks}:{}}}function wd(e){return{id:String(e.id),worktime:Cg(e.worktime)}}function Pn(e,t,r,n=[]){let i=t.map(Ag),a=[...r.map(wd),...n.map(wd)];return{activities:[...e],links:i,calendars:a}}var Od={id:"ignored",proplannerId:"ignored",parentId:"tracked",name:"tracked",description:"tracked",type:"tracked",startDate:"tracked",endDate:"tracked",durationHours:"tracked",constraintType:"tracked",constraintDate:"tracked",autoScheduling:"tracked",calendarId:"tracked",assignedDefaultCalendar:"ignored",dateOrigin:"tracked",progress:"tracked",cost:"tracked",usedCost:"tracked",realCost:"tracked",workHours:"tracked",realWorkHours:"tracked",ponderator:"tracked",hasCustomPonderator:"tracked",correlativeId:"tracked",uniqueCorrelativeId:"tracked",customId:"tracked",subcontractId:"tracked",isLookahead:"tracked",hasLookaheadTasks:"ignored",newActivityIds:"tracked",hasNewActivities:"tracked",isNewActivity:"ignored",pendingRequestIds:"ignored",responsableIds:"tracked",tagIds:"tracked",baselinePoints:"ignored",baselineSnapshot:"ignored",recursiveDurationHours:"ignored",isCritical:"ignored",freeSlackHours:"ignored",calendarDuration:"ignored",expectedProgress:"ignored",expectedProgressBaseline:"ignored",status:"ignored",criticalPath:"ignored"},xd=Object.keys(Od).filter(e=>Od[e]==="tracked"),Fd=new Set(["startDate","endDate","constraintDate","dateOrigin"]),Nd=new Set(["newActivityIds","responsableIds","tagIds"]);function Md(e){let t=xd.map(r=>[r,Ig(r,e[r])]);return Object.fromEntries(t)}function Ig(e,t){return Fd.has(e)?t instanceof Date?new Date(t):null:Nd.has(e)?Array.isArray(t)?[...t]:[]:t}function cr(e,t){for(let r of xd)if(!Sg(r,e[r],t[r]))return!0;return!1}function Sg(e,t,r){return Fd.has(e)?kg(t,r):Nd.has(e)?Dg(t,r):(t??null)===(r??null)}function kg(e,t){let r=e instanceof Date?e.getTime():null,n=t instanceof Date?t.getTime():null;return r===n}function Dg(e,t){let r=new Set(Array.isArray(e)?e.map(String):[]),n=new Set(Array.isArray(t)?t.map(String):[]);if(r.size!==n.size)return!1;for(let i of r)if(!n.has(i))return!1;return!0}var Wd={id:"ignored",source:"tracked",target:"tracked",type:"tracked",lag:"tracked",freeSlackHours:"ignored",isCritical:"ignored",ganttId:"ignored",sectorId:"ignored",proplannerId:"ignored"},Tg=Object.keys(Wd).filter(e=>Wd[e]==="tracked");function Rn(e,t){return Tg.some(r=>e[r]!==t[r])}function Bd(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?Rn(i,n):!1})}function Pt(e){if(e==null||e===0)return!1;if(!(typeof e=="number"&&Number.isSafeInteger(e)&&e>0))throw new Error(`invalid proplannerId ${String(e)}`);return!0}function Ud(e,t){for(let r of e)Pt(r.proplannerId);for(let r of t)Pt(r.proplannerId)}var bn=class e{trackingEnabled;initialized=!1;dirtyActivityIds=new Set;dirtyLinkIds=new Set;initialCalendarRepairIds=new Set;linksAtLastSave=new Map;activitiesAtLastSave=new Map;constructor(t=!0){this.trackingEnabled=t}fork(){let t=new e(!1);t.initialized=this.initialized;for(let[r,n]of this.linksAtLastSave)t.linksAtLastSave.set(r,b(n));for(let[r,n]of this.activitiesAtLastSave)t.activitiesAtLastSave.set(r,b(n));return t}init(t,r){if(this.trackingEnabled){Ud(t,r),this.snapshotActivities(t),this.snapshotLinks(r);for(let n of t)if(n.assignedDefaultCalendar){let i=String(n.id);this.initialCalendarRepairIds.add(i),this.dirtyActivityIds.add(i)}this.initialized=!0}}acknowledge(t,r){this.trackingEnabled&&(Ud(t,r),this.snapshotActivities(t),this.snapshotLinks(r))}snapshotActivities(t){if(this.trackingEnabled){this.activitiesAtLastSave.clear(),this.dirtyActivityIds.clear(),this.initialCalendarRepairIds.clear();for(let r of t){let n=String(r.id);if(!Pt(r.proplannerId)){this.dirtyActivityIds.add(n);continue}let i=Md(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}}),cr(r,i)&&this.dirtyActivityIds.add(n)}}}snapshotLinks(t){if(this.trackingEnabled){this.linksAtLastSave.clear(),this.dirtyLinkIds.clear();for(let r of t){let n=String(r.id);if(!Pt(r.proplannerId)){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.trackingEnabled||!this.initialized)){for(let a of t){let s=String(a.id),o=n(s);this.activityIsDirty(s,o)?this.dirtyActivityIds.add(s):this.dirtyActivityIds.delete(s)}for(let a of r){let s=String(a.id),o=i(s);this.linkIsDirty(s,o)?this.dirtyLinkIds.add(s):this.dirtyLinkIds.delete(s)}}}activityIsDirty(t,r){let n=this.activitiesAtLastSave.get(t);return r===null?n!==void 0:this.initialCalendarRepairIds.has(t)||!Pt(r.proplannerId)||n===void 0||cr(r,n.persistable)}linkIsDirty(t,r){let n=this.linksAtLastSave.get(t);return r===null?n!==void 0:!Pt(r.proplannerId)||n===void 0||Rn(n,r)}acknowledgePersistedLookahead(t,r){if(!this.trackingEnabled||!this.initialized)return;let n=t.map(i=>{let a=typeof i=="string"?i:String(i.id),s=r(a),o=this.activitiesAtLastSave.get(a);if(s===null||o===void 0)throw new Error(`unknown persisted activity "${a}"`);return{activityId:a,acknowledgesLookahead:typeof i=="string"||!!i.fields?.isLookahead,acknowledgesProgress:typeof i!="string"&&!!i.fields?.progress,current:s,saved:o}});for(let{activityId:i,acknowledgesLookahead:a,acknowledgesProgress:s,current:o,saved:c}of n){let l={...c.persistable,...a?{isLookahead:o.isLookahead}:{},...s?{progress:o.progress}:{}};this.activitiesAtLastSave.set(i,{...c,persistable:l}),this.initialCalendarRepairIds.has(i)||!Pt(o.proplannerId)||cr(o,l)?this.dirtyActivityIds.add(i):this.dirtyActivityIds.delete(i)}}hasCheckpointActivityId(t){return this.activitiesAtLastSave.has(t)}hasCheckpointLinkId(t){return this.linksAtLastSave.has(t)}hasUnsavedChanges(){return this.trackingEnabled&&this.initialized&&(this.dirtyActivityIds.size>0||this.dirtyLinkIds.size>0)}newActivities(t){if(!this.trackingEnabled||!this.initialized)return[];let r=[];for(let n of this.dirtyActivityIds){let i=t(n);i!==null&&!Pt(i.proplannerId)&&r.push(i)}return r}newLinks(t){if(!this.trackingEnabled||!this.initialized)return[];let r=[];for(let n of this.dirtyLinkIds){let i=t(n);i!==null&&!Pt(i.proplannerId)&&r.push(i)}return r}deletedActivities(t){if(!this.trackingEnabled||!this.initialized)return[];let r=[];for(let n of this.dirtyActivityIds){let i=this.activitiesAtLastSave.get(n);i&&t(n)===null&&r.push({...i.deletedSnapshot})}return r}deletedLinks(t){if(!this.trackingEnabled||!this.initialized)return[];let r=[];for(let n of this.dirtyLinkIds){let i=this.linksAtLastSave.get(n);i&&t(n)===null&&r.push({...i})}return r}modifiedActivities(t){if(!this.trackingEnabled||!this.initialized)return[];let r=[];for(let n of this.dirtyActivityIds){let i=t(n);if(i===null||!Pt(i.proplannerId))continue;let a=this.activitiesAtLastSave.get(n);(a===void 0||this.initialCalendarRepairIds.has(n)||cr(i,a.persistable))&&r.push(i)}return r}modifiedLinks(t){if(!this.trackingEnabled||!this.initialized)return[];let r=[];for(let n of this.dirtyLinkIds){let i=t(n);if(i===null||!Pt(i.proplannerId))continue;let a=this.linksAtLastSave.get(n);(a===void 0||Rn(a,i))&&r.push(i)}return r}clear(){this.initialized=!1,this.dirtyActivityIds.clear(),this.dirtyLinkIds.clear(),this.initialCalendarRepairIds.clear(),this.linksAtLastSave.clear(),this.activitiesAtLastSave.clear()}};var jd=/^(\d{4})[/-](\d{1,2})[/-](\d{1,2})/;var ga=[!1,!0,!0,!0,!0,!0,!1],Hd=new Set(["1","true"]),va="DURATION",Vd="asap",Yd={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 Kd(e,t){let r=[],n=e.map(a=>{let s=Ng(a,t);return a.should_be_showed===!1&&r.push(s.id),s});Wg(n);let i=new Set(n.map(a=>a.id));return Bg(n,i,t.reporter),{activities:n,activityIds:i,hiddenIds:r}}function _g(e){return e===0}function Pg(e,t){if(!e)return null;let r=Yd[e.toUpperCase()];return r===void 0?(t.warn(`[parseFromBackend] unknown constraint label "${e}" \u2014 defaulting to "asap"`),Vd):r}function Rg(e,t){let r=Pg(e.constraint,t),i=r!=="asap"&&r!=="alap"&&e.constraint_date?Nt(e.constraint_date):null;return{constraintType:r,constraintDate:i}}function bg(e,t,r){if(e==null)return r;let n=String(e);return t.has(n)?n:r}function Eg(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 Lg(e){if(typeof e!="object"||e===null||!("id"in e))return!1;let t=e.id;return typeof t=="string"||typeof t=="number"}function Aa(e){if(!Array.isArray(e))return[];let t=[];for(let r of e)Lg(r)&&t.push(String(r.id));return t}function wg(e){return e==="0"?null:String(e)}function Og(e){if(e==null)return null;if(!(typeof e=="number"&&(e===0||Number.isSafeInteger(e)&&e>0)))throw new Error(`invalid activity proplannerId ${String(e)}`);return e}function xg(e,t){return typeof e.is_critical=="boolean"?e.is_critical:(t.error("[parseFromBackend] invalid activity is_critical \u2014 defaulting to false",new TypeError(`activity "${e.unique_id}" received ${typeof e.is_critical}`)),!1)}function Fg(e,t){return Array.isArray(e)?e.map(r=>mn(r,t)).filter(r=>r!==null):[]}function Ng(e,t){let r=bg(e.calendarId,t.knownCalendarIds,t.defaultCalendarId),n=e.calendarId==null||!t.knownCalendarIds.has(String(e.calendarId)),i=Number(e.progress),{constraintType:a,constraintDate:s}=Rg(e,t.reporter),o=e.type==="milestone",c=Nt(e.start_date),l=o?c:Nt(e.end_date),d=o?0:Number(e.duration),u=xg(e,t.reporter);return{id:String(e.unique_id),proplannerId:Og(e.id),parentId:wg(e.parent_id),name:e.name,description:e.description??"",type:e.type,startDate:c,endDate:l,durationHours:ee(d,t.hoursPerDay),constraintType:a,constraintDate:s,autoScheduling:_g(i),calendarId:r,assignedDefaultCalendar:r!=null&&n,dateOrigin:e.date_origin==null?null:Nt(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:Mg(e),subcontractId:e.subcontractId,isLookahead:e.isOnLookahead,hasLookaheadTasks:Array.isArray(e.tasks)&&e.tasks.length>0,newActivityIds:Eg(e.newActivitiesArray),hasNewActivities:e.hasNewActivities??!1,...e.isNewActivity===!0?{isNewActivity:!0}:{},pendingRequestIds:Aa(e.pendingRequests),responsableIds:Aa(e.responsables),tagIds:Aa(e.tags),baselinePoints:Fg(e.baseline_points,t.reporter),baselineSnapshot:null,recursiveDurationHours:ee(Number(e.sumOfDurationRecursively??0),t.hoursPerDay),calendarDuration:bt({type:e.type,startDate:c,endDate:l}),isCritical:u,freeSlackHours:null,expectedProgress:null,expectedProgressBaseline:null,status:null,criticalPath:null}}function Mg(e){return e.has_childs?null:e.custom_id}function Wg(e){let t=e.find(r=>r.correlativeId===0&&r.type==="project");t&&(t.parentId=null)}function Bg(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 qd(e,t,r,n=null){let s=(e!==void 0&&e.length>0?e:t??[]).map(c=>Hg(c,n)),o=(r??[]).map(c=>Vg(c,n));return{calendars:s,baseCalendars:o,knownCalendarIds:new Set(s.map(c=>c.id)),defaultCalendarId:jg(s)}}function jg(e){let t=e.find(n=>n.is_default);if(t)return t.id;let r=e[0];return r?r.id:null}function Jd(e,t){let r=qg(e.working_days),{days:n,hours:i}=zg(e,r),a=Yg(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 Hg(e,t){let r=e.baseDefault,n=typeof r=="boolean"?r:void 0;return Jd(e,{idSuffix:"",isDefault:!!e.is_default,baseDefault:n,exceptionsSource:e.exceptiondays,exceptionRange:t})}function Vg(e,t){return Jd(e,{idSuffix:"-base",isDefault:!1,baseDefault:!!e.is_default,exceptionsSource:e.baseexceptiondays??e.exceptiondays,exceptionRange:t})}function Yg(e,t){if(!Array.isArray(e)||e.length===0)return null;let r={};for(let n of e){if(!n)continue;let i=Kg(n.from_date,n.to_date,t);if(i.length===0)continue;let a=Gg(n);if(a!==void 0)for(let s of i)r[s]=a}return Object.keys(r).length>0?r:null}function Kg(e,t,r){let n=Gd(e),i=Gd(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 Gd(e){if(typeof e!="string")return null;let t=jd.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 Gg(e){if(e.workable===!1)return!1;let t=e.shifts;if(Array.isArray(t)&&t.length>0){let r=$g(t);if(r.length>0)return r}}var $d=/^\d{1,2}:\d{2}$/;function $g(e){let t=[];for(let r of e){let n=Qd(r?.shift_string);if(!n)continue;if(!n.startsCsv.includes(",")&&!n.endsCsv.includes(",")){let o=n.startsCsv.trim(),c=n.endsCsv.trim();!En(o)&&!En(c)&&$d.test(o)&&$d.test(c)&&t.push(`${o}-${c}`);continue}let s=Zd(n.startsCsv,n.endsCsv).find(o=>o!==null);s&&t.push(s)}return t.sort(Xd),t}function zd(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 Xd(e,t){return zd(e)-zd(t)}function zg(e,t){let r=Array.from({length:7},()=>[]),n=(l,d)=>{let u=Zd(l,d);for(let f=0;f<7;f+=1){let p=u[f],h=r[f];p&&h&&h.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=Qd(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(Xd);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 Zd(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];En(c)||En(l)||(s[o]=`${c}-${l}`)}return s}function Qd(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 qg(e){if(typeof e!="string")return[...ga];let t=e.split(",").map(r=>r.trim());return t.length!==7?[...ga]:t.map(r=>Hd.has(r))}var Jg=new Set(["false","null"]);function En(e){return!e||Jg.has(e)}function Xg(e){return e==="0"||e==="1"||e==="2"||e==="3"}function Zg(e){if(typeof e!="string")return null;let t=ao(e);return t||(Xg(e)?e:null)}function Qg(e){if(e==null)return;if(!(typeof e=="number"&&(e===0||Number.isSafeInteger(e)&&e>0)))throw new Error(`invalid link proplannerId ${String(e)}`);return e}function eu(e,t){let r=[];for(let n of e)try{r.push(tv(n,t.knownActivityIds,t.hoursPerDay))}catch(i){t.reporter.warn("[parseFromBackend] dropping invalid link",i)}return ev(r)}function tv(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=Zg(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=Qg(e.id);return{id:n,source:i,target:a,type:s,lag:vt(Number(e.lag??0),r),freeSlackHours:null,isCritical:!1,...typeof o=="number"?{ganttId:o}:{},...typeof c=="number"?{sectorId:c}:{},...l===void 0?{}:{proplannerId:l}}}function ev(e){let t=new Map;for(let r of e){let n=`${r.source}-${r.target}-${r.type}`,i=t.get(n);(!i||tu(r)>tu(i))&&t.set(n,r)}return[...t.values()]}function tu(e){let t=Number(e.id);return Number.isFinite(t)?t:-1/0}function rv(e){if(typeof e!="string")return va;switch(e.toUpperCase()){case"DURATION":return"DURATION";case"COST":return"COST";case"HH":return"HH";default:return va}}function nv(e){let t=e.custom_id_prefix;return typeof t=="string"&&t.length>0?t:void 0}function iv(e){let t=e.custom_id_increment;return typeof t=="string"?t:typeof t=="number"&&Number.isFinite(t)?String(t):void 0}function ru(e){let t=nv(e),r=iv(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:rv(e.activity_creter),statusCriteria:Kn,ganttId:null}}function Ln(e,t=Ae){let r=ru(e.sector),{calendars:n,baseCalendars:i,knownCalendarIds:a,defaultCalendarId:s}=qd(e.calendars,e.sector.calendars,e.baseCalendars,av(e.activities)),{activities:o,activityIds:c,hiddenIds:l}=Kd(e.activities,{knownCalendarIds:a,defaultCalendarId:s,hoursPerDay:r.hoursPerDay,reporter:t}),d=eu(e.links,{knownActivityIds:c,hoursPerDay:r.hoursPerDay,reporter:t});return{sector:r,activities:o,links:d,calendars:n,baseCalendars:i,viewStateSeed:{hiddenIds:l}}}function av(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 Ia(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{fork(){return Ia({seed:t})},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 Sa(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{fork(){return Sa({seed:t})},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 ka(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{fork(){return ka({seed:t})},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 nu(e){return!!e&&typeof e=="string"&&e.trim().length>0}function wn(e){if(!e||typeof e!="string"||e.trim().length===0)return"";let t=e.match(/^(.*?)(\d+)$/);return t?t[1]??"":e}function On(e){if(!e||typeof e!="string"||e.trim().length===0)return"";let t=e.match(/(\d+)$/);return t?t[1]??"":""}function iu(e){if(!e||typeof e!="object")return"";let t=e.customId;return typeof t=="string"?t:""}function au(e,t){return!t&&nu(e)}function su(e,t){return t&&nu(e)}function dr(e){return typeof e=="string"&&e.length>0&&/^\d+$/.test(e)}function lr(e){if(!dr(e))return 0n;try{return BigInt(e)}catch{return 0n}}function sv(e,t){if(typeof e!="bigint")return"";let r=e.toString();if(!dr(t))return r;let n=t.length;return r.padStart(n,"0")}function It(e,t){let r=lr(e),n=lr(t),i=r+n;return sv(i,e)}function xn(e,t){let r=lr(e),n=lr(t);return r<n?-1:r>n?1:0}function Fn(e,t){return xn(e,t)<=0?e:t}function Nn(e,t){return xn(e,t)>=0?e:t}function ou(e){if(!e||e.length===0)throw new Error("minSuffixFromArray requires non-empty array");return e.reduce((t,r)=>Fn(t,r))}function cu(e){if(!e||e.length===0)throw new Error("maxSuffixFromArray requires non-empty array");return e.reduce((t,r)=>Nn(t,r))}function lu(e){return{prefix:e,baseSuffix:null}}function du(e,t){let r=On(e);return{prefix:wn(e),baseSuffix:It(r,t)}}function uu(e){return{prefix:e,baseSuffix:null}}function fu(e,t){return au(e,t)?"parentConversion":su(e,t)?"pasteReference":"noContext"}function pu(e){return{...e,usedSuffixes:new Set(e.usedSuffixes)}}var Mn=class e{prefixMap=new Map;processedIds=new Set;_journalPrefixBefore=null;_journalIds=null;beginCustomIdTransaction(){this._journalPrefixBefore=new Map,this._journalIds=[]}commitCustomIdTransaction(){this._journalPrefixBefore=null,this._journalIds=null}rollbackCustomIdTransaction(){let t=this._journalPrefixBefore,r=this._journalIds;if(!(t===null||r===null)){for(let[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?pu(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=ou(n),r.max=cu(n),r.quantity=n.length,this._recalculateNext(t)}defaultPrefix;suffixIncrement;constructor(t={}){this.defaultPrefix=t.defaultPrefix??"A",this.suffixIncrement=t.suffixIncrement??"10"}fork(){let t=new e({defaultPrefix:this.defaultPrefix,suffixIncrement:this.suffixIncrement});for(let[r,n]of this.prefixMap)t.prefixMap.set(r,pu(n));for(let r of this.processedIds)t.processedIds.add(r);return t}extractPrefix(t){return wn(t)}extractSuffix(t){return On(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=Fn(r,n.min),n.max=Nn(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=Fn(n,i.min),i.max=Nn(n,i.max),i.quantity+=1,this._recalculateNext(r))}else this.prefixMap.set(r,{min:n,max:n,next:It(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}${It(r.max,this.suffixIncrement)}`.length>20}_suffixForUnknownPrefix(t,r){let n=r&&dr(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(;xn(n,r.max)<0;){if(`${t}${n}`.length>20)return null;if(!r.usedSuffixes.has(n))return n;n=It(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||!dr(r)){let o=It(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=It(a,i)}let s=It(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,It(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=iu(r),a=fu(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=It(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 lu(this.defaultPrefix);case"pasteReference":return du(r,this.suffixIncrement);default:return uu(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=It(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 ov=1,cv=-1;function lv(e,t){return!e&&!t?null:e&&t?0:e?ov:cv}function hu(e){return e==null}function yu(e,t){let r=t.indexOf(String(e));return r===-1?t.length:r}function dv(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 uv(e,t){let r=Wt(e.field);return r===null?null:(n,i)=>{let a=r.extract(n,t),s=r.extract(i,t),o=lv(hu(a),hu(s));if(o!==null)return o;let c=r.valueKind==="enum"?yu(a,r.order)-yu(s,r.order):dv(a,s,t.locale);return e.direction==="desc"?-c:c}}function mu(e,t){let r=e.rules.map(n=>uv(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 gu(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,E.TYPE,ve),fv(e,r)}function fv(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,E.START_DATE,i),e.setActivityField(t,E.END_DATE,a)}function vu(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?dt(a.workHours,a.progress):s.reduce((c,l)=>c+n(String(l)),0);return e.setActivityField(i,E.REAL_WORK_HOURS,o),r.push(i),o};for(let i of t)n(i);return r}async function Au(e){let{state:t,sector:r,scheduler:n,skipAutoSchedule:i,now:a}=e;if(at(t),r.updateDurationForPrimaveraEndDate&&hv(t),yv(t),vu(t),i){a&&(ie(t,a),Mt(t,r.statusCriteria));return}let s=await n.schedule({});Ke(t,s),mv(t),pv(t),await Se(t,void 0,!1),a&&(ie(t,a),Mt(t,r.statusCriteria))}function pv(e){e.forEachActivity(t=>{t.autoScheduling||!t.startDate||t.durationHours==null||e.getChildren(t.id).length>0||(t.endDate=e.calculateEndDate({startDate:t.startDate,durationHours:t.durationHours,task:t}),t.calendarDuration=bt(t))})}function hv(e){e.forEachActivity(t=>{!t.startDate||!t.endDate||(t.durationHours=e.calculateDuration({startDate:t.startDate,endDate:t.endDate,task:t}))})}function yv(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=xt(t.constraintDate,i,r))})}function mv(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=xt(t.constraintDate,n,r))})}var St={READY:"ready",DESTROYED:"destroyed",POISONED:"poisoned"};function Cu(e){let t=e.clock??null,r=t?.()??null,n=r?jr(r):null,i=e.reporter??Ae,a=Ln({sector:e.sector,activities:e.activities,links:e.links,calendars:e.calendars,baseCalendars:e.baseCalendars},i),s=a.sector;s.statusCriteria=gr(e.statusCriteria),s.ganttId=e.ganttId??null;let o=a.calendars,c=a.baseCalendars??[],l=Pn(a.activities,a.links,a.calendars,c),d=g=>mu(g,Qt(s.hoursPerDay)),u=new Ue(l,d);u.hydrateViewState({hiddenIds:a.viewStateSeed.hiddenIds});let f=new Ce(u,i);gu(u);let p=Ia({knownIds:a.activities.map(g=>g.id)}),h=Sa({seed:r?.getTime()??0,knownIds:a.links.map(g=>g.id)}),A=ka({knownIds:a.activities.map(g=>g.uniqueCorrelativeId)}),C=new Mn({defaultPrefix:s.customIdPrefix,suffixIncrement:s.customIdIncrement});if(C.populateFromActivities(a.activities),e.baselinePoints&&e.baselinePoints.length>0){let g=c.find(k=>k.baseDefault)?.id??null;gn(u,e.baselinePoints,n,i,g)}let T=Au({state:u,sector:s,scheduler:f,skipAutoSchedule:e.skipInitialAutoSchedule===!0,now:n??void 0});return{sector:s,state:u,scheduler:f,activityIdGen:p,linkIdGen:h,uidGen:A,customIdTracker:C,calendars:o,baseCalendars:c,clock:t,reporter:i,initPromise:T}}function je(e){if(e===void 0)return["undefined"];if(e===null)return["null"];if(typeof e=="string")return["string",e];if(typeof e=="boolean")return["boolean",e];if(typeof e=="number")return["number",Object.is(e,-0)?"-0":String(e)];if(typeof e=="bigint")return["bigint",String(e)];if(e instanceof Date)return["date",String(e.getTime())];if(Array.isArray(e))return["array",e.map(je)];if(e instanceof Map)return["map",Array.from(e,([t,r])=>[je(t),je(r)]).sort((t,r)=>JSON.stringify(t).localeCompare(JSON.stringify(r)))];if(e instanceof Set)return["set",Array.from(e,je).sort((t,r)=>JSON.stringify(t).localeCompare(JSON.stringify(r)))];if(typeof e=="object")return["object",Object.entries(e).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,je(r)])];throw new TypeError(`Unsupported canonical value: ${typeof e}`)}function ue(e){return JSON.stringify(je(e))}function Da(e,t){let r=new Map(e.map(s=>[String(s.id),s])),n=new Map(t.map(s=>[String(s.id),s])),i=[...new Set([...r.keys(),...n.keys()])].sort(),a=[];for(let s of i){let o=n.get(s),c=r.get(s);if(c===void 0){a.push({id:s,kind:"deleted",after:null});continue}if(o===void 0){a.push({id:s,kind:"created",after:b(c)});continue}let l=gv(o,c);Object.keys(l).length>0&&a.push({id:s,kind:"updated",fields:l,after:b(c)})}return a}function gv(e,t){let r={},n=[...new Set([...Object.keys(e),...Object.keys(t)])].sort();for(let i of n)ue(e[i])!==ue(t[i])&&(r[i]={before:b(e[i]),after:b(t[i])});return r}function vv(e,t){let r=new Set(t.selectedIds.map(String)),n=new Set(e.selectedIds.map(String)),i=new Set(t.hiddenIds.map(String)),a=new Set(e.hiddenIds.map(String)),s=e.activities.map(({id:c})=>String(c)).sort(),o=[];for(let c of s){let l=r.has(c),d=n.has(c),u=!i.has(c),f=!a.has(c);l===d&&u===f||o.push({activityId:c,...l===d?{}:{checked:{before:l,after:d}},...u===f?{}:{visible:{before:u,after:f}}})}return o}function Iu(e,t){let r=ue(e.order)!==ue(t.order);return{source:{kind:"init"},activities:Da(e.activities,t.activities),links:Da(e.links,t.links),calendars:Da(e.calendars,t.calendars),trackingEvents:[],effects:[],viewState:vv(e,t),...r?{order:b(e.order)}:{}}}var Av=()=>({constantStart:null,variableStartOffset:null,constantEnd:null,variableEndOffset:null}),Ta=(e,t)=>e===null?t:Math.min(e,t),_a=(e,t)=>e===null?t:Math.max(e,t);function ku(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=Cv(e,t,n);return Iv(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=kv(o,s),l=Dv(o,s);if(c===null||l===null)throw new Error(`[ScheduleCore] incomplete date gesture bounds for ${String(a)}`);return{startTimeMs:c,endTimeMs:l}}}}function Cv(e,t,r){let n=new Map,i=t.kind==="move"?String(t.anchorActivityId):null,a=i===null?null:Su(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=Su(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 Iv(e,t,r){let n=Je(e,new Set(t));for(let i of n){let a=Av();for(let s of e.getChildren(i)){let o=r.get(s);if(o){Sv(a,o);continue}let c=e.getActivity(s);if(!c)throw new Error(`[ScheduleCore] missing child ${s} while previewing parent ${i}`);a.constantStart=Ta(a.constantStart,c.startDate.getTime()),a.constantEnd=_a(a.constantEnd,c.endDate.getTime())}r.set(i,a)}}function Su(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 Sv(e,t){t.constantStart!==null&&(e.constantStart=Ta(e.constantStart,t.constantStart)),t.variableStartOffset!==null&&(e.variableStartOffset=Ta(e.variableStartOffset,t.variableStartOffset)),t.constantEnd!==null&&(e.constantEnd=_a(e.constantEnd,t.constantEnd)),t.variableEndOffset!==null&&(e.variableEndOffset=_a(e.variableEndOffset,t.variableEndOffset))}function kv(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 Dv(e,t){if(e.variableEndOffset===null)return e.constantEnd;let r=t+e.variableEndOffset;return e.constantEnd===null?r:Math.max(e.constantEnd,r)}var Pa=Symbol("ScheduleCore.fork.source");function Tv(e){return e.kind==="persistence-acknowledge"||e.kind==="activity-lookahead-sync"&&e.acknowledgePersistedLookahead===!0}function _v(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 Pv(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 Rv(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 Wn=class e{_activityClipboard={value:null};_status=St.READY;coreRuntime;_isFork;_undo=new _n;_opQueue=Promise.resolve();_scheduleRevision=0;_pendingScheduleRevision=0;_criticalPathRevision=-1;_activeCriticalPath=null;constructor(t){if(Pa in t){this._isFork=!0;let i=t[Pa],a=i.coreRuntime.state.fork();this.coreRuntime={state:a,scheduler:new Ce(a,i.coreRuntime.reporter),sector:b(i.coreRuntime.sector),activityIdGenerator:i.coreRuntime.activityIdGenerator.fork(),linkIdGenerator:i.coreRuntime.linkIdGenerator.fork(),uniqueCorrelativeIdGenerator:i.coreRuntime.uniqueCorrelativeIdGenerator.fork(),customIdTracker:i.coreRuntime.customIdTracker.fork(),calendars:new Map(Array.from(i.coreRuntime.calendars,([s,o])=>[s,b(o)])),baseCalendars:b(i.coreRuntime.baseCalendars),clock:i.coreRuntime.clock,reporter:i.coreRuntime.reporter},this._activityClipboard.value=b(i._activityClipboard.value),this._undo=i._undo.fork(),this._saveTracker=i._saveTracker.fork(),this._scheduleRevision=i._scheduleRevision,this._pendingScheduleRevision=i._scheduleRevision,this._criticalPathRevision=i._criticalPathRevision,this._initPromise=Promise.resolve(),this._criticalPathReady=Promise.resolve(null),this._ready=this._initPromise;return}this._isFork=!1;let r=Cu(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!==St.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}fork(){return this._enqueue(async()=>(await this._ready,this.assertReady(),new e({[Pa]:this})))}get criticalPathReady(){return this._criticalPathReady}get status(){return this._status}getSector(){return b(this.coreRuntime.sector)}getActivityView(t){return this.assertReady(),od(this.coreRuntime.state,t)}createDateGesturePreview(t){this.assertReady();let r=this._scheduleRevision;return ku(this.coreRuntime.state,t,()=>{if(this.assertReady(),this._scheduleRevision!==r)throw new Error("[ScheduleCore] date gesture preview is stale")})}getAllActivitiesView(){return this.assertReady(),cd(this.coreRuntime.state)}getIndentTargetParentIds(t){this.assertReady();let r=yn(t.map(n=>String(n)),this.coreRuntime.state);return[...new Set(r.allowedMoves.map(n=>String(n.newParentId)))]}getChildrenView(t){return this.assertReady(),ud(this.coreRuntime.state,t)}getLinkView(t){return this.assertReady(),fa(this.coreRuntime.state,t)}getLinksForActivityView(t){this.assertReady();let r=this.coreRuntime.state,n=[],i=new Set,a=s=>{if(i.has(s))return;i.add(s);let o=fa(r,s);o&&n.push(o)};for(let s of r.getOutgoingLinkIds(t))a(s);for(let s of r.getIncomingLinkIds(t))a(s);return n}getAllLinksView(){return this.assertReady(),hd(this.coreRuntime.state)}auditEffectiveGraph(){this.assertReady();let t=this.coreRuntime.state,r=t.getAllLinks(),n=$e(t,r),i=br(n),a=0;for(let s of i)s.length>a&&(a=s.length);return{activityCount:t.getAllIds().length,logicalLinkCount:r.length,effectiveEdgeCount:n.length,circularComponents:i,largestComponentSize:a}}getProperty(t,r){this.assertReady();let n=this.coreRuntime.state.getActivity(t);return n?b(n[r]):null}getAllIds(){return this.assertReady(),ld(this.coreRuntime.state)}forEachActivityId(t){this.assertReady(),dd(this.coreRuntime.state,t)}getChildrenIds(t){return this.assertReady(),ua(this.coreRuntime.state,t)}getSelectedActivityIds(){return this.assertReady(),fd(this.coreRuntime.state)}getHiddenActivityIds(){return this.assertReady(),this.coreRuntime.state.hiddenIds().map(String)}getActiveFilter(){return this.assertReady(),b(this.coreRuntime.state.getActiveFilter())}getActiveOrder(){return this.assertReady(),b(this.coreRuntime.state.getActiveOrder())}getVisualOrderIds(){return this.assertReady(),[...this.coreRuntime.state.getVisualOrderIds()]}hasChild(t){return this.assertReady(),pd(this.coreRuntime.state,t)}getCalendar(t){this.assertReady();let r=this.coreRuntime.calendars.get(t);return r?b(r):null}getAllCalendars(){return this.assertReady(),Array.from(this.coreRuntime.calendars.values(),t=>b(t))}getBaseCalendars(){return this.assertReady(),this.coreRuntime.baseCalendars.map(t=>b(t))}isCustomIdInUse(t,r=null){return this.assertReady(),this.coreRuntime.customIdTracker.isCustomIdInUse(t,r)}getProjectWorkHours(){return this.assertReady(),yd(this.coreRuntime.calendars.values())}getModifiedLinks(){return this.assertReady(),this._saveTracker.modifiedLinks(t=>this.coreRuntime.state.getLink(t)).map(b)}getNewLinks(){return this.assertReady(),this._saveTracker.newLinks(t=>this.coreRuntime.state.getLink(t)).map(b)}getModifiedActivities(){return this.assertReady(),this._saveTracker.modifiedActivities(t=>this.coreRuntime.state.getActivity(t)).map(b)}getNewActivities(){return this.assertReady(),this._saveTracker.newActivities(t=>this.coreRuntime.state.getActivity(t)).map(b)}hasUnsavedChanges(){return this.assertReady(),this._saveTracker.hasUnsavedChanges()}getScheduleRevision(){return this._scheduleRevision}getCanonicalDigest(){this.assertReady();let t=(r,n)=>String(r.id).localeCompare(String(n.id));return ue({sector:this.getSector(),activities:[...this.getAllActivitiesView()].sort(t),links:[...this.getAllLinksView()].sort(t),calendars:[...this.getAllCalendars()].sort(t),baseCalendars:[...this.getBaseCalendars()].sort(t)})}createProjectionChangeSetFrom(t){this.assertReady(),t.assertReady();let r=n=>({activities:n.getAllActivitiesView(),links:n.getAllLinksView(),calendars:n.getAllCalendars(),selectedIds:n.getSelectedActivityIds(),hiddenIds:n.getHiddenActivityIds(),order:me(n.coreRuntime.state)});return Iu(r(this),r(t))}getDeletedActivitiesSinceLastSave(){return this.assertReady(),this._saveTracker.deletedActivities(t=>this.coreRuntime.state.getActivity(t)).map(b)}getDeletedLinksSinceLastSave(){return this.assertReady(),this._saveTracker.deletedLinks(t=>this.coreRuntime.state.getLink(t)).map(b)}_enqueue(t){let r=this._opQueue.then(t,t);return this._opQueue=r.then(()=>{},()=>{}),r}_beginScheduleMutation(t){return Ni(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){if(this.assertReady(),this._isFork&&Tv(t))return{result:{ok:!1,reason:S.SANDBOX_PERSISTENCE_FORBIDDEN},changedState:!1};let n=md(this.coreRuntime.state,{hoursPerDay:this.coreRuntime.sector.hoursPerDay,dateFormat:this.coreRuntime.sector.dateFormat}),i=_d(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 Fl(t,r,{adapter:this.coreRuntime.state,ctx:n,scheduler:this.coreRuntime.scheduler,sector:this.coreRuntime.sector,calendars:this.coreRuntime.calendars,activityIdGen:this.coreRuntime.activityIdGenerator,linkIdGen:this.coreRuntime.linkIdGenerator,isActivityIdReserved:o=>this._saveTracker.hasCheckpointActivityId(o),isLinkIdReserved:o=>this._saveTracker.hasCheckpointLinkId(o),uidGen:this.coreRuntime.uniqueCorrelativeIdGenerator,customIdTracker:this.coreRuntime.customIdTracker,reporter:this.coreRuntime.reporter,activityClipboard:this._activityClipboard,defaultBaseCalendarId:this.coreRuntime.baseCalendars.find(o=>o.baseDefault)?.id??null,now:this.coreRuntime.clock?jr(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"&&ma(s.changes)){let o=Sd(this.coreRuntime.state,s.changes);this._undo.record(pa(Id(s.changes),s.__beforeSnap,s.__beforeLinks,o.afterSnap,o.afterLinks),kd(t),Date.now())}return s.ok&&(i==="clear-on-success"?(this._saveTracker.acknowledge(this.coreRuntime.state.getAllActivities(),this.coreRuntime.state.getAllLinks()),this._undo.clear()):t.kind==="activity-lookahead-sync"&&t.acknowledgePersistedLookahead===!0?(this._saveTracker.acknowledgePersistedLookahead(s.changes.activities,o=>this.coreRuntime.state.getActivity(o)),t.persistedProgress!==void 0&&this._undo.clear()):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?Ni(t)&&ma(s.changes)?(this._recordScheduleMutation(r.skipAutoSchedule!==!0&&r.skipCriticalPath!==!0&&oe(t)),{result:Du(s),changedState:!0}):{result:Du(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),!_c(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=Ld(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=Yn(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:me(n)};let a=new Set(r);for(let o of t.activities){if(o.kind==="deleted")return{...t,order:me(n)};let c=n.getParentId(o.id);a.add(c===null?"0":String(c))}let s=Yn(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=Rv(a,n,i),o=_v(t)?null:Pv(t,r),c,l;if(o===null||!s){let f=hr({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=Ma(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===St.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 Ue(Pn(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!==St.DESTROYED&&this._scheduleRevision===t&&this._pendingScheduleRevision===this._scheduleRevision,a=(async()=>{let o=await xi(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.activities)wi(this.coreRuntime.state,l,d);for(let[l,d]of o.links)Oi(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===St.DESTROYED)return{changes:{source:{kind:"init"},activities:[],links:[],calendars:[],trackingEvents:[]}};this.coreRuntime.state.beginWriteCapture(),this.coreRuntime.customIdTracker.beginCustomIdTransaction();let t;try{await tn(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;Pd(this.coreRuntime.state,n),this._recordScheduleMutation(!1),r(!0),ha(n)&&this._resyncCustomIdTrackerFromModel(),this._undo.pushRedo(n),this._undo.resetCoalesce();let i=ya(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;Rd(this.coreRuntime.state,r),this._recordScheduleMutation(!1),t(!0),ha(r)&&this._resyncCustomIdTrackerFromModel(),this._undo.pushUndo(r),this._undo.resetCoalesce();let n=ya(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=St.DESTROYED}_initPromise;_criticalPathReady;_ready;_saveTracker=new bn;assertReady(){if(this._status===St.DESTROYED)throw new Error("[ScheduleCore] instance is destroyed");if(this._status===St.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=St.POISONED,this.coreRuntime.reporter.error("[ScheduleCore] rollback failed \u2014 core poisoned",r),r}}};function Du(e){let{__beforeSnap:t,__beforeLinks:r,...n}=e;return n}var Tu=(e=[])=>(e??[]).filter(t=>!t.proplannerId);var _u={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 Pu=8;var G={ACTIVITY_CLIPBOARD_CLEAR:"activity-clipboard-clear",ACTIVITY_COPY:"activity-copy",ACTIVITY_PASTE_COPIED:"activity-paste-copied",PERSISTENCE_ACKNOWLEDGE:"persistence-acknowledge",BASELINE_APPLY:"baseline-apply",PONDERATOR_CRITERION_SET:"ponderator-criterion-set",STATUS_CRITERIA_SET:"status-criteria-set",INLINE_EDIT:"inline-edit",DATES_BATCH:"dates-batch",BULK_EDIT:"bulk-edit",LINK_CREATE:"link-create",LINK_UPDATE:"link-update",LINK_DELETE:"link-delete",LINKS_BATCH:"links-batch",ACTIVITY_CREATE:"activity-create",ACTIVITY_DELETE:"activity-delete",ACTIVITY_MOVE:"activity-move",ACTIVITY_INDENT:"activity-indent",ACTIVITY_OUTDENT:"activity-outdent",ACTIVITY_SET_PROGRESS:"activity-set-progress",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"},bv={[G.ACTIVITY_CLIPBOARD_CLEAR]:!0,[G.ACTIVITY_COPY]:!0,[G.ACTIVITY_PASTE_COPIED]:!0,[G.PERSISTENCE_ACKNOWLEDGE]:!0,[G.BASELINE_APPLY]:!0,[G.PONDERATOR_CRITERION_SET]:!0,[G.STATUS_CRITERIA_SET]:!0,[G.INLINE_EDIT]:!0,[G.DATES_BATCH]:!0,[G.BULK_EDIT]:!0,[G.LINK_CREATE]:!0,[G.LINK_UPDATE]:!0,[G.LINK_DELETE]:!0,[G.LINKS_BATCH]:!0,[G.ACTIVITY_CREATE]:!0,[G.ACTIVITY_DELETE]:!0,[G.ACTIVITY_MOVE]:!0,[G.ACTIVITY_INDENT]:!0,[G.ACTIVITY_OUTDENT]:!0,[G.ACTIVITY_SET_PROGRESS]:!0,[G.SELECTION_TOGGLE]:!0,[G.SELECTION_REPLACE]:!0,[G.VISIBILITY_SET]:!0,[G.FILTER_SET]:!0,[G.SORT_SET]:!0,[G.SIR_SYNC]:!0,[G.ACTIVITY_LOOKAHEAD_SYNC]:!0},Ru=Object.keys(bv);var bu={CHILD:"child",CHILD_CONFIRMED:"child-confirmed",LINE:"line",ROOT:"root"};return Nu(Ev);})();
1
+ "use strict";var ScheduleCore=(()=>{var jn=Object.defineProperty;var Ou=Object.getOwnPropertyDescriptor;var xu=Object.getOwnPropertyNames;var Fu=Object.prototype.hasOwnProperty;var Nu=(e,t)=>{for(var r in t)jn(e,r,{get:t[r],enumerable:!0})},Mu=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of xu(t))!Fu.call(e,i)&&i!==r&&jn(e,i,{get:()=>t[i],enumerable:!(n=Ou(t,i))||n.enumerable});return e};var Wu=e=>Mu(jn({},"__esModule",{value:!0}),e);var Hv={};Nu(Hv,{ACTIVITY_TYPE:()=>Sr,CALENDAR_UNIT:()=>ot,COLUMN:()=>_,CONSTRAINT_TYPE:()=>K,CONSTRAINT_TYPE_TO_LABEL:()=>Ru,CREATION_KIND:()=>Lu,DEFAULT_HOURS_PER_DAY:()=>bu,DISPATCH_ACTION_KIND:()=>G,DISPATCH_ACTION_KINDS:()=>Eu,DISPATCH_TRACK_EVENT:()=>It,LINK_CODE_TO_TYPE:()=>Qt,LINK_TYPE:()=>W,LINK_TYPE_CODE:()=>ao,NEW_ACTIVITY_DEFAULTS:()=>dn,REJECTION_REASON:()=>S,ROOT_PARENT_ID:()=>F,SCHEDULE_CORE_STATUS:()=>St,STATUS:()=>Rt,ScheduleCore:()=>Un,WORK_TIME_DIRECTION:()=>X,checkNoUpdatedLinks:()=>jd,computeExpectedProgress:()=>pi,expectedProgressFromBaseline:()=>Le,getActiveBaseline:()=>ut,getUnsavedActivities:()=>Pu,isRootParent:()=>L,normalizeParentKey:()=>Bt,parseFromBackend:()=>On,willRunCriticalPath:()=>Ad,yieldToBrowser:()=>Z});var ht=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 pr=e=>String(e);function La(e){let{clickedId:t,isChecked:r,currentSelection:n,hierarchy:i,isFrozen:a,exists:s,autoCheckParents:o}=e,c=pr(t),l=new Set([...n].map(String)),d=new Set(l),u=Bu(c,i).filter(s),f=u.filter(h=>!a(h)),p=r&&f.length<u.length;r&&!p?d.add(c):d.delete(c);for(let h of f)r?d.add(h):d.delete(h);return p||Uu({id:c,isChecked:r,autoCheckParents:o,hierarchy:i,isFrozen:a,exists:s,next:d}),{nextSelection:d,changed:ju(l,d),parentBlocked:p}}function Bu(e,t){let r=[],n=new ht;n.enqueue(e);let i=new Set([e]);for(;!n.isEmpty();){let a=n.dequeue();for(let s of t.getChildrenIds(a)){let o=pr(s);i.has(o)||(i.add(o),r.push(o),n.enqueue(o))}}return r}function Uu(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=pr(c);if(a(l))return;let d=i.getChildrenIds(l).map(pr).filter(s),u=d.some(a),f=d.filter(A=>!a(A)),h=f.length>0&&f.every(A=>o.has(A))&&!u;if(r){if(!n||!h||o.has(l))return;o.add(l)}else{if(h||!o.has(l))return;o.delete(l)}c=i.getParentId(l)}}function ju(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 he(e){return(e.pendingRequestIds?.length??0)>0}var S={CANNOT_EDIT:"cannot_edit",PARSE_ERROR:"parse_error",INVALID:"invalid",CUSTOM_ID_DUPLICATE:"custom_id_duplicate",INVALID_LINK_TYPE:"invalid_link_type",INVALID_LINK_LAG:"invalid_link_lag",INVALID_VALUE:"invalid_value",NO_PIPELINE_FOR_COLUMN:"no_pipeline_for_column",ACTIVITY_NOT_FOUND:"activity_not_found",PARENT_NOT_FOUND:"parent_not_found",ACTIVITY_IDS_EMPTY:"activity_ids_empty",NO_ACTIVITY_SELECTION:"no_activity_selection",CLIPBOARD_EMPTY:"clipboard_empty",ACTIVITY_PASTE_INVARIANT_FAILED:"activity_paste_invariant_failed",ANCHOR_SIBLING_CONFLICT:"anchor_sibling_conflict",ANCHOR_SIBLING_NOT_FOUND:"anchor_sibling_not_found",ANCHOR_SIBLING_WRONG_PARENT:"anchor_sibling_wrong_parent",PARENT_FROZEN_BY_SIR:"parent_frozen_by_sir",CANNOT_MOVE_INTO_OWN_DESCENDANT:"cannot_move_into_own_descendant",INDENT_NO_ELIGIBLE_SIBLING:"indent_no_eligible_sibling",OUTDENT_ROOT_LEVEL_NOT_EDITABLE:"outdent_root_level_not_editable",HIERARCHY_CYCLE:"hierarchy_cycle",SANDBOX_PERSISTENCE_FORBIDDEN:"sandbox_persistence_forbidden",INVALID_PROGRESS_VALUE:"invalid_progress_value_must_be_0_or_100"};var wa=(e,t)=>{let r=e.getActivity(t);return r!=null&&he(r)},Oa=(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 xa(e,t){let{adapter:r}=t,n=e.activityId;if(!r.getActivity(n))return{ok:!1,reason:S.ACTIVITY_NOT_FOUND};let i=e.frozenIds?new Set(e.frozenIds):null,a=i?o=>i.has(o):o=>wa(r,o),s=La({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:Oa(e,r,s.changed)}}function hr(e,t){let{adapter:r}=t,n=new Set(e.activityIds.map(String).filter(s=>r.activityExists(s)).filter(s=>!wa(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:Oa(e,r,a)}}function ye(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 Fa(e,t){let{adapter:r}=t,n=new Set(e.visibleIds.map(String)),i=ye(r,n);return{ok:!0,changes:{source:e,activities:[],links:[],calendars:[],trackingEvents:[],viewState:i}}}var Hu=["Waiting","Done","Doing","Overdue","Advancement"],Vu=["mfo","mso","snlt","snet","alap","asap","fnet","fnlt"];function Hn(e,t){return e===null||t<=0?null:e/t}function Yu(e,t){let r=Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()),n=Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate());return Math.floor((n-r)/864e5)+1}var Ku={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=>{let t=Number(e.uniqueCorrelativeId);return Number.isFinite(t)?t:null}},progress:{valueKind:"number",extract:e=>e.progress},durationDays:{valueKind:"number",extract:(e,t)=>Hn(e.durationHours,t.hoursPerDay)},calendarDuration:{valueKind:"number",extract:e=>e.type==="milestone"?0:Yu(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)=>Hn(e.freeSlackHours,t.hoursPerDay)},totalSlackDays:{valueKind:"number",extract:(e,t)=>Hn(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:Hu,extract:e=>e.status},constraintType:{valueKind:"enum",order:Vu,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 Wt(e){return Ku[e]??null}function mr(e,t,r){let n=String(t.branchParentId);if(String(r(e)??"0")!==n)return!1;let a=String(t.referenceId);return a===n||String(r(a)??"0")===n}var yr=class{checkedSet=new Set;hiddenSet=new Set;activeFilter=null;activeOrder=null;relativePlacementPins=new Map;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}setRelativePlacementPin(t,r){this.relativePlacementPins.set(String(t),{referenceId:String(r.referenceId),branchParentId:String(r.branchParentId),side:r.side})}getRelativePlacementPins(){return this.relativePlacementPins}restoreRelativePlacementPins(t){this.relativePlacementPins=new Map(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),this.relativePlacementPins.delete(t);for(let[r,n]of this.relativePlacementPins)n.referenceId===t&&this.relativePlacementPins.delete(r)}hydrate(t){this.checkedSet=new Set(t.checkedIds??[]),this.hiddenSet=new Set(t.hiddenIds??[]),this.activeFilter=null,this.activeOrder=null,this.relativePlacementPins=new Map}snapshot(){return{checked:new Set(this.checkedSet),hidden:new Set(this.hiddenSet),activeFilter:this.activeFilter,activeOrder:this.activeOrder,relativePlacementPins:new Map(this.relativePlacementPins)}}restore(t){this.checkedSet=new Set(t.checked),this.hiddenSet=new Set(t.hidden),this.activeFilter=t.activeFilter,this.activeOrder=t.activeOrder,this.relativePlacementPins=new Map(t.relativePlacementPins)}};function Gu(e){return e instanceof Date?e:typeof e=="string"||typeof e=="number"?new Date(e):new Date(Number.NaN)}function $u(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 zu(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 qu(e,t,r){return e instanceof Date?r==="after"?e.getTime()>t.getTime():r==="before"?e.getTime()<t.getTime():!1:!1}function Ju(e,t,r){let i=(Array.isArray(e)?e:[]).some(a=>t.has(String(a)));return r==="someOf"?i:r==="notSomeOf"?!i:!1}function Xu(e,t,r){let n=e!==null&&t.has(String(e));return r==="someOf"?n:r==="notSomeOf"?!n:!1}function Na(e){let t=Array.isArray(e)?e:[e];return new Set(t.map(r=>String(r)))}function Ma(e,t,r){let n=Wt(t.field);if(n===null)return!1;let i=n.extract(e,r),{operator:a}=t;return n.valueKind==="string"?$u(i,String(t.value),a):n.valueKind==="number"?zu(i,Number(t.value),a):n.valueKind==="date"?qu(i,Gu(t.value),a):n.valueKind==="id-array"?Ju(i,Na(t.value),a):Xu(i,Na(t.value),a)}function Zu(e,t,r){return t.criteria.length===0?!0:t.logic==="or"?t.criteria.some(n=>Ma(e,n,r)):t.criteria.every(n=>Ma(e,n,r))}function Qu(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 Vn(e,t,r){let n=Zu(e,t,r),i=t.dateRange,a=i===void 0||Qu(e,i);return n&&a}function tf(e,t,r){let n=t(e);for(;n!==null&&!r.has(String(n));)r.add(String(n)),n=t(n)}function Wa(e){let{activities:t,parentOf:r,filter:n,context:i}=e,a=new Set,s=[];for(let o of t)Vn(o,n,i)&&(a.add(String(o.id)),s.push(o.id));for(let o of s)tf(o,r,a);return a}function ef(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=Vn(d,n,i);o.set(u,p?1:0),p&&a.add(u)}return{matchedIds:a,pinnedVisibleIds:s,visibleReferenceCounts:o,parentIds:c,remainingChildren:l}}function rf(e,t){if(t!==void 0)for(let[r,n]of t){let i=String(r),a=String(n.referenceId);if(!e.parentIds.has(i)||!e.parentIds.has(a)||!mr(i,n,o=>e.parentIds.get(o)??null)||(e.visibleReferenceCounts.get(a)??0)===0)continue;e.pinnedVisibleIds.add(i);let s=i;for(;s!==null;)e.visibleReferenceCounts.set(s,(e.visibleReferenceCounts.get(s)??0)+1),s=e.parentIds.get(s)??null}}function nf(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 af(e){let t=new Set;for(let[r,n]of e)n>0&&t.add(r);return t}function gr(e){let t=ef(e);nf(t),rf(t,e.relativePlacementPins);let r=af(t.visibleReferenceCounts);return{filter:e.filter,context:e.context,matchedIds:t.matchedIds,pinnedVisibleIds:t.pinnedVisibleIds,visibleIds:r,visibleReferenceCounts:t.visibleReferenceCounts}}function Ba(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=Vn(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 sf={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 Ua(e){if(e===void 0)return{ok:!0,dateRange:void 0};if(typeof e!="object"||e===null)return{ok:!1,reason:"invalid_value"};let{start:t,end:r}=e;if(!(t instanceof Date)||!(r instanceof Date))return{ok:!1,reason:"invalid_value"};let n=t.getTime(),i=r.getTime();return!Number.isFinite(n)||!Number.isFinite(i)||n>i?{ok:!1,reason:"invalid_value"}:{ok:!0,dateRange:{start:new Date(n),end:new Date(i)}}}function ja(e){let t=Wt(e.field);if(t===null)return{ok:!1,reason:"unknown_field"};if(!sf[t.valueKind].has(e.operator))return{ok:!1,reason:"unknown_operator"};if(t.valueKind==="number"){let n=cf(e.value);return n===null?{ok:!1,reason:"invalid_value"}:{ok:!0,criterion:{...e,value:n}}}if(t.valueKind==="date"){let n=lf(e.value);return n===null?{ok:!1,reason:"invalid_value"}:{ok:!0,criterion:{...e,value:n}}}let r=of(e,t.valueKind);return r!==null?{ok:!1,reason:r}:t.valueKind==="boolean"?{ok:!0,criterion:{...e,value:[...new Set(e.value)]}}:t.valueKind==="id-array"||t.valueKind==="enum"||t.valueKind==="reference"?{ok:!0,criterion:{...e,value:[...new Set(e.value.map(String))]}}:{ok:!0,criterion:e}}function of(e,t){let{value:r}=e;return t==="boolean"?Array.isArray(r)&&r.every(n=>typeof n=="boolean")?null:"invalid_value":t==="id-array"||t==="enum"||t==="reference"?Array.isArray(r)&&r.every(n=>typeof n=="string"||typeof n=="number")?null:"invalid_value":Array.isArray(r)?"invalid_value":null}function cf(e){if(typeof e=="string"&&e.trim()===""||typeof e!="string"&&typeof e!="number")return null;let t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?t:null}function lf(e){let t;if(e instanceof Date)t=new Date(e.getTime());else if(typeof e=="string")t=new Date(e);else if(typeof e=="number")t=new Date(e);else return null;return Number.isFinite(t.getTime())?t:null}function b(e){return structuredClone(e)}function Ha(e){return e.criteria.length===0&&e.dateRange===void 0}function df(e,t,r){let n=e.getAllActivities();if(Ha(t))return{visibleIds:Wa({activities:n,parentOf:a=>e.getParentId(a),filter:t,context:Zt(r)}),projection:null};let i=gr({activities:n,parentOf:a=>e.getParentId(a),filter:t,context:Zt(r),relativePlacementPins:e.getRelativePlacementPins()});return{visibleIds:i.visibleIds,projection:i}}function Va(e,t){let{adapter:r,hoursPerDay:n}=t,i=[];for(let u of e.criteria){let f=ja(u);if(!f.ok)return{ok:!1,reason:f.reason};i.push(f.criterion)}let a=Ua(e.dateRange);if(!a.ok)return{ok:!1,reason:a.reason};let s=b(a.dateRange===void 0?{criteria:i,logic:e.logic}:{criteria:i,logic:e.logic,dateRange:a.dateRange});r.setActiveFilter(Ha(s)?null:s);let{visibleIds:o,projection:c}=df(r,s,n);r.setFilterProjection(c);let l=ye(r,o);return{ok:!0,changes:{source:e,activities:[],links:[],calendars:[],trackingEvents:[],viewState:l}}}var F="0";function L(e){return e==null||e===0||e==="0"}function Bt(e){return L(e)?"0":String(e)}var Yn=Number.MAX_SAFE_INTEGER,uf=new Map;function He(e){let t=new Map;for(let[r,n]of e.getRelativePlacementPins?.()??[]){let i=String(r),a=String(n.referenceId);if(e.getActivity(i)===null||e.getActivity(a)===null||!mr(i,n,c=>e.getParentId(c)))continue;let s=String(n.branchParentId),o=t.get(s)??new Map;o.set(i,n),t.set(s,o)}return t}function gt(e,t,r=He(t)){let n=Ve(e,t),i=t.getOrderComparator?.()??null;return n.sort(i===null?vr:(a,s)=>i(a,s)||vr(a,s)),ff(n.map(a=>String(a.id)),e,r.get(String(e))??uf)}function ff(e,t,r){let n=pf(e);for(let[i,a]of r){let s=String(i),o=String(a.referenceId),c=o===String(t);!n.previous.has(s)||!c&&(!n.previous.has(o)||s===o)||(hf(n,s),c?yf(n,s):mf(n,s,o,a.side))}return gf(n)}function pf(e){let t=new Map,r=new Map;for(let n=0;n<e.length;n++){let i=e[n];i!==void 0&&(t.set(i,e[n-1]??null),r.set(i,e[n+1]??null))}return{previous:t,next:r,head:e[0]??null}}function hf(e,t){let r=e.previous.get(t)??null,n=e.next.get(t)??null;r===null?e.head=n:e.next.set(r,n),n!==null&&e.previous.set(n,r)}function yf(e,t){e.previous.set(t,null),e.next.set(t,e.head),e.head!==null&&e.previous.set(e.head,t),e.head=t}function mf(e,t,r,n){if(n==="before"){let a=e.previous.get(r)??null;e.previous.set(t,a),e.next.set(t,r),e.previous.set(r,t),a===null?e.head=t:e.next.set(a,t);return}let i=e.next.get(r)??null;e.previous.set(t,r),e.next.set(t,i),e.next.set(r,t),i!==null&&e.previous.set(i,t)}function gf(e){let t=[],r=e.head;for(;r!==null;)t.push(r),r=e.next.get(r)??null;return t}function Ka(e){let t=[],r=He(e),n=a=>{t.push(a);let s=gt(String(a.id),e,r);for(let o of s){let c=e.getActivity(o);c&&n(c)}},i=gt("0",e,r);for(let a of i){let s=e.getActivity(a);s&&n(s)}return t}function Ga(e,t,r){let n=r.getActivity(e);if(!n)return null;let i=$a(n),a=gt(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&&!vf(t,c))return c}return null}function Kn(e,t){let r=t.getActivity(e);if(!r)return-1;let n=$a(r);return gt(n,t).findIndex(a=>String(a)===String(e))}function Ve(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 vr(e,t){let r=Ya(e),n=Ya(t);return r!==n?r-n:String(e.id).localeCompare(String(t.id))}function Ya(e){let t=e.correlativeId,r=typeof t=="number"?t:Number(t);return Number.isFinite(r)?r:Yn}function $a(e){let t=e.parentId;return t===null?"0":t}function vf(e,t){return e.has(t)?!0:e.has(String(t))}function me(e){let t=[],r=He(e),n=i=>{let a=gt(i,e,r);a.length>1&&t.push({parentId:i,childIds:a});for(let s of a)n(s)};return n("0"),t}function Gn(e,t){let r=[],n=He(e);for(let i of t){let a=gt(i,e,n);a.length>1&&r.push({parentId:i,childIds:a})}return r}function Af(e){return Wt(e.field)===null?"unknown_field":e.direction!=="asc"&&e.direction!=="desc"?"unknown_operator":null}function za(e,t){let{adapter:r}=t;for(let a of e.rules){let s=Af(a);if(s!==null)return{ok:!1,reason:s}}let n=e.rules.length===0?null:b({rules:e.rules});return r.setActiveOrder(n),{ok:!0,changes:{source:e,activities:[],links:[],calendars:[],trackingEvents:[],order:me(r)}}}var qa="text";var Ja="description";var Xa="duration";var Za="progress";var Qa="cost";var ts="used_cost";var es="hhWorkTime";var rs="start_date";var ns="end_date";var is="constraint_type";var as="constraint_date";var ss="calendar_id";var os="custom_id";var cs="subcontractId";var ls="responsables";var ds="tags";var us="custom_predecessors";var fs="custom_sucessors";var ps="real_work";var hs="real_cost";var ys="expected_progress";var ms="expected_progress_base";var gs="start_base";var vs="end_base";var As="duration_base";var Is="cost_base";var Cs="work_base";var Ss="calendarDuration";var ks="is_critical",Ds="earlyStart",Ts="earlyFinish",_s="lateStart",Ps="lateFinish",Rs="freeSlack",bs="totalSlack";var Es="correlative_id";var Ls="unique_correlative_id";var ws="ponderator";var X={FUTURE:"future",PAST:"past"},ot={HOUR:"hour",DAY:"day"},Rt={DONE:"Done",OVERDUE:"Overdue",ADVANCEMENT:"Advancement",WAITING:"Waiting",DOING:"Doing"};var Ar="status";var $n="Baseline";function Ir(e){return e==="Actual"?"Actual":$n}var If={TEXT:qa,DESCRIPTION:Ja,DURATION:Xa,PROGRESS:Za,COST:Qa,USED_COST:ts,HH_WORK_TIME:es,START_DATE:rs,END_DATE:ns,CONSTRAINT_TYPE:is,CONSTRAINT_DATE:as,CALENDAR_ID:ss,CUSTOM_ID:os,SUBCONTRACT_ID:cs,RESPONSABLES:ls,TAGS:ds,CUSTOM_PREDECESSORS:us,CUSTOM_SUCESSORS:fs},Cf={REAL_WORK:ps,REAL_COST:hs,EXPECTED_PROGRESS:ys,EXPECTED_PROGRESS_BASE:ms,START_BASE:gs,END_BASE:vs,DURATION_BASE:As,COST_BASE:Is,WORK_BASE:Cs,CALENDAR_DURATION:Ss,IS_CRITICAL:ks,EARLY_START:Ds,EARLY_FINISH:Ts,LATE_START:_s,LATE_FINISH:Ps,FREE_SLACK:Rs,TOTAL_SLACK:bs,CORRELATIVE_ID:Es,UNIQUE_CORRELATIVE_ID:Ls,PONDERATOR:ws,STATUS:Ar},_={...If,...Cf};function Os(e,t){throw new Error(t)}function xs(e,t){return()=>t()===e}var K={ASAP:"asap",ALAP:"alap",SNET:"snet",SNLT:"snlt",FNET:"fnet",FNLT:"fnlt",MSO:"mso",MFO:"mfo"},Sf={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 Ns(e,t,r){if(!t)return{violated:!1};let n=Sf[e];return n?n(t,r)?{violated:!0,constraintType:e,constraintDate:t}:{violated:!1}:{violated:!1}}var kf=new Set(["mso","snet","snlt"]);function Ye(e,t,r){return kf.has(e)?t:r}function Ms(e,t,r){return{type:"constraint",messageKey:"constraint_violation",data:{constraintType:e,constraintDate:t,...r?{projectedDate:r}:{}}}}var Df={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}},Cr=e=>new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate())),Fs=(e,t)=>new Date(e.getTime()+t*864e5),Tf=(e,t)=>e.getUTCFullYear()===t.getUTCFullYear()&&e.getUTCMonth()===t.getUTCMonth()&&e.getUTCDate()===t.getUTCDate();function zn(e,t){if(!e.constraintDate||!e.constraintType)return null;let r=Df[e.constraintType];if(!r)return e.constraintDate;let n=e.constraintDate,i=t.getClosestWorkTime({date:Cr(n),dir:X.FUTURE,task:e});if(Tf(i,n))return n.getTime()!==Cr(n).getTime()?n:r.startOfDay?i:t.getClosestWorkTime({date:Fs(Cr(n),1),dir:X.PAST,task:e});let a=Cr(t.getClosestWorkTime({date:n,dir:r.direction,task:e}));return r.startOfDay?t.getClosestWorkTime({date:a,dir:X.FUTURE,task:e}):t.getClosestWorkTime({date:Fs(a,1),dir:X.PAST,task:e})}function Ws(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=zn(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 Bs(e,t){return!(t.earliestStart&&e<t.earliestStart||t.latestStart&&e>t.latestStart)}function qn(e,t){return t.latestStart&&e>t.latestStart?t.latestStart:t.earliestStart&&e<t.earliestStart?t.earliestStart:e}var W={FINISH_TO_START:"0",START_TO_START:"1",FINISH_TO_FINISH:"2",START_TO_FINISH:"3"};var Sr={TASK:"task",PROJECT:"project",MILESTONE:"milestone"},Us={ALAP_DEBOUNCE_MS:1e3,CRITICAL_PATH_DEBOUNCE_MS:1e3,YIELD_SLICE_MS:8};var Jn=typeof window>"u",_f=!Jn&&typeof MessageChannel<"u";function Z(){return _f?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 kr(e,t){return performance.now()-e<Us.YIELD_SLICE_MS?{aborted:!1,newSliceStart:e}:(await Z(),t()?{aborted:!1,newSliceStart:performance.now()}:{aborted:!0,newSliceStart:performance.now()})}async function ge(e){return Jn||await Z(),e()?{aborted:!1}:{aborted:!0}}function Dr(e,t){let{inDegree:r,successors:n}=Pf(e,t),i=Rf(r),a=bf(i,r,n),s=a.length<e.length,o=s?Ef(e,a):[],c=[...a].reverse();return{ordered:a,reversed:c,hasCycles:s,cycleNodes:o}}function Pf(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 Rf(e){let t=new ht;for(let[r,n]of e)n===0&&t.enqueue(r);return t}function bf(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 Ef(e,t){let r=new Set(t);return e.filter(n=>!r.has(n))}var Tr=class{cached=null;invalidate(){this.cached=null}get(t,r){return this.cached?this.cached:(this.cached=Dr(t,r),this.cached)}};function js(e,t){let r=[];for(let n of e)t.has(n)&&r.push(n);return r}var Xn={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 Zn(e){return e==="project"||e==="task"||e==="milestone"}function Lt(e,t){return t||Zn(e)&&Xn[e].alwaysSummary}function wt(e){return e==="milestone"}function Ut(e){return Zn(e)&&Xn[e].promotesToProjectOnFirstChild}var Qn="project",ve="task";function Ke(e,t){return t===0?"milestone":e===0&&t>0?"task":null}function _r(e,t){let r=t.getActivity(e);return r?Lt(r.type,t.getChildren(e).length>0):!1}function Pr(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 ti(e,t,r){let n=_r(e,r);return _r(t,r)&&Pr(e,t,r)||n&&Pr(t,e,r)}function Ys(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 Lf(e){let t=new Map;for(let r of e)Hs(t,String(r.source),r),Hs(t,String(r.target),r);return t}function Hs(e,t,r){let n=e.get(t);if(n){n.push(r);return}e.set(t,[r])}function wf(e,t,r,n){if(e.length<=1)return e;let i=new Set(e.map(String)),a=[];for(let s of e)Of(s,i,t,r,n)||a.push(s);return a.length>0?a:e}function Of(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(xf(c,a,s,t,r,i))return!0;return!1}function xf(e,t,r,n,i,a){if(Ff(e)||!(a?String(e.source)===t:String(e.target)===t))return!1;let o=Nf(e,t);if(!n.has(String(o)))return!1;let c=i.getActivity(o);return!!(c?.autoScheduling!==!1&&c&&Mf(e,r,c))}function Ff(e){return e.source===e.target}function Nf(e,t){return String(e.source)===t?e.target:e.source}function Mf(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 br(e,t){let r=[],n=Lf(e),i=0;for(let a of e){let s=_r(a.source,t),o=_r(a.target,t);if(Wf(a,s,o,t))continue;if(!s&&!o){r.push(a);continue}let c=Vs(a.source,s,t,n,!0),l=Vs(a.target,o,t,n,!1);i=Kf(r,c,l,a,t,i,n)}return r}function Wf(e,t,r,n){return r&&Pr(e.source,e.target,n)||t&&Pr(e.target,e.source,n)}function Vs(e,t,r,n,i){return t?wf(Ys(e,r),r,n,i):[e]}function Bf(e,t,r){let n=Ys(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 Rr(e,t){return Bf(e,t,r=>{let n=t.getActivity(r);return n?{startDate:n.startDate,endDate:n.endDate}:null})}function Uf(e,t,r){return e?t?r.calculateDuration({startDate:t.startDate,endDate:t.endDate,task:e}):e.durationHours:0}function jf(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 Hf(e,t){let r=String(e);return(t.get(r)??[]).some(i=>String(i.target)===r)}function Vf(e,t,r,n,i){if(Hf(e,i))return 0;let a=n.getActivity(e);return!t||!a||!r?0:n.calculateDuration({startDate:t,endDate:a.startDate,task:r})}function Yf(e,t){let r=t.getActivity(e.source),n=t.getActivity(e.target),i=Rr(e.source,t),a=Rr(e.target,t),s=e.type===W.START_TO_START||e.type===W.START_TO_FINISH,o=e.type===W.FINISH_TO_FINISH||e.type===W.START_TO_FINISH;return{source:r,sourceBounds:i,targetStart:a?.startDate??n?.startDate,userLag:e.lag??0,sourceEndpointIsStart:s,targetLag:o?-Uf(n,a,t):0,summarySourceId:e.type===W.START_TO_START&&i?e.source:void 0}}function Kf(e,t,r,n,i,a,s){let o=Yf(n,i),{source:c,sourceBounds:l,targetStart:d,userLag:u}=o,{sourceEndpointIsStart:f,targetLag:p,summarySourceId:h}=o,A=a;for(let I of t){let T=f?jf(I,c,l,i):0;for(let g of r){if(String(I)===String(g))continue;let k=Vf(g,d,c,i,s);e.push(Gf(n,I,g,A,T,p,u+k,h,k!==0&&p===0?n.target:void 0)),A+=1}}return A}function Gf(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,freeSlackHours:null,isCritical:!1,_sourceLag:i,_targetLag:a,_trueLag:s,...o===void 0?{}:{_summarySourceId:o},...c===void 0?{}:{_summaryTargetId:c}}}var Er=class{invalidate(){}get(t,r){return br(t,r)}};function $f(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 zf(e,t,r){let n=new Set,i=new Map,a=new ht;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 Ks(e,t){let r=new Map;for(let s of t)r.set(s.id,s);let n=$f(t),i=zf(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===W.FINISH_TO_START,i=r.type===W.FINISH_TO_FINISH;if(r._targetLag!==void 0)return{sourceLag:r._sourceLag??0,targetLag:r._targetLag,trueLag:r._trueLag??r.lag??0,isFS:n,isFF:i,isZeroDurationCase:!1};let a=r.lag??0;switch(r.type){case W.FINISH_TO_START:return{sourceLag:0,targetLag:0,trueLag:a,isFS:n,isFF:i,isZeroDurationCase:!1};case W.START_TO_START:return{sourceLag:-e.durationHours,targetLag:0,trueLag:a,isFS:n,isFF:i,isZeroDurationCase:!1};case W.FINISH_TO_FINISH:return{sourceLag:0,targetLag:-t.durationHours,trueLag:a,isFS:n,isFF:i,isZeroDurationCase:!1};case W.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 qf(e,t,r){if(e._summarySourceId===void 0)return null;let n=r.getActivity(e._summarySourceId);if(!n)return null;let i=Rr(e._summarySourceId,r);return i?-r.calculateDuration({startDate:i.startDate,endDate:t.endDate,task:n}):null}function Jf(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 $s(e,t,r,n){let{sourceLag:i,targetLag:a,trueLag:s,isFS:o,isFF:c}=Gs(e,t,r),l=qf(r,e,n)??i,d=l+a+s;if(!(t.durationHours===0?d!==0:l!==0||a!==0||s!==0))return Jf(e,t,r,n,o||c);let p=o?t:e,h=n.getClosestWorkTime({date:e.endDate,dir:"future",task:p});if(l!==0&&(h=n.calculateEndDate({startDate:h,durationHours:l,task:e})),a!==0&&(h=n.calculateEndDate({startDate:h,durationHours:a,task:t})),s!==0&&(h=n.calculateEndDate({startDate:h,durationHours:s,task:t})),t.durationHours===0){if(o||c)return{successorStart:n.getClosestWorkTime({date:h,dir:"past",task:t}),link:r};let A=new Date(Date.UTC(h.getUTCFullYear(),h.getUTCMonth(),h.getUTCDate()));return{successorStart:n.getClosestWorkTime({date:A,dir:"future",task:t}),link:r}}return{successorStart:n.getClosestWorkTime({date:h,dir:"future",task:t}),link:r}}function zs(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 qs(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=Ws(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 Lr(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=qn(e.startDate,n):Bs(i,n)?a=i:a=qn(i,n),t.startDate=a,t.endDate=r.calculateEndDate({startDate:a,durationHours:e.durationHours,task:e})}function Js(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 Xf(e,t){return t.length?t.some(r=>String(r)===String(e)):!1}function Xs(e,t,r){return ei(e.id,t,r)?{startDate:e.startDate,endDate:e.endDate}:{startDate:e.startDate,endDate:e.endDate}}function ei(e,t,r){return t.dragWithMultiple&&Xf(e,r)}async function Qs(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 kr(d,i);if(f.aborted)return a;d=f.newSliceStart;let p=r.getActivity(u);if(!p||!p.autoScheduling||p.progress===100||Zf(p,r))continue;let h=s.get(String(u))??[],A=null,I=null,T=!1;for(let w of h){let v=r.getActivity(w.source);if(!v)continue;let C=o(w.source),R=C.startDate.getTime()!==v.startDate.getTime()||C.endDate.getTime()!==v.endDate.getTime(),N={...v,startDate:C.startDate,endDate:C.endDate},x=Xs(N,c,l),z={...N,startDate:x.startDate,endDate:x.endDate},Q=ei(w.source,c,l)?{...w,lag:0}:w,lt=$s(z,p,Q,r);(!A||lt.successorStart>A)&&(A=lt.successorStart,I=String(w.id),T=w._summaryTargetId!==void 0&&!R)}A!==null&&T&&A<p.startDate&&(A=new Date(p.startDate));let k=a.get(u),m=k?{...k}:{activityId:u,startDate:p.startDate,endDate:p.endDate,drivingLinkId:null,kind:"asap",conflict:!1},P=m.earliestStart||m.latestStart||m.earliestEnd||m.latestEnd;if(!(!A&&!P)){if(A){let w=A;p.type===Sr.MILESTONE&&(w=Js(p,A)),m.drivingLinkId=I,m.startDate=w,m.endDate=r.calculateEndDate({startDate:w,durationHours:p.durationHours,task:p}),m.earliestSchedulingStart=w,m.earliestSchedulingEnd=m.endDate}else p.constraintType===K.MSO?m.earliestStart&&(m.startDate=m.earliestStart,m.endDate=m.earliestEnd??r.calculateEndDate({startDate:m.earliestStart,durationHours:p.durationHours,task:p})):p.constraintType===K.MFO&&m.latestStart&&(m.startDate=m.latestStart,m.endDate=m.latestEnd??r.calculateEndDate({startDate:m.latestStart,durationHours:p.durationHours,task:p}));Lr(p,m,r),a.set(u,m)}}return a}function Zf(e,t){return Lt(e.type,t.getChildren(e.id).length>0)}async function to(e,t,r,n,i,a){let s=new Map(r),o=n.getAllActivities(),c=o.length,l=[];for(let I of o)I.constraintType===K.ALAP&&l.push(I.id);if(l.length===0)return s;let d=new Map,u=new Map;for(let I of t){let T=String(I.source);d.has(T)||d.set(T,[]),d.get(T).push(I);let g=String(I.target);u.has(g)||u.set(g,[]),u.get(g).push(I)}let f=I=>{let T=s.get(I);if(T)return{startDate:T.startDate,endDate:T.endDate};let g=n.getActivity(I);return g?{startDate:g.startDate,endDate:g.endDate}:{startDate:new Date,endDate:new Date}},p=I=>!I.parentId||L(I.parentId)?n.getProjectEnd():f(I.parentId).endDate,h=(I,T)=>{let g=I,k=0;for(;g&&!L(g)&&k++<c+1;){if(String(g)===String(T))return!0;let m=n.getActivity(g);if(!m||!m.parentId)break;g=m.parentId}return!1},A=performance.now();for(let I of e){let T=await kr(A,a);if(T.aborted)return s;A=T.newSliceStart;let g=n.getActivity(I);if(!g||g.constraintType!==K.ALAP||!g.autoScheduling||g.progress===100||Lt(g.type,n.getChildren(I).length>0))continue;let k=p(g);if(!k)continue;let m=k,P=null,w=!1,v=d.get(String(I))??[];for(let kt of v){if((kt.lag??0)<0)continue;let pe=n.getActivity(kt.target);if(!pe||pe.autoScheduling===!1)continue;let Ea=f(kt.target),wu={...pe,startDate:Ea.startDate,endDate:Ea.endDate},fr=zs(wu,g,kt,n);fr<m&&(m=fr),(P===null||fr<P)&&(P=fr,w=g.parentId&&!L(g.parentId)?h(kt.target,g.parentId):!1)}if(P!==null)if(w)m=P;else{let kt=f(I).endDate,pe=kt.getTime()>k.getTime()?kt:k;m=P<pe?P:pe}else m>k&&(m=k);let R=(u.get(String(I))??[]).some(kt=>kt.type===W.FINISH_TO_START||kt.type===W.FINISH_TO_FINISH),N=new Date(Date.UTC(m.getUTCFullYear(),m.getUTCMonth(),m.getUTCDate())),x=()=>n.getClosestWorkTime({date:N,dir:"past",task:g}),z=n.getClosestWorkTime({date:m,dir:"future",task:g}).getTime()===m.getTime(),Q;g.durationHours===0&&P===null?Q=R&&z?x():n.getClosestWorkTime({date:m,dir:"past",task:g}):g.durationHours===0?R?Q=x():Q=n.getClosestWorkTime({date:m,dir:"future",task:g}):Q=n.getClosestWorkTime({date:m,dir:"future",task:g});let lt=n.calculateEndDate({startDate:Q,durationHours:-g.durationHours,task:g}),pt=s.get(I),nt=pt?{...pt}:{activityId:I,startDate:lt,endDate:Q,drivingLinkId:null,kind:"alap",conflict:!1};nt.startDate=lt,nt.endDate=Q,nt.drivingLinkId=null,nt.kind="alap";let ue=nt.earliestSchedulingStart??null;nt.earliestSchedulingStart=null,nt.earliestSchedulingEnd=null;let fe=ue!==null&&ue.getTime()>lt.getTime()?ue:lt;nt.latestSchedulingStart=fe,nt.latestSchedulingEnd=fe===lt?Q:n.calculateEndDate({startDate:fe,durationHours:g.durationHours,task:g}),Lr(g,nt,n),s.set(I,nt)}return s}var Ae={warn(){},error(){}};function bt(e){if(e.type==="milestone")return 0;let t=e.startDate?.getTime(),r=e.endDate?.getTime();return t==null||r==null||Number.isNaN(t)||Number.isNaN(r)?null:Math.floor((r-t)/864e5)+1}function Ge(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,i.calendarDuration=bt(i),e.updateActivity(r))}})}function ri(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 Qf(i,n,r)}function $e(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 ht;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 Qf(e,t,r){if(t===r)return!0;let n=new Set([t]),i=new ht;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 wr(e){let t=tp(e);for(let r of t.adjacency.keys())t.records.has(r)||ep(r,t);return t.components}function tp(e){let t=new Map,r=new Set;for(let n of e){let i=String(n.source),a=String(n.target),s=eo(t,i);if(eo(t,a),i===a){r.add(i);continue}s.push(a)}return{adjacency:t,selfLooped:r,records:new Map,componentStack:[],nextIndex:0,components:[]}}function eo(e,t){let r=e.get(t);if(r)return r;let n=[];return e.set(t,n),n}function ep(e,t){let r=[];for(r.push({node:e,record:ro(e,t),neighborCursor:0});r.length>0;){let n=r[r.length-1];if(n===void 0)break;let i=t.adjacency.get(n.node)??[];if(n.neighborCursor<i.length){let o=i[n.neighborCursor];if(n.neighborCursor+=1,o===void 0)continue;rp(n,o,r,t);continue}r.pop();let a=r[r.length-1];a&&n.record.lowLink<a.record.lowLink&&(a.record.lowLink=n.record.lowLink),n.record.lowLink===n.record.visitIndex&&np(n.node,t)}}function rp(e,t,r,n){let i=n.records.get(t);if(!i){r.push({node:t,record:ro(t,n),neighborCursor:0});return}i.onStack&&i.visitIndex<e.record.lowLink&&(e.record.lowLink=i.visitIndex)}function ro(e,t){let r={visitIndex:t.nextIndex,lowLink:t.nextIndex,onStack:!0};return t.nextIndex+=1,t.records.set(e,r),t.componentStack.push({node:e,record:r}),r}function np(e,t){let r=[];for(;;){let s=t.componentStack.pop();if(s===void 0||(s.record.onStack=!1,r.push(s.node),s.node===e))break}let n=r[0],i=r.length===1&&n!==void 0&&t.selfLooped.has(n);(r.length>1||i)&&t.components.push(r)}function ze(e,t,r){let n=r?new ni(e,r):e;return br([...t],n)}var ni=class{constructor(t,r){this.base=t;for(let[n,i]of r.reparented){let a=String(n),s=i===null||L(i)?null:i,o=t.getActivity(n)?.parentId??null,c=o===null||L(o)?null:String(o),l=s===null?null:String(s);if(c!==l){if(this.reparented.set(a,s),c!==null){let d=this.movedOutByParent.get(c)??new Set;d.add(a),this.movedOutByParent.set(c,d)}if(l!==null){let d=this.movedInByParent.get(l)??[];d.push(n),this.movedInByParent.set(l,d)}}}}base;reparented=new Map;movedOutByParent=new Map;movedInByParent=new Map;withOverride(t){if(!t)return null;let r=this.reparented.get(String(t.id));return r===void 0?t:{...t,parentId:r}}getActivity(t){return this.withOverride(this.base.getActivity(t))}getLiveActivity(t){return this.withOverride(this.base.getLiveActivity(t))}getAllActivities(){return this.base.getAllActivities().map(t=>this.withOverride(t)??t)}getChildren(t){let r=String(t),n=this.movedOutByParent.get(r),i=this.base.getChildren(t),a=n?i.filter(o=>!n.has(String(o))):[...i],s=this.movedInByParent.get(r);return s&&a.push(...s),a}getParent(t){let r=this.reparented.get(String(t));return r===void 0?this.base.getParent(t):r===null?null:this.getActivity(r)}isChildOf(t,r){let n=String(r),i=new Set,a=this.getActivity(t);for(;a;){let s=a.parentId;if(s===null||L(s))return!1;let o=String(s);if(o===n)return!0;if(i.has(o))return!1;i.add(o),a=this.getActivity(s)}return!1}getAllLinks(){return this.base.getAllLinks()}getAllIds(){return this.base.getAllIds()}getLink(t){return this.base.getLink(t)}activityExists(t){return this.base.activityExists(t)}getOutgoingLinkIds(t){return this.base.getOutgoingLinkIds(t)}getIncomingLinkIds(t){return this.base.getIncomingLinkIds(t)}getClosestWorkTime(t){return this.base.getClosestWorkTime(t)}calculateEndDate(t){return this.base.calculateEndDate(t)}calculateDuration(t){return this.base.calculateDuration(t)}batchUpdate(t){this.base.batchUpdate(t)}updateActivity(t){this.base.updateActivity(t)}getFlags(){return this.base.getFlags()}getProjectEnd(){return this.base.getProjectEnd()}};function qe(e){let{port:t,currentLinks:r,proposedLinks:n,proposal:i}=e,a=ze(t,n,i);if(!$e(a))return{ok:!0};let s=ze(t,r),o=no(s),l=[...no(a)].filter(d=>!o.has(d));return l.length===0?{ok:!0}:{ok:!1,newlyCyclicActivityIds:l}}function no(e){let t=new Set;for(let r of wr(e))for(let n of r)t.add(n);return t}function jt(e,t){switch(e.kind){case"create":return ip(e,t);case"update":return Je(e,t.port);case"delete":return ap(e,t)}}function xr(e,t){if(e.length===0)return{applied:!0};let r=t.port.getAllLinks(),n=new Map,i=[];for(let l of r){let d=io(l);n.has(d)||n.set(d,l.id),i.push({source:l.source,target:l.target})}let a=$e(i),s=null;for(let{operation:l,linkId:d}of e){if(String(l.source)===String(l.target)){s={applied:!1,rejected:"self-link"};break}if(!t.port.getActivity(l.source)||!t.port.getActivity(l.target)){s={applied:!1,rejected:"activity-missing"};break}if(ti(l.source,l.target,t.port)){s={applied:!1,rejected:"hierarchy-link"};break}let u=io(l),f=n.get(u);if(f!==void 0){s={applied:!1,rejected:"duplicate",linkId:f};break}if(n.set(u,d),a&&ri(i,{source:l.source,target:l.target}))return{applied:!1,rejected:"cycle"};i.push({source:l.source,target:l.target})}if(!a&&$e(i))return{applied:!1,rejected:"cycle"};if(s)return s;let o=[...r,...e.map(({operation:l,linkId:d})=>({id:d,source:l.source,target:l.target,type:l.type,lag:l.lag,freeSlackHours:null,isCritical:!1}))];if(!qe({port:t.port,currentLinks:r,proposedLinks:o}).ok)return{applied:!1,rejected:"cycle"};for(let{operation:l,linkId:d}of e){let u=t.preserved?.get(d);t.port.addLink({id:d,source:l.source,target:l.target,type:l.type,lag:l.lag,freeSlackHours:null,isCritical:!1,...u?.ganttId===void 0?{}:{ganttId:u.ganttId},...u?.sectorId===void 0?{}:{sectorId:u.sectorId},...u?.proplannerId===void 0?{}:{proplannerId:u.proplannerId}})}return{applied:!0}}function io(e){return JSON.stringify([String(e.source),String(e.target),e.type])}function ip(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"};if(ti(e.source,e.target,r))return{applied:!1,rejected:"hierarchy-link"};let a=r.getAllLinks();for(let d of a)if(String(d.source)===String(e.source)&&String(d.target)===String(e.target)&&d.type===e.type)return{applied:!1,rejected:"duplicate",linkId:d.id};let s=a.map(d=>({source:d.source,target:d.target}));if(ri(s,{source:e.source,target:e.target}))return{applied:!1,rejected:"cycle"};let o=(t.newLinkId??sp)(),c={id:o,source:e.source,target:e.target,type:e.type,lag:e.lag,freeSlackHours:null,isCritical:!1};return qe({port:r,currentLinks:a,proposedLinks:[...a,c]}).ok?(r.addLink(c),{applied:!0,linkId:o}):{applied:!1,rejected:"cycle"}}function Je(e,t){return t.getLink(e.linkId)?(e.lag!==void 0&&t.setLinkField(e.linkId,"lag",e.lag),e.type!==void 0&&t.setLinkField(e.linkId,"type",e.type),{applied:!0,linkId:e.linkId}):{applied:!1,rejected:"link-missing"}}function ap(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 Or=null;function sp(){return Or===null&&(Or=Date.now()),Or+=1,String(Or)}var ao={[W.FINISH_TO_START]:"fs",[W.START_TO_START]:"ss",[W.FINISH_TO_FINISH]:"ff",[W.START_TO_FINISH]:"sf"},Qt={fs:W.FINISH_TO_START,ss:W.START_TO_START,ff:W.FINISH_TO_FINISH,sf:W.START_TO_FINISH},so="fs";function oo(e){if(e in Qt)return Qt[e]}var co=";",lo=/^(\d+)(fs|ss|ff|sf)?(?:([+-]?)(\d+(?:\.\d+)?)d?)?$/i;function Fr(e){let t=[],r=[],n=e.replace(/\s+/g,"");if(n.length===0)return{specs:t,errors:r};for(let i of n.split(co)){if(i.length===0)continue;let a=op(i);a?t.push(a):r.push(i)}return{specs:t,errors:r}}function op(e){let t=e.toLowerCase(),r=lo.exec(t);if(!r)return null;let[,n,i,a,s]=r,o=i?Qt[i]:Qt[so],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=Nr(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(Nr(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 Nr(e,t){return`${String(e)}::${t}`}function Wr(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=Nr(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(Nr(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 Br(e){let t=Math.sign(e)*Math.round(Math.abs(e));return Object.is(t,-0)?0:t}function vt(e,t){return Math.sign(e)*Math.round(Math.abs(e)*t)}var uo={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 ii(e,t,r){switch(r){case"0":return{sourceDate:e.endDate,targetDate:t.startDate};case"1":return{sourceDate:e.startDate,targetDate:t.startDate};case"2":return{sourceDate:e.endDate,targetDate:t.endDate};case"3":return{sourceDate:e.startDate,targetDate:t.endDate}}}var ai=uo;var Ie=class{adapter;reporter;currentCalculationId=0;topoCache=new Tr;expandedLinksCache=new Er;constructor(t,r=Ae){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=xs(r,()=>this.currentCalculationId),i={plans:new Map,updatedIds:[],cycles:[],cancelled:!1};try{up(this.adapter);let a=Ht("schedule.total"),s=Ht("schedule.expandParentLinks"),o=this.adapter.getAllLinks(),c=this.expandedLinksCache.get(o,this.adapter);Ot(s);let l=c;if((await ge(n)).aborted)return{...i,cancelled:!0};let d=Ht("schedule.scoping"),u=this.adapter.getAllIds(),f=fp(t,l,this.adapter),p=f.links,h=f.idSet;Ot(d);let A=Ht("schedule.topologicalSort"),I=hp(this.topoCache,u,l,h);if(Ot(A),I.hasCycles)return Ot(a),{...i,cycles:[I.cycleNodes]};if((await ge(n)).aborted)return{...i,cancelled:!0};let T=Ht("schedule.processConstraints"),g=new Map;if(qs(I.ordered,this.adapter,g),Ot(T),(await ge(n)).aborted)return{...i,cancelled:!0};let k=Ht("schedule.asapPass"),m=await Qs(I.ordered,p,this.adapter,t,n,g);if(Ot(k),(await ge(n)).aborted)return{...i,cancelled:!0};let P=Ht("schedule.alapPass"),w=await to(I.reversed,p,m,this.adapter,t,n);if(Ot(P),(await ge(n)).aborted)return{...i,cancelled:!0};let v=Ht("schedule.diff"),C=[];for(let[R,N]of w){let x=this.adapter.getActivity(R);if(!x)continue;let z=x.startDate.getTime()!==N.startDate.getTime(),Q=x.endDate.getTime()!==N.endDate.getTime();(z||Q)&&C.push(R)}return Ot(v),Ot(a),{plans:w,updatedIds:C,cycles:[],cancelled:!1}}catch(a){return this.reporter.error("[AutoScheduler] Error during scheduling",a),i}}},lp=!1;function dp(){let e=globalThis.__SCHEDULER_PHASE_LOG__;return typeof e=="boolean"?e:lp}function Ht(e){return{name:e,startedAt:performance.now()}}function up(e){let t=e;typeof t.clearCalendarCache=="function"&&t.clearCalendarCache()}function Ot(e){if(!dp())return;let t=performance.now()-e.startedAt;console.log(`[scheduler] ${e.name} ${t.toFixed(1)}ms`)}function fp(e,t,r){let n=e.triggerId;if(n==null)return{idSet:null,links:t};let i=Ks(n,t);return pp(i,t,r)}function pp(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 hp(e,t,r,n){let i=e.get(t,r);if(i.hasCycles){let s=n?Array.from(n):t;return Dr(s,r)}if(!n)return i;let a=js(i.ordered,n);return{ordered:a,reversed:[...a].reverse(),hasCycles:!1,cycleNodes:[]}}function fo(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"||wt(n.type)&&(o.type===W.START_TO_FINISH||o.type===W.FINISH_TO_FINISH))continue;let{sourceDate:d,targetDate:u}=ii(c,i,o.type),f=ai.computeLagBetweenTasks(d,u,a);f!==o.lag&&Je({kind:"update",linkId:o.id,lag:f},t)}}function po(e,t){let r=t.getActivity(e);r&&wt(r.type)&&(r.durationHours=0)}function Ce(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 Ur(e){return Number(e.toFixed(2))}function dt(e,t){return(Number(e)||0)*(Number(t)||0)/100}async function Se(e,t,r=!0,n={}){let i=t?Xe(e,t):Ip(e),a=r?n.progressMode??"freeze-when-no-contribution":"skip";await yp(i,e,a,{recomputeRealWork:n.recomputeRealWork??!1})}function jr(e,t){ho(e,t,"skip")}async function yp(e,t,r,n={recomputeRealWork:!1}){let a=0;for(let s of e)ho(s,t,r,n.recomputeRealWork),a+=1,a%200===0&&await Z()}function Xe(e,t){let r=new Set,n=new Map;for(let s of t)mp(s,e,r,n);if(r.size===0)return[];let i=Array.from(r),a=gp(i,n);return yo(i,a)}function mp(e,t,r,n){let i=t.getParentId(e);for(;i&&!L(i);){if(r.has(i))return;r.add(i);let a=t.getParentId(i);n.set(i,a),i=a}}function gp(e,t){let r=new Map;for(let n of e){if(r.has(n))continue;let i=[],a=new Set,s=n;for(;s&&!L(s)&&!r.has(s)&&!a.has(s);)i.push(s),a.add(s),s=t.get(s)??null;let o=s?r.get(s)??0:0;for(let c=i.length-1;c>=0;c-=1)o+=1,r.set(i[c],o)}return r}function vp(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+=Ap(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 ho(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=vp(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=Ce(s.weightedChildren);r!=="skip"&&(f!==null||r==="zero-when-no-contribution")&&t.setActivityField(e,"progress",Ur(f??0)),n&&t.setActivityField(e,"realWorkHours",s.realWorkSum)}function Ap(e,t){return t?Number(e.realWorkHours)||0:dt(e.workHours,e.progress)}function Ip(e){let t=Cp(e),r=Sp(t,e);return yo(t,r)}function Cp(e){let t=new Set;return e.forEachActivity(r=>{r.parentId!==null&&t.add(r.parentId)}),Array.from(t)}function Sp(e,t){let r=new Map;for(let n of e)r.set(n,kp(n,t));return r}function kp(e,t){let r=0,n=e;for(;n&&!L(n)&&t.getActivity(n);)r+=1,n=t.getParentId(n);return r}function yo(e,t){return[...e].sort((r,n)=>(t.get(n)??0)-(t.get(r)??0))}var mo={updateActivityDuration:po,updateTaskTiming:Tp("updateTaskTiming"),adjustLinkLagOnTaskMove:fo,recordLastStartDate:Dp};function Dp(e,t){let r=t.getActivity(e);r&&t.setLastStartDate(e,r.startDate)}function Vt(e,t,r,n){for(let i of t){let a=i in mo?mo[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 Tp(e){return()=>{console.debug(`[replay post-processors] ${e}: not yet ported to adapter \u2014 no-op.`)}}function O(e,t){return t!==void 0?{ok:!0,value:e,raw:t}:{ok:!0,value:e}}function M(e){return{ok:!1,reason:e}}function j(){return{valid:!0}}function tt(e,t){return t!==void 0?{valid:!1,reason:e,notification:t}:{valid:!1,reason:e}}function H(){return{allowed:!0}}function q(e,t){return t!==void 0?{allowed:!1,reason:e,alertKey:t}:{allowed:!1,reason:e}}function U(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 go={targetField:"name",canEdit(){return H()},parseInput(e){return typeof e!="string"?M("not_a_string"):O(e)},validate(){return j()},transform(e,t){return U({name:t},{autoSchedule:!1,postProcessors:[]})},trackEvent:"activity_name_entry"};var vo={targetField:"description",canEdit(){return H()},parseInput(e){return typeof e!="string"?M("not_a_string"):O(e.trim())},validate(){return j()},transform(e,t){return U({description:t},{autoSchedule:!1,postProcessors:[]})},trackEvent:"activity_description_entry"};function Dt(e){return e.constraintType??K.ASAP}var Hr=100;function ke(e){return e.progress>=Hr}function et(e,t){return Lt(e.type,t.hasChildren(e.id))}function Ao(e){return e.progress>0}function Io(e){return e.hasLookaheadTasks}function te(e,t){return Math.round(Math.ceil(e*t*60)/60)}var De=e=>({endDate:e});function Yt(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 Yr(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 _p(e,t){let r=Yt(t,"UTC");for(;!e.isWorkTime(r,ot.DAY);)r=new Date(r),r.setUTCDate(r.getUTCDate()+1),r=Yt(r,"UTC");return r}function si(e,t){return e.getClosestWorkTime({direction:X.FUTURE,date:t,unit:ot.HOUR})}function oi(e,t){let r=_p(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 Vr=new Set(["snet","snlt","mso"]),ci=new Set(["fnet","fnlt","mfo"]),Kt=new Set(["asap","alap"]),Kr="snet";function xt(e,t,r){let n=Yt(e,"UTC");if(!Vr.has(r)&&!ci.has(r))return n;let i=Vr.has(r)?si(t,n):oi(t,n),a=new Date(n);return a.setUTCHours(i.getUTCHours(),i.getUTCMinutes(),i.getUTCSeconds(),i.getUTCMilliseconds()),a}var Gt=()=>({constraintType:Kr});var ee=e=>({constraintDate:e}),Co=e=>({constraintDate:e});var So={UPDATE_TASK_TIMING:"updateTaskTiming",ADJUST_LINK_LAG_ON_TASK_MOVE:"adjustLinkLagOnTaskMove",RECORD_LAST_START_DATE:"recordLastStartDate"};var ko={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 Te(e,t,r){return Ns(e,t,r)}function _e(e,t,r){return Ms(e,t,r)}var To={targetField:"durationHours",canEdit(e,t){return ke(e)?q("completed","cant_edit_completed_activity"):et(e,t)?q("summary","summary_column_value"):H()},parseInput(e,t,r){let n=parseFloat(String(e));return Number.isFinite(n)?O(te(n,r.hoursPerDay)):M("not_a_number")},validate(e,t,r){return Do(r)?tt(ko.NEGATIVE_DURATION):Pp(t,r)?tt("unchanged"):j()},transform(e,t,r){if(Do(t))return U({},{autoSchedule:!1,postProcessors:[]});let n=Rp(e,t,r),i=bp(e,t,r,n.violated);return{...U(i,{autoSchedule:!0,postProcessors:[So.RECORD_LAST_START_DATE]}),...n.violated?{constraintWarning:_e(n.constraintType,n.constraintDate,_o(e,t,r)??void 0)}:{}}},trackEvent:"activity_duration_entry"};function Do(e){return Math.sign(e)===-1}function Pp(e,t){return e===t}function Rp(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 Te(i,e.constraintDate,a)}function bp(e,t,r,n=!1){let i={};n&&Object.assign(i,Gt(),ee(e.startDate));let a=Ke(e.durationHours,t);a&&(i.type=a),i.durationHours=t;let s=_o(e,t,r);return s&&Object.assign(i,De(s)),i}function _o(e,t,r){let n=r.calendars.getCalendar(e.calendarId);return n?n.calculateEndDate(e.startDate,t):null}var Pe=e=>({realWorkHours:e});var Ep=0,Lp=Hr,Po=0,Ro={targetField:"progress",canEdit(e,t){return Io(e)?q("has_lookahead_tasks","cant_edit_actvity_with_task"):et(e,t)?q("summary","summary_column_value"):H()},parseInput(e){let t=parseFloat(String(e));return Number.isNaN(t)?M("not_a_number"):O(t)},validate(e,t,r){return wp(r)?tt("out_of_range"):j()},transform(e,t,r){let n=Op(t),i=xp(t),a=Mp(e,t,r.hierarchy),s={progress:t,autoScheduling:n,...Pe(a.get(e.id)??0)},o=i?Fp(e,t,n,r.hierarchy,a):[],c=i?Bp(e,t,r.hierarchy):[],l=o.length+c.length>0?[...o,...c]:void 0,d=[],u=i?jp(e,t):void 0;return U(s,{autoSchedule:!1,postProcessors:d,cascadeMutations:l,trackingEvents:u})},trackEvent:"activity_progress_entry"};function wp(e){return e<Ep||e>Lp}function Op(e){return e===Po}function xp(e){return e===Hr||e===Po}function Fp(e,t,r,n,i){return n.getDescendantIds(e.id).map(s=>({activityId:s,fields:Np(t,r,i.get(s)??0)}))}function Np(e,t,r){return{progress:e,autoScheduling:t,...Pe(r)}}function Mp(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):dt(c.workHours,t);n.set(c.id,l),o+=l}return o},a=r.hasChildren(e.id)?i(e.id):dt(e.workHours,t);return n.set(e.id,a),n}function Wp(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 Bp(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=[...Wp(e,r),...r.getAncestorIds(e.id)],a=[];for(let s of i){let o=Up(s,n,r);n.set(s,o),a.push({activityId:s,fields:{progress:o}})}return a}function Up(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((Ce(n)??0).toFixed(2))}function jp(e,t){return[{name:"activity_progress_update_radio_button",properties:{activity_id:e.id,activity_name:e.name,progress_updated:t}}]}var bo={targetField:"cost",canEdit(e,t){return et(e,t)?q("summary","summary_column_value"):H()},parseInput(e){if(String(e).trim()==="")return O(0);let t=parseFloat(String(e));return Number.isNaN(t)?M("not_a_number"):O(t)},validate(){return j()},transform(e,t,r){let n=Hp(e,t,r.hierarchy);return U({cost:t},{autoSchedule:!1,postProcessors:[],cascadeMutations:n})},trackEvent:"activity_cost_budgeted_entry"};function Hp(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 Eo={targetField:"usedCost",canEdit(e,t){return et(e,t)?q("summary","summary_column_value"):H()},parseInput(e){if(String(e).trim()==="")return O(0);let t=parseFloat(String(e));return Number.isNaN(t)?M("not_a_number"):O(t)},validate(){return j()},transform(e,t,r){let n=Vp(e,t,r.hierarchy);return U({usedCost:t},{autoSchedule:!1,postProcessors:[],cascadeMutations:n})},trackEvent:"activity_cost_spent_entry"};function Vp(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 Lo={targetField:"workHours",canEdit(e,t){return et(e,t)?q("summary","summary_column_value"):H()},parseInput(e){if(String(e).trim()==="")return O(0,e);let t=parseFloat(String(e));return Number.isNaN(t)?M("not_a_number"):O(t)},validate(){return j()},transform(e,t,r,n){let i=wo(t,e.progress),a=String(n).trim()===""?[]:Yp(e,t,i,r.hierarchy);return U({workHours:t,...Pe(i)},{autoSchedule:!1,postProcessors:[],cascadeMutations:a})},trackEvent:"activity_labor_hours_budgeted_entry"};function wo(e,t){return dt(e,t)}function Yp(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??wo(d.workHours,d.progress);c+=u,l+=f}i.set(o,c),a.set(o,l),s.push({activityId:o,fields:{workHours:c,...Pe(l)}})}return s}function Gr(e,t){return e.getUTCFullYear()===t.getUTCFullYear()&&e.getUTCMonth()===t.getUTCMonth()&&e.getUTCDate()===t.getUTCDate()}function li(e,t){return e.getTime()<t.getTime()}function Re(e){return e instanceof Date&&!Number.isNaN(e.getTime())}var $r=e=>({durationHours:e});var Oo={targetField:"startDate",canEdit(e,t){return et(e,t)?q("summary","summary_column_value"):Ao(e)?q("has_progress","cant_edit_activity_with_progress"):H()},parseInput(e,t,r){return Re(e)?O(Yt(e,"UTC")):M("invalid_date")},validate(e,t,r,n){if(Gr(t,r))return tt("unchanged");let i=Kp(e,r,n);return i||j()},transform(e,t,r){let n=r.calendars.getCalendar(e.calendarId);if(!n)throw new Error("startDatePipeline: no calendar resolved (integrity)");let i=si(n,t),a=e.type==="milestone",s=a?i:n.calculateEndDate(i,e.durationHours),o=i;return{...U({startDate:i,...De(s),...a?$r(0):{},...Gt(),...ee(o)},{autoSchedule:!0,postProcessors:["adjustLinkLagOnTaskMove"]}),constraintWarning:Gp(e,i,n)}},trackEvent:"activity_start_date_entry"};function Kp(e,t,r){let n=r.hierarchy.getParentStartDateIfHasPredecessors(e.id);if(!n)return null;let i=Yt(n,"UTC");return t.getTime()<i.getTime()?tt("before_parent_start"):null}function Gp(e,t,r){let n=r.calculateEndDate(t,e.durationHours),i=Ye(Dt(e),t,n),a=Te(Dt(e),e.constraintDate,i);if(a.violated)return _e(a.constraintType,a.constraintDate,i)}var $p=99.999,Fo={targetField:"endDate",canEdit(e,t){return et(e,t)?q("summary","summary_column_value"):zp(e)?q("completed","cant_edit_completed_activity"):H()},parseInput(e,t,r){if(!Re(e))return M("invalid_date");let n=Yt(e,"UTC"),i=r.calendars.getCalendar(t.calendarId);return i?i.isWorkTime(n,ot.DAY)?O(oi(i,n)):O(i.getClosestWorkTime({direction:"past",date:n,unit:ot.HOUR})):O(n)},validate(e,t,r,n){if(Gr(e.endDate,r))return tt("unchanged");if(qp(r,e))return tt("before_date_origin");if(Jp(r,e))return tt("before_start_date");let i=Xp(r,e,n);return i||j()},transform(e,t,r){let n=Zp(e,t),i=Qp(e,t,r,!!n);return{...U(i,{autoSchedule:!0,postProcessors:["updateTaskTiming"]}),...n?{constraintWarning:n}:{}}},trackEvent:"activity_end_date_entry"};function zp(e){return e.progress>=$p}function qp(e,t){return t.dateOrigin?li(e,t.dateOrigin):!1}function Jp(e,t){return li(e,t.startDate)}function Xp(e,t,r){let n=r.calendars.getCalendar(t.calendarId);return n?n.isWorkTime(e,ot.DAY)?null:tt("not_working_day"):null}function Zp(e,t){if(Dt(e)===K.MSO)return;let n=Ye(Dt(e),e.startDate,t),i=Te(Dt(e),e.constraintDate,n);if(i.violated)return _e(i.constraintType,i.constraintDate,n)}function Qp(e,t,r,n=!1){let i={};wt(e.type)&&!n&&xo(e)?Object.assign(i,ee(e.startDate)):(n||xo(e))&&Object.assign(i,Gt(),ee(e.startDate));let o=th(e,t,r),c=Ke(e.durationHours,o);return c&&(i.type=c),Object.assign(i,$r(o)),i.endDate=t,i}function xo(e){return Kt.has(Dt(e))}function th(e,t,r){let n=r.calendars.getCalendar(e.calendarId);return n?n.calculateDuration(e.startDate,t):e.durationHours}var eh=new Set(Object.values(K)),No={targetField:"constraintType",canEdit(e,t){return ke(e)?q("completed","cant_edit_completed_activity"):et(e,t)?q("summary","summary_column_value"):H()},parseInput(e){let t=String(e).toLowerCase();return rh(t)?O(t):M("invalid_constraint_type")},validate(){return j()},transform(e,t,r){let n=nh(e,t,r);return U(n,{autoSchedule:!0})}};function rh(e){return eh.has(e)}function nh(e,t,r){let n=ah(e,t);return{constraintType:t,...Co(ih(e,t,n,r))}}function ih(e,t,r,n){if(e.type!=="milestone"||!r)return r;let i=n.calendars.getCalendar(String(e.calendarId));return i?xt(r,i,t):r}function ah(e,t){return Kt.has(t)?null:Vr.has(t)?e.startDate:ci.has(t)?e.endDate:e.constraintDate}var Mo={targetField:"constraintDate",canEdit(e,t){return ke(e)?q("completed","cant_edit_completed_activity"):et(e,t)?q("summary","summary_column_value"):H()},parseInput(e){return Re(e)?O(e):M("invalid_date")},validate(){return j()},transform(e,t,r){let n=Wo(e)?Kr:Dt(e),i=r.calendars.getCalendar(e.calendarId);if(!i)throw new Error("constraintDatePipeline: no calendar resolved (integrity)");let a=xt(t,i,n),s=sh(e,a);return U(s,{autoSchedule:!0})}};function sh(e,t){return{constraintDate:t,...Wo(e)?Gt():{}}}function Wo(e){return Kt.has(Dt(e))||!e.constraintType}var Bo={targetField:"calendarId",canEdit(){return H()},parseInput(e){let t=String(e).trim();return oh(t)?M("empty_calendar"):O(t)},validate(e,t,r,n){return ch(e.calendarId,r)?tt("unchanged"):n.calendars.getCalendar(r)?j():tt("unknown_calendar")},transform(e,t,r){return U(lh(e,t,r),{autoSchedule:!0,postProcessors:[]})},trackEvent:"activity_calendar_assignment"};function oh(e){return e===""}function ch(e,t){return e===t}function lh(e,t,r){let n={calendarId:t,assignedDefaultCalendar:!1},i=r.calendars.getCalendar(t);if(i){let a=e.durationHours===0,s=a?dh(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,De(i.calculateEndDate(c,e.durationHours)))}return n}function dh(e){return new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()))}var Uo={targetField:"customId",canEdit(e,t){return et(e,t)?q("summary","summary_column_value"):H()},parseInput(e){if(e==null)return M("empty_custom_id");if(typeof e!="string")return M("not_a_string");let t=e.trim();return t.length===0?M("empty_custom_id"):t.length>20?M("exceeds_max_length"):O(t)},validate(){return j()},transform(e,t){return U({customId:t},{autoSchedule:!1,postProcessors:[]})},trackEvent:"schedule_custom_id_edition"};var jo={targetField:"subcontractId",canEdit(){return H()},parseInput(e){if(e==null)return O(null);if(typeof e=="string"){let t=e.trim();if(t.length===0)return O(null);let r=Number(t);return!Number.isFinite(r)||!Number.isInteger(r)?M("not_an_integer"):O(r)}return typeof e=="number"?!Number.isFinite(e)||!Number.isInteger(e)?M("not_an_integer"):O(e):M("not_an_integer")},validate(){return j()},transform(e,t){return U({subcontractId:t},{autoSchedule:!1,postProcessors:[]})}};function Ze(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 zr(e){return e.some(t=>Ze(t)===null)}var Ho={targetField:"responsableIds",canEdit(){return H()},parseInput(e){return e==null?O([]):Array.isArray(e)?O(e):M("not_an_array")},validate(e,t,r){return zr(r)?tt("missing_id"):j()},transform(e,t){let r=t.map(Ze).filter(n=>n!==null);return U({responsableIds:r},{autoSchedule:!1,postProcessors:[]})}};var Vo={targetField:"tagIds",canEdit(){return H()},parseInput(e){return e==null?O([]):Array.isArray(e)?O(e):M("not_an_array")},validate(e,t,r){return zr(r)?tt("missing_id"):j()},transform(e,t){let r=t.map(Ze).filter(n=>n!==null);return U({tagIds:r},{autoSchedule:!1,postProcessors:[]})}};var uh=new Map([[_.TEXT,go],[_.DESCRIPTION,vo],[_.DURATION,To],[_.PROGRESS,Ro],[_.COST,bo],[_.USED_COST,Eo],[_.HH_WORK_TIME,Lo],[_.START_DATE,Oo],[_.END_DATE,Fo],[_.CONSTRAINT_TYPE,No],[_.CONSTRAINT_DATE,Mo],[_.CALENDAR_ID,Bo],[_.CUSTOM_ID,Uo],[_.SUBCONTRACT_ID,jo],[_.RESPONSABLES,Ho],[_.TAGS,Vo]]);function $t(e){return uh.get(e)}function be(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 fh=["name","description","type","startDate","endDate","durationHours","constraintType","constraintDate","calendarId","assignedDefaultCalendar","autoScheduling","progress","cost","usedCost","workHours","realWorkHours","customId","subcontractId","responsableIds","tagIds"],Yo=new Set(fh);var E={ID:"id",PROPLANNER_ID:"proplannerId",PARENT:"parentId",NAME:"name",DESCRIPTION:"description",TYPE:"type",START_DATE:"startDate",END_DATE:"endDate",DURATION_HOURS:"durationHours",CONSTRAINT_TYPE:"constraintType",CONSTRAINT_DATE:"constraintDate",AUTO_SCHEDULING:"autoScheduling",CALENDAR_ID:"calendarId",ASSIGNED_DEFAULT_CALENDAR:"assignedDefaultCalendar",DATE_ORIGIN:"dateOrigin",PROGRESS:"progress",COST:"cost",USED_COST:"usedCost",REAL_COST:"realCost",WORK_HOURS:"workHours",REAL_WORK_HOURS:"realWorkHours",PONDERATOR:"ponderator",HAS_CUSTOM_PONDERATOR:"hasCustomPonderator",CORRELATIVE_ID:"correlativeId",UNIQUE_CORRELATIVE_ID:"uniqueCorrelativeId",CUSTOM_ID:"customId",SUBCONTRACT_ID:"subcontractId",IS_LOOKAHEAD:"isLookahead",HAS_LOOKAHEAD_TASKS:"hasLookaheadTasks",NEW_ACTIVITIES_ARRAY:"newActivityIds",HAS_NEW_ACTIVITIES:"hasNewActivities",IS_NEW_ACTIVITY:"isNewActivity",PENDING_REQUEST_IDS:"pendingRequestIds",RESPONSABLE_IDS:"responsableIds",TAG_IDS:"tagIds",BASELINE_POINTS:"baselinePoints",BASELINE_SNAPSHOT:"baselineSnapshot",SUM_OF_DURATION_RECURSIVELY:"recursiveDurationHours",CALENDAR_DURATION:"calendarDuration",IS_CRITICAL:"isCritical",FREE_SLACK_HOURS:"freeSlackHours",EXPECTED_PROGRESS:"expectedProgress",EXPECTED_PROGRESS_BASELINE:"expectedProgressBaseline",STATUS:"status",CRITICAL_PATH:"criticalPath"},Qe={ID:"id",SOURCE:"source",TARGET:"target",TYPE:"type",LAG:"lag",FREE_SLACK_HOURS:"freeSlackHours",IS_CRITICAL:"isCritical",SOURCE_LAG:"_sourceLag",TARGET_LAG:"_targetLag",TRUE_LAG:"_trueLag",SUMMARY_SOURCE_ID:"_summarySourceId",SUMMARY_TARGET_ID:"_summaryTargetId",GANTT_ID:"ganttId",SECTOR_ID:"sectorId",PROPLANNER_ID:"proplannerId"};function rt(e,t,r,n){e.setActivityFieldDynamic(t,r,n)}function Ko(e,t,r,n){e.setLinkFieldDynamic(t,r,n)}function Ft(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:ph(e.baselineSnapshot),criticalPath:hh(e.criticalPath)}}function Et(e){return e===null?null:new Date(e)}function ph(e){return e===null?null:{...e,startDate:Et(e.startDate),endDate:Et(e.endDate)}}function hh(e){return e===null?null:{...e,earlyStart:Et(e.earlyStart),earlyFinish:Et(e.earlyFinish),lateStart:Et(e.lateStart),lateFinish:Et(e.lateFinish)}}var zo=200;function zt(e,t){let r=new Set([String(e)]);for(let n of t.cascadeMutations??[])r.add(String(n.activityId));return r}async function $(e,t){let r=new Map,n=0;for(let i of t){n+=1,n%zo===0&&await Z();let a=e.getActivity(i);a&&r.set(i,J(a))}return r}function J(e){return Ft(e)}function qr(e,t){let r=e.getActivity(t);return r?Ft(r):null}function qt(e,t,r){Go(e,t,r.patch);for(let n of r.cascadeMutations??[])Go(e,n.activityId,n.fields)}function Go(e,t,r){for(let[n,i]of Object.entries(r)){if(!Yo.has(n))throw new Error(`applyFieldChanges: column write to non-writable field "${n}"`);rt(e,t,n,i)}}async function Jr(e,t,r,n){let i=[],a=0;for(let s of r){a+=1,a%zo===0&&await Z();let o=yh(e,t,s,n);o&&i.push(o)}return i}function yh(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 mh(r,n.get(r),i);let s=ui(a,i);return gh(s,n,r,i),a&&Object.keys(s).length===0?null:{id:r,kind:a?"updated":"created",fields:s,after:J(i)}}function mh(e,t,r){return t===r.correlativeId?null:{id:e,kind:"updated",fields:{correlativeId:{before:t,after:r.correlativeId}},after:J(r)}}function gh(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 ui(e,t){let r={},n=e??{},i=t,a=new Set([...Object.keys(n),...Object.keys(i)]);a.delete(E.CALENDAR_DURATION);for(let s of a)(Object.hasOwn(n,s)!==Object.hasOwn(i,s)||!di(n[s],i[s]))&&(r[s]={before:$o(n[s]),after:$o(i[s])});return r}function $o(e){return e===null||typeof e!="object"?e:b(e)}function di(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)=>di(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)&&di(r[s],n[s]))}function Xr(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 fi(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 Ee(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 vh=/^(\d{4})\/(\d{1,2})\/(\d{1,2})\s+(\d{1,2}):(\d{2})$/;function Nt(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(vh);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 Le(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 Ah=e=>e.type==="project",Ih=(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:Nt(String(s));return Le(a(e.startDate),a(e.endDate),t,i)};function Ch(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(!Ah(o)){let d=Ih(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 ne(e,t){let r=[];e.forEachActivity((n,i)=>{n.parentId===null&&r.push(i)}),Ch(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 Sh=e=>e.type==="project",kh=e=>ut(e),Dh=(e,t,r,n)=>{let i=kh(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:Le(i.startDate,i.endDate,t,a)};function pi(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(!Sh(c)){let u=Dh(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),h=typeof p?.ponderator=="number"?p.ponderator:0;l+=f*h}let d=l/100;return a(o,d),d};for(let o of e)s(o);return i}function we(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)}),pi(i,t,n,r)}var qo=e=>Math.round(e*100)/100;function Th(e,t){return(t==="Baseline"?e.expectedProgressBaseline:e.expectedProgress)??void 0}function _h(e,t){let r=qo(e),n=qo(t);return r>99.99?Rt.DONE:n>r?Rt.OVERDUE:e>0&&r>n?Rt.ADVANCEMENT:e===0&&t===0?Rt.WAITING:e>0&&r<n?Rt.DOING:Rt.WAITING}function Mt(e,t){let r=[];return e.forEachActivity((n,i)=>{let a=typeof n.progress=="number"?n.progress:0,s=_h(a,Th(n,t));n.status!==s&&(rt(e,i,Ar,s),r.push(i))}),r}function hi(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:()=>hi(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}hi.isMoment=e=>!!e&&typeof e=="object"&&e.__isMomentShim===!0;var At=hi;function Ph(e){return e&&e.constructor===Date?!!(e.getFullYear&&e.getMonth&&e.getDate):!1}function Zr(e){return Ph(e)&&!isNaN(e.getTime())}function D(e,t,r,n){if(!Zr(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 yt(e){if(!Zr(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 Rh=e=>e?e.$level===1:!1,bh=e=>e.type==="project",Eh=e=>e.$level!==0,Lh=e=>e.type==="task",wh=e=>e.type==="task"||e.type==="milestone",ct={byFirstLevel:Rh,filterByParentType:bh,avoidSubproject:Eh,byTaskType:Lh,byTaskTypeAndMilestone:wh};var y=Object.freeze({MFO:"mfo",MSO:"mso",FNLT:"fnlt",FNET:"fnet",SNET:"snet",SNLT:"snlt",ALAP:"alap",ASAP:"asap"});var V=Object.freeze({FS:"fs",SS:"ss",FF:"ff",SF:"sf"});function ie(e){return{0:"fs",1:"ss",2:"ff",3:"sf"}[Number(e)]||"sf"}function Jo(e){let{gantt:t,pendingParentsWithNoLinks:r,calculations:n,linkProperty:i}=e;try{let a=Oh({gantt:t,pendingParentsWithNoLinks:r});if(a.length===0)return new Set;let s=xh({gantt:t,subprojectsWithNoLinks:a}),o=Fh({gantt:t,childrenIds:s,linkProperty:i,getArrayOfLinkedActivities:Nh,calculations:n});return new Set(o.map(c=>c.id))}catch(a){throw a}}function Oh(e){let{gantt:t,pendingParentsWithNoLinks:r}=e;return t.getTaskByTime().filter(ct.filterByParentType).filter(n=>r.has(n.id)).map(n=>n.id)}function xh(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 Fh(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 Nh(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 Xo({gantt:e,linkProperty:t,direction:r}){try{let n=Mh(e,t);if(r==="forward")return{chainStartActivities:n,activitiesStartChainButChildrenOfLinkedParents:null};if(r==="backward")return Wh(n,e,t)}catch(n){throw console.log("Critical Path",n),n}}function Mh(e,t){return e.getTaskByTime().filter(ct.avoidSubproject).filter(ct.byTaskTypeAndMilestone).filter(r=>!r[t].length)}function Wh(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 Zo({gantt:e,direction:t,linkProperty:r}){try{let n=Bh(e),i=new Set,a=new Set,s=new Set;t==="backward"&&Hh(n).forEach(d=>{i.add(d.id)});let o=Uh(n,t,r),c=jh(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 Bh(e){return e.getTaskByTime().filter(ct.filterByParentType).filter(ct.avoidSubproject)}function Uh(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 jh(e,t){let r=new Set(t.map(n=>n.id));return e.filter(n=>!r.has(n.id))}function Hh(e){return e.filter(t=>{let r=Number(t.progress);return Number.isNaN(r)?!1:r===100})}function Qo({pendingParentsWithLinks:e,gantt:t,direction:r}){try{let n=new Set;return e.forEach(i=>{let a=t.getTask(i),s=Vh(r),o=Yh(r),c=a[s];if(!Array.isArray(c))return;Kh(t,c,o).forEach(d=>{n.add(d)})}),n}catch(n){throw n}}function Vh(e){return e==="forward"?"$source":"$target"}function Yh(e){return e==="forward"?"target":"source"}function Kh(e,t,r){return t.map(n=>{let a=e.getLink(n)[r];return Number(a)})}var tr={identifySecondLevelActivities:Jo,identifyInitialActivities:Xo,identifyParentsWithAndWithoutLinks:Zo,identifyForbiddenActivities:Qo};function Qr(e){return e.length?e.reduce((t,r)=>r.ef>t.ef?r:t):!1}function yi({linkType:e,lag:t,predecessorTime:r,activityCalendar:n,activity:i}){return e===V.FS&&t===0?yt({predecessorTime:r,activityCalendar:n,direction:"future",activity:i}):er(r,e,n,i)}function tc({duration:e,constraintDate:t,activityCalendar:r,activity:n}){let i=new Date(t);return{es:D(r,i,e,n),ef:i}}function ec({duration:e,constraintDate:t,activityCalendar:r,activity:n}){let i=new Date(t),a=D(r,i,e,n);return{es:i,ef:a}}function er(e,t,r,n){if(![V.FS,V.SS,V.FF].includes(t))return e;let a=[V.FS,V.SS].includes(t)?"future":"past";return yt({dateBaseToCalculate:e,activityCalendar:r,direction:a,activity:n})}var mi=class{constructor(t,r,n,i){if(this.linkedActivitiesData=t,this.activity=r,this.gantt=n,this.linkCandidates=i,this.activityCalendar=this.gantt.getCalendar(this.activity.calendar_id),!this.activityCalendar)throw new Error(`Error trying to get calendar with id: ${this.activity.calendar_id}`)}calculate(){let t=this.calculateLinks(),r=Qr(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=ie(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&&(this.linkCandidates?.set(r.linkId,{targetId:String(this.activity.id),...c}),t.push(c))}return t}handleSNETConstraint(t){let r=ec({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=tc({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=yi({linkType:"ss",lag:t,predecessorTime:r,activityCalendar:this.activityCalendar,activity:this.activity}),i=D(this.activityCalendar,n,t,this.activity);t>0&&(i=er(i,"ss",this.activityCalendar,this.activity));let a=D(this.activityCalendar,i,this.activity.duration,this.activity);return{es:i,ef:a}}calculateFFLink({lag:t,predecessorEf:r}){let n=yi({linkType:"ff",lag:t,predecessorTime:r,activityCalendar:this.activityCalendar,activity:this.activity}),i=D(this.activityCalendar,n,t,this.activity),a=D(this.activityCalendar,i,-this.activity.duration,this.activity);return t>0&&(a=er(a,"ff",this.activityCalendar,this.activity)),{es:a,ef:i}}calculateFSLink({lag:t,predecessorEf:r}){let n=r;t===0&&(n=yt({dateBaseToCalculate:r,activityCalendar:this.activityCalendar,direction:"future",activity:this.activity}));let i=D(this.activityCalendar,n,t,this.activity),a=D(this.activityCalendar,i,this.activity.duration,this.activity);return{es:i,ef:a}}calculateSFLink({lag:t,predecessorEs:r}){let n=D(this.activityCalendar,r,t,this.activity),i=D(this.activityCalendar,n,-this.activity.duration,this.activity);return t>0&&(i=er(i,"sf",this.activityCalendar,this.activity)),{es:i,ef:n}}},rc=mi;var gi=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=ie(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:D(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=D(this.activityCalendar,r,i,this.activity),s=D(this.activityCalendar,a,n,this.activity),{ls:s,lf:a};let o=r;return t>0&&(o=this.getLastWorkingHour(o,this.activityCalendar,"past")),a=D(this.activityCalendar,o,i,this.activity),s=D(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=D(this.activityCalendar,l,i,this.activity),s=this.getLastWorkingHour(s,this.activityCalendar,"past"),o=D(this.activityCalendar,s,n,this.activity),{ls:o,lf:s}}let c=r;return a||(c=this.getLastWorkingHour(r,this.activityCalendar)),s=D(this.activityCalendar,c,i,this.activity),o=D(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=D(this.activityCalendar,o,n,this.activity),a=D(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=D(this.activityCalendar,r,n,this.activity),s=D(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=D(this.activityCalendar,c,n,this.activity),s=D(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:D(this.activityCalendar,t,-r,this.activity),lf:t}}getLastWorkingHour(t,r,n="past"){let i=t instanceof Date?t:new Date(t),a=At(i).clone();return this.isActivityInInitHour(r,i)&&n==="past"&&(a=a.hours(0).minutes(0).seconds(0).milliseconds(0)),yt({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),At.isMoment(r)?r.hours()===s:n.getUTCHours()===s)}},nc=gi;function ic(e){let{parent:t,linkProperty:r,linkDirection:n,calculations:i,gantt:a,direction:s,linkCandidates:o}=e,c=t[r],l=Gh(t),d=null;if(s==="forward"){let u=$h(c,n,i,a);d=new rc(u,t,a,o),d=d.calculate()}else{let u=zh(c,n,i,a);d=new nc({linksWithActivityData:u,activity:t,parentData:l,gantt:a}).calculate()}return d}function Gh(e){return{duration:e.duration,calendarId:e.calendar_id}}function $h(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?{linkId:String(a.id),es:o.es,ef:o.ef,linkLag:a.lag,linkType:a.type}:(console.warn(`Calculations not found for activity: ${s}`),null)}).filter(Boolean)}function zh(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 oc(e){let{activityData:t,calculations:r,singleParents:n,direction:i}=e;if(qh(t.id,r))return null;let a=Jh(t.id,n),s=Xh(a,r);return s.length===0?null:Zh(s,i)}function qh(e,t){return t.has(e)}function Jh(e,t){let r=t.get(e);return r?r.childrens:[]}function Xh(e,t){return e.filter(r=>t.has(r)).map(r=>t.get(r))}function Zh(e,t){if(t==="forward"){let r=ac(e,"es"),n=sc(e,"ef");return{es:r,ef:n}}else{let r=ac(e,"ls"),n=sc(e,"lf");return{ls:r,lf:n}}}function ac(e,t){return e.reduce((r,n)=>n[t]<r[t]?n:r)[t]}function sc(e,t){return e.reduce((r,n)=>n[t]>r[t]?n:r)[t]}var vi={parentWithLinks:ic,parentWithNoLinks:oc};var Ai=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.linkCandidates=t.linkCandidates,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=vi.parentWithLinks({parent:t,linkProperty:this.linkProperty,linkDirection:this.linkDirection,gantt:this.gantt,calculations:this.calculations,direction:this.direction,linkCandidates:this.linkCandidates});this.calculationsOfParentThatImpactChildrens.set(t.id,r),this.calculationOfParentsFromLinks.add(t.id)}areAllLinksCalculated(t){return t.every(r=>this.calculations.has(r))}shouldSetDatesToParentsWithLinks(t){let r=t.includes(this.activity.constraint_type),n=this.calculationOfParentsFromLinks.has(this.activity.id);return r&&n}handleParentWithNoLinks(){let t=vi.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)})}},cc=Ai;var Ii=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}}},lc=Ii;var Ci=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}=tr.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=tr.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 lc({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=tr.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}=tr.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:At(n.start_date).clone(),lf:At(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=At(t.start_date).clone(),i=At(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=D(r,i,-a,t);else{let c=[y.SNLT,y.MSO],l=[y.FNLT,y.MFO];c.includes(o)&&(n=t.constraint_date,i=D(r,n,a,t)),l.includes(o)&&(i=t.constraint_date,n=D(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 cc({activity:t,direction:this.direction,calculationsOfParentThatImpactChildrens:this.calculationsOfParentThatImpactChildrens,calculations:this.calculations,calculationOfParentsFromLinks:this.calculationOfParentsFromLinks,singleParents:this.singleParents,parentCalculationFromChildren:this.parentCalculationFromChildren,linkCandidates:this.linkCandidates,gantt:this.gantt});this.pendingParentsWithLinks.has(t.id)?r.handleParentWithLinks():r.handleParentWithNoLinks()}},Jt=Ci;function Qh(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=D(r,i,e.duration,e)}else if([y.FNLT,y.FNET].includes(t)){let i=new Date(e.constraint_date);n.es=D(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=D(r,i,e.duration,e)}else if(t===y.MFO){let i=new Date(e.constraint_date);n.es=D(r,i,-e.duration,e),n.ef=i}return n}var tn=Qh;var Si=class{constructor(t){this.referenceActivity=t.activity,this.activityToCalculate=null,this.links=t.links,this.calculatedActivities=t.calculatedActivitiesMap,this.alapMap=t.calculatedAlapsMap,this.parentsWithLinks=t.parentsWithLinks,this.parentsCalculations=t.parentsCalculations,this.gantt=t.ganttInstance,this.linkCandidates=t.linkCandidates}getEsAndEfFromPreviousCalculatedActivities(t){return this.alapMap.has(t)?this.alapMap.get(Number(t)):this.calculatedActivities.get(Number(t))}calculateSucessorTimes(t,r,n=0,i,a=V.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===V.FS&&i===0?o=yt({dateBaseToCalculate:o,activityCalendar:s,direction:"future",activity:this.referenceActivity}):o=this.mutateTheDateToFutureOrPastInBaseRestriction(t,a,s)),[V.FF,V.SF].includes(a)?(l=D(s,o,n,this.referenceActivity),c=D(s,l,r,this.referenceActivity),!d&&i>0&&(c=this.mutateTheDateToFutureOrPastInBaseRestriction(c,a,s))):(c=D(s,o,r,this.referenceActivity),!d&&i>0&&(c=this.mutateTheDateToFutureOrPastInBaseRestriction(c,a,s)),l=D(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,V.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,V.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,V.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,V.SF)}mutateTheDateToFutureOrPastInBaseRestriction(t,r,n){if(![V.FS,V.SS,V.FF].includes(r))return t;let a=[V.FS,V.SS].includes(r)?"future":"past";return yt({dateBaseToCalculate:t,activityCalendar:n,direction:a,activity:this.referenceActivity})}},dc=Si;var rr=class extends dc{constructor(t){super(t)}calculate(){if(this.links.length===0)return new Jt(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}});let a=this.calculateLink(i);return this.linkCandidates?.set(String(i.id),{targetId:String(this.referenceActivity.id),...a}),a}),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=D(n,i,this.referenceActivity.duration,this.referenceActivity);t.push({es:i,ef:a})}return Qr(t)}calculateLink(t){return{0:()=>this.calculateFS(t),1:()=>this.calculateSS(t),2:()=>this.calculateFF(t),3:()=>this.calculateSF(t)}[t.type]()}};var ki=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}},en=ki;var Di=(e,t)=>()=>t()===e;var Ti=e=>!e?.fullyParsed||typeof window<"u"&&window.to_use_react_gantt?.conversionMode?.isActive;var ty=16,ae=async e=>performance.now()-e>ty?(await Z(),performance.now()):e;var nr=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 ae(c);let{activitiesThatCanBeCalculated:l,pendingActivities:d}=t.checkActivitiesThatNowCanBeCalculated(o);if(l.size===0)break;for(let u of l){if(!s())return;c=await ae(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 _i=class extends Jt{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.linkCandidates=new Map,this.calculationOfParentsFromLinks=new Set,this.parentCalculationFromChildren=new Set,this.forbiddenActivitiesLinkedToParentsWithLinks=new Set,this.activitiesStartChainButChildrenOfLinkedParents=new Set,this.identifyInitialActivities(),this.initActivitiesWaitingForCalculation()}async calculateAsync(t){this.identifyParentsWithAndWithoutLinks(),t()&&(this.identifyForbiddenActivitiesLinkedToParentsWithLinks(),t()&&(this.initializeActivitiesWithFullProgress(),t()&&(this.calculateStartAndFinishOfActivitiesThatStartChain(),t()&&(this.identifySecondLevelActivities(),t()&&(this.identifyThirdLevelActivities(),t()&&await this.iterativeCalculateEfAndEs(t))))))}async iterativeCalculateEfAndEs(t){let r=new en({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 nr({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 rr({links:i,activity:n,calculatedActivitiesMap:this.calculations,calculatedAlapsMap:this.alapMap,constraint:a,parentsWithLinks:this.pendingParentsWithLinks,parentsCalculations:this.calculationsOfParentThatImpactChildrens,ganttInstance:this.gantt,linkCandidates:this.linkCandidates}).calculate(),a===y.ASAP&&this.totalFloatForAsap.set(r,{es:f.es,ef:f.ef,text:n.text})):{es:d,ef:u}=new rr({links:i,activity:n,calculatedActivitiesMap:this.calculations,calculatedAlapsMap:this.alapMap,constraint:a,parentsWithLinks:this.pendingParentsWithLinks,parentsCalculations:this.calculationsOfParentThatImpactChildrens,ganttInstance:this.gantt,linkCandidates:this.linkCandidates}).calculate(),a===y.ALAP&&this.alapMap.set(r,{es:n.start_date,ef:n.end_date,text:n.text});let p=tn(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 h=n.end_date;a===y.MFO&&(h=Math.max(p.ef,n.end_date)),d=n.start_date,u=h}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)}},uc=_i;var Pi=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=V.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=D(s,o,r,this.activity),u=D(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===V.FS){let{ls:d,lf:u}=this.calculateFsLink(l);return{ls:d,lf:u}}if(a===V.FF){let{ls:d,lf:u}=this.calculateFFLink(l);return{ls:d,lf:u}}if(a===V.SS){let{ls:d,lf:u}=this.calculateSSlink(l);return{ls:d,lf:u}}if(a===V.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,V.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,V.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,V.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,V.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=At(r).clone();return D(t,new Date(i),n,this.activity)}getLastWorkingHour(t,r,n="past"){let i=t instanceof Date?t:new Date(t),a=At(i).clone();return this.isActivityInInitHour(r,i)&&n==="past"&&(a=a.hours(0).minutes(0).seconds(0).milliseconds(0)),yt({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),At.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=D(n,d,a,this.activity),o=this.getLastWorkingHour(o,n,"past"),c=D(n,o,i,this.activity),{ls:c,lf:o}}let l=r;return s||(l=this.getLastWorkingHour(r,n)),o=D(n,l,a,this.activity),c=D(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=D(n,r,a,this.activity),o=D(n,s,i,this.activity),{ls:o,lf:s};let c=r;return t>0&&(c=this.getLastWorkingHour(c,n,"past")),s=D(n,c,a,this.activity),o=D(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=D(n,r,i,this.activity),o=D(n,c,a,this.activity),{ls:c,lf:o};let l=r;return t<0&&!s&&(l=this.getLastWorkingHour(l,n,"future")),c=D(n,l,i,this.activity),o=D(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=D(n,r,i),s=D(n,o,a,this.activity),{ls:o,lf:s}):(o=D(n,r,i,this.activity),s=D(n,o,a,this.activity),{ls:o,lf:s})}},fc=Pi;var Ri=class extends fc{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 Jt(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=D(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:D(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))}},pc=Ri;function ey(e,t,r){let n={ls:null,lf:null};return r===y.MSO&&(n.ls=t.constraint_date,n.lf=D(e,n.ls,t.duration,t)),r===y.MFO&&(n.lf=t.constraint_date,n.ls=D(e,n.lf,-t.duration,t)),n}var hc=ey;var bi=class extends Jt{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 en({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 nr({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=tn(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 pc({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=hc(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=D(this.gantt.getCalendar(t.calendar_id),a,-t.duration,t);if([y.SNLT].includes(t.constraint_type)){let l=this.calculationsOfParentThatImpactChildrens.get(r),d=D(this.gantt.getCalendar(t.calendar_id),l.lf,-t.duration,t),u=t.constraint_date??d;i=new Date(Math.min(u.getTime(),d.getTime())),a=D(this.gantt.getCalendar(t.calendar_id),i,t.duration,t)}if([y.FNLT].includes(t.constraint_type)){let l=this.calculationsOfParentThatImpactChildrens.get(r),d=t.constraint_date??l.lf;i=new Date(Math.min(d.getTime(),l.lf.getTime())),a=D(this.gantt.getCalendar(t.calendar_id),i,t.duration,t)}[y.MSO].includes(t.constraint_type)&&(i=t.constraint_date,a=D(this.gantt.getCalendar(t.calendar_id),i,t.duration,t)),[y.MFO].includes(t.constraint_type)&&(a=t.constraint_date,i=D(this.gantt.getCalendar(t.calendar_id),a,-t.duration,t));let s=this.projectDates.end_date,o=[{ls:i,lf:a}];o.push({ls:D(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}},yc=bi;function mc(){return null}var gc=({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 Ei=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)})}},vc=Ei;var Li=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){let r=t===y.ALAP?this.backwardMap.get(this.activity.id):this.forwardMap.get(this.activity.id);return this.parseHoursToDays(this.calculationWithCalendar(this.gantt.getSubtaskDates().end_date,t===y.ALAP?r?.lf:r?.ef))}calculateFreeFloatOfRestriction(t){let r=this.forwardMap.get(this.activity.id);return this.parseHoursToDays(this.calculationWithCalendar(this.activity.constraint_date,t===y.FNLT?r?.ef:r?.es))}getLinkData(t){let r=this.gantt.getLink(t)||{},n=ie(r.type);return{LINK:r,LINK_TYPE:n}}getSucessorAndPredecessorDates({constraint:t,isSuscessorAlap:r,sucessorId:n,predecessorId:i}){let a=(r?this.backwardMap:this.forwardMap).get(n),s=(t===y.ALAP?this.backwardMap:this.forwardMap).get(i),o=t===y.ALAP?s?.ls:s?.es,c=t===y.ALAP?s?.lf:s?.ef;return{fs:{sucessor:a?.ls??a?.es,predecessor:c},ss:{sucessor:a?.ls??a?.es,predecessor:o},ff:{sucessor:a?.lf??a?.ef,predecessor:c},sf:{sucessor:a?.lf??a?.ef,predecessor:o}}}calculateMsoMfo(t){let r=this.activity.constraint_date||new Date,n=this.forwardMap.get(this.activity.id),i=t===y.MSO?n?.es:n?.ef,a=this.calculationWithCalendar(r,i);return Math.max(0,this.parseHoursToDays(a))}getMinValue(...t){let r=t.filter(n=>n!=null);return r.length?Math.min(...r):0}calculationWithCalendar(t,r){if(!(t instanceof Date)||!(r instanceof Date)||!Number.isFinite(t.getTime())||!Number.isFinite(r.getTime()))return Number.NaN;let 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==null?0:t/this.gantt.config.hoursPerDay}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)}},Ac=Li;var Ic=e=>({totalFloat:new vc(e.totalFloat).getTotalFloat(),freeFloat:new Ac(e.freeFloat).getFreeFloat()});var wi=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=gc({forward:t,backward:r,id:l,activity:d,gantt:n,projectDates:i}),{totalFloat:f,freeFloat:p}=Ic(u);o.set(l,f),c.set(l,p),s=await ae(s)}return{totalFloatMap:o,freeFloatMap:c}};var Oi=class{constructor(t){this.gantt=t,this.forwardPathCalculations=null,this.backwardPathCalculations=null,this.totalFloat=new Map,this.freeFloat=new Map,this.linkResidualHours=new Map,this.currentCalculationId=0}getCurrentCalculationId=()=>this.currentCalculationId;async calculate(t,r=()=>!0){let n=++this.currentCalculationId,i=Di(n,this.getCurrentCalculationId),a=()=>i()&&r();try{let s=t||this.gantt;if(this.gantt=s||mc(),Ti(this.gantt))return!1;let o=new uc(this.gantt);if(await o.calculateAsync(a),!a())return!1;let c=o.calculations,l=o.constraintsMap,d=new yc(this.gantt,c,l);if(await d.calculateAsync(a),!a())return!1;this.forwardPathCalculations=c,this.backwardPathCalculations=d.calculations;let u=await this.calculateLinkResidualHours(o.linkCandidates,c,a);if(!u||!a())return!1;this.linkResidualHours=u;let{totalFloatMap:f,freeFloatMap:p}=await this.calculateFloatsAsync(o,d,a);return a()?(this.totalFloat=f,this.freeFloat=p,this.gantt.refreshData(),!0):!1}catch(s){throw this.forwardPathCalculations?.size,s}}async calculateLinkResidualHours(t,r,n=()=>!0){let i=new Map,a=performance.now();for(let[s,o]of t){if(a=await ae(a),!n())return null;let c=Number(o.targetId),l=this.gantt.getTask(c),d=r.get(c),u=o.ef,f=d?.ef,p=l&&this.gantt.getCalendar(l.calendar_id);if(!p||!(u instanceof Date)||!(f instanceof Date)||!Number.isFinite(u.getTime())||!Number.isFinite(f.getTime())){i.set(s,null);continue}let h=u.getTime(),I=f.getTime()>=h?p.calculateDuration({start_date:u,end_date:f}):-p.calculateDuration({start_date:f,end_date:u});i.set(s,Number.isFinite(I)?Object.is(I,-0)?0:I:null)}return i}async calculateFloatsAsync(t,r,n){try{let i=this.gantt.getSubtaskDates(),a=Array.from(this.forwardPathCalculations.keys());return await wi({activityIds:a,forward:t,backward:r,gantt:this.gantt,projectDates:i,isCurrent:n})}catch(i){throw this.forwardPathCalculations?.size,i}}},Cc=Oi;var ry=e=>e==="fnet"||e==="fnlt"||e==="mfo",ny=e=>new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()));function iy(e,t){let r=e.constraintDate;if(!r||!ry(e.constraintType))return r;let n=ny(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()?zn(e,t):r}function ay(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 sy(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 oy(e){let t=new Set;e.forEachActivity((o,c)=>{t.add(String(c)),o.parentId!==null&&t.add(String(o.parentId))});let r=new Map;for(let o of t){let c=Number(o);Number.isSafeInteger(c)&&c!==0&&r.set(c,(r.get(c)??0)+1)}let n=new Map,i=new Map;for(let o of t){let c=Number(o);Number.isSafeInteger(c)&&c!==0&&r.get(c)===1&&(n.set(o,c),i.set(c,o))}let a=1,s=o=>{let c=String(o),l=n.get(c);if(l!==void 0)return l;for(;i.has(a);)a+=1;return n.set(c,a),i.set(a,c),a++};for(let o of t)s(o);return{toLegacy:s,toCanonical:o=>typeof o=="number"?i.get(o)??null:n.has(String(o))?String(o):null}}function cy(e,t){let r=sy(e),n=new Map;return e.forEachActivity((i,a)=>{let s=String(a);n.set(s,{id:t.toLegacy(s),parent:i.parentId===null?0:t.toLegacy(i.parentId),$level:r.get(s)??0,$source:e.getOutgoingLinkIds(s),$target:e.getIncomingLinkIds(s),start_date:i.startDate,end_date:i.endDate,duration:i.durationHours,progress:i.progress,type:i.type,calendar_id:i.calendarId,constraint_type:i.constraintType,constraint_date:iy(i,e)})}),n}function ly(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 dy(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 Sc(e,t){let r=new Map,n=l=>{let d=l==null?"__default__":String(l),u=r.get(d);if(u)return u;let f=e.calendarReader.getCalendar(String(l)),p=ay(f);return r.set(d,p),p},i=dy(e);await Z();let a=oy(e),s=cy(e,a);await Z();let o=[...s.values()].sort((l,d)=>(l.start_date?.getTime()??0)-(d.start_date?.getTime()??0));await Z();let c=ly(s);return{fullyParsed:!0,config:{hoursPerDay:t},getTask:l=>{let d=a.toCanonical(l);return d===null?null:s.get(d)??null},getLink:l=>{let d=e.getLink(l);return d?{...d,source:a.toLegacy(d.source),target:a.toLegacy(d.target),lag:d.lag}:null},getCalendar:n,getChildren:l=>{let d=a.toCanonical(l);return d===null?[]:e.getChildren(d).map(a.toLegacy)},eachTask:l=>{for(let d of c)l(d)},getTaskByTime:()=>o,getSubtaskDates:()=>i,getCanonicalActivityId:a.toCanonical,refreshData:()=>{}}}var Dc=1e3;function uy(e,t,r,n){let i=typeof e=="number"&&Number.isFinite(e)?Object.is(e,-0)?0:e:null;return{freeSlackHours:i,isCritical:i!==null&&i<=0&&t&&r&&n===0}}async function fy(e,t,r,n,i){let a=new Map,s=0;for(let o of t.forward?.keys()??[]){if(++s>=Dc&&(s=0,await Z(),!i()))return null;let c=n(o);if(c===null)continue;let l=e.getActivity(c);l&&a.set(String(c),hy(o,Number(l.progress??0),t,r))}return i()?a:null}async function py(e,t,r,n){let i=new Map,a=0;for(let s of e.getAllLinks()){if(++a>=Dc&&(a=0,await Z(),!n()))return null;i.set(String(s.id),uy(t.get(String(s.id)),r.get(s.source)?.isCritical===!0,r.get(s.target)?.isCritical===!0,e.getActivity(s.target)?.progress))}return n()?i:null}var kc=(e,t)=>{if(typeof e!="number"||!Number.isFinite(e)||!Number.isFinite(t)||t<=0)return null;let r=e*t;return Number.isFinite(r)?Object.is(r,-0)?0:r:null};function hy(e,t,r,n){let i=c=>{if(c==null)return null;let l=new Date(c);return Number.isFinite(l.getTime())?l:null},a=r.forward?.get(e),s=r.backward?.get(e),o=kc(r.totalFloat.get(e),n);return{criticalPath:{earlyStart:i(a?.es),earlyFinish:i(a?.ef),lateStart:i(s?.ls),lateFinish:i(s?.lf),totalSlackHours:o},isCritical:t<100&&o!==null&&o<=0,freeSlackHours:kc(r.freeFloat.get(e)?.activityFreeFloat,n)}}var rn=(e,t)=>e===t||e!==null&&t!==null&&e.getTime()===t.getTime();function xi(e,t,r){let n=e.getActivity(t),i=n?.criticalPath,a=r.criticalPath;n&&i&&rn(i.earlyStart,a.earlyStart)&&rn(i.earlyFinish,a.earlyFinish)&&rn(i.lateStart,a.lateStart)&&rn(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)}function Fi(e,t,r){let n=e.getLink(t);!n||Object.is(n.freeSlackHours,r.freeSlackHours)&&Object.is(n.isCritical,r.isCritical)||(e.setLinkField(t,"freeSlackHours",r.freeSlackHours),e.setLinkField(t,"isCritical",r.isCritical))}async function Ni(e,t,r=()=>!0){if(!r())return null;let n=await Sc(e,t);if(!r())return null;let i=new Cc(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=await fy(e,s,t,n.getCanonicalActivityId,r);if(!o)return null;let c=await py(e,i.linkResidualHours,o,r);return c?{activities:o,links:c}:null}async function nn(e,t,r=()=>!0){let n=await Ni(e,t,r);if(!n||!r())return!1;for(let[i,a]of n.activities){if(!r())return!1;xi(e,i,a)}for(let[i,a]of n.links){if(!r())return!1;Fi(e,i,a)}return!0}function Oe(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),E.REAL_COST,o),r.push(String(i)),o};for(let i of t)n(i);return r}var Tc=new Set;var _c=new Set(["activity-outdent","activity-indent"]);var ir=new Set([_.TEXT,_.DESCRIPTION,_.COST,_.USED_COST,_.CUSTOM_ID,_.RESPONSABLES,_.SUBCONTRACT_ID,_.TAGS]),yy=new Set(["activity-clipboard-clear","activity-copy","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"]),my=new Set(["activity-clipboard-clear","activity-copy","selection-toggle","selection-replace","visibility-set","filter-set","sort-set"]);function Rc(e){return!my.has(e.kind)}var gy=new Set;function vy(e){return e.kind==="inline-edit"?ir.has(e.column):e.kind==="bulk-edit"?e.edits.every(t=>ir.has(t.column)):!1}function Mi(e,t){return!(yy.has(e.kind)||t.has(e.kind)||vy(e))}function Wi(e){return e.kind==="activity-lookahead-sync"?e.persistedProgress!==void 0:Mi(e,gy)}function se(e){return e.kind==="activity-lookahead-sync"?e.persistedProgress!==void 0:Mi(e,Tc)}function bc(e){return Mi(e,_c)}function Bi(e){return e.kind==="activity-set-progress"?!0:e.kind==="inline-edit"?e.column===_.PROGRESS:e.kind==="bulk-edit"?e.edits.some(t=>t.column===_.PROGRESS):!1}function Ay(e){return bc(e)&&Bi(e)}var Pc=new Set([_.PROGRESS,_.HH_WORK_TIME,_.DURATION,_.COST,_.USED_COST,_.REAL_COST]);function Iy(e){return e.kind==="activity-set-progress"?!0:e.kind==="inline-edit"?Pc.has(e.column):e.kind==="bulk-edit"?e.edits.some(t=>Pc.has(t.column)):!1}var it={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 Ec(e,t,r){let n=new Set;t.ran&&n.add(it.AUTOSCHEDULE),n.add(it.PARENT_BOUNDS),Iy(e)&&n.add(it.PARENT_PROGRESS),Bi(e)&&n.add(it.REAL_WORK);let i=!r.skipAutoSchedule;return i&&bc(e)&&n.add(it.EXPECTED_PROGRESS),i&&Ay(e)&&n.add(it.REAL_COST),i&&se(e)&&!r.skipCriticalPath&&n.add(it.CRITICAL_PATH),n}async function Y(e,t){let r=Cy(t);r.has(it.AUTOSCHEDULE)&&await Ty(e.adapter,t);let n=r.has(it.AUTOSCHEDULE)?await Sy(e,t.autoscheduleFrom):Dy();return await _y(e.adapter,t,n.scheduledIds,r),await Py(e,r,t.now),n}function Cy(e){let t=e.autoscheduleFrom!==null,r=!e.options.skipAutoSchedule&&t,n=new Set(Ec(e.action,{requested:t,ran:r},e.options));return e.recomputeParentProgress&&n.add(it.PARENT_PROGRESS),n}async function Sy(e,t){let r=t==="roots"?{}:{triggerId:t},n=await e.scheduler.schedule(r),i=ky(e.adapter,n.updatedIds);return Ge(e.adapter,n),i}function ky(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 Dy(){return{scheduledIds:[]}}async function Ty(e,t){let r=t.collectDirty?t.collectDirty([]):fi(t.recomputeParentsFrom,[]);r.size!==0&&await Se(e,r,!1)}async function _y(e,t,r,n){let i=t.collectDirty?t.collectDirty(r):fi(t.recomputeParentsFrom,r);await Se(e,i,n.has(it.PARENT_PROGRESS),{recomputeRealWork:n.has(it.REAL_WORK),progressMode:t.recomputeParentProgress?"zero-when-no-contribution":"freeze-when-no-contribution"})}async function Py(e,t,r){t.has(it.EXPECTED_PROGRESS)&&r!==null&&(Ry(e.adapter)&&we(e.adapter,r,e.defaultBaseCalendarId??null),ne(e.adapter,r),Mt(e.adapter,e.sector.statusCriteria)),t.has(it.REAL_COST)&&Oe(e.adapter),t.has(it.CRITICAL_PATH)&&await nn(e.adapter,e.sector.hoursPerDay)}function Ry(e){let t=!1;return e.forEachActivity(r=>{ut(r)&&(t=!0)}),t}var by=new Set([_.CONSTRAINT_TYPE,_.CONSTRAINT_DATE]),Ey=new Set(["mso","mfo"]);function an(e){return by.has(e)}function sn(e){return e===_.CONSTRAINT_DATE}function on(e,t,r,n){let i=r.getActivity(e);if(!i)return!1;let a=i.constraintType;if(!a||Kt.has(a)||Ey.has(a))return!1;let s=Ui(i.startDate),o=Ui(r.getLastStartDate(e));if(!o||!s||s.getTime()!==o.getTime())return!1;let c=Ly(t,a,String(i.calendarId??""),n),l=Ui(i.constraintDate);return wy(l,c)?!1:(r.setActivityField(e,"constraintDate",c),!0)}function Ly(e,t,r,n){if(e===null)return null;let i=n.getCalendar(r);return i?xt(e,i,t):e}function Ui(e){if(e instanceof Date)return e;if(typeof e=="string"||typeof e=="number"){let t=new Date(e);return Number.isNaN(t.getTime())?null:t}return null}function wy(e,t){return e===null&&t===null?!0:e===null||t===null?!1:e.getTime()===t.getTime()}async function cn(e,{postMutationArgs:t,revertTargets:r,revert:n}){let{scheduledIds:i}=await Y(e,Lc(t)),a=!1;for(let{activityId:s,priorConstraintDate:o}of r){let c=n(s,o);a=a||c}if(a){let s=await Y(e,Lc(t));i=xy(i,s.scheduledIds)}return se(t.action)&&await Y(e,Oy(t)),{scheduledIds:i}}function Lc(e){return{...e,options:{...e.options,skipCriticalPath:!0}}}function Oy(e){return{action:e.action,autoscheduleFrom:null,recomputeParentsFrom:[],now:null,options:e.options}}function xy(e,t){let r=new Set(e);for(let n of t)r.add(n);return[...r]}function Fy(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 ji(e,t,r){let n=[];for(let i of r){let a=e.get(i);if(!a)continue;let s=a.pendingRequestIds??[];if(!he({pendingRequestIds:s}))continue;let o=t.getActivity(i),c=o==null;if(!c&&!Fy(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}function ft(e){let t={id:String(e.id),source:String(e.source),target:String(e.target),type:e.type,lag:Number(e.lag),freeSlackHours:typeof e.freeSlackHours=="number"&&Number.isFinite(e.freeSlackHours)?e.freeSlackHours:null,isCritical:e.isCritical===!0};return e.proplannerId!=null&&(t.proplannerId=Number(e.proplannerId)),e.ganttId!=null&&(t.ganttId=Number(e.ganttId)),e.sectorId!=null&&(t.sectorId=Number(e.sectorId)),t}async function B(e,t){let r=By(e,t),n=new Map(t.beforeSnap),i=e.peekWriteCapture();if(i){let f=jy(i);Uy(e,i,f,n,r)}let a=t.sirDetection,s=a==="before-diff"?ji(n,e,r):[],o=Wy(t.correlativeShifts,r),c=await Jr(e,n,r,o),l=a==="after-diff"?ji(n,e,r):s,d=t.warnings??[],u=My(t.links??[],i?Ny(e,i):[]);return{source:t.source,activities:c,links:u,calendars:[],trackingEvents:t.trackingEvents??[],...l.length>0?{effects:l}:{},...d.length>0?{warnings:d}:{}}}function Ny(e,t){let r=[];for(let n of t.ops){if(n.kind!=="link-field")continue;let i=e.getLink(n.linkId);if(!i)continue;let a={};for(let s of["freeSlackHours","isCritical"])Object.is(n.before[s],i[s])||(a[s]={before:n.before[s],after:i[s]});Object.keys(a).length!==0&&r.push({id:n.linkId,kind:"updated",fields:a,after:ft(i)})}return r}function My(e,t){let r=[],n=new Map;for(let i of e){let a=n.get(i.id);if(a===void 0){n.set(i.id,r.length),r.push(i);continue}let s=r[a];if((s.kind==="updated"||s.kind==="created")&&i.kind==="updated"){r[a]={...s,fields:{...s.fields,...i.fields},after:i.after};continue}r[a]=i}for(let i of t){let a=n.get(i.id);if(a===void 0){n.set(i.id,r.length),r.push(i);continue}let s=r[a];if(s.kind==="deleted")continue;let o=s.kind==="created"?Object.fromEntries(Object.entries(i.fields??{}).map(([c,l])=>[c,{before:void 0,after:l.after}])):i.fields;r[a]={...s,fields:{...s.fields,...o},after:i.after}}return r}function Wy(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 By(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 Uy(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(ui(s,o)).length!==0&&(n.set(a,s),i.add(a))}}function jy(e){return new Set(e.ops.filter(t=>t.kind==="insert").map(t=>t.activityId))}function xe(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:ft(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:ft(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:ft(c)})}return n}function Fe(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 Ne(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:ft(a)})}return n}function ln(e,t){typeof e=="string"&&e.length>0&&t.releaseCustomId(e)}async function wc(e,t,r){let{adapter:n,ctx:i,scheduler:a,sector:s}=r,o=$t(e.column);if(!o)return{ok:!1,reason:S.NO_PIPELINE_FOR_COLUMN};e.column===_.DURATION&&a.invalidateExpandedLinksCache();let c=i.activityReader.getActivity(e.activityId);if(!c)return{ok:!1,reason:S.ACTIVITY_NOT_FOUND};let l=o.canEdit(c,i.hierarchy);if(!l.allowed)return{ok:!1,reason:l.reason??S.CANNOT_EDIT,alertKey:l.alertKey};let d=o.parseInput(e.newValue,c,i);if(!d.ok)return{ok:!1,reason:d.reason??S.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??S.INVALID,alertKey:f.notification?.messageKey};if(e.column===_.CUSTOM_ID&&d.value!==null){let C=n.getActivity(e.activityId),R=C?C.customId:null,N=typeof R=="string"?R:null;if(r.customIdTracker.isCustomIdInUse(String(d.value),N))return{ok:!1,reason:S.CUSTOM_ID_DUPLICATE}}let p=o.transform(c,d.value,i,d.raw),h=zt(e.activityId,p),A=await $(n,h),I=Fe(n,String(e.activityId)),T=c.constraintDate;qt(n,e.activityId,p),Vt(e.activityId,p.postProcessors??[],n,A.get(String(e.activityId))??null);let g=Ne(I,n,String(e.activityId));if(e.column===_.CUSTOM_ID){let C=A.get(String(e.activityId)),R=C?C.customId:null,N=typeof R=="string"?R:null,x=typeof d.value=="string"?d.value:null;N!==x&&r.customIdTracker.trackCustomIdChange(N,x)}let k=()=>({action:e,autoscheduleFrom:p.needsAutoSchedule?String(e.activityId):null,recomputeParentsFrom:[],collectDirty:C=>Xr(e.activityId,h,C),now:r.now,options:t}),m=an(e.column),{scheduledIds:P}=await(m?cn({adapter:n,scheduler:a,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{postMutationArgs:k(),revertTargets:sn(e.column)?[]:[{activityId:e.activityId,priorConstraintDate:T}],revert:(C,R)=>on(C,R,n,i.calendars)}):Y({adapter:n,scheduler:a,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},k())),w=(p.trackingEvents??[]).map(C=>({name:C.name,properties:C.properties??{}})),v=be(e.activityId,p.constraintWarning);return{ok:!0,changes:await B(n,{source:e,beforeSnap:A,touchedIds:h,scheduledIds:P,sirDetection:"before-diff",links:g,trackingEvents:w,...v?{warnings:[v]}:{},hoursPerDay:s.hoursPerDay})}}function Hy(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 Vy(e,t,r,n){return e.map((i,a)=>{let s=i.kind==="create"?n?.get(a):void 0,o=jt(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 Yy(e){return new Map([...e].map(([t,r])=>[String(t),r]))}async function Oc(e,t,r){if(e.kind==="link-create"||e.kind==="link-update"){let n=e.type;if(n!==void 0&&!Object.values(W).some(a=>a===n))return{ok:!1,reason:S.INVALID_LINK_TYPE};let i=e.lag;if(i!==void 0&&!Number.isFinite(i))return{ok:!1,reason:S.INVALID_LINK_LAG}}return Hi([Jy(e,r.sector.hoursPerDay)],e,t,r,e.kind==="link-create"&&e.linkId?new Map([[0,e.linkId]]):void 0)}async function xc(e,t,r){let{hoursPerDay:n}=r.sector,i=e.operations.map(s=>$y(s,n)),a=Ky(e.operations);return Hi(i,e,t,r,a)}function Ky(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 Gy(e,t){if(e===void 0)return;let r=new Map,n=new Set,i=()=>{let a=t.linkIdGen.next();for(;t.adapter.getLink(a)!==null||t.isLinkIdReserved(String(a))||n.has(String(a));)a=t.linkIdGen.next();return a};for(let[a,s]of e){let o=t.adapter.getLink(s)!==null||t.isLinkIdReserved(String(s))||n.has(String(s)),c=o?i():s;o||t.linkIdGen.bump(s),n.add(String(c)),r.set(a,c)}return r}function $y(e,t){return e.kind==="create"?{kind:"create",source:e.source,target:e.target,type:e.type,lag:vt(e.lag??0,t)}:e.kind==="update"?{kind:"update",linkId:e.linkId,type:e.type,lag:e.lag===void 0?void 0:vt(e.lag,t)}:{kind:"delete",linkId:e.linkId}}async function Hi(e,t,r,n,i){let{adapter:a,scheduler:s,sector:o,linkIdGen:c}=n;s.invalidateAllCaches();let{activityIds:l,links:d}=Hy(e,a),u=await $(a,l),f=Vy(e,a,c,Gy(i,n));if(e.length===1&&f[0]&&f[0].rejected!==null&&t.kind!=="inline-edit")return{ok:!1,reason:f[0].rejected};let p=zy(f,d,a),{scheduledIds:h}=await Y({adapter:a,scheduler:s,sector:n.sector,defaultBaseCalendarId:n.defaultBaseCalendarId},{action:t,autoscheduleFrom:p,recomputeParentsFrom:l,now:n.now,options:r}),A=xe(f,d,a);return{ok:!0,linkVerdicts:f.map((I,T)=>I.rejected===null?{operationIndex:T,kind:I.op.kind,ok:!0,linkId:String(I.finalLinkId)}:{operationIndex:T,kind:I.op.kind,ok:!1,reason:I.rejected}),__beforeLinks:Yy(d),changes:await B(a,{source:t,beforeSnap:u,touchedIds:l,scheduledIds:h,links:A,hoursPerDay:o.hoursPerDay})}}function zy(e,t,r){for(let n of e){if(n.rejected!==null)continue;let i=qy(n.op,t,r);if(i!==null)return r.hasChildren(i)?"roots":String(i)}return null}function qy(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 Jy(e,t){return e.kind==="link-create"?{kind:"create",source:e.source,target:e.target,type:e.type,lag:vt(e.lag,t)}:e.kind==="link-update"?{kind:"update",linkId:e.linkId,type:e.type,lag:e.lag===void 0?void 0:vt(e.lag,t)}:{kind:"delete",linkId:e.linkId}}async function Fc(e,t,r){let{adapter:n,sector:i}=r;if(typeof e.newValue!="string")return{ok:!1,reason:S.INVALID_VALUE};if(!n.getActivity(e.activityId))return{ok:!1,reason:S.ACTIVITY_NOT_FOUND};let s=e.column===_.CUSTOM_PREDECESSORS,{specs:o}=Fr(e.newValue),c=o.map(h=>({...h,lag:vt(Br(h.lag),i.hoursPerDay)})),l=new Map;n.forEachActivity(h=>{h.correlativeId!=null&&l.set(String(h.correlativeId),h.id)});let d=h=>l.get(h)??null,u=s?n.getIncomingLinkIds(e.activityId):n.getOutgoingLinkIds(e.activityId),f=[];for(let h of u){let A=n.getLink(h);A&&f.push(A)}let p=s?Mr({targetActivityId:e.activityId,currentLinks:f,desiredSpecs:c,resolveActivityByCorrelative:d}):Wr({sourceActivityId:e.activityId,currentLinks:f,desiredSpecs:c,resolveActivityByCorrelative:d});return Hi(p.operations,e,t,r)}var It={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 at(e){e.invalidateVisualOrderIds?.();let t=[];e.forEachActivity(a=>{L(a.parentId)&&t.push(a)}),t.sort(Wc);let r=[];Nc(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),Xy(a,i)}i+=1;let s=Ve(String(a.id),e);s.sort(Wc),Nc(r,s)}return n}function Nc(e,t){for(let r=t.length-1;r>=0;r-=1)e.push(t[r])}function Mc(e){let t=e.correlativeId,r=typeof t=="number"?t:Number(t);return Number.isFinite(r)?r:Yn}var Wc=(e,t)=>Mc(e)-Mc(t);function Xy(e,t){e.correlativeId=t}function Vi(e,t){if(!e||e==="0")return;let r=String(e);for(;r!==null;){let{workHours:n,realWorkHours:i}=jc(r,t);t.setActivityField(r,E.WORK_HOURS,n),t.setActivityField(r,E.REAL_WORK_HOURS,i);let a=t.getActivity(r);if(!a)break;let s=a.parentId;if(!s||L(s))break;r=s}}function Bc(e,t){let r=t.getActivity(e);if(!r)return;let n=r.parentId;!n||L(n)||Vi(n,t)}function Uc(e,t,r){for(let n of e){if(r.hasChildren(n))continue;let i=r.getActivity(n);i&&r.setActivityField(n,E.REAL_WORK_HOURS,dt(ar(i,E.WORK_HOURS),ar(i,E.PROGRESS)))}for(let n of t)r.setActivityField(n,E.REAL_WORK_HOURS,jc(n,r).realWorkHours)}function jc(e,t){let r=0,n=0;for(let i of t.getChildren(e)){let a=t.getActivity(i);if(!a)continue;let s=ar(a,E.WORK_HOURS);r+=s,n+=Zy(i,a,s,t)}return{workHours:r,realWorkHours:n}}function ar(e,t){let r=e[t];return typeof r=="number"&&Number.isFinite(r)?r:0}function Zy(e,t,r,n){return n.hasChildren(e)?ar(t,E.REAL_WORK_HOURS):dt(r,ar(t,E.PROGRESS))}function Yi(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+=Qy(c,E.USED_COST))}t.setActivityField(r,E.USED_COST,i);let a=t.getActivity(r);if(!a)break;let s=a.parentId;if(!s||L(s))break;r=s}}function Hc(e,t){let r=t.getActivity(e);if(!r)return;let n=r.parentId;!n||L(n)||Yi(n,t)}function Qy(e,t){let r=e[t];return typeof r=="number"&&Number.isFinite(r)?r:0}function Ki(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+=tm(c,E.COST))}t.setActivityField(r,E.COST,i);let a=t.getActivity(r);if(!a)break;let s=a.parentId;if(!s||L(s))break;r=s}}function Vc(e,t){let r=t.getActivity(e);if(!r)return;let n=r.parentId;!n||L(n)||Ki(n,t)}function tm(e,t){let r=e[t];return typeof r=="number"&&Number.isFinite(r)?r:0}var dn=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}),Yc="New Master Plan",Kc="New Activity";var em=["name","description","type","startDate","durationHours","constraintType","constraintDate","calendarId","assignedDefaultCalendar","autoScheduling","progress","cost","usedCost","realCost","workHours","realWorkHours","ponderator","hasCustomPonderator","customId","subcontractId","responsableIds","tagIds","isLookahead"],un=new Set(em);function rm(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"||!un.has(r))throw new Error(`activity-create: rejected override key "${String(r)}" \u2014 not a creation-writable canonical field`);return e}function Gc(e,t){let r=e.parentId!=null?t.getActivity(e.parentId):null,n=rm(e.activityOverrides??{}),i=e.numTasksInGantt===0?Yc:Kc,a=n.name??i,s=n.durationHours??e.sector.hoursPerDay,o=n.calendarId??e.sector.defaultCalendar,c=nm(r,e.fallbackStartDate,n.startDate),l={...dn,...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});if(!n.startDate&&r&&wt(r.type)){let p=new Date(r.startDate);p.setUTCHours(0,0,0,0);let h=new Date(d);h.setUTCHours(0,0,0,0),h.getTime()!==p.getTime()&&(d=t.getClosestWorkTime({date:p,dir:X.FUTURE,task:l}))}let u=t.calculateEndDate({startDate:d,durationHours:l.durationHours,task:l});return{newTask:{...l,startDate:d,endDate:u,calendarDuration:bt({type:l.type,startDate:d,endDate:u}),newActivityIds:[...l.newActivityIds],pendingRequestIds:[...l.pendingRequestIds],responsableIds:[...l.responsableIds],tagIds:[...l.tagIds],baselinePoints:[...l.baselinePoints]}}}function nm(e,t,r){return r?new Date(r):e?new Date(e.startDate):t?new Date(t):new Date}function im(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 Me(e){let t=e.getParent(e.parentId);if(!t)return null;let r=e.isCurrentlyLeaf!==void 0?e.isCurrentlyLeaf&&Ut(t.type):am(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=Qn,(e.promotionSource??"create")==="create"&&(a.constraintType=K.ASAP,a.constraintDate=null,a.progress=0)),{parentId:e.parentId,fields:a,promotionSnapshot:im(t)}}function am(e){return Ut(e.type)&&(!Array.isArray(e.newActivityIds)||e.newActivityIds.length===0)}function fn(e,t,r,n){let i=t,a=i==="0",s=Gi(e,i);if(n!==void 0){let c=s.find(l=>l.id===n);if(c){let l=st(c),d=s.map(st).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=st(c),d=s.map(st).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(st))+1}var oe=Number.MAX_SAFE_INTEGER,$c=Number.MAX_SAFE_INTEGER-1;function st(e){let t=e.correlativeId,r=typeof t=="number"?t:Number(t);return Number.isFinite(r)?r:oe}function Gi(e,t){return Ve(t,e)}function zc(e,t,r){let n=e,i=Xt(e,r);for(;i!=null&&t.has(i);)n=i,i=Xt(i,r);return n}function pn(e,t,r){let n=new Set([e]),i=Bt(r.getActivity(e)?.parentId);for(;i!=="0"&&!n.has(i);){if(t.has(i))return!0;n.add(i),i=Bt(r.getActivity(i)?.parentId)}return!1}function Xt(e,t){let r=t.getActivity(e);if(!r)return null;let n=Bt(r.parentId),i=gt(n,t),a=i.findIndex(s=>String(s)===String(e));return a<=0?null:i[a-1]??null}function qc(e,t,r,n){let i=gt(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(st);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}var sm=new Set([...[...un].filter(e=>e!=="durationHours"),"durationDays"]);function hn(e,t){if(e===void 0)return{ok:!0,value:{}};let r=Object.getPrototypeOf(e);if(r!==null&&r!==Object.prototype)return{ok:!1,reason:S.INVALID_VALUE};for(let a of Reflect.ownKeys(e))if(typeof a=="symbol"||!sm.has(a))return{ok:!1,reason:S.INVALID_VALUE};let{durationDays:n,...i}=e;return n!==void 0&&(!Number.isFinite(n)||n<0)?{ok:!1,reason:S.INVALID_VALUE}:{ok:!0,value:{...i,...n===0&&(i.type===void 0||i.type==="task")?{type:"milestone"}:{},...n===void 0?{}:{durationHours:te(n,t)}}}}async function sr(e,t,r={}){let{adapter:n,scheduler:i,sector:a,calendars:s,activityIdGen:o,uidGen:c}=t;r.skipCacheInvalidation||i.invalidateAllCaches();let l=om(e,n);if(!l.ok)return l;let{parent:d,anchorSiblingId:u,isRoot:f}=l,p=lm(e.activityId,n,o,t.isActivityIdReserved),h=c.next(),A={id:p,parentId:f?null:e.parentId,sector:{id:a.id,hoursPerDay:a.hoursPerDay,defaultCalendar:ym(s)},numTasksInGantt:n.activityCount(),nextUniqueCorrelativeId:h,activityOverrides:e.overrides??{}},T=Gc(A,{getActivity:v=>n.getActivity(v),calculateEndDate:v=>n.calculateEndDate(v),getClosestWorkTime:v=>n.getClosestWorkTime(v)}).newTask;T.realWorkHours=dt(T.workHours,T.progress),um(T,e,t,u,d,r);let g=r.insertionCorrelativeId??fn(n,f?"0":e.parentId,e.afterSiblingId,e.beforeSiblingId);T.correlativeId=g;let k=new Set([p]);d&&k.add(d.id);let m=d!==null&&n.getChildren(d.id).length===0,P=m?d?.customId:null,w=r.skipBeforeSnap?new Map:await $(n,k);return n.addActivity(T),fm(e,p,d,n,m),P&&t.customIdTracker.releaseCustomId(P),r.skipRollupCascades||(Bc(p,n),Hc(p,n),Vc(p,n)),pm(n,p,w,k,r),{ok:!0,newId:p,parent:d,newActivity:T,beforeSnap:w,initialTouched:k}}function om(e,t){let r=L(e.parentId),n=r?null:t.getActivity(e.parentId);if(!r&&!n)return{ok:!1,reason:S.PARENT_NOT_FOUND};if(n!==null&&he(n))return{ok:!1,reason:S.PARENT_FROZEN_BY_SIR};if(e.afterSiblingId!==void 0&&e.beforeSiblingId!==void 0)return{ok:!1,reason:S.ANCHOR_SIBLING_CONFLICT};let s=e.afterSiblingId??e.beforeSiblingId,o=cm(e,t,r,s);return o||{ok:!0,parent:n,anchorSiblingId:s,isRoot:r}}function cm(e,t,r,n){if(n===void 0)return null;let i=t.getActivity(n);if(!i)return{ok:!1,reason:S.ANCHOR_SIBLING_NOT_FOUND};let a=r?"0":e.parentId;return(i.parentId==null?"0":String(i.parentId))!==a?{ok:!1,reason:S.ANCHOR_SIBLING_WRONG_PARENT}:null}function lm(e,t,r,n){let i=()=>{let a=r.next();for(;t.activityExists(a)||n(String(a));)a=r.next();return a};return e===void 0||t.activityExists(e)||n(String(e))?i():(r.bump(e),e)}function dm(e){let t=e.overrides?.customId;return typeof t=="string"?t:void 0}function um(e,t,r,n,i,a){let{adapter:s,customIdTracker:o}=r,c=dm(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 fm(e,t,r,n,i){if(!r)return;let a=Me({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 pm(e,t,r,n,i){if(i.skipCorrelativeRecompute)return;let a=at(e);i.skipBeforeSnap||Ee(e,a,new Set([String(t)]),r,n)}async function hm(e,t,r,n,i){let{newId:a,newActivity:s,beforeSnap:o,initialTouched:c}=r,l={name:It.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 Jc(e,t,r){let{adapter:n,scheduler:i,sector:a}=r,s=hn(e.overrides,a.hoursPerDay);if(!s.ok)return s;let o=await sr({...e,overrides:s.value},r);if(!o.ok)return o;let{newId:c}=o,l=o.newActivity.autoScheduling;n.setActivityField(c,"autoScheduling",!1);let d;try{d=await Y({adapter:n,scheduler:i,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:"roots",recomputeParentsFrom:[c],now:r.now,options:t})}finally{n.setActivityField(c,"autoScheduling",l)}let{scheduledIds:u}=d;return{ok:!0,changes:await hm(n,e,o,u,a.hoursPerDay)}}function ym(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 Tt(e,t){Vi(e,t),Yi(e,t),Ki(e,t)}function Xc(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 Zc(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 mm(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 gm(e,t,r){let n=e.startDate;return!r||!(n instanceof Date)?{}:{endDate:r(n,t)}}function We(e){if(e.remainingChildIds.length>0)return null;let t=e.parent,r=e.defaultDurationHours,n=Number.isFinite(r),i=mm(e.promotionSnapshot)??(n?{type:ve,durationHours:r,progress:0,autoScheduling:!0,constraintType:"asap",constraintDate:null,hasNewActivities:!1,...gm(t,r,e.computeEndDate)}:{type:ve});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 Qc(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 tl=200;async function el(e,t,r){let{adapter:n,scheduler:i,customIdTracker:a,sector:s}=r;if(i.invalidateAllCaches(),e.activityIds.length===0)return{ok:!1,reason:S.ACTIVITY_IDS_EMPTY};for(let v of e.activityIds)if(!n.getActivity(v))return{ok:!1,reason:S.ACTIVITY_NOT_FOUND};let o=Xc(e.activityIds,n),c=Zc(o,n),l=new Set;for(let v of e.activityIds){let C=n.getActivity(v);if(!C)continue;let R=C.parentId;if(L(R))continue;let N=String(R);o.has(N)||l.add(N)}let d=new Set([...o,...l]),u=await $(n,d),f=new Map;for(let v of c){let C=n.getLink(v);C&&f.set(v,{...C})}let p=new Set,h=0;for(let v of o){h+=1,h%tl===0&&await Z();let C=n.getActivity(v);if(!C)continue;let R=L(C.parentId)?null:n.getActivity(String(C.parentId)),N=R?.hasNewActivities===!0&&R.newActivityIds.some(z=>String(z)===String(v));(C.isNewActivity===!0||N)&&p.add(v);let x=C.customId;typeof x=="string"&&x.length>0&&a.releaseCustomId(x)}for(let v of c)n.removeLink(v);let A=$i(n,o),I=0;for(let v of o)I+=1,I%tl===0&&await Z(),n.removeActivity(v);for(let v of l){let C=n.getActivity(v);if(!C)continue;vm(C,p,n);let R=n.getChildren(v),N=We({parent:C,remainingChildIds:R.map(String),defaultDurationHours:s.hoursPerDay,promotionSnapshot:n.getPromotionSnapshot(v),computeEndDate:(x,z)=>n.calculateEndDate({startDate:x,durationHours:z,task:C}),idsRemoved:o});if(!N){jr(v,n);continue}for(let[x,z]of Object.entries(N.fields))rt(n,v,x,z);if(C.customId==null||C.customId===""){let x=Xt(v,n),z=x?n.getActivity(x)?.customId:null,Q=a.generateCustomIdForRestoredChild(typeof z=="string"&&z?z:null);n.setActivityField(v,E.CUSTOM_ID,Q)}}for(let v of l)Tt(v,n);let T=at(n),{scheduledIds:g}=await Y({adapter:n,scheduler:i,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:"roots",recomputeParentsFrom:l,now:r.now,options:t}),k={name:It.ACTIVITY_DELETION,properties:{activity_ids:[...e.activityIds],cascade_count:o.size}};e.eventSource!==void 0&&(k.properties.event_source=e.eventSource);let m=new Map;for(let[v,C]of f)m.set(v,C);let P=new Map;for(let v of o){let C=u.get(String(v));C&&P.set(String(v),C)}let w=await B(n,{source:e,beforeSnap:u,touchedIds:d,scheduledIds:g,sirDetection:"after-diff",links:Am(f),trackingEvents:[k],hoursPerDay:s.hoursPerDay,correlativeShifts:T});return{ok:!0,changes:A.length>0?{...w,viewState:A}:w,__beforeSnap:P,__beforeLinks:m}}function vm(e,t,r){let n=Qc({parent:e,idsRemoved:t});if(n)for(let[i,a]of Object.entries(n.fields))rt(r,n.parentId,i,a)}function $i(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 Am(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 il(e,t,r){let n=Im(e,r);if(n)return{ok:!1,reason:n};let i=Sm(e,r);if(!i.ok)return i;let a=e.mode==="replace"?new Set(r.adapter.getAllIds().map(m=>String(m))):new Set,s=e.mode==="replace"?await $(r.adapter,a):new Map,o=e.mode==="replace"?Rm(r):new Map,c=e.mode==="replace"?$i(r.adapter,a):[];r.scheduler.invalidateAllCaches();let l=[];if(e.mode==="replace"){for(let m of o.keys()){let P=jt({kind:"delete",linkId:m},{port:r.adapter});if(!P.applied)return{ok:!1,reason:P.rejected??S.INVALID};l.push({op:{kind:"delete",linkId:m},finalLinkId:m,rejected:null})}for(let m of a){let P=r.adapter.getActivity(m)?.customId;typeof P=="string"&&P.length>0&&r.customIdTracker.releaseCustomId(P),r.adapter.removeActivity(m)}}let d=await Pm(e,i.plan.items,r);if(!d.ok)return d;let u=al(e)?[]:at(r.adapter),f=new Set(i.plan.items.map(m=>String(m.activityId))),p=u.filter(m=>!f.has(m.activityId)),h=e.mode==="replace"?new Set(a):new Set;Ee(r.adapter,u,f,s,h);for(let m of i.plan.items)h.add(String(m.activityId));let A=i.plan.links.map(m=>({operation:{kind:"create",source:m.source,target:m.target,type:m.type,lag:vt(m.lag,r.sector.hoursPerDay)},linkId:m.linkId})),I=xr(A,{port:r.adapter,preserved:o});if(!I.applied)return{ok:!1,reason:I.rejected??S.INVALID};for(let{operation:m,linkId:P}of A)l.push({op:m,finalLinkId:P,rejected:null});let T=i.plan.items.map(m=>m.activityId),{scheduledIds:g}=await Y({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:T,now:r.now,options:t}),k=await B(r.adapter,{source:e,beforeSnap:s,touchedIds:h,scheduledIds:g,links:xe(l,o,r.adapter),hoursPerDay:r.sector.hoursPerDay,correlativeShifts:p,...e.mode==="replace"?{sirDetection:"after-diff"}:{}});return{ok:!0,changes:c.length>0?{...k,viewState:c}:k,...e.mode==="replace"?{__beforeSnap:s,__beforeLinks:bm(o)}:{}}}function Im(e,t){if(e.mode!=="append"&&e.mode!=="replace")return S.INVALID;let r=new Set,n=new Set;for(let a of e.items){if(a.batchId.length===0||r.has(a.batchId))return S.INVALID;if(r.add(a.batchId),a.index!==void 0&&(!Number.isInteger(a.index)||a.index<0))return S.INVALID;if(a.activityId!==void 0){let s=String(a.activityId);if(s.length===0||s==="0"||n.has(s))return S.INVALID;n.add(s)}}for(let a of e.items)if(!zi(a.parent,!0,e.mode,r,t))return S.PARENT_NOT_FOUND;if(Cm(e.items))return S.INVALID;let i=new Set;for(let a of e.links){if(!Object.values(W).includes(a.type)||!Number.isFinite(a.lag))return Number.isFinite(a.lag)?S.INVALID_LINK_TYPE:S.INVALID_LINK_LAG;if(!zi(a.source,!1,e.mode,r,t)||!zi(a.target,!1,e.mode,r,t))return S.ACTIVITY_NOT_FOUND;if(a.linkId!==void 0){let s=String(a.linkId);if(s.length===0||i.has(s))return S.INVALID;i.add(s)}}return null}function zi(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 Cm(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 Sm(e,t){let r=new Map;for(let d of e.items){let u=hn(d.overrides,t.sector.hoursPerDay);if(!u.ok)return u;r.set(d.batchId,u.value)}let n=new Map,i=new Set;for(let d of e.items){let u=km(d.activityId,e.mode,i,t);i.add(String(u)),n.set(d.batchId,u)}let a=new Set,s=e.links.map(d=>{let u=Dm(d.linkId,e.mode,a,t);return a.add(String(u)),u}),o=Tm(e,n,t),c=[];for(let d of e.items){let u=n.get(d.batchId),f=o.get(d.batchId);if(u===void 0||f===void 0)return{ok:!1,reason:S.INVALID};let p=typeof d.parent=="string"?null:d.parent.batchId,h=typeof d.parent=="string"?d.parent:n.get(d.parent.batchId);if(h===void 0)return{ok:!1,reason:S.PARENT_NOT_FOUND};c.push({input:d,activityId:u,parentId:h,parentBatchId:p,insertionCorrelativeId:f,overrides:r.get(d.batchId)??{}})}let l=[];for(let[d,u]of e.links.entries()){let f=nl(u.source,n),p=nl(u.target,n),h=s[d];if(f===null||p===null||h===void 0)return{ok:!1,reason:S.ACTIVITY_NOT_FOUND};l.push({source:f,target:p,type:u.type,lag:u.lag,linkId:h})}return{ok:!0,plan:{items:c,links:l}}}function km(e,t,r,n){if(e!==void 0&&(t==="replace"||n.adapter.getActivity(e)===null&&!n.isActivityIdReserved(String(e)))&&!r.has(String(e)))return n.activityIdGen.bump(e),e;let a=n.activityIdGen.next();for(;r.has(String(a))||t==="append"&&(n.adapter.getActivity(a)!==null||n.isActivityIdReserved(String(a)));)a=n.activityIdGen.next();return a}function Dm(e,t,r,n){if(e!==void 0&&(t==="replace"||n.adapter.getLink(e)===null&&!n.isLinkIdReserved(String(e)))&&!r.has(String(e)))return n.linkIdGen.bump(e),e;let a=n.linkIdGen.next();for(;r.has(String(a))||t==="append"&&(n.adapter.getLink(a)!==null||n.isLinkIdReserved(String(a)));)a=n.linkIdGen.next();return a}function Tm(e,t,r){if(al(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)?[]:Gi(r.adapter,d).sort((A,I)=>st(A)-st(I)||String(A.id).localeCompare(String(I.id))).map(A=>String(A.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?rl(c[d-1],r):null,p=l<c.length?rl(c[l],r):null;for(let h=0;h<u;h+=1){let A=c[d+h],I=s.get(A);I!==void 0&&a.set(I,_m(f,p,h+1,u))}}}return a}function al(e){return e.mode==="append"&&e.items.every(t=>t.parent==="0"&&t.index===void 0)}function rl(e,t){let r=t.adapter.getActivity(e);return r?st(r):0}function _m(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 Pm(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 sr({kind:"activity-create",parentId:o.parentId,activityId:o.activityId,overrides:o.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:S.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)),Tt(o,r.adapter))}return{ok:!0}}function nl(e,t){return typeof e=="string"?e:t.get(e.batchId)??null}function Rm(e){return new Map(e.adapter.getAllLinks().map(t=>[String(t.id),{...t}]))}function bm(e){return new Map(Array.from(e,([t,r])=>[String(t),r]))}function sl(e,t){let{adapter:r}=t,n=e.activityId,i=r.getActivity(n);if(!i)return{ok:!1,reason:S.ACTIVITY_NOT_FOUND};let a=i.pendingRequestIds??[],s=e.pendingRequests.map(l=>l.id);r.setActivityField(e.activityId,"pendingRequestIds",s);let o=r.getActivity(n);if(!o)return{ok:!1,reason:S.ACTIVITY_NOT_FOUND};let c={id:n,kind:"updated",fields:{pendingRequestIds:{before:a,after:s}},after:J(o)};return{ok:!0,changes:{source:e,activities:[c],links:[],calendars:[],trackingEvents:[]}}}function ol(e){for(let t of Em(e))ll(t,e)}function cl(e,t){for(let r of e)ll(r,t)}function Em(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,Lm(n,e));return[...t].sort((n,i)=>(r.get(i)??0)-(r.get(n)??0))}function Lm(e,t){let r=0,n=e;for(;n&&n!=="0"&&t.getActivity(n);)r+=1,n=t.getParentId(n);return r}function ll(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=Ce(n);i!==null&&t.setActivityField(e,_.PROGRESS,Ur(i))}function dl(e){let t=new Map;for(let r of e){let n=r.proplannerId;typeof n=="number"&&Number.isSafeInteger(n)&&n>0&&t.set(n,String(r.id))}return t}function ul(e,t,r){let n=new Set(t.map(({id:i})=>String(i)));for(let i of e)if((i.proplannerId==null||i.proplannerId===0)&&!n.has(String(i.id)))throw new Error(`persistence-acknowledge: missing ${r} proplannerId for "${String(i.id)}"`)}function wm(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!==0&&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 fl(e,t,r,n){let i=new Set,a=new Set;for(let s of e)wm(s,t,r,n,i,a)}function Om(e,t){let r=new Set;for(let n of e){let i=String(n.activityId);if(i.length===0||r.has(i))throw new Error(`persistence-acknowledge: duplicate or empty reconciled activity id "${i}"`);if(!Number.isFinite(n.progress)||n.progress<0||n.progress>100)throw new Error(`persistence-acknowledge: invalid reconciled progress ${String(n.progress)} for "${i}"`);if(!t.adapter.getActivity(i))throw new Error(`persistence-acknowledge: unknown reconciled activity id "${i}"`);r.add(i)}}async function qi(e,t){let r=e.filter(o=>{let c=t.adapter.getActivity(String(o.activityId));return c!==null&&c.progress!==o.progress}),n=new Set(r.map(o=>String(o.activityId))),i=Xe(t.adapter,n),a=new Set(n);for(let o of i)a.add(String(o));let s=await $(t.adapter,a);return t.adapter.batchUpdate(()=>{for(let o of r)t.adapter.setActivityField(String(o.activityId),"progress",o.progress);cl(i,t.adapter),Uc(n,i,t.adapter)}),[...await Jr(t.adapter,s,a)]}async function pl(e,t){let r=e.activities??[],n=e.links??[],i=e.reconciledProgress??[];Om(i,t);let a=t.adapter.getAllActivities(),s=t.adapter.getAllLinks(),o=dl(a),c=dl(s);fl(r,"activity",u=>{let f=t.adapter.getActivity(u);return{exists:f!==null,current:f?.proplannerId??null}},o),fl(n,"link",u=>{let f=t.adapter.getLink(u);return{exists:f!==null,current:f?.proplannerId??null}},c),ul(a,r,"activity"),ul(s,n,"link");let l=await qi(i,t),d=[];return t.adapter.batchUpdate(()=>{for(let u of r){let f=t.adapter.getActivity(u.id);if(!f||f.proplannerId===u.proplannerId)continue;let p=f.proplannerId;t.adapter.setActivityField(u.id,"proplannerId",u.proplannerId),l.push({id:u.id,kind:"updated",fields:{proplannerId:{before:p,after:u.proplannerId}},after:{...f,proplannerId:u.proplannerId}})}for(let u of n){let f=t.adapter.getLink(u.id);if(!f||f.proplannerId===u.proplannerId)continue;let p=f.proplannerId;t.adapter.setLinkProplannerId(u.id,u.proplannerId),d.push({id:u.id,kind:"updated",fields:{proplannerId:{before:p,after:u.proplannerId}},after:{...f,proplannerId:u.proplannerId}})}}),{ok:!0,changes:{source:e,activities:l,links:d,calendars:[],trackingEvents:[]}}}async function hl(e,t,r){if(xm(e))return{ok:!1,reason:S.INVALID_VALUE};let n=[...new Set(e.activityIds.map(String))];if(e.acknowledgePersistedLookahead===!0&&n.some(o=>!r.isActivityIdReserved(o)))return{ok:!1,reason:S.INVALID};let a=n.map(o=>r.adapter.getActivity(o));if(a.some(o=>!o))return{ok:!1,reason:S.ACTIVITY_NOT_FOUND};let s=[];for(let[o,c]of n.entries()){let l=a[o];if(!l)continue;let d={};l.isLookahead!==e.isLookahead&&(d.isLookahead={before:l.isLookahead,after:e.isLookahead},r.adapter.setActivityField(c,"isLookahead",e.isLookahead)),l.hasLookaheadTasks!==e.hasLookaheadTasks&&(d.hasLookaheadTasks={before:l.hasLookaheadTasks,after:e.hasLookaheadTasks},r.adapter.setActivityField(c,"hasLookaheadTasks",e.hasLookaheadTasks)),Object.keys(d).length!==0&&s.push({id:c,kind:"updated",fields:d,after:{...l,isLookahead:e.isLookahead,hasLookaheadTasks:e.hasLookaheadTasks}})}return e.persistedProgress!==void 0&&(await qi([{activityId:n[0],progress:e.persistedProgress}],r)).length>0?(await Y({adapter:r.adapter,scheduler:r.scheduler,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:null,recomputeParentsFrom:[],now:r.now,options:t}),{ok:!0,changes:await B(r.adapter,{source:e,beforeSnap:new Map,touchedIds:[],scheduledIds:[],hoursPerDay:r.sector.hoursPerDay})}):{ok:!0,changes:{source:e,activities:s,links:[],calendars:[],trackingEvents:[]}}}function xm(e){let t=e.persistedProgress;return t!==void 0&&(e.activityIds.length!==1||!Number.isFinite(t)||t<0||t>100)}function yn(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)||(yl(s,a,t)||yl(a,s,t))&&n.push(String(i.id))}return n}function yl(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}function mn(e,t){let r=e.getAllLinks();return!qe({port:e,currentLinks:r,proposedLinks:r,proposal:{reparented:t}}).ok}function gn(e,t){let r=new Set;if(e.length===0)return r;let n=new Map(e.map(a=>[a.activityId,a.newParentId]));if(!mn(t,n))return r;let i=new Map;for(let a of e){let s=new Map(i);if(s.set(a.activityId,a.newParentId),mn(t,s)){r.add(a.activityId);continue}i.set(a.activityId,a.newParentId)}return r}async function ml(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:S.ACTIVITY_NOT_FOUND};let o=L(e.parentId);if(!o&&!n.getActivity(e.parentId))return{ok:!1,reason:S.PARENT_NOT_FOUND};if(!o&&(e.parentId===e.activityId||n.isChildOf(e.parentId,e.activityId)))return{ok:!1,reason:S.CANNOT_MOVE_INTO_OWN_DESCENDANT};if(e.afterSiblingId!==void 0&&e.beforeSiblingId!==void 0)return{ok:!1,reason:S.ANCHOR_SIBLING_CONFLICT};let c=e.afterSiblingId??e.beforeSiblingId;if(c!==void 0){let P=n.getActivity(c);if(!P)return{ok:!1,reason:S.ANCHOR_SIBLING_NOT_FOUND};if((P.parentId===null?"0":String(P.parentId))!==e.parentId)return{ok:!1,reason:S.ANCHOR_SIBLING_WRONG_PARENT}}let l=s.parentId,d=Bt(l),u=String(e.parentId),f=d!==u;if(f){let P=new Map([[e.activityId,o?null:e.parentId]]);if(mn(n,P))return{ok:!1,reason:S.HIERARCHY_CYCLE}}let p=new Set([e.activityId]);f?(d!=="0"&&p.add(d),u!=="0"&&p.add(u)):d!=="0"&&p.add(d);let h=await $(n,p);f&&n.setActivityField(e.activityId,E.PARENT,u);let A=fn(n,e.parentId,e.afterSiblingId,e.beforeSiblingId);if(n.setActivityField(e.activityId,E.CORRELATIVE_ID,A),f){if(!o){let P=n.getActivity(e.parentId);if(P){let w=P.customId,v=Ut(P.type)&&n.getChildren(e.parentId).filter(R=>R!==e.activityId).length===0,C=Me({parentId:e.parentId,newChildId:e.activityId,getParent:R=>n.getActivity(R)??null,isCurrentlyLeaf:v,promotionSource:"reparent"});if(C){for(let[R,N]of Object.entries(C.fields))rt(n,C.parentId,R,N);C.promotionSnapshot&&n.setPromotionSnapshot(C.parentId,C.promotionSnapshot),C.fields.customId===null&&ln(w,r.customIdTracker)}}}if(d!=="0"){let P=n.getActivity(d);if(P){let w=n.getChildren(d),v=We({parent:P,remainingChildIds:w.map(String),defaultDurationHours:a.hoursPerDay,promotionSnapshot:n.getPromotionSnapshot(d),computeEndDate:(C,R)=>n.calculateEndDate({startDate:C,durationHours:R,task:P}),idsRemoved:new Set([e.activityId])});if(v){for(let[z,Q]of Object.entries(v.fields))rt(n,d,z,Q);let C=Xt(d,n),R=C?n.getActivity(C)?.customId:null,N=typeof R=="string"&&R?R:null,x=r.customIdTracker.generateCustomIdForRestoredChild(N);n.setActivityField(d,E.CUSTOM_ID,x)}}}}f&&(d!=="0"&&Tt(d,n),o||Tt(e.parentId,n));let I=at(n);for(let P of I){if(p.add(P.activityId),h.has(P.activityId))continue;let w=n.getActivity(P.activityId);if(!w)continue;let v=J(w);P.before!==void 0&&(v.correlativeId=P.before),h.set(P.activityId,v)}let T=f&&d!=="0"?n.getChildren(d).map(String):[],{scheduledIds:g}=await Y({adapter:n,scheduler:i,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:e.activityId,recomputeParentsFrom:[e.activityId,e.parentId,...T],now:r.now,options:t,recomputeParentProgress:f}),k=f?yn([e.activityId],n):[],m={name:It.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:k.map(String)}};return e.eventSource!==void 0&&(m.properties.event_source=e.eventSource),{ok:!0,changes:await B(n,{source:e,beforeSnap:h,touchedIds:p,scheduledIds:g,sirDetection:"before-diff",trackingEvents:[m],hoursPerDay:a.hoursPerDay})}}function vn(e,t){let r=new Set(e),n=[],i=[],a=new Set,s=new Set(r),o=[...e].sort((d,u)=>{let f=t.getActivity(d),p=t.getActivity(u),h=f?st(f):oe,A=p?st(p):oe;return h-A});for(let d of o){if(!t.getActivity(d)){n.push({activityId:d,reason:S.ACTIVITY_NOT_FOUND}),s.delete(d);continue}if(pn(d,a,t))continue;let f=Ga(d,s,t);if(f==null){n.push({activityId:d,reason:S.INDENT_NO_ELIGIBLE_SIBLING}),s.delete(d);continue}let p=t.getActivity(d)?.parentId,h=L(p)?"0":String(p);i.push({activityId:d,newParentId:f,oldParentId:h}),a.add(d)}let c=gn(i,t);for(let d of c)n.push({activityId:d,reason:S.HIERARCHY_CYCLE});let l=i.filter(d=>!c.has(d.activityId));return{moves:i,cyclicMoveIds:c,allowedMoves:l,failed:n}}async function gl(e,t,r){let{adapter:n,scheduler:i,sector:a}=r;if(i.invalidateAllCaches(),e.activityIds.length===0)return{ok:!1,reason:S.ACTIVITY_IDS_EMPTY};let s=new Set,o=[],c=vn(e.activityIds,n),l=[...c.failed];for(let g of c.moves)s.add(String(g.activityId)),s.add(String(g.newParentId)),g.oldParentId!=="0"&&s.add(String(g.oldParentId));let d=c.allowedMoves,u=await $(n,s);for(let{activityId:g,newParentId:k}of d)n.setActivityField(g,E.PARENT,k),n.setActivityField(g,E.CORRELATIVE_ID,$c),o.push(g);let f=new Set;for(let{activityId:g,newParentId:k}of d){if(f.has(k))continue;f.add(k);let m=n.getActivity(k);if(!m)continue;let P=m.customId,w=Ut(m.type)&&n.getChildren(k).filter(R=>!o.includes(R)).length===0,v=m.hasNewActivities&&m.newActivityIds.some(R=>String(R)===String(g)),C=Me({parentId:k,newChildId:g,getParent:R=>n.getActivity(R)??null,isCurrentlyLeaf:w,promotionSource:"reparent"});if(C){for(let[R,N]of Object.entries(C.fields))rt(n,C.parentId,R,N);C.promotionSnapshot&&n.setPromotionSnapshot(C.parentId,C.promotionSnapshot),v||(n.setActivityField(k,E.HAS_NEW_ACTIVITIES,!1),n.setActivityField(k,E.NEW_ACTIVITIES_ARRAY,[]))}n.setActivityField(k,E.CONSTRAINT_TYPE,"asap"),n.setActivityField(k,E.CONSTRAINT_DATE,null),n.setActivityField(k,E.CUSTOM_ID,null),ln(P,r.customIdTracker)}let p=new Set;for(let g of d)g.oldParentId!=="0"&&p.add(g.oldParentId),p.add(g.newParentId);for(let g of p)Tt(g,n);let h=at(n);for(let g of h){if(s.add(g.activityId),u.has(g.activityId))continue;let k=n.getActivity(g.activityId);if(!k)continue;let m=J(k);g.before!==void 0&&(m.correlativeId=g.before),u.set(g.activityId,m)}let{scheduledIds:A}=await Y({adapter:n,scheduler:i,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:null,recomputeParentsFrom:o,now:r.now,options:t}),I=yn(o,n),T={name:It.ACTIVITY_INDENT,properties:{activity_ids:o,failed:l.map(g=>({activity_id:g.activityId,reason:g.reason})),invalid_link_ids:I}};return e.eventSource!==void 0&&(T.properties.event_source=e.eventSource),{ok:!0,activityVerdicts:e.activityIds.map(g=>{let k=l.find(m=>String(m.activityId)===String(g));return k?{activityId:String(g),ok:!1,reason:k.reason}:{activityId:String(g),ok:!0}}),changes:await B(n,{source:e,beforeSnap:u,touchedIds:s,scheduledIds:A,trackingEvents:[T],hoursPerDay:a.hoursPerDay})}}async function vl(e,t,r){let{adapter:n,scheduler:i,sector:a}=r;if(i.invalidateAllCaches(),e.activityIds.length===0)return{ok:!1,reason:S.ACTIVITY_IDS_EMPTY};let s=new Set(e.activityIds),o=new Map,c=new Map;for(let v of e.activityIds){let C=v;n.getActivity(C)&&(o.set(C,Kn(C,n)),c.set(C,zc(C,s,n)))}let l=new Set,d=[],u=[],f=new Set,p=[],h=new Set,A=[...e.activityIds].sort((v,C)=>{let R=n.getActivity(v),N=n.getActivity(C),x=R?st(R):oe,z=N?st(N):oe;return x-z});for(let v of A){let C=v,R=n.getActivity(C);if(!R){d.push({activityId:C,reason:S.ACTIVITY_NOT_FOUND});continue}if(pn(C,h,n))continue;let N=R.parentId;if(L(N)){d.push({activityId:C,reason:S.OUTDENT_ROOT_LEVEL_NOT_EDITABLE});continue}let x=String(N),z=n.getActivity(x);if(!z){d.push({activityId:C,reason:S.ACTIVITY_NOT_FOUND});continue}let Q=z.parentId;if(L(Q)){d.push({activityId:C,reason:S.OUTDENT_ROOT_LEVEL_NOT_EDITABLE});continue}let lt=String(Q),pt=Kn(x,n)+1,nt=c.get(C);if(nt!=null&&s.has(nt)){let ue=o.get(nt)??-1,fe=o.get(C)??-1;ue>=0&&fe>=0&&(pt+=fe-ue)}p.push({activityId:C,grandparentKey:lt,oldParentKey:x,targetIndexInGrandparent:pt}),h.add(C),l.add(String(C)),l.add(String(x)),lt!=="0"&&l.add(String(lt)),f.add(x)}let I=gn(p.map(v=>({activityId:v.activityId,newParentId:v.grandparentKey})),n);for(let v of I)d.push({activityId:v,reason:S.HIERARCHY_CYCLE});let T=p.filter(v=>!I.has(v.activityId)),g=await $(n,l);for(let v of T){n.setActivityField(v.activityId,E.PARENT,v.grandparentKey);let C=qc(n,v.grandparentKey,v.targetIndexInGrandparent,v.activityId);n.setActivityField(v.activityId,E.CORRELATIVE_ID,C),u.push(v.activityId)}for(let v of f){let C=n.getActivity(v);if(!C)continue;let R=n.getChildren(v),N=We({parent:C,remainingChildIds:R.map(String),defaultDurationHours:a.hoursPerDay,promotionSnapshot:n.getPromotionSnapshot(v),computeEndDate:(pt,nt)=>n.calculateEndDate({startDate:pt,durationHours:nt,task:C}),idsRemoved:new Set(T.filter(pt=>pt.oldParentKey===v).map(pt=>pt.activityId))});if(!N){jr(v,n);continue}for(let[pt,nt]of Object.entries(N.fields))rt(n,v,pt,nt);let x=Xt(v,n),z=x?n.getActivity(x)?.customId:null,Q=typeof z=="string"&&z?z:null,lt=r.customIdTracker.generateCustomIdForRestoredChild(Q);n.setActivityField(v,E.CUSTOM_ID,lt)}let k=new Set;for(let v of f)k.add(String(v));for(let v of T)v.grandparentKey!=="0"&&k.add(String(v.grandparentKey));for(let v of k)Tt(v,n);let m=at(n);for(let v of m){if(l.add(v.activityId),g.has(v.activityId))continue;let C=n.getActivity(v.activityId);if(!C)continue;let R=J(C);v.before!==void 0&&(R.correlativeId=v.before),g.set(v.activityId,R)}let{scheduledIds:P}=await Y({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}),w={name:It.ACTIVITY_OUTDENT,properties:{activity_ids:u.map(String),failed:d.map(v=>({activity_id:String(v.activityId),reason:v.reason}))}};return e.eventSource!==void 0&&(w.properties.event_source=e.eventSource),{ok:!0,activityVerdicts:e.activityIds.map(v=>{let C=d.find(R=>String(R.activityId)===String(v));return C?{activityId:String(v),ok:!1,reason:C.reason}:{activityId:String(v),ok:!0}}),changes:await B(n,{source:e,beforeSnap:g,touchedIds:l,scheduledIds:P,trackingEvents:[w],hoursPerDay:a.hoursPerDay})}}async function Al(e,t,r){let{adapter:n,ctx:i,scheduler:a,sector:s}=r;if(e.newValue!==0&&e.newValue!==100)return{ok:!1,reason:S.INVALID_PROGRESS_VALUE};let o=i.activityReader.getActivity(e.activityId);if(!o)return{ok:!1,reason:S.ACTIVITY_NOT_FOUND};let c=$t(_.PROGRESS);if(!c)throw new Error("[ScheduleCore] progressPipeline not registered \u2014 cannot dispatch activity-set-progress");let l=c.canEdit(o,i.hierarchy);if(!l.allowed&&!(e.origin==="action-button"&&(l.reason==="has_lookahead_tasks"||l.reason==="summary")))return{ok:!1,reason:l.reason,...l.alertKey?{alertKey:l.alertKey}:{}};let d=c.transform(o,e.newValue,i,e.newValue),u=zt(e.activityId,d),f=await $(n,u);qt(n,e.activityId,d),Vt(e.activityId,d.postProcessors??[],n);let{scheduledIds:p}=await Y({adapter:n,scheduler:a,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:d.needsAutoSchedule?e.activityId:null,recomputeParentsFrom:[],collectDirty:A=>Xr(e.activityId,u,A),now:r.now,options:t}),h=(d.trackingEvents??[]).map(A=>({name:A.name,properties:A.properties??{}}));return{ok:!0,changes:await B(n,{source:e,beforeSnap:f,touchedIds:u,scheduledIds:p,trackingEvents:h,hoursPerDay:s.hoursPerDay})}}async function Il(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 h of e.edits){let A=Fm(h,r);if(s.push(A.verdict),!A.verdict.ok||!A.changes)continue;let I=zt(h.activityId,A.changes);Nm(o,I,r);for(let m of I)c.add(m);let T=Fe(n,h.activityId),g=qr(n,String(h.activityId));qt(n,h.activityId,A.changes),Vt(h.activityId,A.changes.postProcessors??[],n,g),d.push(...Ne(T,n,h.activityId)),f||=!!A.changes.needsAutoSchedule;for(let m of A.changes.trackingEvents??[])l.push({name:m.name,properties:m.properties??{}});let k=be(h.activityId,A.changes.constraintWarning);k&&u.push(k)}let{scheduledIds:p}=await Y({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 Fm(e,t){let{ctx:r}=t,n=e.activityId,i=$t(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??S.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??S.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??S.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 Nm(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 Ji=_.CUSTOM_ID;async function Cl(e,t,r){let{adapter:n,scheduler:i,sector:a}=r;e.edits.some(k=>k.column===_.DURATION)&&i.invalidateExpandedLinksCache();let o=[],c=new Map,l=new Map,d=new Set,u=new Set,f=[],p=[],h=[],A=!1;for(let k of e.edits){let m=Mm(k,r);if(o.push(m.verdict),!m.verdict.ok||!m.changes)continue;let P=be(k.activityId,m.changes.constraintWarning);P&&h.push(P);let w=zt(k.activityId,m.changes);jm(c,w,r);for(let x of w)u.add(x);Um(l,k,c),sn(k.column)&&d.add(String(k.activityId));let v=Fe(n,k.activityId),C=qr(n,String(k.activityId)),R=Wm(k,r),N=m.changes;qt(n,k.activityId,N),Vt(k.activityId,m.changes.postProcessors??[],n,C),Bm(k,R,r),p.push(...Ne(v,n,k.activityId)),A||=!!m.changes.needsAutoSchedule;for(let x of m.changes.trackingEvents??[])f.push({name:x.name,properties:x.properties??{}})}let I={action:e,autoscheduleFrom:A?"roots":null,recomputeParentsFrom:u,now:r.now,options:t},T=l.size>0,{scheduledIds:g}=await(T?cn({adapter:n,scheduler:i,sector:a,defaultBaseCalendarId:r.defaultBaseCalendarId},{postMutationArgs:I,revertTargets:[...l].filter(([k])=>!d.has(k)).map(([k,m])=>({activityId:k,priorConstraintDate:m})),revert:(k,m)=>on(k,m,n,r.ctx.calendars)}):Y({adapter:n,scheduler:i,sector:a,defaultBaseCalendarId:r.defaultBaseCalendarId},I));return{ok:!0,verdicts:o,changes:await B(n,{source:e,beforeSnap:c,touchedIds:u,scheduledIds:g,sirDetection:"before-diff",links:p,trackingEvents:f,warnings:h,hoursPerDay:a.hoursPerDay})}}function Mm(e,t){let{ctx:r}=t,n=e.activityId,i=$t(e.column);if(!i)return{verdict:{activityId:n,ok:!1,reason:S.NO_PIPELINE_FOR_COLUMN},changes:null};let a=r.activityReader.getActivity(e.activityId);if(!a)return{verdict:{activityId:n,ok:!1,reason:S.ACTIVITY_NOT_FOUND},changes:null};let s=i.canEdit(a,r.hierarchy);if(!s.allowed)return{verdict:{activityId:n,ok:!1,reason:s.reason??S.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??S.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??S.INVALID,...l.notification?.messageKey?{alertKey:l.notification.messageKey}:{}},changes:null};if(e.column===Ji&&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:S.CUSTOM_ID_DUPLICATE},changes:null}}let d=i.transform(a,o.value,r,o.raw);return{verdict:{activityId:n,ok:!0},changes:d}}function Wm(e,t){if(e.column!==Ji)return null;let r=t.adapter.getActivity(e.activityId),n=r?r.customId:null;return typeof n=="string"?n:null}function Bm(e,t,r){if(e.column!==Ji)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 Um(e,t,r){if(!an(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 jm(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 Sl(e){return typeof e=="string"&&e.length>0?Nt(e):e instanceof Date?e:null}function Xi(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 An(e,t){let r=Xi(e.duration),n=Xi(e.cost),i=Xi(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:Sl(e.start_date),endDate:Sl(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 kl(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=>An(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 Hm(e){let t=ut(e);return t?{startDate:t.startDate,endDate:t.endDate,durationDays:t.durationDays,cost:t.cost,workHours:t.workHours}:null}function Dl(e){let t=[];return e.forEachActivity((r,n)=>{let i=Hm(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 In(e,t,r,n,i=null){let a=new Set;for(let s of kl(e,t,n))a.add(s);if(r)for(let s of we(e,r,i))a.add(s);for(let s of Dl(e))a.add(s);for(let s of Oe(e))a.add(s);return[...a]}function Tl(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=Vm(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,_.PONDERATOR,s*u)}else(!Array.isArray(l)||l.length===0)&&r.setActivityField(o,_.PONDERATOR,0)}}function Vm(e,t,r){let n=r.getActivity(e);if(!n)return 0;let i=ut(n);if(!i)return 0;if(t==="COST")return Cn(i.cost);if(t==="HH")return Cn(i.workHours);let a=n.type;return a==="project"?_l(e,r):a==="milestone"?0:Cn(i.durationDays)}function _l(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+=_l(String(n),t):s!=="milestone"&&(r+=Cn(a.durationDays))}return r}function Cn(e){let t=typeof e=="string"?parseFloat(e):e;return typeof t=="number"&&Number.isFinite(t)?t:0}function Pl(e,t){t.forEachActivity((r,n)=>{t.setActivityField(n,_.PONDERATOR,0)}),t.forEachActivity((r,n)=>{t.getChildren(n).length>0&&Tl(String(n),e,t)})}function Sn(e,t){Pl(t,e.adapter),ol(e.adapter),e.now&&(we(e.adapter,e.now,e.defaultBaseCalendarId??null),ne(e.adapter,e.now)),Oe(e.adapter),e.now&&Mt(e.adapter,e.sector.statusCriteria)}function Rl(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 bl(e,t){let r=await $(t.adapter,new Set(t.adapter.getAllIds())),n=Rl(t),i=In(t.adapter,e.points,t.now,t.reporter,t.defaultBaseCalendarId??null);return Rl(t)!==n&&Sn(t,t.sector.activityCreter??"DURATION"),{ok:!0,changes:await B(t.adapter,{source:e,beforeSnap:r,touchedIds:i,scheduledIds:[],hoursPerDay:t.sector.hoursPerDay})}}function Ym(e){if(!(e==="DURATION"||e==="COST"||e==="HH"))throw new Error(`ponderator-criterion-set: invalid criterion "${String(e)}"`)}async function El(e,t){Ym(e.criterion);let r=new Set(t.adapter.getAllIds()),n=await $(t.adapter,r);return Sn(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 Ll(e,t){let r=Ir(e.criteria),n=new Set(t.adapter.getAllIds()),i=await $(t.adapter,n),a=Mt(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})}}var wl=["name","description","type","startDate","durationHours","constraintType","constraintDate","calendarId","cost","hasCustomPonderator","subcontractId","responsableIds","tagIds"];function Km(e){let t={};for(let r of wl)Object.assign(t,{[r]:b(e[r])});return t}function Gm(e,t){let r=[],n=i=>{t.has(String(i))&&r.push(i);for(let a of e.getChildren(i))n(a)};for(let i of e.getRootIds())n(i);return r}function Ol(e,t){let r=new Set(t.adapter.checkedIds().map(String));if(r.size===0)return{ok:!1,reason:S.NO_ACTIVITY_SELECTION};let n=Gm(t.adapter,r);t.clipboard.value={activities:n.map(a=>{let s=t.adapter.getActivity(a);if(s===null)throw new Error(`Selected activity ${a} is missing`);return{originalId:a,originalParentId:s.parentId??"0",overrides:Km(s)}}),links:t.adapter.getAllLinks().filter(a=>r.has(String(a.source))&&r.has(String(a.target))).map(a=>b(a))};let i=hr({kind:"selection-replace",activityIds:[]},{adapter:t.adapter});return i.ok?{...i,changes:{...i.changes,source:e}}:i}function xl(e,t){return t.value=null,{ok:!0,changes:{source:e,activities:[],links:[],calendars:[],trackingEvents:[]}}}function $m(e,t){let r=t.getActivity(e);return r?{ok:!0,parentId:r.parentId==null?"0":String(r.parentId)}:{ok:!1,reason:S.ANCHOR_SIBLING_NOT_FOUND}}var Fl=()=>({ok:!1,reason:S.ACTIVITY_PASTE_INVARIANT_FAILED});async function Nl(e,t,r){let n=r.activityClipboard.value;if(n===null)return{ok:!1,reason:S.CLIPBOARD_EMPTY};let i=$m(e.destination.afterSiblingId,r.adapter);if(!i.ok)return i;let a=await $(r.adapter,new Set),s=new Set,o=new Map,c=[],l;for(let A of n.activities){let I=o.get(A.originalParentId),T=await sr({kind:"activity-create",parentId:I??i.parentId,...I===void 0?{afterSiblingId:l??e.destination.afterSiblingId}:{},overrides:b(A.overrides),eventSource:e.eventSource},r,{skipCorrelativeRecompute:!0,skipBeforeSnap:!0,customIdReferenceId:e.destination.afterSiblingId});if(!T.ok)return T;o.set(A.originalId,T.newId),c.push(T.newId),I===void 0&&(l=T.newId)}let d=at(r.adapter),u=new Set(c.map(String));Ee(r.adapter,d,u,a,s);for(let A of c)s.add(String(A));let f=[];for(let A of n.links){let I=o.get(A.source),T=o.get(A.target);if(I===void 0||T===void 0)return Fl();let g={kind:"create",source:I,target:T,type:A.type,lag:A.lag},k=jt(g,{port:r.adapter,newLinkId:r.linkIdGen.next});if(!k.applied)return Fl();f.push({op:g,finalLinkId:k.linkId,rejected:null})}let{scheduledIds:p}=await Y({adapter:r.adapter,scheduler:r.scheduler,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:c[0]??null,recomputeParentsFrom:c,now:r.now,options:t}),h=xe(f,new Map,r.adapter);return{ok:!0,changes:await B(r.adapter,{source:e,beforeSnap:a,touchedIds:s,scheduledIds:p,links:h,hoursPerDay:r.sector.hoursPerDay})}}async function Ml(e,t,r){return e.kind==="activity-copy"?Ol(e,{adapter:r.adapter,clipboard:r.activityClipboard}):e.kind==="activity-clipboard-clear"?xl(e,r.activityClipboard):e.kind==="activity-paste-copied"?Nl(e,t,r):e.kind==="activity-batch"?il(e,t,r):e.kind==="persistence-acknowledge"?pl(e,r):e.kind==="baseline-apply"?bl(e,r):e.kind==="ponderator-criterion-set"?El(e,r):e.kind==="status-criteria-set"?Ll(e,r):e.kind==="link-create"||e.kind==="link-update"||e.kind==="link-delete"?Oc(e,t,r):e.kind==="links-batch"?xc(e,t,r):e.kind==="activity-create"?Jc(e,t,r):e.kind==="activity-delete"?el(e,t,r):e.kind==="activity-move"?ml(e,t,r):e.kind==="activity-indent"?gl(e,t,r):e.kind==="activity-outdent"?vl(e,t,r):e.kind==="activity-set-progress"?Al(e,t,r):e.kind==="dates-batch"?Il(e,t,r):e.kind==="bulk-edit"?Cl(e,t,r):e.kind==="selection-toggle"?xa(e,Zi(r)):e.kind==="selection-replace"?hr(e,Zi(r)):e.kind==="visibility-set"?Fa(e,Zi(r)):e.kind==="filter-set"?Va(e,{adapter:r.adapter,hoursPerDay:r.sector.hoursPerDay}):e.kind==="sort-set"?za(e,{adapter:r.adapter}):e.kind==="sir-sync"?sl(e,r):e.kind==="activity-lookahead-sync"?hl(e,t,r):e.kind==="inline-edit"&&(e.column===_.CUSTOM_PREDECESSORS||e.column===_.CUSTOM_SUCESSORS)?Fc(e,t,r):e.kind!=="inline-edit"?Os(e,`[ScheduleCore] dispatch kind "${e.kind}" not supported yet`):wc(e,t,r)}function Zi(e){return{adapter:e.adapter}}var zm=new Set(["startDate","endDate","constraintDate"]);function Wl(e,t){return zm.has(e)&&typeof t=="string"?new Date(t):t}function Bl(e,t={}){let r=t.defaultUnit??"hour";return{getCalendar(n){let i=e.getCalendar(String(n));return i?qm(i,r):null}}}function qm(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 Jm(e){return Array.isArray?Array.isArray(e):e&&e.length!==void 0&&e.pop&&e.push}function ce(e){return e&&typeof e=="object"?!!(e.getFullYear&&e.getMonth&&e.getDate):!1}function le(e){return ce(e)&&!isNaN(e.getTime())}var Xm={}.constructor.toString();function Zm(e){var t=e.constructor.toString();return t!==Xm}function Qm(e){return e.$$typeof&&e.$$typeof.toString().includes("react.")}function _t(e){var t,r;if(e&&typeof e=="object")switch(!0){case ce(e):r=new Date(e);break;case Jm(e):for(r=new Array(e.length),t=0;t<e.length;t++)r[t]=_t(e[t]);break;default:if(Zm(e))r=Object.create(e);else{if(Qm(e))return r=e,r;r={}}for(t in e)Object.prototype.hasOwnProperty.apply(e,[t])&&(r[t]=_t(e[t]));break}return r||e}function Be(e,t,r){for(var n in t)(e[n]===void 0||r)&&(e[n]=t[n]);return e}function Ul(e){return typeof e<"u"}var kn;function Qi(){return kn||(kn=new Date().valueOf()),kn++,kn}function mt(e,t){return e.bind?e.bind(t):function(){return e.apply(t,arguments)}}var eg=(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)},rg=(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)},jl={date_to_str:eg,str_to_date:rg},ng=(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}}),ig=(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])},Hl={date_to_str:ng,str_to_date:ig};function Vl(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=jl;return a()&&(l=Hl),l.date_to_str(o,c,e)},str_to_date:function(o,c){var l=jl;return a()&&(l=Hl),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 ta(e,t,r,n,i){return this.date=e,this.unit=t,this.task=r,this.id=n,this.calendar=i,this}function ea(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 ra(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 ag(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 Yl=function(e){return{getWorkHoursArguments:function(){var t=arguments[0];if(ce(t)?t={date:t}:t=Be({},t),!le(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 ta)return t;var r;if(t.date?r=new ta(t.date,t.unit,t.task,null,t.calendar):r=new ta(arguments[0],arguments[1],arguments[2],null,arguments[3]),r.unit=r.unit||e.config.duration_unit,!le(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 ea)return r;var n;if(ce(r)?n=new ea(r):n=new ea(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,!le(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=ag,n;if(t instanceof r)return t;if(ce(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,!le(n.start_date))throw e.assert(!1,"Invalid start_date argument for getDuration method"),new Error("Invalid start_date argument for getDuration method");if(!le(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 ra)return a;var s;if(ce(a)?s=new ra(arguments[0],arguments[1],arguments[2],void 0,arguments[3],void 0,arguments[4]):s=new ra(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,!le(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 Kl(){}Kl.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=_t(e.getConfig()),n=_t(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 h=d.dates[p];if(p==u&&(s.dates[u]=!!(f&&h)),Array.isArray(f)){let A=Array.isArray(h)?h:d.hours;s.dates[u]=this._toHoursArray(this._mergeHoursConfig(f,A))}}}};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 na=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}},ia=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={}}},aa=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 sg(){return typeof Map<"u"?new na:new ia}var sa=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 oa(e,t){this.argumentsHelper=t,this.$gantt=e,this._workingUnitsCache=sg(),this._largeUnitsCache=new aa(this),this._dateDurationCache=new sa,this._worktime=null,this._cached_timestamps={},this._cached_timestamps_count=0}oa.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 h=this._getUnitOrder(r),A=this.units[h-1];A&&!this._isWorkTime(a,A)&&(c=this._getClosestWorkTimeFuture(a,A))}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=mt(this._getMinutesPerDay,this):o=mt(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 oa))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(mt(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(mt(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 h=r;return n===t&&(h=new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate(),0,0,s))),{added:n,end:h}},_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,h=this._getTimeOfDayStamp(n,u);if(!c.length||!l){n=this.$gantt.date.add(n,-1,"day");continue}if(c[c.length-1].end<=h&&p>l){i+=l,n=this.$gantt.date.add(n,-1,"day");continue}for(var A=!1,I=null,T=null,g=c.length-1;g>=0;g--)if(c[g].start<h-1&&c[g].end>=h-1){A=!0,I=c[g],T=c[g-1];break}if(A)if(h===I.end&&p>=I.durationMinutes)i+=I.durationMinutes,n=this.$gantt.date.add(n,-I.durationMinutes,"minute");else if(!a&&p<=h/60-I.startMinute)i+=p,n=this.$gantt.date.add(n,-p,"minute");else if(a)p<=h/60-I.startMinute?(i+=p,n=this.$gantt.date.add(n,-p,"minute")):(i+=h/60-I.startMinute,T?n=new Date(Date.UTC(n.getUTCFullYear(),n.getUTCMonth(),n.getUTCDate(),0,0,T.end)):n=this.$gantt.date.day_start(n));else{var k=this._getMinutesPerHour(n);k<=p?(i+=k,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 m=this._getClosestWorkTimePast(n,"hour");if(m.valueOf()===n.valueOf()){var m=this.$gantt.date.add(n,-1,"day"),P=this._getWorkHours(m);if(P.length){var w=P[P.length-1];m.setUTCSeconds(w.durationSeconds)}}n=m}else n=this._getClosestWorkTimePast(new Date(n-1),"hour")}if(i<t){var v=t-i;s=this._subtractMinutesUntilHourStart(n,v),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,h=null,A=0;A<o.length;A++)if(o[A].start<=f&&o[A].end>f){p=!0,h=o[A];break}if(p)if(f===h.start&&u>=h.durationMinutes)i+=h.durationMinutes,n=this.$gantt.date.add(n,h.durationMinutes,"minute");else if(u<=h.endMinute-f/60)i+=u,n=this.$gantt.date.add(n,u,"minute");else{var I=this._getMinutesPerHour(n);I<=u?(i+=I,l?n=this.$gantt.date.add(n,I,"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=t-i;a=this._addMinutesUntilHourEnd(n,T),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 or={isLegacyResourceCalendarFormat:function(e){if(!e)return!1;for(var t in e)if(e[t]&&typeof e[t]=="object")return!0;return!1},getResourceProperty:function(e){var t=e.resource_calendars,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 og(){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 cg=og();function Gl(e){this.$gantt=e,this._calendars={},this._legacyConfig=void 0,this.$gantt.attachEvent("onGanttReady",(function(){this.$gantt.config.resource_calendars&&(this._isLegacyConfig=or.isLegacyResourceCalendarFormat(this.$gantt.config.resource_calendars))}).bind(this)),this.$gantt.attachEvent("onBeforeGanttReady",(function(){this.createDefaultCalendars()}).bind(this)),this.$gantt.attachEvent("onBeforeGanttRender",(function(){this.createDefaultCalendars()}).bind(this))}Gl.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 Kl,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 oa(this.$gantt,Yl(this.$gantt));t.id=String(Qi());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=_t(e.getConfig()):e.worktime?t=_t(e.worktime):t=_t(e);var r=_t(this.defaults.fulltime.worktime);return Be(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=or.getResourceProperty(t),Array.isArray(e[i])&&e[i].length)t.dynamic_resource_calendars?n=cg.getCalendarIdFromMultipleResources(e[i],this):r=this.getResourceCalendar(e[i]);else if(this._legacyConfig===void 0&&(this._legacyConfig=or.isLegacyResourceCalendarFormat(t.resource_calendars)),this._legacyConfig)var n=or.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=or.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||Qi(),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 ca(e,t){this.argumentsHelper=t,this.$gantt=e}ca.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 ca},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 $l(e){this.$gantt=e.$gantt,this.argumentsHelper=Yl(this.$gantt),this.calendarManager=e,this.$disabledCalendar=new ca(this.$gantt,this.argumentsHelper)}$l.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 lg=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:mt(e.mergeCalendars,e),createCalendar:mt(e.createCalendar,e),addCalendar:mt(e.addCalendar,e),getCalendar:mt(e.getCalendar,e),getCalendars:mt(e.getCalendars,e),getResourceCalendar:mt(e.getResourceCalendar,e),getTaskCalendar:mt(e.getTaskCalendar,e),deleteCalendar:mt(e.deleteCalendar,e)}},dg={create:lg};function zl(e){var t=new Gl(e),r=new $l(t),n=dg.create(t,r);Be(e,n)}var ql={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 Jl(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||ql,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:Ul,mixin:Be,copy:_t,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=Vl(r),r.date.init(),zl(r),r}function ug(e={}){let t=Jl(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 Xl={createCalendar:ug};var bF=3600*1e3;function ed(e){return{getActivity(t){return e.getActivity(t)}}}var{createCalendar:fg}=Xl,cr="__replay_default__";function pg(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 Zl={hours:["8:00-16:00"],days:[!1,!0,!0,!0,!0,!0,!1]},Ql="__main_global__",hg={hours:["8:00-12:00","13:00-17:00"],days:[!1,!0,!0,!0,!0,!0,!1]};function td(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 yg(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:pg(e.hours),dates:t};return e.customWeeks&&(r.customWeeks=e.customWeeks),r}function rd(e){let t=fg({config:{work_time:!0}});t.addCalendar({id:cr,worktime:Zl}),t.addCalendar({id:Ql,worktime:hg});let r=new Set(e.filter(d=>!td(d.worktime)).map(d=>String(d.id))),n=e.filter(d=>td(d.worktime));for(let d of n)t.addCalendar({id:d.id,worktime:d.worktime?yg(d.worktime):Zl});let i=Bl(t),a=i.getCalendar(cr),s=i.getCalendar(Ql);if(!a||!s)throw new Error("[replay-calendar] fallback calendars failed to register in work-calendar instance");let o=new Set([cr]);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 nd(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 mg(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 mg(e,t){let r=[],n=new ht;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 Dn=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,Ft(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:Ft(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:id(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=Ft(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:id(r)}))}};function id(e){return{...e}}var Tn=class{_cache={closestWorkTime:new Map,endDate:new Map,duration:new Map};reader;constructor(t){this.reader=t.reader}resolveCalendar(t){let r=ad(t);return this.reader.getCalendar(r??cr)}getClosestWorkTime(t){let r=`${da(t.task)}|${t.dir}|${t.date.getTime()}`;return la(this._cache.closestWorkTime,r,()=>this.resolveCalendar(t.task).getClosestWorkTime({direction:t.dir,date:t.date,unit:ot.HOUR}))}calculateEndDate(t){let r=`${da(t.task)}|${t.startDate.getTime()}|${t.durationHours}`;return la(this._cache.endDate,r,()=>this.resolveCalendar(t.task).calculateEndDate(t.startDate,t.durationHours))}calculateDuration(t){let r=`${da(t.task)}|${t.startDate.getTime()}|${t.endDate.getTime()}`;return la(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 la(e,t,r){let n=e.get(t);if(n!==void 0)return n;let i=r();return e.set(t,i),i}var gg="__default__";function ad(e){if(!e)return null;let t=e.calendarId;return t==null?null:String(t)}function da(e){return ad(e)??gg}var _n=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?vr(i,a):String(r).localeCompare(String(n))};this._roots.sort(t);for(let r of this._childrenByParent.values())r.sort(t)}};var Ue=class e{_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 Dn;_viewState=new yr;_filterProjection=null;_viewStateBefore=null;_lastStartDateBefore=null;_promotionSnapshotBefore=null;_calendar;_flags;_calendarSnapshot;constructor(t,r=()=>null){this._buildOrderComparator=r,this._calendarSnapshot=b(t.calendars);for(let n of t.activities)this._activities.set(n.id,n);for(let n of t.links){let i={...n,freeSlackHours:n.freeSlackHours??null,isCritical:n.isCritical===!0};this._links.set(String(n.id),i),this._indexLink(i)}this._calendar=new Tn(rd(this._calendarSnapshot)),this._flags=Ag(t),this._hierarchy=new _n(this._activities),this._hierarchy.rebuild()}fork(){let t=new e({activities:this.getAllActivities().map(Ft),links:this.getAllLinks().map(r=>({...r})),calendars:b(this._calendarSnapshot)},this._buildOrderComparator);return t._viewState.restore(b(this._viewState.snapshot())),t._lastStartDate=new Map(Array.from(this._lastStartDate,([r,n])=>[r,new Date(n)])),t._promotionSnapshot=new Map(Array.from(this._promotionSnapshot,([r,n])=>[r,b(n)])),t._flags=b(this._flags),t._filterProjection=b(this._filterProjection),t}getAllActivities(){return Array.from(this._activities.values())}getAllLinks(){return Array.from(this._links.values())}getAllIds(){return this._cache.ids?this._cache.ids:(this._cache.ids=Array.from(this._activities.keys()),this._cache.ids)}activityCount(){return this._activities.size}getVisualOrderIds(){return this._cache.visualOrderIds?this._cache.visualOrderIds:(this._cache.visualOrderIds=Ka(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()}setRelativePlacementPin(t,r){this._viewState.setRelativePlacementPin(String(t),r),this.invalidateVisualOrderIds()}getRelativePlacementPins(){return this._viewState.getRelativePlacementPins()}restoreRelativePlacementPins(t){this._viewState.restoreRelativePlacementPins(t),this._filterProjection=null,this.invalidateVisualOrderIds()}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))??sd}getIncomingLinkIds(t){return this._incoming.get(String(t))??sd}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,fa(i,r),r===E.PARENT&&this._hierarchy.markDirty(),ua(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,Wl(r,n)),fa(i,r),r===E.PARENT&&this._hierarchy.markDirty(),ua(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)),fa(n,a),a===E.PARENT&&(i=!0),ua(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);let n={...t,freeSlackHours:t.freeSlackHours??null,isCritical:t.isCritical===!0};this._links.set(String(t.id),n),this._indexLink(n)}_indexLink(t){cd(this._outgoing,String(t.source),t.id),cd(this._incoming,String(t.target),t.id)}_deindexLink(t){let r=this._outgoing.get(String(t.source));r&&this._outgoing.set(String(t.source),od(r,t.id));let n=this._incoming.get(String(t.target));n&&this._incoming.set(String(t.target),od(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(!vg(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),i=this._viewState.getRelativePlacementPins(),a=[...i.values()].some(({referenceId:s})=>s===n);(this._viewState.isChecked(n)||!this._viewState.isVisible(n)||i.has(n)||a)&&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))}},sd=[];function vg(e){return e===Qe.LAG||e===Qe.TYPE||e===Qe.FREE_SLACK_HOURS||e===Qe.IS_CRITICAL}function ua(e){return e===E.PARENT||e===E.CORRELATIVE_ID}function fa(e,t){t!==E.START_DATE&&t!==E.END_DATE&&t!==E.TYPE||(e.calendarDuration=bt(e))}function od(e,t){return e.filter(r=>String(r)!==String(t))}function cd(e,t,r){let n=e.get(t);n?n.push(r):e.set(t,[r])}function Ag(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 ld(e,t){let r=e.getActivity(t);return r?b(r):null}function dd(e){return e.getAllActivities().map(b)}function ud(e){return e.getAllIds().map(String)}function fd(e,t){e.forEachActivity((r,n)=>t(n))}function pd(e,t){let r=t==="0"?pa(e,"0"):e.getChildren(t),n=[];for(let i of r){let a=e.getActivity(i);a&&n.push(b(a))}return n.sort((i,a)=>(i.correlativeId??0)-(a.correlativeId??0)),n}function pa(e,t){return gt(t,e)}function hd(e){return e.checkedIds().map(String)}function yd(e,t){if(t==="0"){let r=!1;return e.forEachActivity(n=>{r||=L(n.parentId)}),r}return e.getChildren(t).length>0}function ha(e,t){let r=e.getLink(t);return r?ft(r):null}function md(e){return e.getAllLinks().map(t=>ft(t))}function Pn(e){let[t,r]=e.split(":");return Number(t)*60+Number(r??0)}function Ig(e){return e.reduce((t,r)=>Pn(r)<Pn(t)?r:t)}function Cg(e){return e.reduce((t,r)=>Pn(r)>Pn(t)?r:t)}function Sg(e){return e.worktime.days.flatMap(t=>Array.isArray(t)?t:t===!0?e.worktime.hours:[])}function gd(e){let t=[...e].find(a=>a.is_default);if(!t)return null;let r=Sg(t);if(r.length===0)return null;let n=r.map(a=>a.split("-")[0]),i=r.map(a=>a.split("-")[1]);return{startHour:Ig(n),endHour:Cg(i)}}function vd(e,t){return{calendars:e.calendarReader,hierarchy:nd(e),activityReader:ed(e),dateFormat:t.dateFormat??"YYYY-MM-DD",customHours:t.customHours??{},hoursPerDay:t.hoursPerDay}}function Ad(e){return se(e)}var kg=new Set(["freeSlackHours","isCritical"]);function Dg(e,t){let r=Object.fromEntries(Object.entries(e.fields??{}).filter(([n])=>!t.has(n)));return e.kind==="updated"&&Object.keys(r).length===0?null:{...e,...e.fields===void 0?{}:{fields:r},after:null}}function kd(e){let t=e.activities.map(i=>({...i,after:null})),r=e.links.map(i=>Dg(i,kg)).filter(i=>i!==null),n=e.source.kind==="activity-batch"?{...e.source,items:[],links:[]}:e.source;return b({...e,source:n,activities:t,links:r})}function ya(e,t,r,n,i,a,s){return{changeSet:e,beforeSnap:t,beforeLinks:Id(r),afterSnap:n,afterLinks:Id(i),relativePlacementPinsBefore:a,relativePlacementPinsAfter:s}}function Id(e){if(e)return new Map(Array.from(e,([t,r])=>[t,{...r,freeSlackHours:null,isCritical:!1}]))}function Dd(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 Td(e){return e.kind!=="inline-edit"||!ir.has(e.column)?null:`inline-edit:${String(e.activityId)}:${e.column}`}function Cd(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 _d(e,t){if(!Cd(e)||!Cd(t))return!1;let r=e.changeSet.activities[0],n=t.changeSet.activities[0];return!!r&&!!n&&String(r.id)===String(n.id)}function Pd(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 ya(o)}function Rd(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==="activity-clipboard-clear"||e.kind==="activity-copy"||e.kind==="selection-toggle"||e.kind==="selection-replace"||e.kind==="visibility-set"||e.kind==="filter-set"||e.kind==="sort-set"?"skip":"record"}function ma(e){for(let t of e.changeSet.activities)if(t.kind==="created"||t.kind==="deleted"||t.kind==="updated"&&t.fields&&_.CUSTOM_ID in t.fields)return!0;return!1}function ga(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:Sd(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:Sd(s.fields,r),after:c?ft(c):null})}else if(s.kind==="deleted")if(r==="before"){let c=e.getLink(o);i.push({id:o,kind:"created",after:c?ft(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?ft(c):null})}}let a=(t.changeSet.viewState??[]).map(s=>r==="before"?Tg(s):s);return{source:{kind:r==="before"?"undo":"redo"},activities:n,links:i,calendars:[],trackingEvents:[],effects:[],viewState:a}}function Sd(e,t){if(e!=null)return Object.fromEntries(Object.entries(e).map(([r,n])=>[r,t==="before"?{before:b(n.after),after:b(n.before)}:{before:b(n.before),after:b(n.after)}]))}function Tg(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 va(e){return e.activities.length>0||e.links.length>0||(e.viewState?.length??0)>0||(e.effects?.length??0)>0}function bd(e,t){Ld(e,t,"before")}function Ed(e,t){Ld(e,t,"after")}function Ld(e,t,r){let n=t.changeSet;for(let a of n.activities)if(a.kind==="updated"){if(!a.fields)continue;for(let[s,o]of Object.entries(a.fields))rt(e,a.id,s,r==="before"?o.before:o.after)}else if(a.kind==="deleted")if(r==="before"){let s=t.beforeSnap?.get(String(a.id));if(!s)throw new Error(`undo: missing beforeSnap for resurrecting activity ${a.id}`);e.addActivity(J(s))}else e.removeActivity(String(a.id));else if(r==="before")e.removeActivity(String(a.id));else{let s=t.afterSnap?.get(String(a.id));if(!s)throw new Error(`redo: missing afterSnap for re-creating activity ${a.id}`);e.addActivity(J(s))}for(let a of n.links)if(a.kind==="updated"){if(!a.fields)continue;if(Object.hasOwn(a.fields,"source")||Object.hasOwn(a.fields,"target")){let s=r==="before"?t.beforeLinks?.get(String(a.id)):t.afterLinks?.get(String(a.id));if(!s)throw new Error(`${r==="before"?"undo":"redo"}: missing link snapshot for ${a.id}`);e.removeLink(String(a.id)),e.addLink({...s});continue}for(let[s,o]of Object.entries(a.fields))Ko(e,String(a.id),s,r==="before"?o.before:o.after)}else if(a.kind==="deleted")if(r==="before"){let s=t.beforeLinks?.get(String(a.id));if(!s)throw new Error(`undo: missing beforeLinks for re-adding link ${a.id}`);e.addLink(s)}else e.removeLink(String(a.id));else if(r==="before")e.removeLink(String(a.id));else{let s=t.afterLinks?.get(String(a.id));if(!s)throw new Error(`redo: missing afterLinks for re-creating link ${a.id}`);e.addLink(s)}for(let a of n.viewState??[])a.checked&&e.setChecked(a.activityId,r==="before"?a.checked.before:a.checked.after),a.visible&&e.setVisible(a.activityId,r==="before"?a.visible.before:a.visible.after);let i=r==="before"?t.relativePlacementPinsBefore:t.relativePlacementPinsAfter;i!==void 0&&e.restoreRelativePlacementPins(i)}var _g=100,Pg=600,Rn=class e{constructor(t=_g){this.maxDepth=t}maxDepth;undoStack=[];redoStack=[];_lastKey=null;_lastTime=0;fork(){let t=new e(this.maxDepth);return t.undoStack.push(...b(this.undoStack)),t.redoStack.push(...b(this.redoStack)),t._lastKey=this._lastKey,t._lastTime=this._lastTime,t}record(t,r=null,n=0){let i=this.undoStack[this.undoStack.length-1];r!=null&&r===this._lastKey&&n-this._lastTime<=Pg&&i!==void 0&&_d(i,t)?this.undoStack[this.undoStack.length-1]=Pd(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 Rg=["parentId","correlativeId"];function Od(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(wd(c.parentId?.before));continue}let s=i.fields;!s||!Rg.some(c=>c in s)||(n(a),"parentId"in s&&r.add(wd(s.parentId?.before)))}return r}function wd(e){return e==null?"0":String(e)}function bg(e){return{...e,id:String(e.id),source:String(e.source),target:String(e.target),type:e.type,lag:Number(e.lag)}}function Eg(e){return{days:e.days,hours:e.hours,...e.dates?{dates:e.dates}:{},...e.customWeeks?{customWeeks:e.customWeeks}:{}}}function xd(e){return{id:String(e.id),worktime:Eg(e.worktime)}}function bn(e,t,r,n=[]){let i=t.map(bg),a=[...r.map(xd),...n.map(xd)];return{activities:[...e],links:i,calendars:a}}var Fd={id:"ignored",proplannerId:"ignored",parentId:"tracked",name:"tracked",description:"tracked",type:"tracked",startDate:"tracked",endDate:"tracked",durationHours:"tracked",constraintType:"tracked",constraintDate:"tracked",autoScheduling:"tracked",calendarId:"tracked",assignedDefaultCalendar:"ignored",dateOrigin:"tracked",progress:"tracked",cost:"tracked",usedCost:"tracked",realCost:"tracked",workHours:"tracked",realWorkHours:"tracked",ponderator:"tracked",hasCustomPonderator:"tracked",correlativeId:"tracked",uniqueCorrelativeId:"tracked",customId:"tracked",subcontractId:"tracked",isLookahead:"tracked",hasLookaheadTasks:"ignored",newActivityIds:"tracked",hasNewActivities:"tracked",isNewActivity:"ignored",pendingRequestIds:"ignored",responsableIds:"tracked",tagIds:"tracked",baselinePoints:"ignored",baselineSnapshot:"ignored",recursiveDurationHours:"ignored",isCritical:"ignored",freeSlackHours:"ignored",calendarDuration:"ignored",expectedProgress:"ignored",expectedProgressBaseline:"ignored",status:"ignored",criticalPath:"ignored"},Nd=Object.keys(Fd).filter(e=>Fd[e]==="tracked"),Md=new Set(["startDate","endDate","constraintDate","dateOrigin"]),Wd=new Set(["newActivityIds","responsableIds","tagIds"]);function Bd(e){let t=Nd.map(r=>[r,Lg(r,e[r])]);return Object.fromEntries(t)}function Lg(e,t){return Md.has(e)?t instanceof Date?new Date(t):null:Wd.has(e)?Array.isArray(t)?[...t]:[]:t}function lr(e,t){for(let r of Nd)if(!wg(r,e[r],t[r]))return!0;return!1}function wg(e,t,r){return Md.has(e)?Og(t,r):Wd.has(e)?xg(t,r):(t??null)===(r??null)}function Og(e,t){let r=e instanceof Date?e.getTime():null,n=t instanceof Date?t.getTime():null;return r===n}function xg(e,t){let r=new Set(Array.isArray(e)?e.map(String):[]),n=new Set(Array.isArray(t)?t.map(String):[]);if(r.size!==n.size)return!1;for(let i of r)if(!n.has(i))return!1;return!0}var Ud={id:"ignored",source:"tracked",target:"tracked",type:"tracked",lag:"tracked",freeSlackHours:"ignored",isCritical:"ignored",ganttId:"ignored",sectorId:"ignored",proplannerId:"ignored"},Fg=Object.keys(Ud).filter(e=>Ud[e]==="tracked");function En(e,t){return Fg.some(r=>e[r]!==t[r])}function jd(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?En(i,n):!1})}function Pt(e){if(e==null||e===0)return!1;if(!(typeof e=="number"&&Number.isSafeInteger(e)&&e>0))throw new Error(`invalid proplannerId ${String(e)}`);return!0}function Hd(e,t){for(let r of e)Pt(r.proplannerId);for(let r of t)Pt(r.proplannerId)}var Ln=class e{trackingEnabled;initialized=!1;dirtyActivityIds=new Set;dirtyLinkIds=new Set;initialCalendarRepairIds=new Set;linksAtLastSave=new Map;activitiesAtLastSave=new Map;constructor(t=!0){this.trackingEnabled=t}fork(){let t=new e(!1);t.initialized=this.initialized;for(let[r,n]of this.linksAtLastSave)t.linksAtLastSave.set(r,b(n));for(let[r,n]of this.activitiesAtLastSave)t.activitiesAtLastSave.set(r,b(n));return t}init(t,r){if(this.trackingEnabled){Hd(t,r),this.snapshotActivities(t),this.snapshotLinks(r);for(let n of t)if(n.assignedDefaultCalendar){let i=String(n.id);this.initialCalendarRepairIds.add(i),this.dirtyActivityIds.add(i)}this.initialized=!0}}acknowledge(t,r){this.trackingEnabled&&(Hd(t,r),this.snapshotActivities(t),this.snapshotLinks(r))}snapshotActivities(t){if(this.trackingEnabled){this.activitiesAtLastSave.clear(),this.dirtyActivityIds.clear(),this.initialCalendarRepairIds.clear();for(let r of t){let n=String(r.id);if(!Pt(r.proplannerId)){this.dirtyActivityIds.add(n);continue}let i=Bd(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}}),lr(r,i)&&this.dirtyActivityIds.add(n)}}}snapshotLinks(t){if(this.trackingEnabled){this.linksAtLastSave.clear(),this.dirtyLinkIds.clear();for(let r of t){let n=String(r.id);if(!Pt(r.proplannerId)){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.trackingEnabled||!this.initialized)){for(let a of t){let s=String(a.id),o=n(s);this.activityIsDirty(s,o)?this.dirtyActivityIds.add(s):this.dirtyActivityIds.delete(s)}for(let a of r){let s=String(a.id),o=i(s);this.linkIsDirty(s,o)?this.dirtyLinkIds.add(s):this.dirtyLinkIds.delete(s)}}}activityIsDirty(t,r){let n=this.activitiesAtLastSave.get(t);return r===null?n!==void 0:this.initialCalendarRepairIds.has(t)||!Pt(r.proplannerId)||n===void 0||lr(r,n.persistable)}linkIsDirty(t,r){let n=this.linksAtLastSave.get(t);return r===null?n!==void 0:!Pt(r.proplannerId)||n===void 0||En(n,r)}acknowledgePersistedLookahead(t,r){if(!this.trackingEnabled||!this.initialized)return;let n=t.map(i=>{let a=typeof i=="string"?i:String(i.id),s=r(a),o=this.activitiesAtLastSave.get(a);if(s===null||o===void 0)throw new Error(`unknown persisted activity "${a}"`);return{activityId:a,acknowledgesLookahead:typeof i=="string"||!!i.fields?.isLookahead,acknowledgesProgress:typeof i!="string"&&!!i.fields?.progress,current:s,saved:o}});for(let{activityId:i,acknowledgesLookahead:a,acknowledgesProgress:s,current:o,saved:c}of n){let l={...c.persistable,...a?{isLookahead:o.isLookahead}:{},...s?{progress:o.progress}:{}};this.activitiesAtLastSave.set(i,{...c,persistable:l}),this.initialCalendarRepairIds.has(i)||!Pt(o.proplannerId)||lr(o,l)?this.dirtyActivityIds.add(i):this.dirtyActivityIds.delete(i)}}hasCheckpointActivityId(t){return this.activitiesAtLastSave.has(t)}hasCheckpointLinkId(t){return this.linksAtLastSave.has(t)}hasUnsavedChanges(){return this.trackingEnabled&&this.initialized&&(this.dirtyActivityIds.size>0||this.dirtyLinkIds.size>0)}newActivities(t){if(!this.trackingEnabled||!this.initialized)return[];let r=[];for(let n of this.dirtyActivityIds){let i=t(n);i!==null&&!Pt(i.proplannerId)&&r.push(i)}return r}newLinks(t){if(!this.trackingEnabled||!this.initialized)return[];let r=[];for(let n of this.dirtyLinkIds){let i=t(n);i!==null&&!Pt(i.proplannerId)&&r.push(i)}return r}deletedActivities(t){if(!this.trackingEnabled||!this.initialized)return[];let r=[];for(let n of this.dirtyActivityIds){let i=this.activitiesAtLastSave.get(n);i&&t(n)===null&&r.push({...i.deletedSnapshot})}return r}deletedLinks(t){if(!this.trackingEnabled||!this.initialized)return[];let r=[];for(let n of this.dirtyLinkIds){let i=this.linksAtLastSave.get(n);i&&t(n)===null&&r.push({...i})}return r}modifiedActivities(t){if(!this.trackingEnabled||!this.initialized)return[];let r=[];for(let n of this.dirtyActivityIds){let i=t(n);if(i===null||!Pt(i.proplannerId))continue;let a=this.activitiesAtLastSave.get(n);(a===void 0||this.initialCalendarRepairIds.has(n)||lr(i,a.persistable))&&r.push(i)}return r}modifiedLinks(t){if(!this.trackingEnabled||!this.initialized)return[];let r=[];for(let n of this.dirtyLinkIds){let i=t(n);if(i===null||!Pt(i.proplannerId))continue;let a=this.linksAtLastSave.get(n);(a===void 0||En(a,i))&&r.push(i)}return r}clear(){this.initialized=!1,this.dirtyActivityIds.clear(),this.dirtyLinkIds.clear(),this.initialCalendarRepairIds.clear(),this.linksAtLastSave.clear(),this.activitiesAtLastSave.clear()}};var Vd=/^(\d{4})[/-](\d{1,2})[/-](\d{1,2})/;var Aa=[!1,!0,!0,!0,!0,!0,!1],Yd=new Set(["1","true"]),Ia="DURATION",Kd="asap",Gd={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 $d(e,t){let r=[],n=e.map(a=>{let s=Gg(a,t);return a.should_be_showed===!1&&r.push(s.id),s});zg(n);let i=new Set(n.map(a=>a.id));return qg(n,i,t.reporter),{activities:n,activityIds:i,hiddenIds:r}}function Ng(e){return e===0}function Mg(e,t){if(!e)return null;let r=Gd[e.toUpperCase()];return r===void 0?(t.warn(`[parseFromBackend] unknown constraint label "${e}" \u2014 defaulting to "asap"`),Kd):r}function Wg(e,t){let r=Mg(e.constraint,t),i=r!=="asap"&&r!=="alap"&&e.constraint_date?Nt(e.constraint_date):null;return{constraintType:r,constraintDate:i}}function Bg(e,t,r){if(e==null)return r;let n=String(e);return t.has(n)?n:r}function Ug(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 jg(e){if(typeof e!="object"||e===null||!("id"in e))return!1;let t=e.id;return typeof t=="string"||typeof t=="number"}function Ca(e){if(!Array.isArray(e))return[];let t=[];for(let r of e)jg(r)&&t.push(String(r.id));return t}function Hg(e){return e==="0"?null:String(e)}function Vg(e){if(e==null)return null;if(!(typeof e=="number"&&(e===0||Number.isSafeInteger(e)&&e>0)))throw new Error(`invalid activity proplannerId ${String(e)}`);return e}function Yg(e,t){return typeof e.is_critical=="boolean"?e.is_critical:(t.error("[parseFromBackend] invalid activity is_critical \u2014 defaulting to false",new TypeError(`activity "${e.unique_id}" received ${typeof e.is_critical}`)),!1)}function Kg(e,t){return Array.isArray(e)?e.map(r=>An(r,t)).filter(r=>r!==null):[]}function Gg(e,t){let r=Bg(e.calendarId,t.knownCalendarIds,t.defaultCalendarId),n=e.calendarId==null||!t.knownCalendarIds.has(String(e.calendarId)),i=Number(e.progress),{constraintType:a,constraintDate:s}=Wg(e,t.reporter),o=e.type==="milestone",c=Nt(e.start_date),l=o?c:Nt(e.end_date),d=o?0:Number(e.duration),u=Yg(e,t.reporter);return{id:String(e.unique_id),proplannerId:Vg(e.id),parentId:Hg(e.parent_id),name:e.name,description:e.description??"",type:e.type,startDate:c,endDate:l,durationHours:te(d,t.hoursPerDay),constraintType:a,constraintDate:s,autoScheduling:Ng(i),calendarId:r,assignedDefaultCalendar:r!=null&&n,dateOrigin:e.date_origin==null?null:Nt(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:$g(e),subcontractId:e.subcontractId,isLookahead:e.isOnLookahead,hasLookaheadTasks:Array.isArray(e.tasks)&&e.tasks.length>0,newActivityIds:Ug(e.newActivitiesArray),hasNewActivities:e.hasNewActivities??!1,...e.isNewActivity===!0?{isNewActivity:!0}:{},pendingRequestIds:Ca(e.pendingRequests),responsableIds:Ca(e.responsables),tagIds:Ca(e.tags),baselinePoints:Kg(e.baseline_points,t.reporter),baselineSnapshot:null,recursiveDurationHours:te(Number(e.sumOfDurationRecursively??0),t.hoursPerDay),calendarDuration:bt({type:e.type,startDate:c,endDate:l}),isCritical:u,freeSlackHours:null,expectedProgress:null,expectedProgressBaseline:null,status:null,criticalPath:null}}function $g(e){return e.has_childs?null:e.custom_id}function zg(e){let t=e.find(r=>r.correlativeId===0&&r.type==="project");t&&(t.parentId=null)}function qg(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 Xd(e,t,r,n=null){let s=(e!==void 0&&e.length>0?e:t??[]).map(c=>Zg(c,n)),o=(r??[]).map(c=>Qg(c,n));return{calendars:s,baseCalendars:o,knownCalendarIds:new Set(s.map(c=>c.id)),defaultCalendarId:Xg(s)}}function Xg(e){let t=e.find(n=>n.is_default);if(t)return t.id;let r=e[0];return r?r.id:null}function Zd(e,t){let r=av(e.working_days),{days:n,hours:i}=iv(e,r),a=tv(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 Zg(e,t){let r=e.baseDefault,n=typeof r=="boolean"?r:void 0;return Zd(e,{idSuffix:"",isDefault:!!e.is_default,baseDefault:n,exceptionsSource:e.exceptiondays,exceptionRange:t})}function Qg(e,t){return Zd(e,{idSuffix:"-base",isDefault:!1,baseDefault:!!e.is_default,exceptionsSource:e.baseexceptiondays??e.exceptiondays,exceptionRange:t})}function tv(e,t){if(!Array.isArray(e)||e.length===0)return null;let r={};for(let n of e){if(!n)continue;let i=ev(n.from_date,n.to_date,t);if(i.length===0)continue;let a=rv(n);if(a!==void 0)for(let s of i)r[s]=a}return Object.keys(r).length>0?r:null}function ev(e,t,r){let n=zd(e),i=zd(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 zd(e){if(typeof e!="string")return null;let t=Vd.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 rv(e){if(e.workable===!1)return!1;let t=e.shifts;if(Array.isArray(t)&&t.length>0){let r=nv(t);if(r.length>0)return r}}var qd=/^\d{1,2}:\d{2}$/;function nv(e){let t=[];for(let r of e){let n=eu(r?.shift_string);if(!n)continue;if(!n.startsCsv.includes(",")&&!n.endsCsv.includes(",")){let o=n.startsCsv.trim(),c=n.endsCsv.trim();!wn(o)&&!wn(c)&&qd.test(o)&&qd.test(c)&&t.push(`${o}-${c}`);continue}let s=tu(n.startsCsv,n.endsCsv).find(o=>o!==null);s&&t.push(s)}return t.sort(Qd),t}function Jd(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 Qd(e,t){return Jd(e)-Jd(t)}function iv(e,t){let r=Array.from({length:7},()=>[]),n=(l,d)=>{let u=tu(l,d);for(let f=0;f<7;f+=1){let p=u[f],h=r[f];p&&h&&h.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=eu(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(Qd);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 tu(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];wn(c)||wn(l)||(s[o]=`${c}-${l}`)}return s}function eu(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 av(e){if(typeof e!="string")return[...Aa];let t=e.split(",").map(r=>r.trim());return t.length!==7?[...Aa]:t.map(r=>Yd.has(r))}var sv=new Set(["false","null"]);function wn(e){return!e||sv.has(e)}function ov(e){return e==="0"||e==="1"||e==="2"||e==="3"}function cv(e){if(typeof e!="string")return null;let t=oo(e);return t||(ov(e)?e:null)}function lv(e){if(e==null)return;if(!(typeof e=="number"&&(e===0||Number.isSafeInteger(e)&&e>0)))throw new Error(`invalid link proplannerId ${String(e)}`);return e}function nu(e,t){let r=[];for(let n of e)try{r.push(dv(n,t.knownActivityIds,t.hoursPerDay))}catch(i){t.reporter.warn("[parseFromBackend] dropping invalid link",i)}return uv(r)}function dv(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=cv(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=lv(e.id);return{id:n,source:i,target:a,type:s,lag:vt(Number(e.lag??0),r),freeSlackHours:null,isCritical:!1,...typeof o=="number"?{ganttId:o}:{},...typeof c=="number"?{sectorId:c}:{},...l===void 0?{}:{proplannerId:l}}}function uv(e){let t=new Map;for(let r of e){let n=`${r.source}-${r.target}-${r.type}`,i=t.get(n);(!i||ru(r)>ru(i))&&t.set(n,r)}return[...t.values()]}function ru(e){let t=Number(e.id);return Number.isFinite(t)?t:-1/0}function fv(e){if(typeof e!="string")return Ia;switch(e.toUpperCase()){case"DURATION":return"DURATION";case"COST":return"COST";case"HH":return"HH";default:return Ia}}function pv(e){let t=e.custom_id_prefix;return typeof t=="string"&&t.length>0?t:void 0}function hv(e){let t=e.custom_id_increment;return typeof t=="string"?t:typeof t=="number"&&Number.isFinite(t)?String(t):void 0}function iu(e){let t=pv(e),r=hv(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:fv(e.activity_creter),statusCriteria:$n,ganttId:null}}function On(e,t=Ae){let r=iu(e.sector),{calendars:n,baseCalendars:i,knownCalendarIds:a,defaultCalendarId:s}=Xd(e.calendars,e.sector.calendars,e.baseCalendars,yv(e.activities)),{activities:o,activityIds:c,hiddenIds:l}=$d(e.activities,{knownCalendarIds:a,defaultCalendarId:s,hoursPerDay:r.hoursPerDay,reporter:t}),d=nu(e.links,{knownActivityIds:c,hoursPerDay:r.hoursPerDay,reporter:t});return{sector:r,activities:o,links:d,calendars:n,baseCalendars:i,viewStateSeed:{hiddenIds:l}}}function yv(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 ka(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{fork(){return ka({seed:t})},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 Da(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{fork(){return Da({seed:t})},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 Ta(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{fork(){return Ta({seed:t})},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 au(e){return!!e&&typeof e=="string"&&e.trim().length>0}function xn(e){if(!e||typeof e!="string"||e.trim().length===0)return"";let t=e.match(/^(.*?)(\d+)$/);return t?t[1]??"":e}function Fn(e){if(!e||typeof e!="string"||e.trim().length===0)return"";let t=e.match(/(\d+)$/);return t?t[1]??"":""}function su(e){if(!e||typeof e!="object")return"";let t=e.customId;return typeof t=="string"?t:""}function ou(e,t){return!t&&au(e)}function cu(e,t){return t&&au(e)}function ur(e){return typeof e=="string"&&e.length>0&&/^\d+$/.test(e)}function dr(e){if(!ur(e))return 0n;try{return BigInt(e)}catch{return 0n}}function mv(e,t){if(typeof e!="bigint")return"";let r=e.toString();if(!ur(t))return r;let n=t.length;return r.padStart(n,"0")}function Ct(e,t){let r=dr(e),n=dr(t),i=r+n;return mv(i,e)}function Nn(e,t){let r=dr(e),n=dr(t);return r<n?-1:r>n?1:0}function Mn(e,t){return Nn(e,t)<=0?e:t}function Wn(e,t){return Nn(e,t)>=0?e:t}function lu(e){if(!e||e.length===0)throw new Error("minSuffixFromArray requires non-empty array");return e.reduce((t,r)=>Mn(t,r))}function du(e){if(!e||e.length===0)throw new Error("maxSuffixFromArray requires non-empty array");return e.reduce((t,r)=>Wn(t,r))}function uu(e){return{prefix:e,baseSuffix:null}}function fu(e,t){let r=Fn(e);return{prefix:xn(e),baseSuffix:Ct(r,t)}}function pu(e){return{prefix:e,baseSuffix:null}}function hu(e,t){return ou(e,t)?"parentConversion":cu(e,t)?"pasteReference":"noContext"}function yu(e){return{...e,usedSuffixes:new Set(e.usedSuffixes)}}var Bn=class e{prefixMap=new Map;processedIds=new Set;_journalPrefixBefore=null;_journalIds=null;beginCustomIdTransaction(){this._journalPrefixBefore=new Map,this._journalIds=[]}commitCustomIdTransaction(){this._journalPrefixBefore=null,this._journalIds=null}rollbackCustomIdTransaction(){let t=this._journalPrefixBefore,r=this._journalIds;if(!(t===null||r===null)){for(let[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?yu(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=lu(n),r.max=du(n),r.quantity=n.length,this._recalculateNext(t)}defaultPrefix;suffixIncrement;constructor(t={}){this.defaultPrefix=t.defaultPrefix??"A",this.suffixIncrement=t.suffixIncrement??"10"}fork(){let t=new e({defaultPrefix:this.defaultPrefix,suffixIncrement:this.suffixIncrement});for(let[r,n]of this.prefixMap)t.prefixMap.set(r,yu(n));for(let r of this.processedIds)t.processedIds.add(r);return t}extractPrefix(t){return xn(t)}extractSuffix(t){return Fn(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=Mn(r,n.min),n.max=Wn(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=Mn(n,i.min),i.max=Wn(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&&ur(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(;Nn(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||!ur(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=su(r),a=hu(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 uu(this.defaultPrefix);case"pasteReference":return fu(r,this.suffixIncrement);default:return pu(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 gv=1,vv=-1;function Av(e,t){return!e&&!t?null:e&&t?0:e?gv:vv}function mu(e){return e==null}function gu(e,t){let r=t.indexOf(String(e));return r===-1?t.length:r}function Iv(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 Cv(e,t){let r=Wt(e.field);return r===null?null:(n,i)=>{let a=r.extract(n,t),s=r.extract(i,t),o=Av(mu(a),mu(s));if(o!==null)return o;let c=r.valueKind==="enum"?gu(a,r.order)-gu(s,r.order):Iv(a,s,t.locale);return e.direction==="desc"?-c:c}}function vu(e,t){let r=e.rules.map(n=>Cv(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 Au(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,E.TYPE,ve),Sv(e,r)}function Sv(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,E.START_DATE,i),e.setActivityField(t,E.END_DATE,a)}function Iu(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?dt(a.workHours,a.progress):s.reduce((c,l)=>c+n(String(l)),0);return e.setActivityField(i,E.REAL_WORK_HOURS,o),r.push(i),o};for(let i of t)n(i);return r}async function Cu(e){let{state:t,sector:r,scheduler:n,skipAutoSchedule:i,now:a}=e;if(at(t),r.updateDurationForPrimaveraEndDate&&Dv(t),Tv(t),Iu(t),i){a&&(ne(t,a),Mt(t,r.statusCriteria));return}let s=await n.schedule({});Ge(t,s),_v(t),kv(t),await Se(t,void 0,!1),a&&(ne(t,a),Mt(t,r.statusCriteria))}function kv(e){e.forEachActivity(t=>{t.autoScheduling||!t.startDate||t.durationHours==null||e.getChildren(t.id).length>0||(t.endDate=e.calculateEndDate({startDate:t.startDate,durationHours:t.durationHours,task:t}),t.calendarDuration=bt(t))})}function Dv(e){e.forEachActivity(t=>{!t.startDate||!t.endDate||(t.durationHours=e.calculateDuration({startDate:t.startDate,endDate:t.endDate,task:t}))})}function Tv(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=xt(t.constraintDate,i,r))})}function _v(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=xt(t.constraintDate,n,r))})}var St={READY:"ready",DESTROYED:"destroyed",POISONED:"poisoned"};function Su(e){let t=e.clock??null,r=t?.()??null,n=r?Yr(r):null,i=e.reporter??Ae,a=On({sector:e.sector,activities:e.activities,links:e.links,calendars:e.calendars,baseCalendars:e.baseCalendars},i),s=a.sector;s.statusCriteria=Ir(e.statusCriteria),s.ganttId=e.ganttId??null;let o=a.calendars,c=a.baseCalendars??[],l=bn(a.activities,a.links,a.calendars,c),d=g=>vu(g,Zt(s.hoursPerDay)),u=new Ue(l,d);u.hydrateViewState({hiddenIds:a.viewStateSeed.hiddenIds});let f=new Ie(u,i);Au(u);let p=ka({knownIds:a.activities.map(g=>g.id)}),h=Da({seed:r?.getTime()??0,knownIds:a.links.map(g=>g.id)}),A=Ta({knownIds:a.activities.map(g=>g.uniqueCorrelativeId)}),I=new Bn({defaultPrefix:s.customIdPrefix,suffixIncrement:s.customIdIncrement});if(I.populateFromActivities(a.activities),e.baselinePoints&&e.baselinePoints.length>0){let g=c.find(k=>k.baseDefault)?.id??null;In(u,e.baselinePoints,n,i,g)}let T=Cu({state:u,sector:s,scheduler:f,skipAutoSchedule:e.skipInitialAutoSchedule===!0,now:n??void 0});return{sector:s,state:u,scheduler:f,activityIdGen:p,linkIdGen:h,uidGen:A,customIdTracker:I,calendars:o,baseCalendars:c,clock:t,reporter:i,initPromise:T}}function je(e){if(e===void 0)return["undefined"];if(e===null)return["null"];if(typeof e=="string")return["string",e];if(typeof e=="boolean")return["boolean",e];if(typeof e=="number")return["number",Object.is(e,-0)?"-0":String(e)];if(typeof e=="bigint")return["bigint",String(e)];if(e instanceof Date)return["date",String(e.getTime())];if(Array.isArray(e))return["array",e.map(je)];if(e instanceof Map)return["map",Array.from(e,([t,r])=>[je(t),je(r)]).sort((t,r)=>JSON.stringify(t).localeCompare(JSON.stringify(r)))];if(e instanceof Set)return["set",Array.from(e,je).sort((t,r)=>JSON.stringify(t).localeCompare(JSON.stringify(r)))];if(typeof e=="object")return["object",Object.entries(e).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>[t,je(r)])];throw new TypeError(`Unsupported canonical value: ${typeof e}`)}function de(e){return JSON.stringify(je(e))}function _a(e,t){let r=new Map(e.map(s=>[String(s.id),s])),n=new Map(t.map(s=>[String(s.id),s])),i=[...new Set([...r.keys(),...n.keys()])].sort(),a=[];for(let s of i){let o=n.get(s),c=r.get(s);if(c===void 0){a.push({id:s,kind:"deleted",after:null});continue}if(o===void 0){a.push({id:s,kind:"created",after:b(c)});continue}let l=Pv(o,c);Object.keys(l).length>0&&a.push({id:s,kind:"updated",fields:l,after:b(c)})}return a}function Pv(e,t){let r={},n=[...new Set([...Object.keys(e),...Object.keys(t)])].sort();for(let i of n)de(e[i])!==de(t[i])&&(r[i]={before:b(e[i]),after:b(t[i])});return r}function Rv(e,t){let r=new Set(t.selectedIds.map(String)),n=new Set(e.selectedIds.map(String)),i=new Set(t.hiddenIds.map(String)),a=new Set(e.hiddenIds.map(String)),s=e.activities.map(({id:c})=>String(c)).sort(),o=[];for(let c of s){let l=r.has(c),d=n.has(c),u=!i.has(c),f=!a.has(c);l===d&&u===f||o.push({activityId:c,...l===d?{}:{checked:{before:l,after:d}},...u===f?{}:{visible:{before:u,after:f}}})}return o}function ku(e,t){let r=de(e.order)!==de(t.order);return{source:{kind:"init"},activities:_a(e.activities,t.activities),links:_a(e.links,t.links),calendars:_a(e.calendars,t.calendars),trackingEvents:[],effects:[],viewState:Rv(e,t),...r?{order:b(e.order)}:{}}}var bv=()=>({constantStart:null,variableStartOffset:null,constantEnd:null,variableEndOffset:null}),Pa=(e,t)=>e===null?t:Math.min(e,t),Ra=(e,t)=>e===null?t:Math.max(e,t);function Tu(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=Ev(e,t,n);return Lv(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=Ov(o,s),l=xv(o,s);if(c===null||l===null)throw new Error(`[ScheduleCore] incomplete date gesture bounds for ${String(a)}`);return{startTimeMs:c,endTimeMs:l}}}}function Ev(e,t,r){let n=new Map,i=t.kind==="move"?String(t.anchorActivityId):null,a=i===null?null:Du(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=Du(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 Lv(e,t,r){let n=Xe(e,new Set(t));for(let i of n){let a=bv();for(let s of e.getChildren(i)){let o=r.get(s);if(o){wv(a,o);continue}let c=e.getActivity(s);if(!c)throw new Error(`[ScheduleCore] missing child ${s} while previewing parent ${i}`);a.constantStart=Pa(a.constantStart,c.startDate.getTime()),a.constantEnd=Ra(a.constantEnd,c.endDate.getTime())}r.set(i,a)}}function Du(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 wv(e,t){t.constantStart!==null&&(e.constantStart=Pa(e.constantStart,t.constantStart)),t.variableStartOffset!==null&&(e.variableStartOffset=Pa(e.variableStartOffset,t.variableStartOffset)),t.constantEnd!==null&&(e.constantEnd=Ra(e.constantEnd,t.constantEnd)),t.variableEndOffset!==null&&(e.variableEndOffset=Ra(e.variableEndOffset,t.variableEndOffset))}function Ov(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 xv(e,t){if(e.variableEndOffset===null)return e.constantEnd;let r=t+e.variableEndOffset;return e.constantEnd===null?r:Math.max(e.constantEnd,r)}var ba=Symbol("ScheduleCore.fork.source");function Fv(e){return e.kind==="persistence-acknowledge"||e.kind==="activity-lookahead-sync"&&e.acknowledgePersistedLookahead===!0}function Nv(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 Mv(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 Wv(e,t,r,n){if(n.size===0)return!1;if(e.activities.some(a=>a.kind==="created"&&n.has(String(a.id))))return!0;let i=new Set([...n.values()].map(({referenceId:a})=>String(a)));for(let a of t){let s=String(a.id);for(;s!==null;){if(i.has(s))return!0;s=r.getParentId(s)}}return!1}function Bv(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}function Uv(e,t){if(e.size!==t.size)return!1;for(let[r,n]of e){let i=t.get(r);if(i===void 0||i.referenceId!==n.referenceId||i.branchParentId!==n.branchParentId||i.side!==n.side)return!1}return!0}var Un=class e{_activityClipboard={value:null};_status=St.READY;coreRuntime;_isFork;_undo=new Rn;_opQueue=Promise.resolve();_scheduleRevision=0;_pendingScheduleRevision=0;_criticalPathRevision=-1;_activeCriticalPath=null;constructor(t){if(ba in t){this._isFork=!0;let i=t[ba],a=i.coreRuntime.state.fork();this.coreRuntime={state:a,scheduler:new Ie(a,i.coreRuntime.reporter),sector:b(i.coreRuntime.sector),activityIdGenerator:i.coreRuntime.activityIdGenerator.fork(),linkIdGenerator:i.coreRuntime.linkIdGenerator.fork(),uniqueCorrelativeIdGenerator:i.coreRuntime.uniqueCorrelativeIdGenerator.fork(),customIdTracker:i.coreRuntime.customIdTracker.fork(),calendars:new Map(Array.from(i.coreRuntime.calendars,([s,o])=>[s,b(o)])),baseCalendars:b(i.coreRuntime.baseCalendars),clock:i.coreRuntime.clock,reporter:i.coreRuntime.reporter},this._activityClipboard.value=b(i._activityClipboard.value),this._undo=i._undo.fork(),this._saveTracker=i._saveTracker.fork(),this._scheduleRevision=i._scheduleRevision,this._pendingScheduleRevision=i._scheduleRevision,this._criticalPathRevision=i._criticalPathRevision,this._initPromise=Promise.resolve(),this._criticalPathReady=Promise.resolve(null),this._ready=this._initPromise;return}this._isFork=!1;let r=Su(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!==St.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}fork(){return this._enqueue(async()=>(await this._ready,this.assertReady(),new e({[ba]:this})))}get criticalPathReady(){return this._criticalPathReady}get status(){return this._status}getSector(){return b(this.coreRuntime.sector)}getActivityView(t){return this.assertReady(),ld(this.coreRuntime.state,t)}createDateGesturePreview(t){this.assertReady();let r=this._scheduleRevision;return Tu(this.coreRuntime.state,t,()=>{if(this.assertReady(),this._scheduleRevision!==r)throw new Error("[ScheduleCore] date gesture preview is stale")})}getAllActivitiesView(){return this.assertReady(),dd(this.coreRuntime.state)}getIndentTargetParentIds(t){this.assertReady();let r=vn(t.map(n=>String(n)),this.coreRuntime.state);return[...new Set(r.allowedMoves.map(n=>String(n.newParentId)))]}getChildrenView(t){return this.assertReady(),pd(this.coreRuntime.state,t)}getLinkView(t){return this.assertReady(),ha(this.coreRuntime.state,t)}getLinksForActivityView(t){this.assertReady();let r=this.coreRuntime.state,n=[],i=new Set,a=s=>{if(i.has(s))return;i.add(s);let o=ha(r,s);o&&n.push(o)};for(let s of r.getOutgoingLinkIds(t))a(s);for(let s of r.getIncomingLinkIds(t))a(s);return n}getAllLinksView(){return this.assertReady(),md(this.coreRuntime.state)}auditEffectiveGraph(){this.assertReady();let t=this.coreRuntime.state,r=t.getAllLinks(),n=ze(t,r),i=wr(n),a=0;for(let s of i)s.length>a&&(a=s.length);return{activityCount:t.getAllIds().length,logicalLinkCount:r.length,effectiveEdgeCount:n.length,circularComponents:i,largestComponentSize:a}}getProperty(t,r){this.assertReady();let n=this.coreRuntime.state.getActivity(t);return n?b(n[r]):null}getAllIds(){return this.assertReady(),ud(this.coreRuntime.state)}forEachActivityId(t){this.assertReady(),fd(this.coreRuntime.state,t)}getChildrenIds(t){return this.assertReady(),pa(this.coreRuntime.state,t)}getSelectedActivityIds(){return this.assertReady(),hd(this.coreRuntime.state)}getHiddenActivityIds(){return this.assertReady(),this.coreRuntime.state.hiddenIds().map(String)}getActiveFilter(){return this.assertReady(),b(this.coreRuntime.state.getActiveFilter())}getActiveOrder(){return this.assertReady(),b(this.coreRuntime.state.getActiveOrder())}getVisualOrderIds(){return this.assertReady(),[...this.coreRuntime.state.getVisualOrderIds()]}hasChild(t){return this.assertReady(),yd(this.coreRuntime.state,t)}getCalendar(t){this.assertReady();let r=this.coreRuntime.calendars.get(t);return r?b(r):null}getAllCalendars(){return this.assertReady(),Array.from(this.coreRuntime.calendars.values(),t=>b(t))}getBaseCalendars(){return this.assertReady(),this.coreRuntime.baseCalendars.map(t=>b(t))}isCustomIdInUse(t,r=null){return this.assertReady(),this.coreRuntime.customIdTracker.isCustomIdInUse(t,r)}getProjectWorkHours(){return this.assertReady(),gd(this.coreRuntime.calendars.values())}getModifiedLinks(){return this.assertReady(),this._saveTracker.modifiedLinks(t=>this.coreRuntime.state.getLink(t)).map(b)}getNewLinks(){return this.assertReady(),this._saveTracker.newLinks(t=>this.coreRuntime.state.getLink(t)).map(b)}getModifiedActivities(){return this.assertReady(),this._saveTracker.modifiedActivities(t=>this.coreRuntime.state.getActivity(t)).map(b)}getNewActivities(){return this.assertReady(),this._saveTracker.newActivities(t=>this.coreRuntime.state.getActivity(t)).map(b)}hasUnsavedChanges(){return this.assertReady(),this._saveTracker.hasUnsavedChanges()}getScheduleRevision(){return this._scheduleRevision}getCanonicalDigest(){this.assertReady();let t=(r,n)=>String(r.id).localeCompare(String(n.id));return de({sector:this.getSector(),activities:[...this.getAllActivitiesView()].sort(t),links:[...this.getAllLinksView()].sort(t),calendars:[...this.getAllCalendars()].sort(t),baseCalendars:[...this.getBaseCalendars()].sort(t)})}createProjectionChangeSetFrom(t){this.assertReady(),t.assertReady();let r=n=>({activities:n.getAllActivitiesView(),links:n.getAllLinksView(),calendars:n.getAllCalendars(),selectedIds:n.getSelectedActivityIds(),hiddenIds:n.getHiddenActivityIds(),order:me(n.coreRuntime.state)});return ku(r(this),r(t))}getDeletedActivitiesSinceLastSave(){return this.assertReady(),this._saveTracker.deletedActivities(t=>this.coreRuntime.state.getActivity(t)).map(b)}getDeletedLinksSinceLastSave(){return this.assertReady(),this._saveTracker.deletedLinks(t=>this.coreRuntime.state.getLink(t)).map(b)}_enqueue(t){let r=this._opQueue.then(t,t);return this._opQueue=r.then(()=>{},()=>{}),r}_beginScheduleMutation(t){return Wi(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){if(this.assertReady(),this._isFork&&Fv(t))return{result:{ok:!1,reason:S.SANDBOX_PERSISTENCE_FORBIDDEN},changedState:!1};let n=vd(this.coreRuntime.state,{hoursPerDay:this.coreRuntime.sector.hoursPerDay,dateFormat:this.coreRuntime.sector.dateFormat}),i=Rd(t),a=t.kind==="activity-create"||t.kind==="activity-delete"||t.kind==="activity-batch"&&t.mode==="replace",s=a?new Map(this.coreRuntime.state.getRelativePlacementPins()):void 0,o=[this.coreRuntime.activityIdGenerator.snapshot(),this.coreRuntime.linkIdGenerator.snapshot(),this.coreRuntime.uniqueCorrelativeIdGenerator.snapshot()];this.coreRuntime.state.beginWriteCapture(),this.coreRuntime.customIdTracker.beginCustomIdTransaction();let c;try{c=await Ml(t,r,{adapter:this.coreRuntime.state,ctx:n,scheduler:this.coreRuntime.scheduler,sector:this.coreRuntime.sector,calendars:this.coreRuntime.calendars,activityIdGen:this.coreRuntime.activityIdGenerator,linkIdGen:this.coreRuntime.linkIdGenerator,isActivityIdReserved:l=>this._saveTracker.hasCheckpointActivityId(l),isLinkIdReserved:l=>this._saveTracker.hasCheckpointLinkId(l),uidGen:this.coreRuntime.uniqueCorrelativeIdGenerator,customIdTracker:this.coreRuntime.customIdTracker,reporter:this.coreRuntime.reporter,activityClipboard:this._activityClipboard,defaultBaseCalendarId:this.coreRuntime.baseCalendars.find(l=>l.baseDefault)?.id??null,now:this.coreRuntime.clock?Yr(this.coreRuntime.clock()):null}),c.ok||this._rollback(o)}catch(l){throw this._rollback(o),l}finally{this.coreRuntime.state.endWriteCapture(),this.coreRuntime.customIdTracker.commitCustomIdTransaction()}if(c.ok&&this._recordRelativePlacementPin(t,c.changes),c.ok&&i==="record"&&va(c.changes)){let l=Dd(this.coreRuntime.state,c.changes),d=a?new Map(this.coreRuntime.state.getRelativePlacementPins()):void 0,u=s!==void 0&&d!==void 0&&!Uv(s,d);this._undo.record(ya(kd(c.changes),c.__beforeSnap,c.__beforeLinks,l.afterSnap,l.afterLinks,u?s:void 0,u?d:void 0),Td(t),Date.now())}return c.ok&&(i==="clear-on-success"?(this._saveTracker.acknowledge(this.coreRuntime.state.getAllActivities(),this.coreRuntime.state.getAllLinks()),this._undo.clear()):t.kind==="activity-lookahead-sync"&&t.acknowledgePersistedLookahead===!0?(this._saveTracker.acknowledgePersistedLookahead(c.changes.activities,l=>this.coreRuntime.state.getActivity(l)),t.persistedProgress!==void 0&&this._undo.clear()):this._saveTracker.recordChanges(c.changes.activities,c.changes.links,l=>this.coreRuntime.state.getActivity(l),l=>this.coreRuntime.state.getLink(l))),c=this._withReappliedViewState(t,c),c.ok?Wi(t)&&va(c.changes)?(this._recordScheduleMutation(r.skipAutoSchedule!==!0&&r.skipCriticalPath!==!0&&se(t)),{result:_u(c),changedState:!0}):{result:_u(c),changedState:!1}:{result:c,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),!Rc(t)))return r;let n=this._reapplyViewState(r.changes);return n===null?r:{...r,changes:n}}_recordRelativePlacementPin(t,r){let n=this.coreRuntime.state;if(t.kind!=="activity-create")return;let i=t.afterSiblingId??t.beforeSiblingId??(t.eventSource==="Creation button (+)"&&t.parentId!=="0"?t.parentId:void 0);if(i===void 0)return;let a=r.activities.find(({kind:s})=>s==="created");a!==void 0&&n.setRelativePlacementPin(a.id,{referenceId:i,branchParentId:t.parentId,side:t.beforeSiblingId===void 0?"after":"before"})}_reapplyViewState(t){let r=this._reapplyActiveFilter(t),n=this._emitTouchedBranchOrder(r??t);return this._reapplyActiveOrder(n.changes??r??t,n.touchedParents)??n.changes??r}_emitTouchedBranchOrder(t){let r=this.coreRuntime.state,n=Od(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=Gn(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:me(n)};let a=new Set(r);for(let o of t.activities){if(o.kind==="deleted")return{...t,order:me(n)};let c=n.getParentId(o.id);a.add(c===null?"0":String(c))}let s=Gn(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=Bv(a,n,i),o=Nv(t)?null:Mv(t,r),c=r.getRelativePlacementPins(),l,d;if(o===null||!s||Wv(t,o,r,c)){let p=gr({activities:r.getAllActivities(),parentOf:h=>r.getParentId(h),filter:n,context:i,relativePlacementPins:c});r.setFilterProjection(p),d=p.visibleIds,l=r.getAllIds()}else l=Ba(a,o,p=>r.getParentId(p)),d=a.visibleIds;let f=ye(r,d,l);return f.length===0?null:{...t,viewState:[...t.viewState??[],...f]}}_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===St.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 Ue(bn(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!==St.DESTROYED&&this._scheduleRevision===t&&this._pendingScheduleRevision===this._scheduleRevision,a=(async()=>{let o=await Ni(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.activities)xi(this.coreRuntime.state,l,d);for(let[l,d]of o.links)Fi(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===St.DESTROYED)return{changes:{source:{kind:"init"},activities:[],links:[],calendars:[],trackingEvents:[]}};this.coreRuntime.state.beginWriteCapture(),this.coreRuntime.customIdTracker.beginCustomIdTransaction();let t;try{await nn(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;bd(this.coreRuntime.state,n),this._recordScheduleMutation(!1),r(!0),ma(n)&&this._resyncCustomIdTrackerFromModel(),this._undo.pushRedo(n),this._undo.resetCoalesce();let i=ga(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;Ed(this.coreRuntime.state,r),this._recordScheduleMutation(!1),t(!0),ma(r)&&this._resyncCustomIdTrackerFromModel(),this._undo.pushUndo(r),this._undo.resetCoalesce();let n=ga(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=St.DESTROYED}_initPromise;_criticalPathReady;_ready;_saveTracker=new Ln;assertReady(){if(this._status===St.DESTROYED)throw new Error("[ScheduleCore] instance is destroyed");if(this._status===St.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=St.POISONED,this.coreRuntime.reporter.error("[ScheduleCore] rollback failed \u2014 core poisoned",r),r}}};function _u(e){let{__beforeSnap:t,__beforeLinks:r,...n}=e;return n}var Pu=(e=[])=>(e??[]).filter(t=>!t.proplannerId);var Ru={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 bu=8;var G={ACTIVITY_CLIPBOARD_CLEAR:"activity-clipboard-clear",ACTIVITY_COPY:"activity-copy",ACTIVITY_PASTE_COPIED:"activity-paste-copied",PERSISTENCE_ACKNOWLEDGE:"persistence-acknowledge",BASELINE_APPLY:"baseline-apply",PONDERATOR_CRITERION_SET:"ponderator-criterion-set",STATUS_CRITERIA_SET:"status-criteria-set",INLINE_EDIT:"inline-edit",DATES_BATCH:"dates-batch",BULK_EDIT:"bulk-edit",LINK_CREATE:"link-create",LINK_UPDATE:"link-update",LINK_DELETE:"link-delete",LINKS_BATCH:"links-batch",ACTIVITY_CREATE:"activity-create",ACTIVITY_DELETE:"activity-delete",ACTIVITY_MOVE:"activity-move",ACTIVITY_INDENT:"activity-indent",ACTIVITY_OUTDENT:"activity-outdent",ACTIVITY_SET_PROGRESS:"activity-set-progress",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"},jv={[G.ACTIVITY_CLIPBOARD_CLEAR]:!0,[G.ACTIVITY_COPY]:!0,[G.ACTIVITY_PASTE_COPIED]:!0,[G.PERSISTENCE_ACKNOWLEDGE]:!0,[G.BASELINE_APPLY]:!0,[G.PONDERATOR_CRITERION_SET]:!0,[G.STATUS_CRITERIA_SET]:!0,[G.INLINE_EDIT]:!0,[G.DATES_BATCH]:!0,[G.BULK_EDIT]:!0,[G.LINK_CREATE]:!0,[G.LINK_UPDATE]:!0,[G.LINK_DELETE]:!0,[G.LINKS_BATCH]:!0,[G.ACTIVITY_CREATE]:!0,[G.ACTIVITY_DELETE]:!0,[G.ACTIVITY_MOVE]:!0,[G.ACTIVITY_INDENT]:!0,[G.ACTIVITY_OUTDENT]:!0,[G.ACTIVITY_SET_PROGRESS]:!0,[G.SELECTION_TOGGLE]:!0,[G.SELECTION_REPLACE]:!0,[G.VISIBILITY_SET]:!0,[G.FILTER_SET]:!0,[G.SORT_SET]:!0,[G.SIR_SYNC]:!0,[G.ACTIVITY_LOOKAHEAD_SYNC]:!0},Eu=Object.keys(jv);var Lu={CHILD:"child",CHILD_CONFIRMED:"child-confirmed",LINE:"line",ROOT:"root"};return Wu(Hv);})();
2
2
  //# sourceMappingURL=schedule-core.global.js.map