@outbuild-company/schedule-core 1.7.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.
- package/dist/cdn/schedule-core.global.js +1 -1
- package/dist/cdn/schedule-core.global.js.map +1 -1
- package/dist/index.cjs +2131 -1182
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +21 -57
- package/dist/index.d.ts +21 -57
- package/dist/index.js +2131 -1182
- package/dist/index.js.map +1 -1
- package/package.json +6 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var ScheduleCore=(()=>{var Fn=Object.defineProperty;var fu=Object.getOwnPropertyDescriptor;var pu=Object.getOwnPropertyNames;var hu=Object.prototype.hasOwnProperty;var yu=(e,t)=>{for(var r in t)Fn(e,r,{get:t[r],enumerable:!0})},mu=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of pu(t))!hu.call(e,i)&&i!==r&&Fn(e,i,{get:()=>t[i],enumerable:!(n=fu(t,i))||n.enumerable});return e};var gu=e=>mu(Fn({},"__esModule",{value:!0}),e);var $g={};yu($g,{ACTIVITY_TYPE:()=>pr,CALENDAR_UNIT:()=>ot,COLUMN:()=>_,CONSTRAINT_TYPE:()=>K,CONSTRAINT_TYPE_TO_LABEL:()=>ou,CREATION_KIND:()=>du,DEFAULT_HOURS_PER_DAY:()=>cu,DISPATCH_ACTION_KIND:()=>Y,DISPATCH_ACTION_KINDS:()=>lu,DISPATCH_TRACK_EVENT:()=>It,LINK_CODE_TO_TYPE:()=>Zt,LINK_TYPE:()=>M,LINK_TYPE_CODE:()=>qs,NEW_ACTIVITY_DEFAULTS:()=>rn,REJECTION_REASON:()=>S,ROOT_PARENT_ID:()=>N,SCHEDULE_CORE_STATUS:()=>kt,STATUS:()=>Pt,ScheduleCore:()=>Nn,WORK_TIME_DIRECTION:()=>X,checkNoUpdatedLinks:()=>Id,computeExpectedProgress:()=>di,expectedProgressFromBaseline:()=>Te,getActiveBaseline:()=>dt,getUnsavedActivities:()=>su,isRootParent:()=>b,normalizeParentKey:()=>Mt,parseFromBackend:()=>Rn,willRunCriticalPath:()=>id,yieldToBrowser:()=>Q});var pt=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 sr=e=>String(e);function Ia(e){let{clickedId:t,isChecked:r,currentSelection:n,hierarchy:i,isFrozen:a,exists:s,autoCheckParents:o}=e,c=sr(t),l=new Set([...n].map(String)),d=new Set(l),u=vu(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||Au({id:c,isChecked:r,autoCheckParents:o,hierarchy:i,isFrozen:a,exists:s,next:d}),{nextSelection:d,changed:Cu(l,d),parentBlocked:p}}function vu(e,t){let r=[],n=new pt;n.enqueue(e);let i=new Set([e]);for(;!n.isEmpty();){let a=n.dequeue();for(let s of t.getChildrenIds(a)){let o=sr(s);i.has(o)||(i.add(o),r.push(o),n.enqueue(o))}}return r}function Au(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=sr(c);if(a(l))return;let d=i.getChildrenIds(l).map(sr).filter(s),u=d.some(a),f=d.filter(v=>!a(v)),h=f.length>0&&f.every(v=>o.has(v))&&!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 Cu(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 ue(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",SIR_REQUEST_NOT_PENDING:"sir_request_not_pending",PREVIEW_UNSUPPORTED_ACTION:"preview_unsupported_action",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",INVALID_PROGRESS_VALUE:"invalid_progress_value_must_be_0_or_100"};var Sa=(e,t)=>{let r=e.getActivity(t);return r!=null&&ue(r)},ka=(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 Da(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=>Sa(r,o),s=Ia({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:ka(e,r,s.changed)}}function or(e,t){let{adapter:r}=t,n=new Set(e.activityIds.map(String).filter(s=>r.activityExists(s)).filter(s=>!Sa(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:ka(e,r,a)}}function Jt(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 Ta(e,t){let{adapter:r}=t,n=new Set(e.visibleIds.map(String)),i=Jt(r,n);return{ok:!0,changes:{source:e,activities:[],links:[],calendars:[],trackingEvents:[],viewState:i}}}var Iu=["Waiting","Done","Doing","Overdue","Advancement"],Su=["mfo","mso","snlt","snet","alap","asap","fnet","fnlt"];function Mn(e,t){return e===null||t<=0?null:e/t}function ku(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 Du={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)=>Mn(e.durationHours,t.hoursPerDay)},calendarDuration:{valueKind:"number",extract:e=>e.type==="milestone"?0:ku(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)=>Mn(e.freeSlackHours,t.hoursPerDay)},totalSlackDays:{valueKind:"number",extract:(e,t)=>Mn(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:Iu,extract:e=>e.status},constraintType:{valueKind:"enum",order:Su,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 Ft(e){return Du[e]??null}function Tu(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 Pu(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 Ru(e,t,r){return e instanceof Date?r==="after"?e.getTime()>t.getTime():r==="before"?e.getTime()<t.getTime():!1:!1}function Eu(e,t,r){let i=(Array.isArray(e)?e:[]).some(a=>t.has(String(a)));return r==="someOf"?i:r==="notSomeOf"?!i:!1}function bu(e,t,r){let n=e!==null&&t.has(String(e));return r==="someOf"?n:r==="notSomeOf"?!n:!1}function _a(e){let t=Array.isArray(e)?e:[e];return new Set(t.map(r=>String(r)))}function Pa(e,t,r){let n=Ft(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"?Pu(i,Number(t.value),a):n.valueKind==="date"?Ru(i,Tu(t.value),a):n.valueKind==="id-array"?Eu(i,_a(t.value),a):bu(i,_a(t.value),a)}function Lu(e,t,r){return t.criteria.length===0?!0:t.logic==="or"?t.criteria.some(n=>Pa(e,n,r)):t.criteria.every(n=>Pa(e,n,r))}function wu(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 Wn(e,t,r){let n=Lu(e,t,r),i=t.dateRange,a=i===void 0||wu(e,i);return n&&a}function Ou(e,t,r){let n=t(e);for(;n!==null&&!r.has(String(n));)r.add(String(n)),n=t(n)}function Ra(e){let{activities:t,parentOf:r,filter:n,context:i}=e,a=new Set,s=[];for(let o of t)Wn(o,n,i)&&(a.add(String(o.id)),s.push(o.id));for(let o of s)Ou(o,r,a);return a}function xu(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=Wn(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 Nu(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 Fu(e){let t=new Set;for(let[r,n]of e)n>0&&t.add(r);return t}function cr(e){let t=xu(e);Nu(t);let r=Fu(t.visibleReferenceCounts);return{filter:e.filter,context:e.context,matchedIds:t.matchedIds,pinnedVisibleIds:t.pinnedVisibleIds,visibleIds:r,visibleReferenceCounts:t.visibleReferenceCounts}}function Ea(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=Wn(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 Xt(e){return{hoursPerDay:e,locale:"en"}}var Mu={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 ba(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 La(e){let t=Ft(e.field);if(t===null)return{ok:!1,reason:"unknown_field"};if(!Mu[t.valueKind].has(e.operator))return{ok:!1,reason:"unknown_operator"};if(t.valueKind==="number"){let n=Uu(e.value);return n===null?{ok:!1,reason:"invalid_value"}:{ok:!0,criterion:{...e,value:n}}}if(t.valueKind==="date"){let n=Bu(e.value);return n===null?{ok:!1,reason:"invalid_value"}:{ok:!0,criterion:{...e,value:n}}}let r=Wu(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 Wu(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 Uu(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 Bu(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 wa(e){return e.criteria.length===0&&e.dateRange===void 0}function ju(e,t,r){let n=e.getAllActivities();if(wa(t))return{visibleIds:Ra({activities:n,parentOf:a=>e.getParentId(a),filter:t,context:Xt(r)}),projection:null};let i=cr({activities:n,parentOf:a=>e.getParentId(a),filter:t,context:Xt(r)});return{visibleIds:i.visibleIds,projection:i}}function Oa(e,t){let{adapter:r,hoursPerDay:n}=t,i=[];for(let u of e.criteria){let f=La(u);if(!f.ok)return{ok:!1,reason:f.reason};i.push(f.criterion)}let a=ba(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(wa(s)?null:s);let{visibleIds:o,projection:c}=ju(r,s,n);r.setFilterProjection(c);let l=Jt(r,o);return{ok:!0,changes:{source:e,activities:[],links:[],calendars:[],trackingEvents:[],viewState:l}}}var N="0";function b(e){return e==null||e===0||e==="0"}function Mt(e){return b(e)?"0":String(e)}var Un=Number.MAX_SAFE_INTEGER;function vt(e,t){let r=Ne(e,t),n=t.getOrderComparator?.()??null;return r.sort(n===null?lr:(i,a)=>n(i,a)||lr(i,a)),r.map(i=>String(i.id))}function Na(e){let t=[],r=i=>{t.push(i);let a=vt(String(i.id),e);for(let s of a){let o=e.getActivity(s);o&&r(o)}},n=vt("0",e);for(let i of n){let a=e.getActivity(i);a&&r(a)}return t}function Fa(e,t,r){let n=r.getActivity(e);if(!n)return null;let i=Ma(n),a=vt(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&&!Hu(t,c))return c}return null}function Bn(e,t){let r=t.getActivity(e);if(!r)return-1;let n=Ma(r);return vt(n,t).findIndex(a=>String(a)===String(e))}function Ne(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 lr(e,t){let r=xa(e),n=xa(t);return r!==n?r-n:String(e.id).localeCompare(String(t.id))}function xa(e){let t=e.correlativeId,r=typeof t=="number"?t:Number(t);return Number.isFinite(r)?r:Un}function Ma(e){let t=e.parentId;return t===null?"0":t}function Hu(e,t){return e.has(t)?!0:e.has(String(t))}function Fe(e){let t=[],r=n=>{let i=vt(n,e);i.length>1&&t.push({parentId:n,childIds:i});for(let a of i)r(a)};return r("0"),t}function jn(e,t){let r=[];for(let n of t){let i=vt(n,e);i.length>1&&r.push({parentId:n,childIds:i})}return r}function Vu(e){return Ft(e.field)===null?"unknown_field":e.direction!=="asc"&&e.direction!=="desc"?"unknown_operator":null}function Wa(e,t){let{adapter:r}=t;for(let a of e.rules){let s=Vu(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:Fe(r)}}}var Ua="text";var Ba="description";var ja="duration";var Ha="progress";var Va="cost";var Ya="used_cost";var Ka="hhWorkTime";var Ga="start_date";var $a="end_date";var za="constraint_type";var qa="constraint_date";var Ja="calendar_id";var Xa="custom_id";var Za="subcontractId";var Qa="responsables";var ts="tags";var es="custom_predecessors";var rs="custom_sucessors";var ns="real_work";var is="real_cost";var as="expected_progress";var ss="expected_progress_base";var os="start_base";var cs="end_base";var ls="duration_base";var ds="cost_base";var us="work_base";var fs="calendarDuration";var ps="is_critical",hs="earlyStart",ys="earlyFinish",ms="lateStart",gs="lateFinish",vs="freeSlack",As="totalSlack";var Cs="correlative_id";var Is="unique_correlative_id";var Ss="ponderator";var X={FUTURE:"future",PAST:"past"},ot={HOUR:"hour",DAY:"day"},Pt={DONE:"Done",OVERDUE:"Overdue",ADVANCEMENT:"Advancement",WAITING:"Waiting",DOING:"Doing"};var dr="status";var Hn="Baseline";function ur(e){return e==="Actual"?"Actual":Hn}var Yu={TEXT:Ua,DESCRIPTION:Ba,DURATION:ja,PROGRESS:Ha,COST:Va,USED_COST:Ya,HH_WORK_TIME:Ka,START_DATE:Ga,END_DATE:$a,CONSTRAINT_TYPE:za,CONSTRAINT_DATE:qa,CALENDAR_ID:Ja,CUSTOM_ID:Xa,SUBCONTRACT_ID:Za,RESPONSABLES:Qa,TAGS:ts,CUSTOM_PREDECESSORS:es,CUSTOM_SUCESSORS:rs},Ku={REAL_WORK:ns,REAL_COST:is,EXPECTED_PROGRESS:as,EXPECTED_PROGRESS_BASE:ss,START_BASE:os,END_BASE:cs,DURATION_BASE:ls,COST_BASE:ds,WORK_BASE:us,CALENDAR_DURATION:fs,IS_CRITICAL:ps,EARLY_START:hs,EARLY_FINISH:ys,LATE_START:ms,LATE_FINISH:gs,FREE_SLACK:vs,TOTAL_SLACK:As,CORRELATIVE_ID:Cs,UNIQUE_CORRELATIVE_ID:Is,PONDERATOR:Ss,STATUS:dr},_={...Yu,...Ku};function ks(e,t){throw new Error(t)}function Ds(e,t){return()=>t()===e}var K={ASAP:"asap",ALAP:"alap",SNET:"snet",SNLT:"snlt",FNET:"fnet",FNLT:"fnlt",MSO:"mso",MFO:"mfo"},Gu={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 _s(e,t,r){if(!t)return{violated:!1};let n=Gu[e];return n?n(t,r)?{violated:!0,constraintType:e,constraintDate:t}:{violated:!1}:{violated:!1}}var $u=new Set(["mso","snet","snlt"]);function Me(e,t,r){return $u.has(e)?t:r}function Ps(e,t,r){return{type:"constraint",messageKey:"constraint_violation",data:{constraintType:e,constraintDate:t,...r?{projectedDate:r}:{}}}}var zu={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}},fr=e=>new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate())),Ts=(e,t)=>new Date(e.getTime()+t*864e5),qu=(e,t)=>e.getUTCFullYear()===t.getUTCFullYear()&&e.getUTCMonth()===t.getUTCMonth()&&e.getUTCDate()===t.getUTCDate();function Vn(e,t){if(!e.constraintDate||!e.constraintType)return null;let r=zu[e.constraintType];if(!r)return e.constraintDate;let n=e.constraintDate,i=t.getClosestWorkTime({date:fr(n),dir:X.FUTURE,task:e});if(qu(i,n))return n.getTime()!==fr(n).getTime()?n:r.startOfDay?i:t.getClosestWorkTime({date:Ts(fr(n),1),dir:X.PAST,task:e});let a=fr(t.getClosestWorkTime({date:n,dir:r.direction,task:e}));return r.startOfDay?t.getClosestWorkTime({date:a,dir:X.FUTURE,task:e}):t.getClosestWorkTime({date:Ts(a,1),dir:X.PAST,task:e})}function Rs(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=Vn(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 Es(e,t){return!(t.earliestStart&&e<t.earliestStart||t.latestStart&&e>t.latestStart)}function Yn(e,t){return t.latestStart&&e>t.latestStart?t.latestStart:t.earliestStart&&e<t.earliestStart?t.earliestStart:e}var M={FINISH_TO_START:"0",START_TO_START:"1",FINISH_TO_FINISH:"2",START_TO_FINISH:"3"};var pr={TASK:"task",PROJECT:"project",MILESTONE:"milestone"},bs={ALAP_DEBOUNCE_MS:1e3,CRITICAL_PATH_DEBOUNCE_MS:1e3,YIELD_SLICE_MS:8};var Kn=typeof window>"u",Ju=!Kn&&typeof MessageChannel<"u";function Q(){return Ju?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 hr(e,t){return performance.now()-e<bs.YIELD_SLICE_MS?{aborted:!1,newSliceStart:e}:(await Q(),t()?{aborted:!1,newSliceStart:performance.now()}:{aborted:!0,newSliceStart:performance.now()})}async function fe(e){return Kn||await Q(),e()?{aborted:!1}:{aborted:!0}}function yr(e,t){let{inDegree:r,successors:n}=Xu(e,t),i=Zu(r),a=Qu(i,r,n),s=a.length<e.length,o=s?tf(e,a):[],c=[...a].reverse();return{ordered:a,reversed:c,hasCycles:s,cycleNodes:o}}function Xu(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 Zu(e){let t=new pt;for(let[r,n]of e)n===0&&t.enqueue(r);return t}function Qu(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 tf(e,t){let r=new Set(t);return e.filter(n=>!r.has(n))}var mr=class{cached=null;invalidate(){this.cached=null}get(t,r){return this.cached?this.cached:(this.cached=yr(t,r),this.cached)}};function Ls(e,t){let r=[];for(let n of e)t.has(n)&&r.push(n);return r}var Gn={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 $n(e){return e==="project"||e==="task"||e==="milestone"}function bt(e,t){return t||$n(e)&&Gn[e].alwaysSummary}function Lt(e){return e==="milestone"}function Wt(e){return $n(e)&&Gn[e].promotesToProjectOnFirstChild}var zn="project",pe="task";function We(e,t){return t===0?"milestone":e===0&&t>0?"task":null}function gr(e,t){let r=t.getActivity(e);return r?bt(r.type,t.getChildren(e).length>0):!1}function vr(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 qn(e,t,r){let n=gr(e,r);return gr(t,r)&&vr(e,t,r)||n&&vr(t,e,r)}function xs(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 ef(e){let t=new Map;for(let r of e)ws(t,String(r.source),r),ws(t,String(r.target),r);return t}function ws(e,t,r){let n=e.get(t);if(n){n.push(r);return}e.set(t,[r])}function rf(e,t,r,n){if(e.length<=1)return e;let i=new Set(e.map(String)),a=[];for(let s of e)nf(s,i,t,r,n)||a.push(s);return a.length>0?a:e}function nf(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(af(c,a,s,t,r,i))return!0;return!1}function af(e,t,r,n,i,a){if(sf(e)||!(a?String(e.source)===t:String(e.target)===t))return!1;let o=of(e,t);if(!n.has(String(o)))return!1;let c=i.getActivity(o);return!!(c?.autoScheduling!==!1&&c&&cf(e,r,c))}function sf(e){return e.source===e.target}function of(e,t){return String(e.source)===t?e.target:e.source}function cf(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 Cr(e,t){let r=[],n=ef(e),i=0;for(let a of e){let s=gr(a.source,t),o=gr(a.target,t);if(lf(a,s,o,t))continue;if(!s&&!o){r.push(a);continue}let c=Os(a.source,s,t,n,!0),l=Os(a.target,o,t,n,!1);i=mf(r,c,l,a,t,i,n)}return r}function lf(e,t,r,n){return r&&vr(e.source,e.target,n)||t&&vr(e.target,e.source,n)}function Os(e,t,r,n,i){return t?rf(xs(e,r),r,n,i):[e]}function df(e,t,r){let n=xs(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 Ar(e,t){return df(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 ff(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 pf(e,t){let r=String(e);return(t.get(r)??[]).some(i=>String(i.target)===r)}function hf(e,t,r,n,i){if(pf(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=Ar(e.source,t),a=Ar(e.target,t),s=e.type===M.START_TO_START||e.type===M.START_TO_FINISH,o=e.type===M.FINISH_TO_FINISH||e.type===M.START_TO_FINISH;return{source:r,sourceBounds:i,targetStart:a?.startDate??n?.startDate,userLag:e.lag??0,sourceEndpointIsStart:s,targetLag:o?-uf(n,a,t):0,summarySourceId:e.type===M.START_TO_START&&i?e.source:void 0}}function mf(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,v=a;for(let I of t){let T=f?ff(I,c,l,i):0;for(let g of r){if(String(I)===String(g))continue;let k=hf(g,d,c,i,s);e.push(gf(n,I,g,v,T,p,u+k,h,k!==0&&p===0?n.target:void 0)),v+=1}}return v}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,_sourceLag:i,_targetLag:a,_trueLag:s,...o===void 0?{}:{_summarySourceId:o},...c===void 0?{}:{_summaryTargetId:c}}}var Ir=class{invalidate(){}get(t,r){return Cr(t,r)}};function vf(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 Af(e,t,r){let n=new Set,i=new Map,a=new pt;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 Ns(e,t){let r=new Map;for(let s of t)r.set(s.id,s);let n=vf(t),i=Af(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 Fs(e,t,r){let n=r.type===M.FINISH_TO_START,i=r.type===M.FINISH_TO_FINISH;if(r._targetLag!==void 0)return{sourceLag:r._sourceLag??0,targetLag:r._targetLag,trueLag:r._trueLag??r.lag??0,isFS:n,isFF:i,isZeroDurationCase:!1};let a=r.lag??0;switch(r.type){case M.FINISH_TO_START:return{sourceLag:0,targetLag:0,trueLag:a,isFS:n,isFF:i,isZeroDurationCase:!1};case M.START_TO_START:return{sourceLag:-e.durationHours,targetLag:0,trueLag:a,isFS:n,isFF:i,isZeroDurationCase:!1};case M.FINISH_TO_FINISH:return{sourceLag:0,targetLag:-t.durationHours,trueLag:a,isFS:n,isFF:i,isZeroDurationCase:!1};case M.START_TO_FINISH:return{sourceLag:-e.durationHours,targetLag:-t.durationHours,trueLag:a,isFS:n,isFF:i,isZeroDurationCase:!1};default:return{sourceLag:0,targetLag:0,trueLag:a,isFS:n,isFF:i,isZeroDurationCase:!1}}}function Cf(e,t,r){if(e._summarySourceId===void 0)return null;let n=r.getActivity(e._summarySourceId);if(!n)return null;let i=Ar(e._summarySourceId,r);return i?-r.calculateDuration({startDate:i.startDate,endDate:t.endDate,task:n}):null}function If(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 Ms(e,t,r,n){let{sourceLag:i,targetLag:a,trueLag:s,isFS:o,isFF:c}=Fs(e,t,r),l=Cf(r,e,n)??i,d=l+a+s;if(!(t.durationHours===0?d!==0:l!==0||a!==0||s!==0))return If(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 v=new Date(Date.UTC(h.getUTCFullYear(),h.getUTCMonth(),h.getUTCDate()));return{successorStart:n.getClosestWorkTime({date:v,dir:"future",task:t}),link:r}}return{successorStart:n.getClosestWorkTime({date:h,dir:"future",task:t}),link:r}}function Ws(e,t,r,n){let{sourceLag:i,targetLag:a,trueLag:s}=Fs(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 Us(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=Rs(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 Sr(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=Yn(e.startDate,n):Es(i,n)?a=i:a=Yn(i,n),t.startDate=a,t.endDate=r.calculateEndDate({startDate:a,durationHours:e.durationHours,task:e})}function Bs(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 Sf(e,t){return t.length?t.some(r=>String(r)===String(e)):!1}function js(e,t,r){return Jn(e.id,t,r)?{startDate:e.startDate,endDate:e.endDate}:{startDate:e.startDate,endDate:e.endDate}}function Jn(e,t,r){return t.dragWithMultiple&&Sf(e,r)}async function Vs(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 hr(d,i);if(f.aborted)return a;d=f.newSliceStart;let p=r.getActivity(u);if(!p||!p.autoScheduling||p.progress===100||kf(p,r))continue;let h=s.get(String(u))??[],v=null,I=null,T=!1;for(let L of h){let A=r.getActivity(L.source);if(!A)continue;let C=o(L.source),R=C.startDate.getTime()!==A.startDate.getTime()||C.endDate.getTime()!==A.endDate.getTime(),F={...A,startDate:C.startDate,endDate:C.endDate},O=js(F,c,l),q={...F,startDate:O.startDate,endDate:O.endDate},Z=Jn(L.source,c,l)?{...L,lag:0}:L,lt=Ms(q,p,Z,r);(!v||lt.successorStart>v)&&(v=lt.successorStart,I=String(L.id),T=L._summaryTargetId!==void 0&&!R)}v!==null&&T&&v<p.startDate&&(v=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(!(!v&&!P)){if(v){let L=v;p.type===pr.MILESTONE&&(L=Bs(p,v)),m.drivingLinkId=I,m.startDate=L,m.endDate=r.calculateEndDate({startDate:L,durationHours:p.durationHours,task:p}),m.earliestSchedulingStart=L,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}));Sr(p,m,r),a.set(u,m)}}return a}function kf(e,t){return bt(e.type,t.getChildren(e.id).length>0)}async function Ys(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||b(I.parentId)?n.getProjectEnd():f(I.parentId).endDate,h=(I,T)=>{let g=I,k=0;for(;g&&!b(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},v=performance.now();for(let I of e){let T=await hr(v,a);if(T.aborted)return s;v=T.newSliceStart;let g=n.getActivity(I);if(!g||g.constraintType!==K.ALAP||!g.autoScheduling||g.progress===100||bt(g.type,n.getChildren(I).length>0))continue;let k=p(g);if(!k)continue;let m=k,P=null,L=!1,A=d.get(String(I))??[];for(let Dt of A){if((Dt.lag??0)<0)continue;let de=n.getActivity(Dt.target);if(!de||de.autoScheduling===!1)continue;let Ca=f(Dt.target),uu={...de,startDate:Ca.startDate,endDate:Ca.endDate},ar=Ws(uu,g,Dt,n);ar<m&&(m=ar),(P===null||ar<P)&&(P=ar,L=g.parentId&&!b(g.parentId)?h(Dt.target,g.parentId):!1)}if(P!==null)if(L)m=P;else{let Dt=f(I).endDate,de=Dt.getTime()>k.getTime()?Dt:k;m=P<de?P:de}else m>k&&(m=k);let R=(u.get(String(I))??[]).some(Dt=>Dt.type===M.FINISH_TO_START||Dt.type===M.FINISH_TO_FINISH),F=new Date(Date.UTC(m.getUTCFullYear(),m.getUTCMonth(),m.getUTCDate())),O=()=>n.getClosestWorkTime({date:F,dir:"past",task:g}),q=n.getClosestWorkTime({date:m,dir:"future",task:g}).getTime()===m.getTime(),Z;g.durationHours===0&&P===null?Z=R&&q?O():n.getClosestWorkTime({date:m,dir:"past",task:g}):g.durationHours===0?R?Z=O():Z=n.getClosestWorkTime({date:m,dir:"future",task:g}):Z=n.getClosestWorkTime({date:m,dir:"future",task:g});let lt=n.calculateEndDate({startDate:Z,durationHours:-g.durationHours,task:g}),ft=s.get(I),nt=ft?{...ft}:{activityId:I,startDate:lt,endDate:Z,drivingLinkId:null,kind:"alap",conflict:!1};nt.startDate=lt,nt.endDate=Z,nt.drivingLinkId=null,nt.kind="alap";let ce=nt.earliestSchedulingStart??null;nt.earliestSchedulingStart=null,nt.earliestSchedulingEnd=null;let le=ce!==null&&ce.getTime()>lt.getTime()?ce:lt;nt.latestSchedulingStart=le,nt.latestSchedulingEnd=le===lt?Z:n.calculateEndDate({startDate:le,durationHours:g.durationHours,task:g}),Sr(g,nt,n),s.set(I,nt)}return s}var he={warn(){},error(){}};function Rt(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 Ue(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=Rt(i),e.updateActivity(r))}})}function Xn(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 Df(i,n,r)}function Be(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 pt;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 Df(e,t,r){if(t===r)return!0;let n=new Set([t]),i=new pt;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 kr(e){let t=Tf(e);for(let r of t.adjacency.keys())t.records.has(r)||_f(r,t);return t.components}function Tf(e){let t=new Map,r=new Set;for(let n of e){let i=String(n.source),a=String(n.target),s=Ks(t,i);if(Ks(t,a),i===a){r.add(i);continue}s.push(a)}return{adjacency:t,selfLooped:r,records:new Map,componentStack:[],nextIndex:0,components:[]}}function Ks(e,t){let r=e.get(t);if(r)return r;let n=[];return e.set(t,n),n}function _f(e,t){let r=[];for(r.push({node:e,record:Gs(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;Pf(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&&Rf(n.node,t)}}function Pf(e,t,r,n){let i=n.records.get(t);if(!i){r.push({node:t,record:Gs(t,n),neighborCursor:0});return}i.onStack&&i.visitIndex<e.record.lowLink&&(e.record.lowLink=i.visitIndex)}function Gs(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 Rf(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 je(e,t,r){let n=r?new Zn(e,r):e;return Cr([...t],n)}var Zn=class{constructor(t,r){this.base=t;for(let[n,i]of r.reparented){let a=String(n),s=i===null||b(i)?null:i,o=t.getActivity(n)?.parentId??null,c=o===null||b(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||b(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 He(e){let{port:t,currentLinks:r,proposedLinks:n,proposal:i}=e,a=je(t,n,i);if(!Be(a))return{ok:!0};let s=je(t,r),o=$s(s),l=[...$s(a)].filter(d=>!o.has(d));return l.length===0?{ok:!0}:{ok:!1,newlyCyclicActivityIds:l}}function $s(e){let t=new Set;for(let r of kr(e))for(let n of r)t.add(n);return t}function Ut(e,t){switch(e.kind){case"create":return Ef(e,t);case"update":return Ve(e,t.port);case"delete":return bf(e,t)}}function Tr(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=zs(l);n.has(d)||n.set(d,l.id),i.push({source:l.source,target:l.target})}let a=Be(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(qn(l.source,l.target,t.port)){s={applied:!1,rejected:"hierarchy-link"};break}let u=zs(l),f=n.get(u);if(f!==void 0){s={applied:!1,rejected:"duplicate",linkId:f};break}if(n.set(u,d),a&&Xn(i,{source:l.source,target:l.target}))return{applied:!1,rejected:"cycle"};i.push({source:l.source,target:l.target})}if(!a&&Be(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}))];if(!He({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,...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 zs(e){return JSON.stringify([String(e.source),String(e.target),e.type])}function Ef(e,t){let{port:r}=t;if(String(e.source)===String(e.target))return{applied:!1,rejected:"self-link"};let n=r.getActivity(e.source),i=r.getActivity(e.target);if(!n||!i)return{applied:!1,rejected:"activity-missing"};if(qn(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(Xn(s,{source:e.source,target:e.target}))return{applied:!1,rejected:"cycle"};let o=(t.newLinkId??Lf)(),c={id:o,source:e.source,target:e.target,type:e.type,lag:e.lag};return He({port:r,currentLinks:a,proposedLinks:[...a,c]}).ok?(r.addLink(c),{applied:!0,linkId:o}):{applied:!1,rejected:"cycle"}}function Ve(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 bf(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 Dr=null;function Lf(){return Dr===null&&(Dr=Date.now()),Dr+=1,String(Dr)}var qs={[M.FINISH_TO_START]:"fs",[M.START_TO_START]:"ss",[M.FINISH_TO_FINISH]:"ff",[M.START_TO_FINISH]:"sf"},Zt={fs:M.FINISH_TO_START,ss:M.START_TO_START,ff:M.FINISH_TO_FINISH,sf:M.START_TO_FINISH},Js="fs";function Xs(e){if(e in Zt)return Zt[e]}var Zs=";",Qs=/^(\d+)(fs|ss|ff|sf)?(?:([+-]?)(\d+(?:\.\d+)?)d?)?$/i;function _r(e){let t=[],r=[],n=e.replace(/\s+/g,"");if(n.length===0)return{specs:t,errors:r};for(let i of n.split(Zs)){if(i.length===0)continue;let a=wf(i);a?t.push(a):r.push(i)}return{specs:t,errors:r}}function wf(e){let t=e.toLowerCase(),r=Qs.exec(t);if(!r)return null;let[,n,i,a,s]=r,o=i?Zt[i]:Zt[Js],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 Rr(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=Pr(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(Pr(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 Pr(e,t){return`${String(e)}::${t}`}function Er(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=Pr(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(Pr(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 At(e,t){return Math.sign(e)*Math.round(Math.abs(e)*t)}var to={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 Qn(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 ti=to;var Lr=class{adapter;reporter;currentCalculationId=0;topoCache=new mr;expandedLinksCache=new Ir;constructor(t,r=he){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=Ds(r,()=>this.currentCalculationId),i={plans:new Map,updatedIds:[],cycles:[],cancelled:!1};try{Ff(this.adapter);let a=Bt("schedule.total"),s=Bt("schedule.expandParentLinks"),o=this.adapter.getAllLinks(),c=this.expandedLinksCache.get(o,this.adapter);wt(s);let l=c;if((await fe(n)).aborted)return{...i,cancelled:!0};let d=Bt("schedule.scoping"),u=this.adapter.getAllIds(),f=Mf(t,l,this.adapter),p=f.links,h=f.idSet;wt(d);let v=Bt("schedule.topologicalSort"),I=Uf(this.topoCache,u,l,h);if(wt(v),I.hasCycles)return wt(a),{...i,cycles:[I.cycleNodes]};if((await fe(n)).aborted)return{...i,cancelled:!0};let T=Bt("schedule.processConstraints"),g=new Map;if(Us(I.ordered,this.adapter,g),wt(T),(await fe(n)).aborted)return{...i,cancelled:!0};let k=Bt("schedule.asapPass"),m=await Vs(I.ordered,p,this.adapter,t,n,g);if(wt(k),(await fe(n)).aborted)return{...i,cancelled:!0};let P=Bt("schedule.alapPass"),L=await Ys(I.reversed,p,m,this.adapter,t,n);if(wt(P),(await fe(n)).aborted)return{...i,cancelled:!0};let A=Bt("schedule.diff"),C=[];for(let[R,F]of L){let O=this.adapter.getActivity(R);if(!O)continue;let q=O.startDate.getTime()!==F.startDate.getTime(),Z=O.endDate.getTime()!==F.endDate.getTime();(q||Z)&&C.push(R)}return wt(A),wt(a),{plans:L,updatedIds:C,cycles:[],cancelled:!1}}catch(a){return this.reporter.error("[AutoScheduler] Error during scheduling",a),i}}},xf=!1;function Nf(){let e=globalThis.__SCHEDULER_PHASE_LOG__;return typeof e=="boolean"?e:xf}function Bt(e){return{name:e,startedAt:performance.now()}}function Ff(e){let t=e;typeof t.clearCalendarCache=="function"&&t.clearCalendarCache()}function wt(e){if(!Nf())return;let t=performance.now()-e.startedAt;console.log(`[scheduler] ${e.name} ${t.toFixed(1)}ms`)}function Mf(e,t,r){let n=e.triggerId;if(n==null)return{idSet:null,links:t};let i=Ns(n,t);return Wf(i,t,r)}function Wf(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 Uf(e,t,r,n){let i=e.get(t,r);if(i.hasCycles){let s=n?Array.from(n):t;return yr(s,r)}if(!n)return i;let a=Ls(i.ordered,n);return{ordered:a,reversed:[...a].reverse(),hasCycles:!1,cycleNodes:[]}}function eo(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"||Lt(n.type)&&(o.type===M.START_TO_FINISH||o.type===M.FINISH_TO_FINISH))continue;let{sourceDate:d,targetDate:u}=Qn(c,i,o.type),f=ti.computeLagBetweenTasks(d,u,a);f!==o.lag&&Ve({kind:"update",linkId:o.id,lag:f},t)}}function ro(e,t){let r=t.getActivity(e);r&&Lt(r.type)&&(r.durationHours=0)}function ye(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 wr(e){return Number(e.toFixed(2))}function ht(e,t){return(Number(e)||0)*(Number(t)||0)/100}async function me(e,t,r=!0,n={}){let i=t?ei(e,t):Yf(e),a=r?n.progressMode??"freeze-when-no-contribution":"skip";await Bf(i,e,a,{recomputeRealWork:n.recomputeRealWork??!1})}function Or(e,t){no(e,t,"skip")}async function Bf(e,t,r,n={recomputeRealWork:!1}){let a=0;for(let s of e)no(s,t,r,n.recomputeRealWork),a+=1,a%200===0&&await Q()}function ei(e,t){let r=new Set;for(let a of t)jf(a,e,r);if(r.size===0)return[];let n=Array.from(r),i=io(n,e);return ao(n,i)}function jf(e,t,r){let n=t.getParentId(e);for(;n&&!b(n);){if(r.has(n))return;r.add(n),n=t.getParentId(n)}}function Hf(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+=Vf(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 no(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=Hf(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=ye(s.weightedChildren);r!=="skip"&&(f!==null||r==="zero-when-no-contribution")&&t.setActivityField(e,"progress",wr(f??0)),n&&t.setActivityField(e,"realWorkHours",s.realWorkSum)}function Vf(e,t){return t?Number(e.realWorkHours)||0:ht(e.workHours,e.progress)}function Yf(e){let t=Kf(e),r=io(t,e);return ao(t,r)}function Kf(e){let t=new Set;return e.forEachActivity(r=>{r.parentId!==null&&t.add(r.parentId)}),Array.from(t)}function io(e,t){let r=new Map;for(let n of e)r.set(n,Gf(n,t));return r}function Gf(e,t){let r=0,n=e;for(;n&&!b(n)&&t.getActivity(n);)r+=1,n=t.getParentId(n);return r}function ao(e,t){return[...e].sort((r,n)=>(t.get(n)??0)-(t.get(r)??0))}var so={updateActivityDuration:ro,updateTaskTiming:zf("updateTaskTiming"),adjustLinkLagOnTaskMove:eo,recordLastStartDate:$f};function $f(e,t){let r=t.getActivity(e);r&&t.setLastStartDate(e,r.startDate)}function jt(e,t,r,n){for(let i of t){let a=i in so?so[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 zf(e){return()=>{console.debug(`[replay post-processors] ${e}: not yet ported to adapter \u2014 no-op.`)}}function w(e,t){return t!==void 0?{ok:!0,value:e,raw:t}:{ok:!0,value:e}}function x(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 J(e,t){return t!==void 0?{allowed:!1,reason:e,alertKey:t}:{allowed:!1,reason:e}}function W(e,t={}){return{patch:e,needsAutoSchedule:t.autoSchedule??!1,postProcessors:t.postProcessors??[],...t.cascadeMutations!==void 0?{cascadeMutations:t.cascadeMutations}:{},...t.trackingEvents!==void 0?{trackingEvents:t.trackingEvents}:{}}}var oo={targetField:"name",canEdit(){return H()},parseInput(e){return typeof e!="string"?x("not_a_string"):w(e)},validate(){return j()},transform(e,t){return W({name:t},{autoSchedule:!1,postProcessors:[]})},trackEvent:"activity_name_entry"};var co={targetField:"description",canEdit(){return H()},parseInput(e){return typeof e!="string"?x("not_a_string"):w(e.trim())},validate(){return j()},transform(e,t){return W({description:t},{autoSchedule:!1,postProcessors:[]})},trackEvent:"activity_description_entry"};function Tt(e){return e.constraintType??K.ASAP}var xr=100;function ge(e){return e.progress>=xr}function et(e,t){return bt(e.type,t.hasChildren(e.id))}function lo(e){return e.progress>0}function uo(e){return e.hasLookaheadTasks}function Ye(e,t){return Math.round(Math.ceil(e*t*60)/60)}var Nr={NOT_A_NUMBER:"not_a_number",NOT_A_STRING:"not_a_string",NOT_AN_ARRAY:"not_an_array",NOT_AN_INTEGER:"not_an_integer",INVALID_DATE:"invalid_date",INVALID_CONSTRAINT_TYPE:"invalid_constraint_type",EMPTY_CALENDAR:"empty_calendar",EMPTY_CUSTOM_ID:"empty_custom_id",EXCEEDS_MAX_LENGTH:"exceeds_max_length",MISSING_INPUT_UNIT:"missing_input_unit",FRACTIONAL_DAYS:"fractional_days"},Fr={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"};var ve=e=>({endDate:e});function Ht(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 Wr(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 qf(e,t){let r=Ht(t,"UTC");for(;!e.isWorkTime(r,ot.DAY);)r=new Date(r),r.setUTCDate(r.getUTCDate()+1),r=Ht(r,"UTC");return r}function ri(e,t){return e.getClosestWorkTime({direction:X.FUTURE,date:t,unit:ot.HOUR})}function ni(e,t){let r=qf(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 Mr=new Set(["snet","snlt","mso"]),ii=new Set(["fnet","fnlt","mfo"]),Vt=new Set(["asap","alap"]),Ur="snet";function Ot(e,t,r){let n=Ht(e,"UTC");if(!Mr.has(r)&&!ii.has(r))return n;let i=Mr.has(r)?ri(t,n):ni(t,n),a=new Date(n);return a.setUTCHours(i.getUTCHours(),i.getUTCMinutes(),i.getUTCSeconds(),i.getUTCMilliseconds()),a}var Yt=()=>({constraintType:Ur});var Qt=e=>({constraintDate:e}),fo=e=>({constraintDate:e});var po={UPDATE_TASK_TIMING:"updateTaskTiming",ADJUST_LINK_LAG_ON_TASK_MOVE:"adjustLinkLagOnTaskMove",RECORD_LAST_START_DATE:"recordLastStartDate"};function Ae(e,t,r){return _s(e,t,r)}function Ce(e,t,r){return Ps(e,t,r)}var yo={targetField:"durationHours",canEdit(e,t){return ge(e)?J("completed","cant_edit_completed_activity"):et(e,t)?J("summary","summary_column_value"):H()},parseInput(e,t,r){let n=parseFloat(String(e));return Number.isFinite(n)?r.inputUnit===void 0?x(Nr.MISSING_INPUT_UNIT):r.inputUnit==="hours"?w(n):Number.isInteger(n)?w(Ye(n,r.hoursPerDay)):x(Nr.FRACTIONAL_DAYS):x(Nr.NOT_A_NUMBER)},validate(e,t,r){return ho(r)?tt(Fr.NEGATIVE_DURATION):Jf(t,r)?tt("unchanged"):j()},transform(e,t,r){if(ho(t))return W({},{autoSchedule:!1,postProcessors:[]});let n=Xf(e,t,r),i=Zf(e,t,r,n.violated);return{...W(i,{autoSchedule:!0,postProcessors:[po.RECORD_LAST_START_DATE]}),...n.violated?{constraintWarning:Ce(n.constraintType,n.constraintDate,mo(e,t,r)??void 0)}:{}}},trackEvent:"activity_duration_entry"};function ho(e){return Math.sign(e)===-1}function Jf(e,t){return e===t}function Xf(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 Ae(i,e.constraintDate,a)}function Zf(e,t,r,n=!1){let i={};n&&Object.assign(i,Yt(),Qt(e.startDate));let a=We(e.durationHours,t);a&&(i.type=a),i.durationHours=t;let s=mo(e,t,r);return s&&Object.assign(i,ve(s)),i}function mo(e,t,r){let n=r.calendars.getCalendar(e.calendarId);return n?n.calculateEndDate(e.startDate,t):null}var Ie=e=>({realWorkHours:e});var Qf=0,tp=xr,go=0,vo={targetField:"progress",canEdit(e,t){return uo(e)?J("has_lookahead_tasks","cant_edit_actvity_with_task"):et(e,t)?J("summary","summary_column_value"):H()},parseInput(e){let t=parseFloat(String(e));return Number.isNaN(t)?x("not_a_number"):w(t)},validate(e,t,r){return ep(r)?tt("out_of_range"):j()},transform(e,t,r){let n=rp(t),i=np(t),a=sp(e,t,r.hierarchy),s={progress:t,autoScheduling:n,...Ie(a.get(e.id)??0)},o=i?ip(e,t,n,r.hierarchy,a):[],c=i?cp(e,t,r.hierarchy):[],l=o.length+c.length>0?[...o,...c]:void 0,d=[],u=i?dp(e,t):void 0;return W(s,{autoSchedule:!1,postProcessors:d,cascadeMutations:l,trackingEvents:u})},trackEvent:"activity_progress_entry"};function ep(e){return e<Qf||e>tp}function rp(e){return e===go}function np(e){return e===xr||e===go}function ip(e,t,r,n,i){return n.getDescendantIds(e.id).map(s=>({activityId:s,fields:ap(t,r,i.get(s)??0)}))}function ap(e,t,r){return{progress:e,autoScheduling:t,...Ie(r)}}function sp(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):ht(c.workHours,t);n.set(c.id,l),o+=l}return o},a=r.hasChildren(e.id)?i(e.id):ht(e.workHours,t);return n.set(e.id,a),n}function op(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 cp(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=[...op(e,r),...r.getAncestorIds(e.id)],a=[];for(let s of i){let o=lp(s,n,r);n.set(s,o),a.push({activityId:s,fields:{progress:o}})}return a}function lp(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((ye(n)??0).toFixed(2))}function dp(e,t){return[{name:"activity_progress_update_radio_button",properties:{activity_id:e.id,activity_name:e.name,progress_updated:t}}]}var Ao={targetField:"cost",canEdit(e,t){return et(e,t)?J("summary","summary_column_value"):H()},parseInput(e,t){if(String(e).trim()==="")return w(t.cost);let r=parseFloat(String(e));return Number.isNaN(r)?x("not_a_number"):w(r)},validate(){return j()},transform(e,t,r){let n=up(e,t,r.hierarchy);return W({cost:t},{autoSchedule:!1,postProcessors:[],cascadeMutations:n})},trackEvent:"activity_cost_budgeted_entry"};function up(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 Co={targetField:"usedCost",canEdit(e,t){return et(e,t)?J("summary","summary_column_value"):H()},parseInput(e,t){if(String(e).trim()==="")return w(t.usedCost);let r=parseFloat(String(e));return Number.isNaN(r)?x("not_a_number"):w(r)},validate(){return j()},transform(e,t,r){let n=fp(e,t,r.hierarchy);return W({usedCost:t},{autoSchedule:!1,postProcessors:[],cascadeMutations:n})},trackEvent:"activity_cost_spent_entry"};function fp(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 Io={targetField:"workHours",canEdit(e,t){return et(e,t)?J("summary","summary_column_value"):H()},parseInput(e){if(String(e).trim()==="")return w(0,e);let t=parseFloat(String(e));return Number.isNaN(t)?x("not_a_number"):w(t)},validate(){return j()},transform(e,t,r,n){let i=So(t,e.progress),a=String(n).trim()===""?[]:pp(e,t,i,r.hierarchy);return W({workHours:t,...Ie(i)},{autoSchedule:!1,postProcessors:[],cascadeMutations:a})},trackEvent:"activity_labor_hours_budgeted_entry"};function So(e,t){return ht(e,t)}function pp(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??So(d.workHours,d.progress);c+=u,l+=f}i.set(o,c),a.set(o,l),s.push({activityId:o,fields:{workHours:c,...Ie(l)}})}return s}function Br(e,t){return e.getUTCFullYear()===t.getUTCFullYear()&&e.getUTCMonth()===t.getUTCMonth()&&e.getUTCDate()===t.getUTCDate()}function ai(e,t){return e.getTime()<t.getTime()}function Se(e){return e instanceof Date&&!Number.isNaN(e.getTime())}var jr=e=>({durationHours:e});var ko={targetField:"startDate",canEdit(e,t){return et(e,t)?J("summary","summary_column_value"):lo(e)?J("has_progress","cant_edit_activity_with_progress"):H()},parseInput(e,t,r){return Se(e)?w(Ht(e,"UTC")):x("invalid_date")},validate(e,t,r,n){if(Br(t,r))return tt("unchanged");let i=hp(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=ri(n,t),a=e.type==="milestone",s=a?i:n.calculateEndDate(i,e.durationHours),o=i;return{...W({startDate:i,...ve(s),...a?jr(0):{},...Yt(),...Qt(o)},{autoSchedule:!0,postProcessors:["adjustLinkLagOnTaskMove"]}),constraintWarning:yp(e,i,n)}},trackEvent:"activity_start_date_entry"};function hp(e,t,r){let n=r.hierarchy.getParentStartDateIfHasPredecessors(e.id);if(!n)return null;let i=Ht(n,"UTC");return t.getTime()<i.getTime()?tt("before_parent_start"):null}function yp(e,t,r){let n=r.calculateEndDate(t,e.durationHours),i=Me(Tt(e),t,n),a=Ae(Tt(e),e.constraintDate,i);if(a.violated)return Ce(a.constraintType,a.constraintDate,i)}var mp=99.999,To={targetField:"endDate",canEdit(e,t){return et(e,t)?J("summary","summary_column_value"):gp(e)?J("completed","cant_edit_completed_activity"):H()},parseInput(e,t,r){if(!Se(e))return x("invalid_date");let n=Ht(e,"UTC"),i=r.calendars.getCalendar(t.calendarId);return i?i.isWorkTime(n,ot.DAY)?w(ni(i,n)):w(i.getClosestWorkTime({direction:"past",date:n,unit:ot.HOUR})):w(n)},validate(e,t,r,n){if(Br(e.endDate,r))return tt("unchanged");if(vp(r,e))return tt("before_date_origin");if(Ap(r,e))return tt("before_start_date");let i=Cp(r,e,n);return i||j()},transform(e,t,r){let n=Ip(e,t),i=Sp(e,t,r,!!n);return{...W(i,{autoSchedule:!0,postProcessors:["updateTaskTiming"]}),...n?{constraintWarning:n}:{}}},trackEvent:"activity_end_date_entry"};function gp(e){return e.progress>=mp}function vp(e,t){return t.dateOrigin?ai(e,t.dateOrigin):!1}function Ap(e,t){return ai(e,t.startDate)}function Cp(e,t,r){let n=r.calendars.getCalendar(t.calendarId);return n?n.isWorkTime(e,ot.DAY)?null:tt("not_working_day"):null}function Ip(e,t){if(Tt(e)===K.MSO)return;let n=Me(Tt(e),e.startDate,t),i=Ae(Tt(e),e.constraintDate,n);if(i.violated)return Ce(i.constraintType,i.constraintDate,n)}function Sp(e,t,r,n=!1){let i={};Lt(e.type)&&!n&&Do(e)?Object.assign(i,Qt(e.startDate)):(n||Do(e))&&Object.assign(i,Yt(),Qt(e.startDate));let o=kp(e,t,r),c=We(e.durationHours,o);return c&&(i.type=c),Object.assign(i,jr(o)),i.endDate=t,i}function Do(e){return Vt.has(Tt(e))}function kp(e,t,r){let n=r.calendars.getCalendar(e.calendarId);return n?n.calculateDuration(e.startDate,t):e.durationHours}var Dp=new Set(Object.values(K)),_o={targetField:"constraintType",canEdit(e,t){return ge(e)?J("completed","cant_edit_completed_activity"):et(e,t)?J("summary","summary_column_value"):H()},parseInput(e){let t=String(e).toLowerCase();return Tp(t)?w(t):x("invalid_constraint_type")},validate(){return j()},transform(e,t,r){let n=_p(e,t,r);return W(n,{autoSchedule:!0})}};function Tp(e){return Dp.has(e)}function _p(e,t,r){let n=Rp(e,t);return{constraintType:t,...fo(Pp(e,t,n,r))}}function Pp(e,t,r,n){if(e.type!=="milestone"||!r)return r;let i=n.calendars.getCalendar(String(e.calendarId));return i?Ot(r,i,t):r}function Rp(e,t){return Vt.has(t)?null:Mr.has(t)?e.startDate:ii.has(t)?e.endDate:e.constraintDate}var Po={targetField:"constraintDate",canEdit(e,t){return ge(e)?J("completed","cant_edit_completed_activity"):et(e,t)?J("summary","summary_column_value"):H()},parseInput(e){return Se(e)?w(e):x("invalid_date")},validate(){return j()},transform(e,t,r){let n=Ro(e)?Ur:Tt(e),i=r.calendars.getCalendar(e.calendarId);if(!i)throw new Error("constraintDatePipeline: no calendar resolved (integrity)");let a=Ot(t,i,n),s=Ep(e,a);return W(s,{autoSchedule:!0})}};function Ep(e,t){return{constraintDate:t,...Ro(e)?Yt():{}}}function Ro(e){return Vt.has(Tt(e))||!e.constraintType}var Eo={targetField:"calendarId",canEdit(){return H()},parseInput(e){let t=String(e).trim();return bp(t)?x("empty_calendar"):w(t)},validate(e,t,r,n){return Lp(e.calendarId,r)?tt("unchanged"):n.calendars.getCalendar(r)?j():tt("unknown_calendar")},transform(e,t,r){return W(wp(e,t,r),{autoSchedule:!0,postProcessors:[]})},trackEvent:"activity_calendar_assignment"};function bp(e){return e===""}function Lp(e,t){return e===t}function wp(e,t,r){let n={calendarId:t,assignedDefaultCalendar:!1},i=r.calendars.getCalendar(t);if(i){let a=e.durationHours===0,s=a?Op(e.startDate):e.startDate,o=i.getClosestWorkTime({date:s,direction:"future",unit:"hour"});if((!e.autoScheduling||a||i.getWorkHours(e.startDate).length===0)&&(n.startDate=o),!e.autoScheduling)return n;let c=n.startDate??e.startDate;Object.assign(n,ve(i.calculateEndDate(c,e.durationHours)))}return n}function Op(e){return new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()))}var bo={targetField:"customId",canEdit(e,t){return et(e,t)?J("summary","summary_column_value"):H()},parseInput(e){if(e==null)return x("empty_custom_id");if(typeof e!="string")return x("not_a_string");let t=e.trim();return t.length===0?x("empty_custom_id"):t.length>20?x("exceeds_max_length"):w(t)},validate(){return j()},transform(e,t){return W({customId:t},{autoSchedule:!1,postProcessors:[]})},trackEvent:"schedule_custom_id_edition"};var Lo={targetField:"subcontractId",canEdit(){return H()},parseInput(e){if(e==null)return w(null);if(typeof e=="string"){let t=e.trim();if(t.length===0)return w(null);let r=Number(t);return!Number.isFinite(r)||!Number.isInteger(r)?x("not_an_integer"):w(r)}return typeof e=="number"?!Number.isFinite(e)||!Number.isInteger(e)?x("not_an_integer"):w(e):x("not_an_integer")},validate(){return j()},transform(e,t){return W({subcontractId:t},{autoSchedule:!1,postProcessors:[]})}};function Ke(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 Hr(e){return e.some(t=>Ke(t)===null)}var wo={targetField:"responsableIds",canEdit(){return H()},parseInput(e){return e==null?w([]):Array.isArray(e)?w(e):x("not_an_array")},validate(e,t,r){return Hr(r)?tt("missing_id"):j()},transform(e,t){let r=t.map(Ke).filter(n=>n!==null);return W({responsableIds:r},{autoSchedule:!1,postProcessors:[]})}};var Oo={targetField:"tagIds",canEdit(){return H()},parseInput(e){return e==null?w([]):Array.isArray(e)?w(e):x("not_an_array")},validate(e,t,r){return Hr(r)?tt("missing_id"):j()},transform(e,t){let r=t.map(Ke).filter(n=>n!==null);return W({tagIds:r},{autoSchedule:!1,postProcessors:[]})}};var xp=new Map([[_.TEXT,oo],[_.DESCRIPTION,co],[_.DURATION,yo],[_.PROGRESS,vo],[_.COST,Ao],[_.USED_COST,Co],[_.HH_WORK_TIME,Io],[_.START_DATE,ko],[_.END_DATE,To],[_.CONSTRAINT_TYPE,_o],[_.CONSTRAINT_DATE,Po],[_.CALENDAR_ID,Eo],[_.CUSTOM_ID,bo],[_.SUBCONTRACT_ID,Lo],[_.RESPONSABLES,wo],[_.TAGS,Oo]]);function Kt(e){return xp.get(e)}function ke(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 Np=["name","description","type","startDate","endDate","durationHours","constraintType","constraintDate","calendarId","assignedDefaultCalendar","autoScheduling","progress","cost","usedCost","workHours","realWorkHours","customId","subcontractId","responsableIds","tagIds"],xo=new Set(Np);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"},si={ID:"id",SOURCE:"source",TARGET:"target",TYPE:"type",LAG:"lag",SOURCE_LAG:"_sourceLag",TARGET_LAG:"_targetLag",TRUE_LAG:"_trueLag",SUMMARY_SOURCE_ID:"_summarySourceId",SUMMARY_TARGET_ID:"_summaryTargetId",GANTT_ID:"ganttId",SECTOR_ID:"sectorId",PROPLANNER_ID:"proplannerId"};function rt(e,t,r,n){e.setActivityFieldDynamic(t,r,n)}function No(e,t,r,n){e.setLinkFieldDynamic(t,r,n)}function ee(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:Fp(e.baselineSnapshot),criticalPath:Mp(e.criticalPath)}}function Et(e){return e===null?null:new Date(e)}function Fp(e){return e===null?null:{...e,startDate:Et(e.startDate),endDate:Et(e.endDate)}}function Mp(e){return e===null?null:{...e,earlyStart:Et(e.earlyStart),earlyFinish:Et(e.earlyFinish),lateStart:Et(e.lateStart),lateFinish:Et(e.lateFinish)}}var Wo=200;function Gt(e,t){let r=new Set([String(e)]);for(let n of t.cascadeMutations??[])r.add(String(n.activityId));return r}async function G(e,t){let r=new Map,n=0;for(let i of t){n+=1,n%Wo===0&&await Q();let a=e.getActivity(i);a&&r.set(i,z(a))}return r}function z(e){return ee(e)}function Vr(e,t){let r=e.getActivity(t);return r?ee(r):null}function $t(e,t,r){Fo(e,t,r.patch);for(let n of r.cascadeMutations??[])Fo(e,n.activityId,n.fields)}function Fo(e,t,r){for(let[n,i]of Object.entries(r)){if(!xo.has(n))throw new Error(`applyFieldChanges: column write to non-writable field "${n}"`);rt(e,t,n,i)}}async function Uo(e,t,r,n){let i=[],a=0;for(let s of r){a+=1,a%Wo===0&&await Q();let o=Wp(e,t,s,n);o&&i.push(o)}return i}function Wp(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 Up(r,n.get(r),i);let s=ci(a,i);return Bp(s,n,r,i),a&&Object.keys(s).length===0?null:{id:r,kind:a?"updated":"created",fields:s,after:z(i)}}function Up(e,t,r){return t===r.correlativeId?null:{id:e,kind:"updated",fields:{correlativeId:{before:t,after:r.correlativeId}},after:z(r)}}function Bp(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 ci(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)||!oi(n[s],i[s]))&&(r[s]={before:Mo(n[s]),after:Mo(i[s])});return r}function Mo(e){return e===null||typeof e!="object"?e:B(e)}function oi(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)=>oi(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)&&oi(r[s],n[s]))}function Yr(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 li(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 De(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=z(s);a.before!==void 0&&(o.correlativeId=a.before),n.set(a.activityId,o)}}var jp=/^(\d{4})\/(\d{1,2})\/(\d{1,2})\s+(\d{1,2}):(\d{2})$/;function xt(e){if(e==null||e==="")throw new Error(`[parseFromBackend] expected a date string, got "${e}"`);if(e.includes("T")||e.endsWith("Z")){let o=new Date(e);if(Number.isNaN(o.getTime()))throw new Error(`[parseFromBackend] invalid ISO date "${e}"`);return o}let t=e.match(jp);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 Te(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 Hp=e=>e.type==="project",Vp=(e,t,r)=>{let n=e.calendarId,i=n!=null?r.calendarReader.getCalendar(String(n)):null;if(!i)return 0;let a=s=>s instanceof Date?s:xt(String(s));return Te(a(e.startDate),a(e.endDate),t,i)};function Yp(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(!Hp(o)){let d=Vp(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 re(e,t){let r=[];e.forEachActivity((n,i)=>{n.parentId===null&&r.push(i)}),Yp(r,t,e)}function dt(e){let t=e?.baselinePoints;return!Array.isArray(t)||t.length===0?null:t.find(r=>r.isActiveVersion)??null}var Kp=e=>e.type==="project",Gp=e=>dt(e),$p=(e,t,r,n)=>{let i=Gp(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:Te(i.startDate,i.endDate,t,a)};function di(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(!Kp(c)){let u=$p(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 _e(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)}),di(i,t,n,r)}var Bo=e=>Math.round(e*100)/100;function zp(e,t){return(t==="Baseline"?e.expectedProgressBaseline:e.expectedProgress)??void 0}function qp(e,t){let r=Bo(e),n=Bo(t);return r>99.99?Pt.DONE:n>r?Pt.OVERDUE:e>0&&r>n?Pt.ADVANCEMENT:e===0&&t===0?Pt.WAITING:e>0&&r<n?Pt.DOING:Pt.WAITING}function Nt(e,t){let r=[];return e.forEachActivity((n,i)=>{let a=typeof n.progress=="number"?n.progress:0,s=qp(a,zp(n,t));n.status!==s&&(rt(e,i,dr,s),r.push(i))}),r}function ui(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:()=>ui(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}ui.isMoment=e=>!!e&&typeof e=="object"&&e.__isMomentShim===!0;var Ct=ui;function Jp(e){return e&&e.constructor===Date?!!(e.getFullYear&&e.getMonth&&e.getDate):!1}function Kr(e){return Jp(e)&&!isNaN(e.getTime())}function D(e,t,r,n){if(!Kr(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(!Kr(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 Xp=e=>e?e.$level===1:!1,Zp=e=>e.type==="project",Qp=e=>e.$level!==0,th=e=>e.type==="task",eh=e=>e.type==="task"||e.type==="milestone",ct={byFirstLevel:Xp,filterByParentType:Zp,avoidSubproject:Qp,byTaskType:th,byTaskTypeAndMilestone:eh};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 ne(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=rh({gantt:t,pendingParentsWithNoLinks:r});if(a.length===0)return new Set;let s=nh({gantt:t,subprojectsWithNoLinks:a}),o=ih({gantt:t,childrenIds:s,linkProperty:i,getArrayOfLinkedActivities:ah,calculations:n});return new Set(o.map(c=>c.id))}catch(a){throw a}}function rh(e){let{gantt:t,pendingParentsWithNoLinks:r}=e;return t.getTaskByTime().filter(ct.filterByParentType).filter(n=>r.has(n.id)).map(n=>n.id)}function nh(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 ih(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 ah(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 Ho({gantt:e,linkProperty:t,direction:r}){try{let n=sh(e,t);if(r==="forward")return{chainStartActivities:n,activitiesStartChainButChildrenOfLinkedParents:null};if(r==="backward")return oh(n,e,t)}catch(n){throw console.log("Critical Path",n),n}}function sh(e,t){return e.getTaskByTime().filter(ct.avoidSubproject).filter(ct.byTaskTypeAndMilestone).filter(r=>!r[t].length)}function oh(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 Vo({gantt:e,direction:t,linkProperty:r}){try{let n=ch(e),i=new Set,a=new Set,s=new Set;t==="backward"&&uh(n).forEach(d=>{i.add(d.id)});let o=lh(n,t,r),c=dh(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 ch(e){return e.getTaskByTime().filter(ct.filterByParentType).filter(ct.avoidSubproject)}function lh(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 dh(e,t){let r=new Set(t.map(n=>n.id));return e.filter(n=>!r.has(n.id))}function uh(e){return e.filter(t=>{let r=Number(t.progress);return Number.isNaN(r)?!1:r===100})}function Yo({pendingParentsWithLinks:e,gantt:t,direction:r}){try{let n=new Set;return e.forEach(i=>{let a=t.getTask(i),s=fh(r),o=ph(r),c=a[s];if(!Array.isArray(c))return;hh(t,c,o).forEach(d=>{n.add(d)})}),n}catch(n){throw n}}function fh(e){return e==="forward"?"$source":"$target"}function ph(e){return e==="forward"?"target":"source"}function hh(e,t,r){return t.map(n=>{let a=e.getLink(n)[r];return Number(a)})}var Ge={identifySecondLevelActivities:jo,identifyInitialActivities:Ho,identifyParentsWithAndWithoutLinks:Vo,identifyForbiddenActivities:Yo};function Gr(e){return e.length?e.reduce((t,r)=>r.ef>t.ef?r:t):!1}function fi({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}):$e(r,e,n,i)}function Ko({duration:e,constraintDate:t,activityCalendar:r,activity:n}){let i=new Date(t);return{es:D(r,i,e,n),ef:i}}function Go({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 $e(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 pi=class{constructor(t,r,n){if(this.linkedActivitiesData=t,this.activity=r,this.gantt=n,this.activityCalendar=this.gantt.getCalendar(this.activity.calendar_id),!this.activityCalendar)throw new Error(`Error trying to get calendar with id: ${this.activity.calendar_id}`)}calculate(){let t=this.calculateLinks(),r=Gr(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=ne(n),a=r.linkLag,s=r.es,o=r.ef,c=null;if(i==="ss")c=this.calculateSSLink({lag:a,predecessorEs:s});else if(i==="ff")c=this.calculateFFLink({lag:a,predecessorEf:o});else if(i==="fs")c=this.calculateFSLink({lag:a,predecessorEf:o});else if(i==="sf")c=this.calculateSFLink({lag:a,predecessorEs:s,predecessorEf:o});else continue;c&&t.push(c)}return t}handleSNETConstraint(t){let r=Go({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=Ko({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=fi({linkType:"ss",lag:t,predecessorTime:r,activityCalendar:this.activityCalendar,activity:this.activity}),i=D(this.activityCalendar,n,t,this.activity);t>0&&(i=$e(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=fi({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=$e(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=$e(i,"sf",this.activityCalendar,this.activity)),{es:i,ef:n}}},$o=pi;var hi=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=ne(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=Ct(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),Ct.isMoment(r)?r.hours()===s:n.getUTCHours()===s)}},zo=hi;function qo(e){let{parent:t,linkProperty:r,linkDirection:n,calculations:i,gantt:a,direction:s}=e,o=t[r],c=yh(t),l=null;if(s==="forward"){let d=mh(o,n,i,a);l=new $o(d,t,a),l=l.calculate()}else{let d=gh(o,n,i,a);l=new zo({linksWithActivityData:d,activity:t,parentData:c,gantt:a}).calculate()}return l}function yh(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?{es:o.es,ef:o.ef,linkLag:a.lag,linkType:a.type}:(console.warn(`Calculations not found for activity: ${s}`),null)}).filter(Boolean)}function gh(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 Zo(e){let{activityData:t,calculations:r,singleParents:n,direction:i}=e;if(vh(t.id,r))return null;let a=Ah(t.id,n),s=Ch(a,r);return s.length===0?null:Ih(s,i)}function vh(e,t){return t.has(e)}function Ah(e,t){let r=t.get(e);return r?r.childrens:[]}function Ch(e,t){return e.filter(r=>t.has(r)).map(r=>t.get(r))}function Ih(e,t){if(t==="forward"){let r=Jo(e,"es"),n=Xo(e,"ef");return{es:r,ef:n}}else{let r=Jo(e,"ls"),n=Xo(e,"lf");return{ls:r,lf:n}}}function Jo(e,t){return e.reduce((r,n)=>n[t]<r[t]?n:r)[t]}function Xo(e,t){return e.reduce((r,n)=>n[t]>r[t]?n:r)[t]}var yi={parentWithLinks:qo,parentWithNoLinks:Zo};var mi=class{constructor(t){this.activity=t.activity,this.direction=t.direction,this.linkProperty=t.direction==="forward"?"$target":"$source",this.linkDirection=t.direction==="forward"?"source":"target",this.calculationsOfParentThatImpactChildrens=t.calculationsOfParentThatImpactChildrens,this.calculations=t.calculations,this.calculationOfParentsFromLinks=t.calculationOfParentsFromLinks,this.singleParents=t.singleParents,this.parentCalculationFromChildren=t.parentCalculationFromChildren,this.gantt=t.gantt}handleParentWithLinks(){try{let t=this.getArrayOfIdOfLinkedActivities(this.activity[this.linkProperty]);if(this.direction==="backward"){let n=[y.FNLT];if(this.shouldCalculateParentWithLinksBackward(n)){this.calculateAndStoreParentWithLinks(this.activity);return}if(this.shouldSetDatesToParentsWithLinks(n)){this.setDatesToParentsWithLinksBackward();return}}if(this.areAllLinksCalculated(t)&&this.calculationsOfParentThatImpactChildrens.has(this.activity.id)){this.direction==="forward"&&this.setDatesToParentsWithLinks(),this.direction==="backward"&&this.setDatesToParentsWithLinksBackward();return}this.calculateAndStoreParentWithLinks(this.activity)}catch(t){throw t}}shouldCalculateParentWithLinksBackward(t){let r=t.includes(this.activity.constraint_type),n=!this.calculationOfParentsFromLinks.has(this.activity.id);return r&&n}calculateAndStoreParentWithLinks(t){let r=yi.parentWithLinks({parent:t,linkProperty:this.linkProperty,linkDirection:this.linkDirection,gantt:this.gantt,calculations:this.calculations,direction:this.direction});this.calculationsOfParentThatImpactChildrens.set(t.id,r),this.calculationOfParentsFromLinks.add(t.id)}areAllLinksCalculated(t){return t.every(r=>this.calculations.has(r))}shouldSetDatesToParentsWithLinks(t){let r=t.includes(this.activity.constraint_type),n=this.calculationOfParentsFromLinks.has(this.activity.id);return r&&n}handleParentWithNoLinks(){let t=yi.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)})}},Qo=mi;var gi=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}}},tc=gi;var vi=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}=Ge.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=Ge.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 tc({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=Ge.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}=Ge.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:Ct(n.start_date).clone(),lf:Ct(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=Ct(t.start_date).clone(),i=Ct(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 Qo({activity:t,direction:this.direction,calculationsOfParentThatImpactChildrens:this.calculationsOfParentThatImpactChildrens,calculations:this.calculations,calculationOfParentsFromLinks:this.calculationOfParentsFromLinks,singleParents:this.singleParents,parentCalculationFromChildren:this.parentCalculationFromChildren,gantt:this.gantt});this.pendingParentsWithLinks.has(t.id)?r.handleParentWithLinks():r.handleParentWithNoLinks()}},zt=vi;function Sh(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 $r=Sh;var Ai=class{constructor(t){this.referenceActivity=t.activity,this.activityToCalculate=null,this.links=t.links,this.calculatedActivities=t.calculatedActivitiesMap,this.alapMap=t.calculatedAlapsMap,this.parentsWithLinks=t.parentsWithLinks,this.parentsCalculations=t.parentsCalculations,this.gantt=t.ganttInstance}getEsAndEfFromPreviousCalculatedActivities(t){return this.alapMap.has(t)?this.alapMap.get(Number(t)):this.calculatedActivities.get(Number(t))}calculateSucessorTimes(t,r,n=0,i,a=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})}},ec=Ai;var ze=class extends ec{constructor(t){super(t)}calculate(){if(this.links.length===0)return new zt(this.gantt,"forward").calculateStartAndFinishOfChainOrigin(this.referenceActivity);let t=this.links.map(n=>{let i=this.gantt.getLink(n);if(!i)throw new Error("Link data not found",{cause:{linkId:n}});return this.calculateLink(i)}),r=Number(this.referenceActivity.parent);if(this.parentsWithLinks.has(r)){let n=this.gantt.getCalendar(this.referenceActivity.calendar_id),i=this.parentsCalculations.get(r).es,a=D(n,i,this.referenceActivity.duration,this.referenceActivity);t.push({es:i,ef:a})}return Gr(t)}calculateLink(t){return{0:()=>this.calculateFS(t),1:()=>this.calculateSS(t),2:()=>this.calculateFF(t),3:()=>this.calculateSF(t)}[t.type]()}};var Ci=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=Ci;var Ii=(e,t)=>()=>t()===e;var Si=e=>!e?.fullyParsed||typeof window<"u"&&window.to_use_react_gantt?.conversionMode?.isActive;var kh=16,qe=async e=>performance.now()-e>kh?(await Q(),performance.now()):e;var Je=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 qe(c);let{activitiesThatCanBeCalculated:l,pendingActivities:d}=t.checkActivitiesThatNowCanBeCalculated(o);if(l.size===0)break;for(let u of l){if(!s())return;c=await qe(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 ki=class extends zt{constructor(t){super(t,"forward"),this.gantt=t,this.chainStartActivities=new Set,this.secondLevelActivities=new Set,this.pendingParentsWithLinks=new Set,this.pendingParentsWithNoLinks=new Set,this.structureOfParents=new Map,this.singleParents=new Map,this.calculations=new Map,this.calculationsOfParentThatImpactChildrens=new Map,this.alapMap=new Map,this.activitiesWaitingForCalculation=new Set,this.constraintsMap=new Map,this.totalFloatSnltFnlt=new Map,this.totalFloatForMsoMfo=new Map,this.totalFloatForAsap=new Map,this.calculationOfParentsFromLinks=new Set,this.parentCalculationFromChildren=new Set,this.forbiddenActivitiesLinkedToParentsWithLinks=new Set,this.activitiesStartChainButChildrenOfLinkedParents=new Set,this.identifyInitialActivities(),this.initActivitiesWaitingForCalculation()}async calculateAsync(t){this.identifyParentsWithAndWithoutLinks(),t()&&(this.identifyForbiddenActivitiesLinkedToParentsWithLinks(),t()&&(this.initializeActivitiesWithFullProgress(),t()&&(this.calculateStartAndFinishOfActivitiesThatStartChain(),t()&&(this.identifySecondLevelActivities(),t()&&(this.identifyThirdLevelActivities(),t()&&await this.iterativeCalculateEfAndEs(t))))))}async iterativeCalculateEfAndEs(t){let r=new 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 Je({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 ze({links:i,activity:n,calculatedActivitiesMap:this.calculations,calculatedAlapsMap:this.alapMap,constraint:a,parentsWithLinks:this.pendingParentsWithLinks,parentsCalculations:this.calculationsOfParentThatImpactChildrens,ganttInstance:this.gantt}).calculate(),a===y.ASAP&&this.totalFloatForAsap.set(r,{es:f.es,ef:f.ef,text:n.text})):{es:d,ef:u}=new ze({links:i,activity:n,calculatedActivitiesMap:this.calculations,calculatedAlapsMap:this.alapMap,constraint:a,parentsWithLinks:this.pendingParentsWithLinks,parentsCalculations:this.calculationsOfParentThatImpactChildrens,ganttInstance:this.gantt}).calculate(),a===y.ALAP&&this.alapMap.set(r,{es:n.start_date,ef:n.end_date,text:n.text});let p=$r(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)}},rc=ki;var Di=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=Ct(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=Ct(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),Ct.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})}},nc=Di;var Ti=class extends nc{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 zt(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))}},ic=Ti;function Dh(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 ac=Dh;var _i=class extends zt{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 Je({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=$r(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 ic({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=ac(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=t.constraint_date,d=this.calculationsOfParentThatImpactChildrens.get(r),u=D(this.gantt.getCalendar(t.calendar_id),d.lf,-t.duration,t);i=new Date(Math.min(l.getTime(),u.getTime())),a=D(this.gantt.getCalendar(t.calendar_id),i,t.duration,t)}if([y.FNLT].includes(t.constraint_type)){let l=t.constraint_date,d=this.calculationsOfParentThatImpactChildrens.get(r);i=new Date(Math.min(l.getTime(),d.lf.getTime())),a=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}},sc=_i;function oc(){return null}var cc=({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 Pi=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)})}},lc=Pi;var Ri=class{constructor(t){this.gantt=t.gantt,this.activity=t.activity,this.forwardMap=t.forwardMap,this.backwardMap=t.backwardMap,this.projectDates=t.projectDates,this.linksFreeFloatArray=[],this.linksFreeFloatObject={},this.durationCache=new Map}getFreeFloat(){let t=Number(this.activity.progress),r=this.getConstraintType();return this.calculateFreeFloatOfLink(r),{activityFreeFloat:t===100?0:this.getFreeFloatBaseConstraint(r),linksFreeFloat:this.linksFreeFloatObject}}getFreeFloatBaseConstraint(t){return t===y.MSO||t===y.MFO?this.calculateMsoMfo(t):this.calculateGeneral(t)}calculateFreeFloatOfLink(t=y.ASAP){let r=this.activity.$source.map(n=>{let{LINK:i,LINK_TYPE:a}=this.getLinkData(n),s=this.gantt.getTask(i.target);if(!s)return{linkId:i.id,freeFloat:null,hasProgress:!1};let o=Number(s.progress)>0,{sucessorDateToCalculate:c,predecessorDateToCalculate:l}=this.getDatesFromSucessorAndPredecessor(a,t,s),d=this.calculationWithCalendar(c,l),u=this.parseHoursToDays(d)-this.parseHoursToDays(i.lag),f=Math.max(0,u);return this.linksFreeFloatObject[i.id]=f,{linkId:i.id,freeFloat:f,hasProgress:o}}).filter(n=>n.freeFloat!==null&&n.freeFloat!==void 0);return this.linksFreeFloatArray=r,r}calculateGeneral(t=y.ASAP){let r=this.getMinFloat(this.linksFreeFloatArray),n=this.calculateFreeFloatForEndOfProject(t),i=0;return[y.SNLT,y.FNLT].includes(t)?i=this.doCalculationForSnltFnlt(t,n,r):i=this.doGeneralCalculation(n,r),Math.max(0,i)}getConstraintType(){let{constraint_type:t}=this.activity;return t||(t=y.ASAP),t}getDatesFromSucessorAndPredecessor(t,r,n){let i=n.constraint_type===y.ALAP,a=this.getSucessorAndPredecessorDates({constraint:r,isSuscessorAlap:i,sucessorId:n.id,predecessorId:this.activity.id}),s=new Date,o=new Date;return s=a[t].sucessor,o=a[t].predecessor,{sucessorDateToCalculate:s,predecessorDateToCalculate:o}}doGeneralCalculation(t,r){return r===null?t:this.getMinValue(r,t)}doCalculationForSnltFnlt(t,r,n){let i=this.calculateFreeFloatOfRestriction(t);return this.getMinValue(n,r,i)}calculateFreeFloatForEndOfProject(t){return this.parseHoursToDays(this.calculationWithCalendar(this.gantt.getSubtaskDates().end_date,t===y.ALAP?this.backwardMap.get(this.activity.id).lf:this.forwardMap.get(this.activity.id).ef))}calculateFreeFloatOfRestriction(t){return this.parseHoursToDays(this.calculationWithCalendar(this.activity.constraint_date,t===y.FNLT?this.forwardMap.get(this.activity.id).ef:this.forwardMap.get(this.activity.id).es))}getLinkData(t){let r=this.gantt.getLink(t)||{},n=ne(r.type);return{LINK:r,LINK_TYPE:n}}getSucessorAndPredecessorDates({constraint:t,isSuscessorAlap:r,sucessorId:n,predecessorId:i}){let a=({direction:s,constraint:o=y.ASAP})=>o===y.ALAP?this.backwardMap.get(i)[s]:this.forwardMap.get(i)[s];if(t===y.ASAP||t===y.SNET||t===y.FNET||t===y.MSO||t===y.MFO)return{fs:{sucessor:r?this.backwardMap.get(n).ls:this.forwardMap.get(n).es,predecessor:a({direction:"ef"})},ss:{sucessor:r?this.backwardMap.get(n).ls:this.forwardMap.get(n).es,predecessor:a({direction:"es"})},ff:{sucessor:r?this.backwardMap.get(n).lf:this.forwardMap.get(n).ef,predecessor:a({direction:"ef"})},sf:{sucessor:r?this.backwardMap.get(n).lf:this.forwardMap.get(n).ef,predecessor:a({direction:"es"})}};if(t===y.ALAP)return{fs:{sucessor:r?this.backwardMap.get(n).ls:this.forwardMap.get(n).es,predecessor:a({constraint:y.ALAP,direction:"lf"})},ss:{sucessor:r?this.backwardMap.get(n).ls:this.forwardMap.get(n).es,predecessor:a({constraint:y.ALAP,direction:"ls"})},ff:{sucessor:r?this.backwardMap.get(n).lf:this.forwardMap.get(n).ef,predecessor:a({constraint:y.ALAP,direction:"lf"})},sf:{sucessor:r?this.backwardMap.get(n).lf:this.forwardMap.get(n).ef,predecessor:a({constraint:y.ALAP,direction:"ls"})}};if(t===y.SNLT)return{fs:{sucessor:r?this.backwardMap.get(n).ls:this.forwardMap.get(n).es,predecessor:a({direction:"ef"})},ss:{sucessor:r?this.backwardMap.get(n).ls:this.forwardMap.get(n).es,predecessor:a({direction:"es"})},ff:{sucessor:r?this.backwardMap.get(n).lf:this.forwardMap.get(n).ef,predecessor:a({direction:"ef"})},sf:{sucessor:r?this.backwardMap.get(n).lf:this.forwardMap.get(n).ef,predecessor:a({direction:"es"})}};if(t===y.FNLT)return{fs:{sucessor:r?this.backwardMap.get(n).ls:this.forwardMap.get(n).es,predecessor:a({direction:"ef"})},ss:{sucessor:r?this.backwardMap.get(n).ls:this.forwardMap.get(n).es,predecessor:a({direction:"es"})},ff:{sucessor:r?this.backwardMap.get(n).lf:this.forwardMap.get(n).ef,predecessor:a({direction:"ef"})},sf:{sucessor:r?this.backwardMap.get(n).lf:this.forwardMap.get(n).ef,predecessor:a({direction:"es"})}}}calculateMsoMfo(t){let r=this.activity.constraint_date||new Date,n=t===y.MSO?this.forwardMap.get(this.activity.id).es:this.forwardMap.get(this.activity.id).ef,i=this.calculationWithCalendar(r,n);return Math.max(0,this.parseHoursToDays(i))}getMinValue(...t){let r=t.filter(n=>n!=null);return r.length?Math.min(...r):0}calculationWithCalendar(t,r){let n=`${r.getTime()}_${t.getTime()}`;if(this.durationCache.has(n))return this.durationCache.get(n);let a=this.gantt.getCalendar(this.activity.calendar_id).calculateDuration({start_date:new Date(r),end_date:new Date(t)});return this.durationCache.set(n,a),a}parseHoursToDays(t){return t?t/this.gantt.config.hoursPerDay:0}getMinFloat(t){if(!t?.length)return null;let r=t.filter(n=>!n.hasProgress).map(n=>n.freeFloat);return r.length===0?null:Math.min(...r)}},dc=Ri;var uc=e=>({totalFloat:new lc(e.totalFloat).getTotalFloat(),freeFloat:new dc(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=cc({forward:t,backward:r,id:l,activity:d,gantt:n,projectDates:i}),{totalFloat:f,freeFloat:p}=uc(u);o.set(l,f),c.set(l,p),s=await qe(s)}return{totalFloatMap:o,freeFloatMap:c}};var bi=class{constructor(t){this.gantt=t,this.forwardPathCalculations=null,this.backwardPathCalculations=null,this.totalFloat=new Map,this.freeFloat=new Map,this.currentCalculationId=0}getCurrentCalculationId=()=>this.currentCalculationId;async calculate(t,r=()=>!0){let n=++this.currentCalculationId,i=Ii(n,this.getCurrentCalculationId),a=()=>i()&&r();try{let s=t||this.gantt;if(this.gantt=s||oc(),Si(this.gantt))return!1;let o=new rc(this.gantt);if(await o.calculateAsync(a),!a())return!1;let c=o.calculations,l=o.constraintsMap,d=new sc(this.gantt,c,l);if(await d.calculateAsync(a),!a())return!1;this.forwardPathCalculations=c,this.backwardPathCalculations=d.calculations;let{totalFloatMap:u,freeFloatMap:f}=await this.calculateFloatsAsync(o,d,a);return a()?(this.totalFloat=u,this.freeFloat=f,this.gantt.refreshData(),!0):!1}catch(s){throw this.forwardPathCalculations?.size,s}}async calculateFloatsAsync(t,r,n){try{let i=this.gantt.getSubtaskDates(),a=Array.from(this.forwardPathCalculations.keys());return await Ei({activityIds:a,forward:t,backward:r,gantt:this.gantt,projectDates:i,isCurrent:n})}catch(i){throw this.forwardPathCalculations?.size,i}}},fc=bi;var Th=e=>e==="fnet"||e==="fnlt"||e==="mfo",_h=e=>new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()));function Ph(e,t){let r=e.constraintDate;if(!r||!Th(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()?Vn(e,t):r}function Rh(e){let t=new Map,r=new Map,n=new Map;return{calculateEndDate:({start_date:i,duration:a})=>{let s=`${i.getTime()}|${a}`,o=t.get(s);if(o!==void 0)return new Date(o);let c=e.calculateEndDate(i,a);return t.set(s,c.getTime()),c},calculateDuration:({start_date:i,end_date:a})=>{let s=`${i.getTime()}|${a.getTime()}`,o=r.get(s);if(o!==void 0)return o;let c=e.calculateDuration(i,a);return r.set(s,c),c},getWorkHours:i=>e.getWorkHours(i),$gantt:{getClosestWorkTime:({date:i,dir:a,unit:s})=>{let o=s??"hour",c=`${i.getTime()}|${a}|${o}`,l=n.get(c);if(l!==void 0)return new Date(l);let d=e.getClosestWorkTime({date:i,direction:a,unit:o});return n.set(c,d.getTime()),d}}}}function Eh(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 bh(e){let t=Eh(e),r=new Map;return e.forEachActivity((n,i)=>{let a=String(i);r.set(a,{id:Number(i),parent:n.parentId===null?0:Number(n.parentId),$level:t.get(a)??0,$source:e.getOutgoingLinkIds(a),$target:e.getIncomingLinkIds(a),start_date:n.startDate,end_date:n.endDate,duration:n.durationHours,progress:n.progress,type:n.type,calendar_id:n.calendarId,constraint_type:n.constraintType,constraint_date:Ph(n,e)})}),r}function Lh(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 wh(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 pc(e,t){let r=new Map,n=c=>{let l=c==null?"__default__":String(c),d=r.get(l);if(d)return d;let u=e.calendarReader.getCalendar(String(c)),f=Rh(u);return r.set(l,f),f},i=wh(e);await Q();let a=bh(e);await Q();let s=[...a.values()].sort((c,l)=>(c.start_date?.getTime()??0)-(l.start_date?.getTime()??0));await Q();let o=Lh(a);return{fullyParsed:!0,config:{hoursPerDay:t},getTask:c=>a.get(String(c))??null,getLink:c=>{let l=e.getLink(c);return l?{...l,source:Number(l.source),target:Number(l.target),lag:l.lag}:null},getCalendar:n,getChildren:c=>e.getChildren(c).map(l=>Number(l)),eachTask:c=>{for(let l of o)c(l)},getTaskByTime:()=>s,getSubtaskDates:()=>i,refreshData:()=>{}}}var Oh=1e3;function xh(e,t,r){let n=o=>o==null?null:new Date(o),i=r.forward?.get(e),a=r.backward?.get(e),s=r.totalFloat.get(e)??null;return{criticalPath:{earlyStart:n(i?.es),earlyFinish:n(i?.ef),lateStart:n(a?.ls),lateFinish:n(a?.lf),totalSlackHours:s},isCritical:t<100&&s!=null&&s<=0,freeSlackHours:r.freeFloat.get(e)?.activityFreeFloat??null}}var qr=(e,t)=>e===t||e!==null&&t!==null&&e.getTime()===t.getTime();function Li(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)}async function wi(e,t,r=()=>!0){if(!r())return null;let n=await pc(e,t);if(!r())return null;let i=new fc(n);if(!await i.calculate(n,r)){if(!r())return null;throw new Error("critical path calculation aborted")}if(!r())return null;let s={forward:i.forwardPathCalculations,backward:i.backwardPathCalculations,totalFloat:i.totalFloat,freeFloat:i.freeFloat},o=new Set([...s.forward?.keys()??[]]),c=new Map,l=0;for(let d of o){if(++l>=Oh&&(l=0,await Q(),!r()))return null;let u=e.getActivity(d);if(!u)continue;let f=Number(u.progress??0);c.set(d,xh(d,f,s))}return r()?c:null}async function Jr(e,t,r=()=>!0){let n=await wi(e,t,r);if(!n||!r())return!1;for(let[i,a]of n){if(!r())return!1;Li(e,i,a)}return!0}function Pe(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=dt(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 hc=new Set;var yc=new Set(["activity-outdent","activity-indent"]);var Xe=new Set([_.TEXT,_.DESCRIPTION,_.COST,_.USED_COST,_.CUSTOM_ID,_.RESPONSABLES,_.SUBCONTRACT_ID,_.TAGS]),Nh=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"]),Fh=new Set(["activity-clipboard-clear","activity-copy","selection-toggle","selection-replace","visibility-set","filter-set","sort-set"]);function gc(e){return!Fh.has(e.kind)}var Mh=new Set;function Wh(e){return e.kind==="inline-edit"?Xe.has(e.column):e.kind==="bulk-edit"?e.edits.every(t=>Xe.has(t.column)):!1}function Oi(e,t){return!(Nh.has(e.kind)||t.has(e.kind)||Wh(e))}function xi(e){return Oi(e,Mh)}function ie(e){return Oi(e,hc)}function vc(e){return Oi(e,yc)}function Ni(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 Uh(e){return vc(e)&&Ni(e)}var mc=new Set([_.PROGRESS,_.HH_WORK_TIME,_.DURATION,_.COST,_.USED_COST,_.REAL_COST]);function Bh(e){return e.kind==="activity-set-progress"?!0:e.kind==="inline-edit"?mc.has(e.column):e.kind==="bulk-edit"?e.edits.some(t=>mc.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 Ac(e,t,r){let n=new Set;t.ran&&n.add(it.AUTOSCHEDULE),n.add(it.PARENT_BOUNDS),Bh(e)&&n.add(it.PARENT_PROGRESS),Ni(e)&&n.add(it.REAL_WORK);let i=!r.skipAutoSchedule;return i&&vc(e)&&n.add(it.EXPECTED_PROGRESS),i&&Uh(e)&&n.add(it.REAL_COST),i&&ie(e)&&!r.skipCriticalPath&&n.add(it.CRITICAL_PATH),n}async function $(e,t){let r=jh(t);r.has(it.AUTOSCHEDULE)&&await Kh(e.adapter,t);let n=r.has(it.AUTOSCHEDULE)?await Hh(e,t.autoscheduleFrom):Yh();return await Gh(e.adapter,t,n.scheduledIds,r),await $h(e,r,t.now),n}function jh(e){let t=e.autoscheduleFrom!==null,r=!e.options.skipAutoSchedule&&t,n=new Set(Ac(e.action,{requested:t,ran:r},e.options));return e.recomputeParentProgress&&n.add(it.PARENT_PROGRESS),n}async function Hh(e,t){let r=t==="roots"?{}:{triggerId:t},n=await e.scheduler.schedule(r),i=Vh(e.adapter,n.updatedIds);return Ue(e.adapter,n),i}function Vh(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 Yh(){return{scheduledIds:[]}}async function Kh(e,t){let r=t.collectDirty?t.collectDirty([]):li(t.recomputeParentsFrom,[]);r.size!==0&&await me(e,r,!1)}async function Gh(e,t,r,n){let i=t.collectDirty?t.collectDirty(r):li(t.recomputeParentsFrom,r);await me(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 $h(e,t,r){t.has(it.EXPECTED_PROGRESS)&&r!==null&&(zh(e.adapter)&&_e(e.adapter,r,e.defaultBaseCalendarId??null),re(e.adapter,r),Nt(e.adapter,e.sector.statusCriteria)),t.has(it.REAL_COST)&&Pe(e.adapter),t.has(it.CRITICAL_PATH)&&await Jr(e.adapter,e.sector.hoursPerDay)}function zh(e){let t=!1;return e.forEachActivity(r=>{dt(r)&&(t=!0)}),t}var qh=new Set([_.CONSTRAINT_TYPE,_.CONSTRAINT_DATE]),Jh=new Set(["mso","mfo"]);function Xr(e){return qh.has(e)}function Zr(e){return e===_.CONSTRAINT_DATE}function Qr(e,t,r,n){let i=r.getActivity(e);if(!i)return!1;let a=i.constraintType;if(!a||Vt.has(a)||Jh.has(a))return!1;let s=Fi(i.startDate),o=Fi(r.getLastStartDate(e));if(!o||!s||s.getTime()!==o.getTime())return!1;let c=Xh(t,a,String(i.calendarId??""),n),l=Fi(i.constraintDate);return Zh(l,c)?!1:(r.setActivityField(e,"constraintDate",c),!0)}function Xh(e,t,r,n){if(e===null)return null;let i=n.getCalendar(r);return i?Ot(e,i,t):e}function Fi(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 Zh(e,t){return e===null&&t===null?!0:e===null||t===null?!1:e.getTime()===t.getTime()}async function tn(e,{postMutationArgs:t,revertTargets:r,revert:n}){let{scheduledIds:i}=await $(e,Cc(t)),a=!1;for(let{activityId:s,priorConstraintDate:o}of r){let c=n(s,o);a=a||c}if(a){let s=await $(e,Cc(t));i=ty(i,s.scheduledIds)}return ie(t.action)&&await $(e,Qh(t)),{scheduledIds:i}}function Cc(e){return{...e,options:{...e.options,skipCriticalPath:!0}}}function Qh(e){return{action:e.action,autoscheduleFrom:null,recomputeParentsFrom:[],now:null,options:e.options}}function ty(e,t){let r=new Set(e);for(let n of t)r.add(n);return[...r]}function ey(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 Mi(e,t,r){let n=[];for(let i of r){let a=e.get(i);if(!a)continue;let s=a.pendingRequestIds??[];if(!ue({pendingRequestIds:s}))continue;let o=t.getActivity(i),c=o==null;if(!c&&!ey(a,o))continue;let l=c?"activity_deleted":"date_changed";for(let d of s)n.push({kind:"sir-auto-reject",activityId:i,sirId:d,reason:l});c||t.setActivityField(i,"pendingRequestIds",[])}return n}async function U(e,t){let r=ny(e,t),n=new Map(t.beforeSnap),i=e.peekWriteCapture();if(i){let u=ay(i);iy(e,i,u,n,r)}let a=t.preview===!0?void 0:t.sirDetection,s=a==="before-diff"?Mi(n,e,r):[],o=ry(t.correlativeShifts,r),c=await Uo(e,n,r,o),l=a==="after-diff"?Mi(n,e,r):s,d=t.warnings??[];return{source:t.source,activities:c,links:t.links??[],calendars:[],trackingEvents:t.trackingEvents??[],...l.length>0?{effects:l}:{},...d.length>0?{warnings:d}:{}}}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 ny(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 iy(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(ci(s,o)).length!==0&&(n.set(a,s),i.add(a))}}function ay(e){return new Set(e.ops.filter(t=>t.kind==="insert").map(t=>t.activityId))}function ut(e){let t={id:String(e.id),source:String(e.source),target:String(e.target),type:e.type,lag:Number(e.lag)};return e.proplannerId!=null&&(t.proplannerId=Number(e.proplannerId)),e.ganttId!=null&&(t.ganttId=Number(e.ganttId)),e.sectorId!=null&&(t.sectorId=Number(e.sectorId)),t}function Re(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:ut(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:ut(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:ut(c)})}return n}function Ee(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 be(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:ut(a)})}return n}function en(e,t){typeof e=="string"&&e.length>0&&t.releaseCustomId(e)}async function Ic(e,t,r){let{adapter:n,ctx:i,scheduler:a,sector:s}=r,o=Kt(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,F=typeof R=="string"?R:null;if(r.customIdTracker.isCustomIdInUse(String(d.value),F))return{ok:!1,reason:S.CUSTOM_ID_DUPLICATE}}let p=o.transform(c,d.value,i,d.raw),h=Gt(e.activityId,p),v=await G(n,h),I=Ee(n,String(e.activityId)),T=c.constraintDate;$t(n,e.activityId,p),jt(e.activityId,p.postProcessors??[],n,v.get(String(e.activityId))??null);let g=be(I,n,String(e.activityId));if(e.column===_.CUSTOM_ID){let C=v.get(String(e.activityId)),R=C?C.customId:null,F=typeof R=="string"?R:null,O=typeof d.value=="string"?d.value:null;F!==O&&r.customIdTracker.trackCustomIdChange(F,O)}let k=()=>({action:e,autoscheduleFrom:p.needsAutoSchedule?String(e.activityId):null,recomputeParentsFrom:[],collectDirty:C=>Yr(e.activityId,h,C),now:r.now,options:t}),m=Xr(e.column),{scheduledIds:P}=await(m?tn({adapter:n,scheduler:a,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{postMutationArgs:k(),revertTargets:Zr(e.column)?[]:[{activityId:e.activityId,priorConstraintDate:T}],revert:(C,R)=>Qr(C,R,n,i.calendars)}):$({adapter:n,scheduler:a,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},k())),L=(p.trackingEvents??[]).map(C=>({name:C.name,properties:C.properties??{}})),A=ke(e.activityId,p.constraintWarning);return{ok:!0,changes:await U(n,{source:e,beforeSnap:v,touchedIds:h,scheduledIds:P,sirDetection:"before-diff",preview:t.preview,links:g,trackingEvents:L,...A?{warnings:[A]}:{},hoursPerDay:s.hoursPerDay})}}function sy(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=Ut(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 cy(e){return new Map([...e].map(([t,r])=>[String(t),r]))}async function Sc(e,t,r){if(e.kind==="link-create"||e.kind==="link-update"){let n=e.type;if(n!==void 0&&!Object.values(M).some(a=>a===n))return{ok:!1,reason:S.INVALID_LINK_TYPE};let i=e.lag;if(i!==void 0&&!Number.isFinite(i))return{ok:!1,reason:S.INVALID_LINK_LAG}}return Wi([py(e,r.sector.hoursPerDay)],e,t,r,e.kind==="link-create"&&e.linkId?new Map([[0,e.linkId]]):void 0)}async function kc(e,t,r){let{hoursPerDay:n}=r.sector,i=e.operations.map(s=>dy(s,n)),a=ly(e.operations);return Wi(i,e,t,r,a)}function ly(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 dy(e,t){return e.kind==="create"?{kind:"create",source:e.source,target:e.target,type:e.type,lag:At(e.lag??0,t)}:e.kind==="update"?{kind:"update",linkId:e.linkId,type:e.type,lag:e.lag===void 0?void 0:At(e.lag,t)}:{kind:"delete",linkId:e.linkId}}async function Wi(e,t,r,n,i){let{adapter:a,scheduler:s,sector:o,linkIdGen:c}=n;s.invalidateAllCaches();let{activityIds:l,links:d}=sy(e,a),u=await G(a,l),f=oy(e,a,c,i);if(e.length===1&&f[0]&&f[0].rejected!==null&&t.kind!=="inline-edit")return{ok:!1,reason:f[0].rejected};let p=uy(f,d,a),{scheduledIds:h}=await $({adapter:a,scheduler:s,sector:n.sector,defaultBaseCalendarId:n.defaultBaseCalendarId},{action:t,autoscheduleFrom:p,recomputeParentsFrom:l,now:n.now,options:r}),v=Re(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:cy(d),changes:await U(a,{source:t,beforeSnap:u,touchedIds:l,scheduledIds:h,links:v,hoursPerDay:o.hoursPerDay})}}function uy(e,t,r){for(let n of e){if(n.rejected!==null)continue;let i=fy(n.op,t,r);if(i!==null)return r.hasChildren(i)?"roots":String(i)}return null}function fy(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 py(e,t){return e.kind==="link-create"?{kind:"create",source:e.source,target:e.target,type:e.type,lag:At(e.lag,t)}:e.kind==="link-update"?{kind:"update",linkId:e.linkId,type:e.type,lag:e.lag===void 0?void 0:At(e.lag,t)}:{kind:"delete",linkId:e.linkId}}async function Dc(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}=_r(e.newValue),c=o.map(h=>({...h,lag:At(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 v=n.getLink(h);v&&f.push(v)}let p=s?Rr({targetActivityId:e.activityId,currentLinks:f,desiredSpecs:c,resolveActivityByCorrelative:d}):Er({sourceActivityId:e.activityId,currentLinks:f,desiredSpecs:c,resolveActivityByCorrelative:d});return Wi(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=>{b(a.parentId)&&t.push(a)}),t.sort(Pc);let r=[];Tc(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),hy(a,i)}i+=1;let s=Ne(String(a.id),e);s.sort(Pc),Tc(r,s)}return n}function Tc(e,t){for(let r=t.length-1;r>=0;r-=1)e.push(t[r])}function _c(e){let t=e.correlativeId,r=typeof t=="number"?t:Number(t);return Number.isFinite(r)?r:Un}var Pc=(e,t)=>_c(e)-_c(t);function hy(e,t){e.correlativeId=t}function Bi(e,t){if(!e||e==="0")return;let r=String(e);for(;r!==null;){let n=t.getChildren(r),i=0,a=0;for(let c of n){let l=t.getActivity(c);if(!l)continue;let d=Ui(l,E.WORK_HOURS),u=yy(c,l,d,t);i+=d,a+=u}t.setActivityField(r,E.WORK_HOURS,i),t.setActivityField(r,E.REAL_WORK_HOURS,a);let s=t.getActivity(r);if(!s)break;let o=s.parentId;if(!o||b(o))break;r=o}}function Rc(e,t){let r=t.getActivity(e);if(!r)return;let n=r.parentId;!n||b(n)||Bi(n,t)}function Ui(e,t){let r=e[t];return typeof r=="number"&&Number.isFinite(r)?r:0}function yy(e,t,r,n){return n.hasChildren(e)?Ui(t,E.REAL_WORK_HOURS):ht(r,Ui(t,E.PROGRESS))}function ji(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+=my(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||b(s))break;r=s}}function Ec(e,t){let r=t.getActivity(e);if(!r)return;let n=r.parentId;!n||b(n)||ji(n,t)}function my(e,t){let r=e[t];return typeof r=="number"&&Number.isFinite(r)?r:0}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+=gy(c,E.COST))}t.setActivityField(r,E.COST,i);let a=t.getActivity(r);if(!a)break;let s=a.parentId;if(!s||b(s))break;r=s}}function bc(e,t){let r=t.getActivity(e);if(!r)return;let n=r.parentId;!n||b(n)||Hi(n,t)}function gy(e,t){let r=e[t];return typeof r=="number"&&Number.isFinite(r)?r:0}var rn=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}),Lc="New Master Plan",wc="New Activity";var vy=["name","description","type","startDate","durationHours","constraintType","constraintDate","calendarId","assignedDefaultCalendar","autoScheduling","progress","cost","usedCost","realCost","workHours","realWorkHours","ponderator","hasCustomPonderator","customId","subcontractId","responsableIds","tagIds","isLookahead"],Oc=new Set(vy);function Ay(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"||!Oc.has(r))throw new Error(`activity-create: rejected override key "${String(r)}" \u2014 not a creation-writable canonical field`);return e}function xc(e,t){let r=e.parentId!=null?t.getActivity(e.parentId):null,n=Ay(e.activityOverrides??{}),i=e.numTasksInGantt===0?Lc:wc,a=n.name??i,s=n.durationHours??e.sector.hoursPerDay,o=n.calendarId??e.sector.defaultCalendar,c=Cy(r,e.fallbackStartDate,n.startDate),l={...rn,...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&&Lt(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:Rt({type:l.type,startDate:d,endDate:u}),newActivityIds:[...l.newActivityIds],pendingRequestIds:[...l.pendingRequestIds],responsableIds:[...l.responsableIds],tagIds:[...l.tagIds],baselinePoints:[...l.baselinePoints]}}}function Cy(e,t,r){return r?new Date(r):e?new Date(e.startDate):t?new Date(t):new Date}function Iy(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 Le(e){let t=e.getParent(e.parentId);if(!t)return null;let r=e.isCurrentlyLeaf!==void 0?e.isCurrentlyLeaf&&Wt(t.type):Sy(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=zn,(e.promotionSource??"create")==="create"&&(a.constraintType=K.ASAP,a.constraintDate=null,a.progress=0)),{parentId:e.parentId,fields:a,promotionSnapshot:Iy(t)}}function Sy(e){return Wt(e.type)&&(!Array.isArray(e.newActivityIds)||e.newActivityIds.length===0)}function nn(e,t,r,n){let i=t,a=i==="0",s=Vi(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 ae=Number.MAX_SAFE_INTEGER,Nc=Number.MAX_SAFE_INTEGER-1;function st(e){let t=e.correlativeId,r=typeof t=="number"?t:Number(t);return Number.isFinite(r)?r:ae}function Vi(e,t){return Ne(t,e)}function Fc(e,t,r){let n=e,i=qt(e,r);for(;i!=null&&t.has(i);)n=i,i=qt(i,r);return n}function an(e,t,r){let n=new Set([e]),i=Mt(r.getActivity(e)?.parentId);for(;i!=="0"&&!n.has(i);){if(t.has(i))return!0;n.add(i),i=Mt(r.getActivity(i)?.parentId)}return!1}function qt(e,t){let r=t.getActivity(e);if(!r)return null;let n=Mt(r.parentId),i=vt(n,t),a=i.findIndex(s=>String(s)===String(e));return a<=0?null:i[a-1]??null}function Mc(e,t,r,n){let i=vt(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}async function Ze(e,t,r={}){let{adapter:n,scheduler:i,sector:a,calendars:s,activityIdGen:o,uidGen:c}=t;r.skipCacheInvalidation||i.invalidateAllCaches();let l=ky(e,n);if(!l.ok)return l;let{parent:d,anchorSiblingId:u,isRoot:f}=l,p=Ty(e.activityId,n,o),h=c.next(),v={id:p,parentId:f?null:e.parentId,sector:{id:a.id,hoursPerDay:a.hoursPerDay,defaultCalendar:Ly(s)},numTasksInGantt:n.activityCount(),nextUniqueCorrelativeId:h,activityOverrides:e.overrides??{}},T=xc(v,{getActivity:A=>n.getActivity(A),calculateEndDate:A=>n.calculateEndDate(A),getClosestWorkTime:A=>n.getClosestWorkTime(A)}).newTask;T.realWorkHours=ht(T.workHours,T.progress),Py(T,e,t,u,d,r);let g=r.insertionCorrelativeId??nn(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,L=r.skipBeforeSnap?new Map:await G(n,k);return n.addActivity(T),Ry(e,p,d,n,m),P&&t.customIdTracker.releaseCustomId(P),r.skipRollupCascades||(Rc(p,n),Ec(p,n),bc(p,n)),Ey(n,p,L,k,r),{ok:!0,newId:p,parent:d,newActivity:T,beforeSnap:L,initialTouched:k}}function ky(e,t){let r=b(e.parentId),n=r?null:t.getActivity(e.parentId);if(!r&&!n)return{ok:!1,reason:S.PARENT_NOT_FOUND};if(n!==null&&ue(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=Dy(e,t,r,s);return o||{ok:!0,parent:n,anchorSiblingId:s,isRoot:r}}function Dy(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 Ty(e,t,r){return e===void 0||t.activityExists(e)?r.next():(r.bump(e),e)}function _y(e){let t=e.overrides?.customId;return typeof t=="string"?t:void 0}function Py(e,t,r,n,i,a){let{adapter:s,customIdTracker:o}=r,c=_y(t);if(c!==void 0){if(c.length===0)return;if(!o.isCustomIdInUse(c)){o.registerCustomId(c);return}}let l=a.customIdReferenceId??n,d=l!==void 0,u=d?s.getActivity(l):i;e.customId=o.generateCustomIdForNewChild({activity:u??{},useActivityCustomIdAsReference:d})}function Ry(e,t,r,n,i){if(!r)return;let a=Le({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 Ey(e,t,r,n,i){if(i.skipCorrelativeRecompute)return;let a=at(e);i.skipBeforeSnap||De(e,a,new Set([String(t)]),r,n)}async function by(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),U(e,{source:t,beforeSnap:o,touchedIds:c,scheduledIds:n,trackingEvents:[l],hoursPerDay:i})}async function Wc(e,t,r){let{adapter:n,scheduler:i,sector:a}=r,s=await Ze(e,r);if(!s.ok)return s;let{newId:o}=s,c=s.newActivity.autoScheduling;n.setActivityField(o,"autoScheduling",!1);let l;try{l=await $({adapter:n,scheduler:i,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:"roots",recomputeParentsFrom:[o],now:r.now,options:t})}finally{n.setActivityField(o,"autoScheduling",c)}let{scheduledIds:d}=l;return{ok:!0,changes:await by(n,e,s,d,a.hoursPerDay)}}function Ly(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 mt(e,t){Bi(e,t),ji(e,t),Hi(e,t)}function Uc(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 Bc(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 wy(e){return e?{type:e.type,startDate:new Date(e.startDate),endDate:new Date(e.endDate),durationHours:e.durationHours,expectedProgressBaseline:e.expectedProgressBaseline,constraintType:e.constraintType,constraintDate:e.constraintDate?new Date(e.constraintDate):null,progress:e.progress}:null}function Oy(e,t,r){let n=e.startDate;return!r||!(n instanceof Date)?{}:{endDate:r(n,t)}}function we(e){if(e.remainingChildIds.length>0)return null;let t=e.parent,r=e.defaultDurationHours,n=Number.isFinite(r),i=wy(e.promotionSnapshot)??(n?{type:pe,durationHours:r,progress:0,autoScheduling:!0,constraintType:"asap",constraintDate:null,hasNewActivities:!1,...Oy(t,r,e.computeEndDate)}:{type:pe});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 jc(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 Hc=200;async function Vc(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 A of e.activityIds)if(!n.getActivity(A))return{ok:!1,reason:S.ACTIVITY_NOT_FOUND};let o=Uc(e.activityIds,n),c=Bc(o,n),l=new Set;for(let A of e.activityIds){let C=n.getActivity(A);if(!C)continue;let R=C.parentId;if(b(R))continue;let F=String(R);o.has(F)||l.add(F)}let d=new Set([...o,...l]),u=await G(n,d),f=new Map;for(let A of c){let C=n.getLink(A);C&&f.set(A,{...C})}let p=new Set,h=0;for(let A of o){h+=1,h%Hc===0&&await Q();let C=n.getActivity(A);if(!C)continue;let R=b(C.parentId)?null:n.getActivity(String(C.parentId)),F=R?.hasNewActivities===!0&&R.newActivityIds.some(q=>String(q)===String(A));(C.isNewActivity===!0||F)&&p.add(A);let O=C.customId;typeof O=="string"&&O.length>0&&a.releaseCustomId(O)}for(let A of c)n.removeLink(A);let v=Yi(n,o),I=0;for(let A of o)I+=1,I%Hc===0&&await Q(),n.removeActivity(A);for(let A of l){let C=n.getActivity(A);if(!C)continue;xy(C,p,n);let R=n.getChildren(A),F=we({parent:C,remainingChildIds:R.map(String),defaultDurationHours:s.hoursPerDay,promotionSnapshot:n.getPromotionSnapshot(A),computeEndDate:(O,q)=>n.calculateEndDate({startDate:O,durationHours:q,task:C}),idsRemoved:o});if(!F){Or(A,n);continue}for(let[O,q]of Object.entries(F.fields))rt(n,A,O,q);if(C.customId==null||C.customId===""){let O=qt(A,n),q=O?n.getActivity(O)?.customId:null,Z=a.generateCustomIdForRestoredChild(typeof q=="string"&&q?q:null);n.setActivityField(A,E.CUSTOM_ID,Z)}}for(let A of l)mt(A,n);let T=at(n),{scheduledIds:g}=await $({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[A,C]of f)m.set(A,C);let P=new Map;for(let A of o){let C=u.get(String(A));C&&P.set(String(A),C)}let L=await U(n,{source:e,beforeSnap:u,touchedIds:d,scheduledIds:g,sirDetection:"after-diff",preview:t.preview,links:Ny(f),trackingEvents:[k],hoursPerDay:s.hoursPerDay,correlativeShifts:T});return{ok:!0,changes:v.length>0?{...L,viewState:v}:L,__beforeSnap:P,__beforeLinks:m}}function xy(e,t,r){let n=jc({parent:e,idsRemoved:t});if(n)for(let[i,a]of Object.entries(n.fields))rt(r,n.parentId,i,a)}function Yi(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 Ny(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 Gc(e,t,r){let n=Fy(e,r);if(n)return{ok:!1,reason:n};let i=Wy(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 G(r.adapter,a):new Map,o=e.mode==="replace"?Hy(r):new Map,c=e.mode==="replace"?Yi(r.adapter,a):[];r.scheduler.invalidateAllCaches();let l=[];if(e.mode==="replace"){for(let m of o.keys()){let P=Ut({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 jy(e,i.plan.items,r);if(!d.ok)return d;let u=$c(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;De(r.adapter,u,f,s,h);for(let m of i.plan.items)h.add(String(m.activityId));let v=i.plan.links.map(m=>({operation:{kind:"create",source:m.source,target:m.target,type:m.type,lag:t.inputUnit==="hours"?m.lag:At(m.lag,r.sector.hoursPerDay)},linkId:m.linkId})),I=Tr(v,{port:r.adapter,preserved:o});if(!I.applied)return{ok:!1,reason:I.rejected??S.INVALID};for(let{operation:m,linkId:P}of v)l.push({op:m,finalLinkId:P,rejected:null});let T=i.plan.items.map(m=>m.activityId),{scheduledIds:g}=await $({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 U(r.adapter,{source:e,beforeSnap:s,touchedIds:h,scheduledIds:g,links:Re(l,o,r.adapter),hoursPerDay:r.sector.hoursPerDay,correlativeShifts:p,preview:t.preview,...e.mode==="replace"?{sirDetection:"after-diff"}:{}});return{ok:!0,changes:c.length>0?{...k,viewState:c}:k,...e.mode==="replace"?{__beforeSnap:s,__beforeLinks:Vy(o)}:{}}}function Fy(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)||e.mode==="append"&&t.adapter.getActivity(s)!==null)return S.INVALID;n.add(s)}}for(let a of e.items)if(!Ki(a.parent,!0,e.mode,r,t))return S.PARENT_NOT_FOUND;if(My(e.items))return S.INVALID;let i=new Set;for(let a of e.links){if(!Object.values(M).includes(a.type)||!Number.isFinite(a.lag))return Number.isFinite(a.lag)?S.INVALID_LINK_TYPE:S.INVALID_LINK_LAG;if(!Ki(a.source,!1,e.mode,r,t)||!Ki(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)||e.mode==="append"&&t.adapter.getLink(s)!==null)return S.INVALID;i.add(s)}}return null}function Ki(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 My(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 Wy(e,t){for(let o of e.items)o.activityId!==void 0&&t.activityIdGen.bump(o.activityId);let r=new Map;for(let o of e.items)r.set(o.batchId,o.activityId??t.activityIdGen.next());for(let o of e.links)o.linkId!==void 0&&t.linkIdGen.bump(o.linkId);let n=e.links.map(o=>o.linkId??t.linkIdGen.next()),i=Uy(e,r,t),a=[];for(let o of e.items){let c=r.get(o.batchId),l=i.get(o.batchId);if(c===void 0||l===void 0)return{ok:!1,reason:S.INVALID};let d=typeof o.parent=="string"?null:o.parent.batchId,u=typeof o.parent=="string"?o.parent:r.get(o.parent.batchId);if(u===void 0)return{ok:!1,reason:S.PARENT_NOT_FOUND};a.push({input:o,activityId:c,parentId:u,parentBatchId:d,insertionCorrelativeId:l})}let s=[];for(let[o,c]of e.links.entries()){let l=Kc(c.source,r),d=Kc(c.target,r),u=n[o];if(l===null||d===null||u===void 0)return{ok:!1,reason:S.ACTIVITY_NOT_FOUND};s.push({source:l,target:d,type:c.type,lag:c.lag,linkId:u})}return{ok:!0,plan:{items:a,links:s}}}function Uy(e,t,r){if($c(e)){let o=r.adapter.activityCount();return new Map(e.items.map((c,l)=>[c.batchId,o+l]))}let n=new Set(Array.from(t.values(),o=>String(o))),i=new Map;for(let o of e.items){let c=t.get(o.batchId);if(c===void 0)continue;let l=typeof o.parent=="string"?o.parent:t.get(o.parent.batchId);if(l===void 0)continue;let d=String(l),u=i.get(d);u||(u={existing:e.mode==="replace"||typeof o.parent!="string"&&t.has(o.parent.batchId)?[]:Vi(r.adapter,d).sort((v,I)=>st(v)-st(I)||String(v.id).localeCompare(String(I.id))).map(v=>String(v.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?Yc(c[d-1],r):null,p=l<c.length?Yc(c[l],r):null;for(let h=0;h<u;h+=1){let v=c[d+h],I=s.get(v);I!==void 0&&a.set(I,By(f,p,h+1,u))}}}return a}function $c(e){return e.mode==="append"&&e.items.every(t=>t.parent==="0"&&t.index===void 0)}function Yc(e,t){let r=t.adapter.getActivity(e);return r?st(r):0}function By(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 jy(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 Ze({kind:"activity-create",parentId:o.parentId,activityId:o.activityId,...o.input.overrides===void 0?{}:{overrides:o.input.overrides},...e.eventSource===void 0?{}:{eventSource:e.eventSource}},r,{skipCorrelativeRecompute:!0,skipBeforeSnap:!0,skipCacheInvalidation:!0,skipRollupCascades:!0,insertionCorrelativeId:o.insertionCorrelativeId});if(!c.ok)return c;for(let l of n.get(o.input.batchId)??[])i.push(l)}if(i.length!==t.length)return{ok:!1,reason: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)),mt(o,r.adapter))}return{ok:!0}}function Kc(e,t){return typeof e=="string"?e:t.get(e.batchId)??null}function Hy(e){return new Map(e.adapter.getAllLinks().map(t=>[String(t.id),{...t}]))}function Vy(e){return new Map(Array.from(e,([t,r])=>[String(t),r]))}function zc(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:z(o)};return{ok:!0,changes:{source:e,activities:[c],links:[],calendars:[],trackingEvents:[]}}}var Gi=_.CUSTOM_ID;async function sn(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=[],v=!1;for(let k of e.edits){let m=Yy(k,r);if(o.push(m.verdict),!m.verdict.ok||!m.changes)continue;let P=ke(k.activityId,m.changes.constraintWarning);P&&h.push(P);let L=Gt(k.activityId,m.changes);zy(c,L,r);for(let O of L)u.add(O);$y(l,k,c),Zr(k.column)&&d.add(String(k.activityId));let A=Ee(n,k.activityId),C=Vr(n,String(k.activityId)),R=Ky(k,r),F=m.changes;$t(n,k.activityId,F),jt(k.activityId,m.changes.postProcessors??[],n,C),Gy(k,R,r),p.push(...be(A,n,k.activityId)),v||=!!m.changes.needsAutoSchedule;for(let O of m.changes.trackingEvents??[])f.push({name:O.name,properties:O.properties??{}})}let I={action:e,autoscheduleFrom:v?"roots":null,recomputeParentsFrom:u,now:r.now,options:t},T=l.size>0,{scheduledIds:g}=await(T?tn({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)=>Qr(k,m,n,r.ctx.calendars)}):$({adapter:n,scheduler:i,sector:a,defaultBaseCalendarId:r.defaultBaseCalendarId},I));return{ok:!0,verdicts:o,changes:await U(n,{source:e,beforeSnap:c,touchedIds:u,scheduledIds:g,sirDetection:"before-diff",preview:t.preview,links:p,trackingEvents:f,warnings:h,hoursPerDay:a.hoursPerDay})}}function Yy(e,t){let{ctx:r}=t,n=e.activityId,i=Kt(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===Gi&&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 Ky(e,t){if(e.column!==Gi)return null;let r=t.adapter.getActivity(e.activityId),n=r?r.customId:null;return typeof n=="string"?n:null}function Gy(e,t,r){if(e.column!==Gi)return;let n=r.adapter.getActivity(e.activityId),i=n?n.customId:null,a=typeof i=="string"?i:null;t!==a&&r.customIdTracker.trackCustomIdChange(t,a)}function $y(e,t,r){if(!Xr(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 zy(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,z(a))}}async function qc(e,t,r){let{adapter:n}=r,i=n.getActivity(e.activityId);if(!i)return{ok:!1,reason:S.ACTIVITY_NOT_FOUND};let a=i.pendingRequestIds??[];if(!a.includes(e.approvedRequestId))return{ok:!1,reason:S.SIR_REQUEST_NOT_PENDING};let s=a.filter(l=>l!==e.approvedRequestId);n.setActivityField(e.activityId,"pendingRequestIds",s);let o=await sn({kind:"bulk-edit",edits:[{activityId:e.activityId,column:_.START_DATE,newValue:e.startDate},{activityId:e.activityId,column:_.END_DATE,newValue:e.endDate},{activityId:e.activityId,column:_.CONSTRAINT_TYPE,newValue:"asap"}],eventSource:e.eventSource},t,r);if(!o.ok)return o;let c="verdicts"in o?o.verdicts.find(l=>!l.ok&&l.reason!==Fr.UNCHANGED):void 0;return c?{ok:!1,reason:c.reason}:{...o,changes:{...o.changes,source:e}}}function Jc(e,t){let r=[...new Set(e.activityIds.map(String))],n=r.map(a=>t.adapter.getActivity(a));if(n.some(a=>!a))return{ok:!1,reason:S.ACTIVITY_NOT_FOUND};let i=[];for(let[a,s]of r.entries()){let o=n[a];if(!o)continue;let c={};o.isLookahead!==e.isLookahead&&(c.isLookahead={before:o.isLookahead,after:e.isLookahead},t.adapter.setActivityField(s,"isLookahead",e.isLookahead)),o.hasLookaheadTasks!==e.hasLookaheadTasks&&(c.hasLookaheadTasks={before:o.hasLookaheadTasks,after:e.hasLookaheadTasks},t.adapter.setActivityField(s,"hasLookaheadTasks",e.hasLookaheadTasks)),Object.keys(c).length!==0&&i.push({id:s,kind:"updated",fields:c,after:{...o,isLookahead:e.isLookahead,hasLookaheadTasks:e.hasLookaheadTasks}})}return{ok:!0,changes:{source:e,activities:i,links:[],calendars:[],trackingEvents:[]}}}function on(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)||(Xc(s,a,t)||Xc(a,s,t))&&n.push(String(i.id))}return n}function Xc(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||b(s))return!1;let o=s;if(o===t)return!0;n=o}return!1}function cn(e,t){let r=e.getAllLinks();return!He({port:e,currentLinks:r,proposedLinks:r,proposal:{reparented:t}}).ok}function ln(e,t){let r=new Set;if(e.length===0)return r;let n=new Map(e.map(a=>[a.activityId,a.newParentId]));if(!cn(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),cn(t,s)){r.add(a.activityId);continue}i.set(a.activityId,a.newParentId)}return r}async function Zc(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=b(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=Mt(l),u=String(e.parentId),f=d!==u;if(f){let P=new Map([[e.activityId,o?null:e.parentId]]);if(cn(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 G(n,p);f&&n.setActivityField(e.activityId,E.PARENT,u);let v=nn(n,e.parentId,e.afterSiblingId,e.beforeSiblingId);if(n.setActivityField(e.activityId,E.CORRELATIVE_ID,v),f){if(!o){let P=n.getActivity(e.parentId);if(P){let L=P.customId,A=Wt(P.type)&&n.getChildren(e.parentId).filter(R=>R!==e.activityId).length===0,C=Le({parentId:e.parentId,newChildId:e.activityId,getParent:R=>n.getActivity(R)??null,isCurrentlyLeaf:A,promotionSource:"reparent"});if(C){for(let[R,F]of Object.entries(C.fields))rt(n,C.parentId,R,F);C.promotionSnapshot&&n.setPromotionSnapshot(C.parentId,C.promotionSnapshot),C.fields.customId===null&&en(L,r.customIdTracker)}}}if(d!=="0"){let P=n.getActivity(d);if(P){let L=n.getChildren(d),A=we({parent:P,remainingChildIds:L.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(A){for(let[q,Z]of Object.entries(A.fields))rt(n,d,q,Z);let C=qt(d,n),R=C?n.getActivity(C)?.customId:null,F=typeof R=="string"&&R?R:null,O=r.customIdTracker.generateCustomIdForRestoredChild(F);n.setActivityField(d,E.CUSTOM_ID,O)}}}}f&&(d!=="0"&&mt(d,n),o||mt(e.parentId,n));let I=at(n);for(let P of I){if(p.add(P.activityId),h.has(P.activityId))continue;let L=n.getActivity(P.activityId);if(!L)continue;let A=z(L);P.before!==void 0&&(A.correlativeId=P.before),h.set(P.activityId,A)}let T=f&&d!=="0"?n.getChildren(d).map(String):[],{scheduledIds:g}=await $({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?on([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 U(n,{source:e,beforeSnap:h,touchedIds:p,scheduledIds:g,sirDetection:"before-diff",preview:t.preview,trackingEvents:[m],hoursPerDay:a.hoursPerDay})}}function dn(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):ae,v=p?st(p):ae;return h-v});for(let d of o){if(!t.getActivity(d)){n.push({activityId:d,reason:S.ACTIVITY_NOT_FOUND}),s.delete(d);continue}if(an(d,a,t))continue;let f=Fa(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=b(p)?"0":String(p);i.push({activityId:d,newParentId:f,oldParentId:h}),a.add(d)}let c=ln(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 Qc(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=dn(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 G(n,s);for(let{activityId:g,newParentId:k}of d)n.setActivityField(g,E.PARENT,k),n.setActivityField(g,E.CORRELATIVE_ID,Nc),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,L=Wt(m.type)&&n.getChildren(k).filter(R=>!o.includes(R)).length===0,A=m.hasNewActivities&&m.newActivityIds.some(R=>String(R)===String(g)),C=Le({parentId:k,newChildId:g,getParent:R=>n.getActivity(R)??null,isCurrentlyLeaf:L,promotionSource:"reparent"});if(C){for(let[R,F]of Object.entries(C.fields))rt(n,C.parentId,R,F);C.promotionSnapshot&&n.setPromotionSnapshot(C.parentId,C.promotionSnapshot),A||(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),en(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)mt(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=z(k);g.before!==void 0&&(m.correlativeId=g.before),u.set(g.activityId,m)}let{scheduledIds:v}=await $({adapter:n,scheduler:i,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:null,recomputeParentsFrom:o,now:r.now,options:t}),I=on(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 U(n,{source:e,beforeSnap:u,touchedIds:s,scheduledIds:v,trackingEvents:[T],hoursPerDay:a.hoursPerDay})}}async function tl(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 A of e.activityIds){let C=A;n.getActivity(C)&&(o.set(C,Bn(C,n)),c.set(C,Fc(C,s,n)))}let l=new Set,d=[],u=[],f=new Set,p=[],h=new Set,v=[...e.activityIds].sort((A,C)=>{let R=n.getActivity(A),F=n.getActivity(C),O=R?st(R):ae,q=F?st(F):ae;return O-q});for(let A of v){let C=A,R=n.getActivity(C);if(!R){d.push({activityId:C,reason:S.ACTIVITY_NOT_FOUND});continue}if(an(C,h,n))continue;let F=R.parentId;if(b(F)){d.push({activityId:C,reason:S.OUTDENT_ROOT_LEVEL_NOT_EDITABLE});continue}let O=String(F),q=n.getActivity(O);if(!q){d.push({activityId:C,reason:S.ACTIVITY_NOT_FOUND});continue}let Z=q.parentId;if(b(Z)){d.push({activityId:C,reason:S.OUTDENT_ROOT_LEVEL_NOT_EDITABLE});continue}let lt=String(Z),ft=Bn(O,n)+1,nt=c.get(C);if(nt!=null&&s.has(nt)){let ce=o.get(nt)??-1,le=o.get(C)??-1;ce>=0&&le>=0&&(ft+=le-ce)}p.push({activityId:C,grandparentKey:lt,oldParentKey:O,targetIndexInGrandparent:ft}),h.add(C),l.add(String(C)),l.add(String(O)),lt!=="0"&&l.add(String(lt)),f.add(O)}let I=ln(p.map(A=>({activityId:A.activityId,newParentId:A.grandparentKey})),n);for(let A of I)d.push({activityId:A,reason:S.HIERARCHY_CYCLE});let T=p.filter(A=>!I.has(A.activityId)),g=await G(n,l);for(let A of T){n.setActivityField(A.activityId,E.PARENT,A.grandparentKey);let C=Mc(n,A.grandparentKey,A.targetIndexInGrandparent,A.activityId);n.setActivityField(A.activityId,E.CORRELATIVE_ID,C),u.push(A.activityId)}for(let A of f){let C=n.getActivity(A);if(!C)continue;let R=n.getChildren(A),F=we({parent:C,remainingChildIds:R.map(String),defaultDurationHours:a.hoursPerDay,promotionSnapshot:n.getPromotionSnapshot(A),computeEndDate:(ft,nt)=>n.calculateEndDate({startDate:ft,durationHours:nt,task:C}),idsRemoved:new Set(T.filter(ft=>ft.oldParentKey===A).map(ft=>ft.activityId))});if(!F){Or(A,n);continue}for(let[ft,nt]of Object.entries(F.fields))rt(n,A,ft,nt);let O=qt(A,n),q=O?n.getActivity(O)?.customId:null,Z=typeof q=="string"&&q?q:null,lt=r.customIdTracker.generateCustomIdForRestoredChild(Z);n.setActivityField(A,E.CUSTOM_ID,lt)}let k=new Set;for(let A of f)k.add(String(A));for(let A of T)A.grandparentKey!=="0"&&k.add(String(A.grandparentKey));for(let A of k)mt(A,n);let m=at(n);for(let A of m){if(l.add(A.activityId),g.has(A.activityId))continue;let C=n.getActivity(A.activityId);if(!C)continue;let R=z(C);A.before!==void 0&&(R.correlativeId=A.before),g.set(A.activityId,R)}let{scheduledIds:P}=await $({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}),L={name:It.ACTIVITY_OUTDENT,properties:{activity_ids:u.map(String),failed:d.map(A=>({activity_id:String(A.activityId),reason:A.reason}))}};return e.eventSource!==void 0&&(L.properties.event_source=e.eventSource),{ok:!0,activityVerdicts:e.activityIds.map(A=>{let C=d.find(R=>String(R.activityId)===String(A));return C?{activityId:String(A),ok:!1,reason:C.reason}:{activityId:String(A),ok:!0}}),changes:await U(n,{source:e,beforeSnap:g,touchedIds:l,scheduledIds:P,trackingEvents:[L],hoursPerDay:a.hoursPerDay})}}async function el(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=Kt(_.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=Gt(e.activityId,d),f=await G(n,u);$t(n,e.activityId,d),jt(e.activityId,d.postProcessors??[],n);let{scheduledIds:p}=await $({adapter:n,scheduler:a,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:d.needsAutoSchedule?e.activityId:null,recomputeParentsFrom:[],collectDirty:v=>Yr(e.activityId,u,v),now:r.now,options:t}),h=(d.trackingEvents??[]).map(v=>({name:v.name,properties:v.properties??{}}));return{ok:!0,changes:await U(n,{source:e,beforeSnap:f,touchedIds:u,scheduledIds:p,trackingEvents:h,hoursPerDay:s.hoursPerDay})}}async function rl(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 v=qy(h,r);if(s.push(v.verdict),!v.verdict.ok||!v.changes)continue;let I=Gt(h.activityId,v.changes);Jy(o,I,r);for(let m of I)c.add(m);let T=Ee(n,h.activityId),g=Vr(n,String(h.activityId));$t(n,h.activityId,v.changes),jt(h.activityId,v.changes.postProcessors??[],n,g),d.push(...be(T,n,h.activityId)),f||=!!v.changes.needsAutoSchedule;for(let m of v.changes.trackingEvents??[])l.push({name:m.name,properties:m.properties??{}});let k=ke(h.activityId,v.changes.constraintWarning);k&&u.push(k)}let{scheduledIds:p}=await $({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 U(n,{source:e,beforeSnap:o,touchedIds:c,scheduledIds:p,sirDetection:"before-diff",preview:t.preview,links:d,trackingEvents:l,warnings:u,hoursPerDay:a.hoursPerDay})}}function qy(e,t){let{ctx:r}=t,n=e.activityId,i=Kt(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 Jy(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,z(a))}}function Xy(e,t,r,n,i,a){let s=String(e.id);if(s.length===0||i.has(s))throw new Error(`persistence-acknowledge: duplicate or empty ${t} id "${s}"`);if(!Number.isSafeInteger(e.proplannerId)||e.proplannerId<=0)throw new Error(`persistence-acknowledge: invalid ${t} proplannerId ${String(e.proplannerId)}`);if(a.has(e.proplannerId))throw new Error(`persistence-acknowledge: duplicate ${t} proplannerId ${String(e.proplannerId)}`);let o=r(s);if(!o.exists)throw new Error(`persistence-acknowledge: unknown ${t} id "${s}"`);if(o.current!==null&&o.current!==e.proplannerId)throw new Error(`persistence-acknowledge: ${t} "${s}" already has proplannerId ${String(o.current)}`);let c=n.get(e.proplannerId);if(c!==void 0&&c!==s)throw new Error(`persistence-acknowledge: ${t} proplannerId ${String(e.proplannerId)} already belongs to "${c}"`);i.add(s),a.add(e.proplannerId)}function nl(e,t,r,n){let i=new Set,a=new Set;for(let s of e)Xy(s,t,r,n,i,a)}function Zy(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 il(e,t){let r=e.activities??[],n=e.links??[],i=e.reconciledProgress??[];Zy(i,t);let a=new Map;for(let p of t.adapter.getAllActivities())p.proplannerId!=null&&a.set(p.proplannerId,String(p.id));let s=new Map;for(let p of t.adapter.getAllLinks())p.proplannerId!=null&&s.set(p.proplannerId,String(p.id));nl(r,"activity",p=>{let h=t.adapter.getActivity(p);return{exists:h!==null,current:h?.proplannerId??null}},a),nl(n,"link",p=>{let h=t.adapter.getLink(p);return{exists:h!==null,current:h?.proplannerId??null}},s);let o=[],c=[],l=i.filter(p=>{let h=t.adapter.getActivity(String(p.activityId));return h!==null&&h.progress!==p.progress}),d=new Set(l.map(p=>String(p.activityId))),u=new Set;for(let p of l){let h=t.adapter.getActivity(String(p.activityId));h&&!b(h.parentId)&&(u.add(String(h.parentId)),d.add(String(h.parentId)))}let f=await G(t.adapter,d);return t.adapter.batchUpdate(()=>{for(let p of l)t.adapter.setActivityField(String(p.activityId),"progress",p.progress);for(let p of u)mt(p,t.adapter);for(let p of d){let h=f.get(p),v=t.adapter.getActivity(p);!h||!v||h.progress===v.progress||o.push({id:p,kind:"updated",fields:{progress:{before:h.progress,after:v.progress}},after:{...v}})}for(let p of r){let h=t.adapter.getActivity(p.id);if(!h||h.proplannerId===p.proplannerId)continue;let v=h.proplannerId;t.adapter.setActivityField(p.id,"proplannerId",p.proplannerId),o.push({id:p.id,kind:"updated",fields:{proplannerId:{before:v,after:p.proplannerId}},after:{...h,proplannerId:p.proplannerId}})}for(let p of n){let h=t.adapter.getLink(p.id);if(!h||h.proplannerId===p.proplannerId)continue;let v=h.proplannerId;t.adapter.setLinkProplannerId(p.id,p.proplannerId),c.push({id:p.id,kind:"updated",fields:{proplannerId:{before:v,after:p.proplannerId}},after:{...h,proplannerId:p.proplannerId}})}}),{ok:!0,changes:{source:e,activities:o,links:c,calendars:[],trackingEvents:[]}}}function al(e){return typeof e=="string"&&e.length>0?xt(e):e instanceof Date?e:null}function $i(e){let t=typeof e=="number"?e:typeof e=="string"&&e.trim()!==""?Number(e):Number.NaN;return!Number.isFinite(t)||t<0?null:t}function un(e,t){let r=$i(e.duration),n=$i(e.cost),i=$i(e.hh_work);return r===null||n===null||i===null?(t.warn(`[baseline] dropping point with non-finite/negative magnitude \u2014 duration=${JSON.stringify(e.duration)}, cost=${JSON.stringify(e.cost)}, hh_work=${JSON.stringify(e.hh_work)}`),null):{startDate:al(e.start_date),endDate:al(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 sl(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=>un(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 Qy(e){let t=dt(e);return t?{startDate:t.startDate,endDate:t.endDate,durationDays:t.durationDays,cost:t.cost,workHours:t.workHours}:null}function ol(e){let t=[];return e.forEachActivity((r,n)=>{let i=Qy(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 fn(e,t,r,n,i=null){let a=new Set;for(let s of sl(e,t,n))a.add(s);if(r)for(let s of _e(e,r,i))a.add(s);for(let s of ol(e))a.add(s);for(let s of Pe(e))a.add(s);return[...a]}function cl(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=tm(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(dt(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 tm(e,t,r){let n=r.getActivity(e);if(!n)return 0;let i=dt(n);if(!i)return 0;if(t==="COST")return pn(i.cost);if(t==="HH")return pn(i.workHours);let a=n.type;return a==="project"?ll(e,r):a==="milestone"?0:pn(i.durationDays)}function ll(e,t){let r=0;for(let n of t.getChildren(e)){let i=t.getActivity(n);if(!i)continue;let a=dt(i);if(!a)continue;let s=i.type;s==="project"?r+=ll(String(n),t):s!=="milestone"&&(r+=pn(a.durationDays))}return r}function pn(e){let t=typeof e=="string"?parseFloat(e):e;return typeof t=="number"&&Number.isFinite(t)?t:0}function dl(e,t){t.forEachActivity((r,n)=>{t.setActivityField(n,_.PONDERATOR,0)}),t.forEachActivity((r,n)=>{t.getChildren(n).length>0&&cl(String(n),e,t)})}function ul(e){for(let t of em(e))nm(t,e)}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,rm(n,e));return[...t].sort((n,i)=>(r.get(i)??0)-(r.get(n)??0))}function rm(e,t){let r=0,n=e;for(;n&&n!=="0"&&t.getActivity(n);)r+=1,n=t.getParentId(n);return r}function nm(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=ye(n);i!==null&&t.setActivityField(e,_.PROGRESS,wr(i))}function hn(e,t){dl(t,e.adapter),ul(e.adapter),e.now&&(_e(e.adapter,e.now,e.defaultBaseCalendarId??null),re(e.adapter,e.now)),Pe(e.adapter),e.now&&Nt(e.adapter,e.sector.statusCriteria)}function fl(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 G(t.adapter,new Set(t.adapter.getAllIds())),n=fl(t),i=fn(t.adapter,e.points,t.now,t.reporter,t.defaultBaseCalendarId??null);return fl(t)!==n&&hn(t,t.sector.activityCreter??"DURATION"),{ok:!0,changes:await U(t.adapter,{source:e,beforeSnap:r,touchedIds:i,scheduledIds:[],hoursPerDay:t.sector.hoursPerDay})}}function im(e){if(!(e==="DURATION"||e==="COST"||e==="HH"))throw new Error(`ponderator-criterion-set: invalid criterion "${String(e)}"`)}async function hl(e,t){im(e.criterion);let r=new Set(t.adapter.getAllIds()),n=await G(t.adapter,r);return hn(t,e.criterion),t.sector.activityCreter=e.criterion,{ok:!0,changes:await U(t.adapter,{source:e,beforeSnap:n,touchedIds:r,scheduledIds:[],hoursPerDay:t.sector.hoursPerDay})}}async function yl(e,t){let r=ur(e.criteria),n=new Set(t.adapter.getAllIds()),i=await G(t.adapter,n),a=Nt(t.adapter,r);return t.sector.statusCriteria=r,{ok:!0,changes:await U(t.adapter,{source:e,beforeSnap:i,touchedIds:a,scheduledIds:[],hoursPerDay:t.sector.hoursPerDay})}}var ml=["name","description","type","startDate","durationHours","constraintType","constraintDate","calendarId","cost","hasCustomPonderator","subcontractId","responsableIds","tagIds"];function am(e){let t={};for(let r of ml)Object.assign(t,{[r]:B(e[r])});return t}function sm(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 gl(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=sm(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:am(s)}}),links:t.adapter.getAllLinks().filter(a=>r.has(String(a.source))&&r.has(String(a.target))).map(a=>B(a))};let i=or({kind:"selection-replace",activityIds:[]},{adapter:t.adapter});return i.ok?{...i,changes:{...i.changes,source:e}}:i}function vl(e,t){return t.value=null,{ok:!0,changes:{source:e,activities:[],links:[],calendars:[],trackingEvents:[]}}}function om(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 Al=()=>({ok:!1,reason:S.ACTIVITY_PASTE_INVARIANT_FAILED});async function Cl(e,t,r){let n=r.activityClipboard.value;if(n===null)return{ok:!1,reason:S.CLIPBOARD_EMPTY};let i=om(e.destination.afterSiblingId,r.adapter);if(!i.ok)return i;let a=await G(r.adapter,new Set),s=new Set,o=new Map,c=[],l;for(let v of n.activities){let I=o.get(v.originalParentId),T=await Ze({kind:"activity-create",parentId:I??i.parentId,...I===void 0?{afterSiblingId:l??e.destination.afterSiblingId}:{},overrides:B(v.overrides),eventSource:e.eventSource},r,{skipCorrelativeRecompute:!0,skipBeforeSnap:!0,customIdReferenceId:e.destination.afterSiblingId});if(!T.ok)return T;o.set(v.originalId,T.newId),c.push(T.newId),I===void 0&&(l=T.newId)}let d=at(r.adapter),u=new Set(c.map(String));De(r.adapter,d,u,a,s);for(let v of c)s.add(String(v));let f=[];for(let v of n.links){let I=o.get(v.source),T=o.get(v.target);if(I===void 0||T===void 0)return Al();let g={kind:"create",source:I,target:T,type:v.type,lag:v.lag},k=Ut(g,{port:r.adapter,newLinkId:r.linkIdGen.next});if(!k.applied)return Al();f.push({op:g,finalLinkId:k.linkId,rejected:null})}let{scheduledIds:p}=await $({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=Re(f,new Map,r.adapter);return{ok:!0,changes:await U(r.adapter,{source:e,beforeSnap:a,touchedIds:s,scheduledIds:p,links:h,hoursPerDay:r.sector.hoursPerDay})}}async function Il(e,t,r){return e.kind==="activity-copy"?gl(e,{adapter:r.adapter,clipboard:r.activityClipboard}):e.kind==="activity-clipboard-clear"?vl(e,r.activityClipboard):e.kind==="activity-paste-copied"?Cl(e,t,r):e.kind==="activity-batch"?Gc(e,t,r):e.kind==="persistence-acknowledge"?il(e,r):e.kind==="baseline-apply"?pl(e,r):e.kind==="ponderator-criterion-set"?hl(e,r):e.kind==="status-criteria-set"?yl(e,r):e.kind==="link-create"||e.kind==="link-update"||e.kind==="link-delete"?Sc(e,t,r):e.kind==="links-batch"?kc(e,t,r):e.kind==="activity-create"?Wc(e,t,r):e.kind==="activity-delete"?Vc(e,t,r):e.kind==="activity-move"?Zc(e,t,r):e.kind==="activity-indent"?Qc(e,t,r):e.kind==="activity-outdent"?tl(e,t,r):e.kind==="activity-set-progress"?el(e,t,r):e.kind==="dates-batch"?rl(e,t,r):e.kind==="bulk-edit"?sn(e,t,r):e.kind==="selection-toggle"?Da(e,zi(r)):e.kind==="selection-replace"?or(e,zi(r)):e.kind==="visibility-set"?Ta(e,zi(r)):e.kind==="filter-set"?Oa(e,{adapter:r.adapter,hoursPerDay:r.sector.hoursPerDay}):e.kind==="sort-set"?Wa(e,{adapter:r.adapter}):e.kind==="sir-sync"?zc(e,r):e.kind==="sir-approve"?qc(e,t,r):e.kind==="activity-lookahead-sync"?Jc(e,r):e.kind==="inline-edit"&&(e.column===_.CUSTOM_PREDECESSORS||e.column===_.CUSTOM_SUCESSORS)?Dc(e,t,r):e.kind!=="inline-edit"?ks(e,`[ScheduleCore] dispatch kind "${e.kind}" not supported yet`):Ic(e,t,r)}function zi(e){return{adapter:e.adapter}}var cm=new Set(["startDate","endDate","constraintDate"]);function Sl(e,t){return cm.has(e)&&typeof t=="string"?new Date(t):t}function kl(e,t={}){let r=t.defaultUnit??"hour";return{getCalendar(n){let i=e.getCalendar(String(n));return i?lm(i,r):null}}}function lm(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 dm(e){return Array.isArray?Array.isArray(e):e&&e.length!==void 0&&e.pop&&e.push}function se(e){return e&&typeof e=="object"?!!(e.getFullYear&&e.getMonth&&e.getDate):!1}function oe(e){return se(e)&&!isNaN(e.getTime())}var um={}.constructor.toString();function fm(e){var t=e.constructor.toString();return t!==um}function pm(e){return e.$$typeof&&e.$$typeof.toString().includes("react.")}function _t(e){var t,r;if(e&&typeof e=="object")switch(!0){case se(e):r=new Date(e);break;case dm(e):for(r=new Array(e.length),t=0;t<e.length;t++)r[t]=_t(e[t]);break;default:if(fm(e))r=Object.create(e);else{if(pm(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 Oe(e,t,r){for(var n in t)(e[n]===void 0||r)&&(e[n]=t[n]);return e}function Dl(e){return typeof e<"u"}var yn;function qi(){return yn||(yn=new Date().valueOf()),yn++,yn}function gt(e,t){return e.bind?e.bind(t):function(){return e.apply(t,arguments)}}var ym=(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)},mm=(e,t,r)=>{let n="var temp=date.match(/[a-zA-Z]+|[0-9]+/g);",i=e.match(/%[a-zA-Z]/g);for(let o=0;o<i.length;o++)switch(i[o]){case"%j":case"%d":n+=`set[2]=temp[${o}]||1;`;break;case"%n":case"%m":n+=`set[1]=(temp[${o}]||1)-1;`;break;case"%y":n+=`set[0]=temp[${o}]*1+(temp[${o}]>50?1900:2000);`;break;case"%g":case"%G":case"%h":case"%H":n+=`set[3]=temp[${o}]||0;`;break;case"%i":n+=`set[4]=temp[${o}]||0;`;break;case"%Y":n+=`set[0]=temp[${o}]||0;`;break;case"%a":case"%A":n+=`set[3]=set[3]%12+((temp[${o}]||'').toLowerCase()=='am'?0:12);`;break;case"%s":n+=`set[5]=temp[${o}]||0;`;break;case"%M":n+=`set[1]=locale.date.month_short_hash[temp[${o}]]||0;`;break;case"%F":n+=`set[1]=locale.date.month_full_hash[temp[${o}]]||0;`;break}let a="set[0],set[1],set[2],set[3],set[4],set[5]";t&&(a=` Date.UTC(${a})`);let s=new Function("date","locale",`var set=[0,0,1,0,0,0]; ${n} return new Date(${a});`);return o=>s(o,r.locale)},Tl={date_to_str:ym,str_to_date:mm},gm=(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}}),vm=(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])},_l={date_to_str:gm,str_to_date:vm};function Pl(e){var t=/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:?\d{2})?)?$/;function r(o){var c=new Date(o);return isNaN(c.getTime())?null:c}var n=null;function i(){try{new Function("canUseCsp = false;")}catch{n=!0}}function a(){var o=!1;return e.config.csp==="auto"?(n===null&&i(),o=n):o=e.config.csp,o}var s={_isoDateDetected:!1,_isoDateOnly:!1,formatISODate:function(o){return o.toISOString()},formatISODateOnly:function(o){return o.getUTCFullYear()+"-"+e.date.to_fixed(o.getUTCMonth()+1)+"-"+e.date.to_fixed(o.getUTCDate())},init:function(){for(var o=e.locale,l=o.date.month_short,d=o.date.month_short_hash={},c=0;c<l.length;c++)d[l[c]]=c;for(var l=o.date.month_full,d=o.date.month_full_hash={},c=0;c<l.length;c++)d[l[c]]=c},date_part:function(o){return o.setUTCHours(0,0,0,0),o},time_part:function(o){return o.valueOf()/1e3%86400},week_start:function(o){var c=o.getUTCDay();return e.config.start_on_monday&&(c===0?c=6:c--),this.date_part(this.add(o,-1*c,"day"))},month_start:function(o){return o.setUTCDate(1),this.date_part(o)},quarter_start:function(o){this.month_start(o);var c=o.getUTCMonth(),l;return c>=9?l=9:c>=6?l=6:c>=3?l=3:l=0,o.setUTCMonth(l),o},year_start:function(o){return o.setUTCMonth(0),this.month_start(o)},day_start:function(o){return this.date_part(o)},hour_start:function(o){return o.getUTCMinutes()&&o.setUTCMinutes(0),this.minute_start(o),o},minute_start:function(o){return o.getUTCSeconds()&&o.setUTCSeconds(0),o.getUTCMilliseconds()&&o.setUTCMilliseconds(0),o},_add_days:function(o,c,l){return o.setUTCDate(o.getUTCDate()+c),o},add:function(o,c,l){var d=new Date(o.valueOf());switch(l){case"day":d=this._add_days(d,c,o);break;case"week":d=this._add_days(d,c*7,o);break;case"month":d.setUTCMonth(d.getUTCMonth()+c);break;case"year":d.setUTCFullYear(d.getUTCFullYear()+c);break;case"hour":d.setTime(d.getTime()+c*60*60*1e3);break;case"minute":d.setTime(d.getTime()+c*60*1e3);break;default:return this["add_"+l](o,c,l)}return d},add_quarter:function(o,c){return this.add(o,c*3,"month")},to_fixed:function(o){return o<10?"0"+o:o},copy:function(o){return new Date(o.valueOf())},date_to_str:function(o,c){var l=Tl;return a()&&(l=_l),l.date_to_str(o,c,e)},str_to_date:function(o,c){var l=Tl;return a()&&(l=_l),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 Ji(e,t,r,n,i){return this.date=e,this.unit=t,this.task=r,this.id=n,this.calendar=i,this}function Xi(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 Zi(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 Am(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 Rl=function(e){return{getWorkHoursArguments:function(){var t=arguments[0];if(se(t)?t={date:t}:t=Oe({},t),!oe(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 Ji)return t;var r;if(t.date?r=new Ji(t.date,t.unit,t.task,null,t.calendar):r=new Ji(arguments[0],arguments[1],arguments[2],null,arguments[3]),r.unit=r.unit||e.config.duration_unit,!oe(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 Xi)return r;var n;if(se(r)?n=new Xi(r):n=new Xi(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,!oe(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=Am,n;if(t instanceof r)return t;if(se(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,!oe(n.start_date))throw e.assert(!1,"Invalid start_date argument for getDuration method"),new Error("Invalid start_date argument for getDuration method");if(!oe(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 Zi)return a;var s;if(se(a)?s=new Zi(arguments[0],arguments[1],arguments[2],void 0,arguments[3],void 0,arguments[4]):s=new Zi(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,!oe(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 El(){}El.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 v=Array.isArray(h)?h:d.hours;s.dates[u]=this._toHoursArray(this._mergeHoursConfig(f,v))}}}};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 Qi=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}},ta=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={}}},ea=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 Cm(){return typeof Map<"u"?new Qi:new ta}var ra=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 na(e,t){this.argumentsHelper=t,this.$gantt=e,this._workingUnitsCache=Cm(),this._largeUnitsCache=new ea(this),this._dateDurationCache=new ra,this._worktime=null,this._cached_timestamps={},this._cached_timestamps_count=0}na.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),v=this.units[h-1];v&&!this._isWorkTime(a,v)&&(c=this._getClosestWorkTimeFuture(a,v))}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=gt(this._getMinutesPerDay,this):o=gt(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 na))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(gt(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(gt(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 v=!1,I=null,T=null,g=c.length-1;g>=0;g--)if(c[g].start<h-1&&c[g].end>=h-1){v=!0,I=c[g],T=c[g-1];break}if(v)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 L=P[P.length-1];m.setUTCSeconds(L.durationSeconds)}}n=m}else n=this._getClosestWorkTimePast(new Date(n-1),"hour")}if(i<t){var A=t-i;s=this._subtractMinutesUntilHourStart(n,A),i+=s.added,n=s.end}return n},_calculateMinuteEndDate:function(e,t,r){var n=new Date(e),i=0;r=r||1,t=Math.abs(t*1),t=Math.round(t);var a=this._addMinutesUntilHourEnd(n,t);i+=a.added,n=a.end;for(var s=0,o=[],c=0,l=this._isMinutePrecision(n);i<t;){var d=this.$gantt.date.day_start(new Date(n)).valueOf();d!==s&&(o=this._getWorkHours(n),c=this._getMinutesPerDay(n),s=d);var u=t-i,f=this._getTimeOfDayStamp(n);if(!o.length||!c){n=this.$gantt.date.add(this.$gantt.date.day_start(n),1,"day");continue}if(o[0].start>=f&&u>=c){if(i+=c,u==c){n=new Date(Date.UTC(n.getUTCFullYear(),n.getUTCMonth(),n.getUTCDate(),0,0,o[o.length-1].end));break}else n=this.$gantt.date.add(n,1,"day"),n=this.$gantt.date.day_start(n);continue}for(var p=!1,h=null,v=0;v<o.length;v++)if(o[v].start<=f&&o[v].end>f){p=!0,h=o[v];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 Qe={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 Im(){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 Sm=Im();function bl(e){this.$gantt=e,this._calendars={},this._legacyConfig=void 0,this.$gantt.attachEvent("onGanttReady",(function(){this.$gantt.config.resource_calendars&&(this._isLegacyConfig=Qe.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))}bl.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 El,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 na(this.$gantt,Rl(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 Oe(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=Qe.getResourceProperty(t),Array.isArray(e[i])&&e[i].length)t.dynamic_resource_calendars?n=Sm.getCalendarIdFromMultipleResources(e[i],this):r=this.getResourceCalendar(e[i]);else if(this._legacyConfig===void 0&&(this._legacyConfig=Qe.isLegacyResourceCalendarFormat(t.resource_calendars)),this._legacyConfig)var n=Qe.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=Qe.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 ia(e,t){this.argumentsHelper=t,this.$gantt=e}ia.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 ia},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 Ll(e){this.$gantt=e.$gantt,this.argumentsHelper=Rl(this.$gantt),this.calendarManager=e,this.$disabledCalendar=new ia(this.$gantt,this.argumentsHelper)}Ll.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 km=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:gt(e.mergeCalendars,e),createCalendar:gt(e.createCalendar,e),addCalendar:gt(e.addCalendar,e),getCalendar:gt(e.getCalendar,e),getCalendars:gt(e.getCalendars,e),getResourceCalendar:gt(e.getResourceCalendar,e),getTaskCalendar:gt(e.getTaskCalendar,e),deleteCalendar:gt(e.deleteCalendar,e)}},Dm={create:km};function wl(e){var t=new bl(e),r=new Ll(t),n=Dm.create(t,r);Oe(e,n)}var Ol={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 xl(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||Ol,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:Dl,mixin:Oe,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=Pl(r),r.date.init(),wl(r),r}function Tm(e={}){let t=xl(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 Nl={createCalendar:Tm};var _x=3600*1e3;function Ul(e){return{getActivity(t){return e.getActivity(t)}}}var{createCalendar:_m}=Nl,tr="__replay_default__";function Pm(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 Fl={hours:["8:00-16:00"],days:[!1,!0,!0,!0,!0,!0,!1]},Ml="__main_global__",Rm={hours:["8:00-12:00","13:00-17:00"],days:[!1,!0,!0,!0,!0,!0,!1]};function Wl(e){return!e||e.hours===void 0||e.hours.length>0||e.days?.some(t=>Array.isArray(t)&&t.length>0)===!0?!0:Object.values(e.dates??{}).some(t=>Array.isArray(t)&&t.length>0)}function Em(e){let t={};if(Array.isArray(e.days))for(let n=0;n<e.days.length;n+=1)t[n]=e.days[n];if(e.dates)for(let[n,i]of Object.entries(e.dates))t[n]=i;let r={hours:Pm(e.hours),dates:t};return e.customWeeks&&(r.customWeeks=e.customWeeks),r}function Bl(e){let t=_m({config:{work_time:!0}});t.addCalendar({id:tr,worktime:Fl}),t.addCalendar({id:Ml,worktime:Rm});let r=new Set(e.filter(d=>!Wl(d.worktime)).map(d=>String(d.id))),n=e.filter(d=>Wl(d.worktime));for(let d of n)t.addCalendar({id:d.id,worktime:d.worktime?Em(d.worktime):Fl});let i=kl(t),a=i.getCalendar(tr),s=i.getCalendar(Ml);if(!a||!s)throw new Error("[replay-calendar] fallback calendars failed to register in work-calendar instance");let o=new Set([tr]);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 jl(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 bm(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 bm(e,t){let r=[],n=new pt;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 mn=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,ee(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:ee(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:Hl(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=ee(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:Hl(r)}))}};function Hl(e){return{...e}}var gn=class{_cache={closestWorkTime:new Map,endDate:new Map,duration:new Map};reader;constructor(t){this.reader=t.reader}resolveCalendar(t){let r=Vl(t);return this.reader.getCalendar(r??tr)}getClosestWorkTime(t){let r=`${sa(t.task)}|${t.dir}|${t.date.getTime()}`;return aa(this._cache.closestWorkTime,r,()=>this.resolveCalendar(t.task).getClosestWorkTime({direction:t.dir,date:t.date,unit:ot.HOUR}))}calculateEndDate(t){let r=`${sa(t.task)}|${t.startDate.getTime()}|${t.durationHours}`;return aa(this._cache.endDate,r,()=>this.resolveCalendar(t.task).calculateEndDate(t.startDate,t.durationHours))}calculateDuration(t){let r=`${sa(t.task)}|${t.startDate.getTime()}|${t.endDate.getTime()}`;return aa(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 aa(e,t,r){let n=e.get(t);if(n!==void 0)return n;let i=r();return e.set(t,i),i}var Lm="__default__";function Vl(e){if(!e)return null;let t=e.calendarId;return t==null?null:String(t)}function sa(e){return Vl(e)??Lm}var vn=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&&!b(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||b(r)?null:this.activities.get(r)??null}getParentId(t){return this.activities.get(t)?.parentId??null}addChild(t,r){if(this._dirty)return;if(b(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(b(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?lr(i,a):String(r).localeCompare(String(n))};this._roots.sort(t);for(let r of this._childrenByParent.values())r.sort(t)}};var An=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 xe=class{_activities=new Map;_lastStartDate=new Map;_promotionSnapshot=new Map;_links=new Map;_outgoing=new Map;_incoming=new Map;_hierarchy;_buildOrderComparator;_cache={ids:null,visualOrderIds:null,orderComparator:null};_writeCapture=new mn;_viewState=new An;_filterProjection=null;_viewStateBefore=null;_lastStartDateBefore=null;_promotionSnapshotBefore=null;_calendar;_flags;constructor(t,r=()=>null){this._buildOrderComparator=r;for(let n of t.activities)this._activities.set(n.id,n);for(let n of t.links)this._links.set(String(n.id),n),this._indexLink(n);this._calendar=new gn(Bl(t.calendars)),this._flags=Om(t),this._hierarchy=new vn(this._activities),this._hierarchy.rebuild()}getAllActivities(){return Array.from(this._activities.values())}getAllLinks(){return Array.from(this._links.values())}getAllIds(){return this._cache.ids?this._cache.ids:(this._cache.ids=Array.from(this._activities.keys()),this._cache.ids)}activityCount(){return this._activities.size}getVisualOrderIds(){return this._cache.visualOrderIds?this._cache.visualOrderIds:(this._cache.visualOrderIds=Na(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))??Yl}getIncomingLinkIds(t){return this._incoming.get(String(t))??Yl}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,ca(i,r),r===E.PARENT&&this._hierarchy.markDirty(),oa(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,Sl(r,n)),ca(i,r),r===E.PARENT&&this._hierarchy.markDirty(),oa(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)),ca(n,a),a===E.PARENT&&(i=!0),oa(a)&&(this._cache.visualOrderIds=null);i&&this._hierarchy.markDirty()}addLink(t){this._writeCapture.noteLinkAdd(String(t.id));let r=this._links.get(String(t.id));r&&this._deindexLink(r),this._links.set(String(t.id),{...t}),this._indexLink(t)}_indexLink(t){Gl(this._outgoing,String(t.source),t.id),Gl(this._incoming,String(t.target),t.id)}_deindexLink(t){let r=this._outgoing.get(String(t.source));r&&this._outgoing.set(String(t.source),Kl(r,t.id));let n=this._incoming.get(String(t.target));n&&this._incoming.set(String(t.target),Kl(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(!wm(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))}},Yl=[];function wm(e){return e===si.LAG||e===si.TYPE}function oa(e){return e===E.PARENT||e===E.CORRELATIVE_ID}function ca(e,t){t!==E.START_DATE&&t!==E.END_DATE&&t!==E.TYPE||(e.calendarDuration=Rt(e))}function Kl(e,t){return e.filter(r=>String(r)!==String(t))}function Gl(e,t,r){let n=e.get(t);n?n.push(r):e.set(t,[r])}function Om(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 $l(e,t){let r=e.getActivity(t);return r?B(r):null}function zl(e){return e.getAllActivities().map(B)}function ql(e){return e.getAllIds().map(String)}function Jl(e,t){e.forEachActivity((r,n)=>t(n))}function Xl(e,t){let r=t==="0"?la(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 la(e,t){return vt(t,e)}function Zl(e){return e.checkedIds().map(String)}function Ql(e,t){if(t==="0"){let r=!1;return e.forEachActivity(n=>{r||=b(n.parentId)}),r}return e.getChildren(t).length>0}function td(e,t){let r=e.getLink(t);return r?ut(r):null}function ed(e){return e.getAllLinks().map(t=>ut(t))}function Cn(e){let[t,r]=e.split(":");return Number(t)*60+Number(r??0)}function xm(e){return e.reduce((t,r)=>Cn(r)<Cn(t)?r:t)}function Nm(e){return e.reduce((t,r)=>Cn(r)>Cn(t)?r:t)}function Fm(e){return e.worktime.days.flatMap(t=>Array.isArray(t)?t:t===!0?e.worktime.hours:[])}function rd(e){let t=[...e].find(a=>a.is_default);if(!t)return null;let r=Fm(t);if(r.length===0)return null;let n=r.map(a=>a.split("-")[0]),i=r.map(a=>a.split("-")[1]);return{startHour:xm(n),endHour:Nm(i)}}function nd(e,t){return{calendars:e.calendarReader,hierarchy:jl(e),activityReader:Ul(e),dateFormat:t.dateFormat??"YYYY-MM-DD",customHours:t.customHours??{},hoursPerDay:t.hoursPerDay,...t.inputUnit!==void 0?{inputUnit:t.inputUnit}:{}}}function id(e){return ie(e)}function da(e){let t=e.activities.map(i=>({...i,after:null})),r=e.links.map(i=>({...i,after:null})),n=e.source.kind==="activity-batch"?{...e.source,items:[],links:[]}:e.source;return B({...e,source:n,activities:t,links:r})}function er(e,t,r,n,i){return{changeSet:e,beforeSnap:t,beforeLinks:r,afterSnap:n,afterLinks:i}}function od(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),z(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 cd(e){return e.kind!=="inline-edit"||!Xe.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 ld(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 dd(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 er(o)}function ud(e,t){return t?.preview===!0?"skip":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 In(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 Sn(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?z(c):null})}else if(s.kind==="deleted")if(r==="before"){let c=e.getActivity(o);n.push({id:o,kind:"created",after:c?z(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?z(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?ut(c):null})}else if(s.kind==="deleted")if(r==="before"){let c=e.getLink(o);i.push({id:o,kind:"created",after:c?ut(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?ut(c):null})}}let a=(t.changeSet.viewState??[]).map(s=>r==="before"?Mm(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 Mm(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 ua(e){return e.activities.length>0||e.links.length>0||(e.viewState?.length??0)>0||(e.effects?.length??0)>0}function fd(e,t){pd(e,t,"before")}function fa(e,t){pd(e,t,"after")}function pd(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(z(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(z(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))No(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 Wm=100,Um=600,kn=class{constructor(t=Wm){this.maxDepth=t}maxDepth;undoStack=[];redoStack=[];_lastKey=null;_lastTime=0;record(t,r=null,n=0){let i=this.undoStack[this.undoStack.length-1];r!=null&&r===this._lastKey&&n-this._lastTime<=Um&&i!==void 0&&ld(i,t)?this.undoStack[this.undoStack.length-1]=dd(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 Bm=["parentId","correlativeId"];function yd(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(hd(c.parentId?.before));continue}let s=i.fields;!s||!Bm.some(c=>c in s)||(n(a),"parentId"in s&&r.add(hd(s.parentId?.before)))}return r}function hd(e){return e==null?"0":String(e)}function jm(e){return{...e,id:String(e.id),source:String(e.source),target:String(e.target),type:e.type,lag:Number(e.lag)}}function Hm(e){return{days:e.days,hours:e.hours,...e.dates?{dates:e.dates}:{},...e.customWeeks?{customWeeks:e.customWeeks}:{}}}function md(e){return{id:String(e.id),worktime:Hm(e.worktime)}}function Dn(e,t,r,n=[]){let i=t.map(jm),a=[...r.map(md),...n.map(md)];return{activities:[...e],links:i,calendars:a}}var gd=["id","proplannerId","parentId","name","description","type","startDate","endDate","durationHours","constraintType","constraintDate","autoScheduling","calendarId","assignedDefaultCalendar","dateOrigin","progress","cost","usedCost","realCost","workHours","realWorkHours","ponderator","hasCustomPonderator","correlativeId","uniqueCorrelativeId","customId","subcontractId","isLookahead","newActivityIds","hasNewActivities","responsableIds","tagIds"],vd=new Set(["startDate","endDate","constraintDate","dateOrigin"]),Ad=new Set(["newActivityIds","responsableIds","tagIds"]);function Cd(e){let t=gd.map(r=>[r,Vm(r,e[r])]);return Object.fromEntries(t)}function Vm(e,t){return vd.has(e)?t instanceof Date?new Date(t):null:Ad.has(e)?Array.isArray(t)?[...t]:[]:t}function rr(e,t){if(e.assignedDefaultCalendar)return!0;for(let r of gd)if(!Ym(r,e[r],t[r]))return!0;return!1}function Ym(e,t,r){return vd.has(e)?Km(t,r):Ad.has(e)?Gm(t,r):(t??null)===(r??null)}function Km(e,t){let r=e instanceof Date?e.getTime():null,n=t instanceof Date?t.getTime():null;return r===n}function Gm(e,t){let r=Array.isArray(e)?[...e].map(String).sort():[],n=Array.isArray(t)?[...t].map(String).sort():[];return r.length!==n.length?!1:r.every((i,a)=>i===n[a])}function Tn(e,t){return e.source!==t.source||e.target!==t.target||e.lag!==t.lag||e.type!==t.type}function Id(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?Tn(i,n):!1})}var _n=class{initialized=!1;dirtyActivityIds=new Set;dirtyLinkIds=new Set;linksAtLastSave=new Map;activitiesAtLastSave=new Map;init(t,r){this.snapshotActivities(t),this.snapshotLinks(r),this.initialized=!0}snapshotActivities(t){this.activitiesAtLastSave.clear(),this.dirtyActivityIds.clear();for(let r of t){let n=String(r.id);if(r.proplannerId==null){this.dirtyActivityIds.add(n);continue}let i=Cd(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}}),rr(r,i)&&this.dirtyActivityIds.add(n)}}snapshotLinks(t){this.linksAtLastSave.clear(),this.dirtyLinkIds.clear();for(let r of t){let n=String(r.id);if(r.proplannerId==null){this.dirtyLinkIds.add(n);continue}this.linksAtLastSave.set(String(r.id),{id:r.id,proplannerId:r.proplannerId,source:r.source,target:r.target,lag:r.lag,type:r.type})}}recordChanges(t,r,n,i){if(this.initialized){for(let a of t){let s=String(a.id),o=n(s),c=this.activitiesAtLastSave.get(s);(o===null?c!==void 0:o.proplannerId==null||c===void 0||rr(o,c.persistable))?this.dirtyActivityIds.add(s):this.dirtyActivityIds.delete(s)}for(let a of r){let s=String(a.id),o=i(s),c=this.linksAtLastSave.get(s);(o===null?c!==void 0:o.proplannerId==null||c===void 0||Tn(c,o))?this.dirtyLinkIds.add(s):this.dirtyLinkIds.delete(s)}}}acknowledgePersistedLookahead(t,r){if(this.initialized)for(let n of t){let i=r(n),a=this.activitiesAtLastSave.get(n);if(i===null||a===void 0)continue;let s={...a.persistable,isLookahead:i.isLookahead};this.activitiesAtLastSave.set(n,{...a,persistable:s}),i.proplannerId==null||rr(i,s)?this.dirtyActivityIds.add(n):this.dirtyActivityIds.delete(n)}}hasUnsavedChanges(){return this.initialized&&(this.dirtyActivityIds.size>0||this.dirtyLinkIds.size>0)}deletedActivities(t){if(!this.initialized)return[];let r=new Set(t.map(i=>String(i.id))),n=[];for(let[i,a]of this.activitiesAtLastSave)r.has(i)||n.push({...a.deletedSnapshot});return n}deletedLinks(t){if(!this.initialized)return[];let r=new Set(t.map(n=>String(n.id)));return Array.from(this.linksAtLastSave.entries(),([n,i])=>r.has(n)?null:{...i}).filter(n=>n!==null)}modifiedActivities(t){return this.initialized?t.filter(r=>{if(r.proplannerId==null)return!1;if(r.assignedDefaultCalendar)return!0;let n=this.activitiesAtLastSave.get(String(r.id));return n?rr(r,n.persistable):!0}):[]}modifiedLinks(t){return this.initialized?t.filter(r=>{if(r.proplannerId==null)return!1;let n=this.linksAtLastSave.get(String(r.id));return n?Tn(n,r):!0}):[]}clear(){this.initialized=!1,this.dirtyActivityIds.clear(),this.dirtyLinkIds.clear(),this.linksAtLastSave.clear(),this.activitiesAtLastSave.clear()}};var Sd=/^(\d{4})[/-](\d{1,2})[/-](\d{1,2})/;var pa=[!1,!0,!0,!0,!0,!0,!1],kd=new Set(["1","true"]),ha="DURATION",Dd="asap",Td={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=eg(a,t);return a.should_be_showed===!1&&r.push(s.id),s});ng(n);let i=new Set(n.map(a=>a.id));return ig(n,i,t.reporter),{activities:n,activityIds:i,hiddenIds:r}}function $m(e){return e===0}function zm(e,t){if(!e)return null;let r=Td[e.toUpperCase()];return r===void 0?(t.warn(`[parseFromBackend] unknown constraint label "${e}" \u2014 defaulting to "asap"`),Dd):r}function qm(e,t){let r=zm(e.constraint,t),i=r!=="asap"&&r!=="alap"&&e.constraint_date?xt(e.constraint_date):null;return{constraintType:r,constraintDate:i}}function Jm(e,t,r){if(e==null)return r;let n=String(e);return t.has(n)?n:r}function Xm(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 Zm(e){if(typeof e!="object"||e===null||!("id"in e))return!1;let t=e.id;return typeof t=="string"||typeof t=="number"}function ya(e){if(!Array.isArray(e))return[];let t=[];for(let r of e)Zm(r)&&t.push(String(r.id));return t}function Qm(e){return e==="0"?null:String(e)}function tg(e,t){return Array.isArray(e)?e.map(r=>un(r,t)).filter(r=>r!==null):[]}function eg(e,t){let r=Jm(e.calendarId,t.knownCalendarIds,t.defaultCalendarId),n=e.calendarId==null||!t.knownCalendarIds.has(String(e.calendarId)),i=Number(e.progress),{constraintType:a,constraintDate:s}=qm(e,t.reporter),o=e.type==="milestone",c=xt(e.start_date),l=o?c:xt(e.end_date),d=o?0:Number(e.duration);return{id:String(e.unique_id),proplannerId:typeof e.id=="number"?e.id:null,parentId:Qm(e.parent_id),name:e.name,description:e.description??"",type:e.type,startDate:c,endDate:l,durationHours:Ye(d,t.hoursPerDay),constraintType:a,constraintDate:s,autoScheduling:$m(i),calendarId:r,assignedDefaultCalendar:r!=null&&n,dateOrigin:e.date_origin==null?null:xt(e.date_origin),progress:i,cost:Number(e.cost),usedCost:Number(e.used_cost??0),realCost:Number(e.real_cost??0),workHours:Number(e.hhWorkTime),realWorkHours:Number(e.real_work??0),ponderator:Number(e.ponderator??0),hasCustomPonderator:e.hasCustomPonderator,correlativeId:e.correlative_id,uniqueCorrelativeId:e.unique_correlative_id,customId:rg(e),subcontractId:e.subcontractId,isLookahead:e.isOnLookahead,hasLookaheadTasks:Array.isArray(e.tasks)&&e.tasks.length>0,newActivityIds:Xm(e.newActivitiesArray),hasNewActivities:e.hasNewActivities??!1,...e.isNewActivity===!0?{isNewActivity:!0}:{},pendingRequestIds:ya(e.pendingRequests),responsableIds:ya(e.responsables),tagIds:ya(e.tags),baselinePoints:tg(e.baseline_points,t.reporter),baselineSnapshot:null,recursiveDurationHours:Ye(Number(e.sumOfDurationRecursively??0),t.hoursPerDay),calendarDuration:Rt({type:e.type,startDate:c,endDate:l}),isCritical:!!e.is_critical,freeSlackHours:null,expectedProgress:null,expectedProgressBaseline:null,status:null,criticalPath:null}}function rg(e){return e.has_childs?null:e.custom_id}function ng(e){let t=e.find(r=>r.correlativeId===0&&r.type==="project");t&&(t.parentId=null)}function ig(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 bd(e,t,r,n=null){let s=(e!==void 0&&e.length>0?e:t??[]).map(c=>og(c,n)),o=(r??[]).map(c=>cg(c,n));return{calendars:s,baseCalendars:o,knownCalendarIds:new Set(s.map(c=>c.id)),defaultCalendarId:sg(s)}}function sg(e){let t=e.find(n=>n.is_default);if(t)return t.id;let r=e[0];return r?r.id:null}function Ld(e,t){let r=hg(e.working_days),{days:n,hours:i}=pg(e,r),a=lg(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 og(e,t){let r=e.baseDefault,n=typeof r=="boolean"?r:void 0;return Ld(e,{idSuffix:"",isDefault:!!e.is_default,baseDefault:n,exceptionsSource:e.exceptiondays,exceptionRange:t})}function cg(e,t){return Ld(e,{idSuffix:"-base",isDefault:!1,baseDefault:!!e.is_default,exceptionsSource:e.baseexceptiondays??e.exceptiondays,exceptionRange:t})}function lg(e,t){if(!Array.isArray(e)||e.length===0)return null;let r={};for(let n of e){if(!n)continue;let i=dg(n.from_date,n.to_date,t);if(i.length===0)continue;let a=ug(n);if(a!==void 0)for(let s of i)r[s]=a}return Object.keys(r).length>0?r:null}function dg(e,t,r){let n=Pd(e),i=Pd(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 Pd(e){if(typeof e!="string")return null;let t=Sd.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 ug(e){if(e.workable===!1)return!1;let t=e.shifts;if(Array.isArray(t)&&t.length>0){let r=fg(t);if(r.length>0)return r}}var Rd=/^\d{1,2}:\d{2}$/;function fg(e){let t=[];for(let r of e){let n=xd(r?.shift_string);if(!n)continue;if(!n.startsCsv.includes(",")&&!n.endsCsv.includes(",")){let o=n.startsCsv.trim(),c=n.endsCsv.trim();!Pn(o)&&!Pn(c)&&Rd.test(o)&&Rd.test(c)&&t.push(`${o}-${c}`);continue}let s=Od(n.startsCsv,n.endsCsv).find(o=>o!==null);s&&t.push(s)}return t.sort(wd),t}function Ed(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 wd(e,t){return Ed(e)-Ed(t)}function pg(e,t){let r=Array.from({length:7},()=>[]),n=(l,d)=>{let u=Od(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=xd(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(wd);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 Od(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];Pn(c)||Pn(l)||(s[o]=`${c}-${l}`)}return s}function xd(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 hg(e){if(typeof e!="string")return[...pa];let t=e.split(",").map(r=>r.trim());return t.length!==7?[...pa]:t.map(r=>kd.has(r))}var yg=new Set(["false","null"]);function Pn(e){return!e||yg.has(e)}function mg(e){return e==="0"||e==="1"||e==="2"||e==="3"}function gg(e){if(typeof e!="string")return null;let t=Xs(e);return t||(mg(e)?e:null)}function Fd(e,t){let r=[];for(let n of e)try{r.push(vg(n,t.knownActivityIds,t.hoursPerDay))}catch(i){t.reporter.warn("[parseFromBackend] dropping invalid link",i)}return Ag(r)}function vg(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=gg(e.type);if(s===null)throw new Error(`[parseFromBackend] link "${n}" has invalid type "${String(e.type)}"`);let o=e.ganttId,c=e.sectorId,l=e.id;return{id:n,source:i,target:a,type:s,lag:At(Number(e.lag??0),r),...typeof o=="number"?{ganttId:o}:{},...typeof c=="number"?{sectorId:c}:{},...typeof l=="number"?{proplannerId:l}:{}}}function Ag(e){let t=new Map;for(let r of e){let n=`${r.source}-${r.target}-${r.type}`,i=t.get(n);(!i||Nd(r)>Nd(i))&&t.set(n,r)}return[...t.values()]}function Nd(e){let t=Number(e.id);return Number.isFinite(t)?t:-1/0}function Cg(e){if(typeof e!="string")return ha;switch(e.toUpperCase()){case"DURATION":return"DURATION";case"COST":return"COST";case"HH":return"HH";default:return ha}}function Ig(e){let t=e.custom_id_prefix;return typeof t=="string"&&t.length>0?t:void 0}function Sg(e){let t=e.custom_id_increment;return typeof t=="string"?t:typeof t=="number"&&Number.isFinite(t)?String(t):void 0}function Md(e){let t=Ig(e),r=Sg(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:Cg(e.activity_creter),statusCriteria:Hn,ganttId:null}}function Rn(e,t=he){let r=Md(e.sector),{calendars:n,baseCalendars:i,knownCalendarIds:a,defaultCalendarId:s}=bd(e.calendars,e.sector.calendars,e.baseCalendars,kg(e.activities)),{activities:o,activityIds:c,hiddenIds:l}=_d(e.activities,{knownCalendarIds:a,defaultCalendarId:s,hoursPerDay:r.hoursPerDay,reporter:t}),d=Fd(e.links,{knownActivityIds:c,hoursPerDay:r.hoursPerDay,reporter:t});return{sector:r,activities:o,links:d,calendars:n,baseCalendars:i,viewStateSeed:{hiddenIds:l}}}function kg(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 Wd(e={}){let t=e.seed??0,r=n=>{n>t&&(t=n)};if(e.knownIds)for(let n of e.knownIds){let i=typeof n=="number"?n:Number(n);Number.isFinite(i)&&r(i)}return{next(){return t+=1,String(t)},bump(n){let i=typeof n=="number"?n:Number(n);Number.isFinite(i)&&r(i)},snapshot(){return t},restore(n){t=n}}}function Ud(e={}){let t=e.seed??0,r=n=>{n>t&&(t=n)};if(e.knownIds)for(let n of e.knownIds){let i=typeof n=="number"?n:Number(n);Number.isFinite(i)&&r(i)}return{next(){return t+=1,String(t)},bump(n){let i=typeof n=="number"?n:Number(n);Number.isFinite(i)&&r(i)},snapshot(){return t},restore(n){t=n}}}function Bd(e={}){let t=e.seed??0,r=n=>{Number.isFinite(n)&&n>0&&n<=9999999&&n>t&&(t=n)};if(e.knownIds)for(let n of e.knownIds){if(n==null)continue;let i=typeof n=="number"?n:Number(n);r(i)}return{next(){return t+=1,String(t)},bump(n){if(n==null)return;let i=typeof n=="number"?n:Number(n);r(i)},snapshot(){return t},restore(n){t=n}}}function jd(e){return!!e&&typeof e=="string"&&e.trim().length>0}function En(e){if(!e||typeof e!="string"||e.trim().length===0)return"";let t=e.match(/^(.*?)(\d+)$/);return t?t[1]??"":e}function bn(e){if(!e||typeof e!="string"||e.trim().length===0)return"";let t=e.match(/(\d+)$/);return t?t[1]??"":""}function Hd(e){if(!e||typeof e!="object")return"";let t=e.customId;return typeof t=="string"?t:""}function Vd(e,t){return!t&&jd(e)}function Yd(e,t){return t&&jd(e)}function ir(e){return typeof e=="string"&&e.length>0&&/^\d+$/.test(e)}function nr(e){if(!ir(e))return 0n;try{return BigInt(e)}catch{return 0n}}function Dg(e,t){if(typeof e!="bigint")return"";let r=e.toString();if(!ir(t))return r;let n=t.length;return r.padStart(n,"0")}function St(e,t){let r=nr(e),n=nr(t),i=r+n;return Dg(i,e)}function Ln(e,t){let r=nr(e),n=nr(t);return r<n?-1:r>n?1:0}function wn(e,t){return Ln(e,t)<=0?e:t}function On(e,t){return Ln(e,t)>=0?e:t}function Kd(e){if(!e||e.length===0)throw new Error("minSuffixFromArray requires non-empty array");return e.reduce((t,r)=>wn(t,r))}function Gd(e){if(!e||e.length===0)throw new Error("maxSuffixFromArray requires non-empty array");return e.reduce((t,r)=>On(t,r))}function $d(e){return{prefix:e,baseSuffix:null}}function zd(e,t){let r=bn(e);return{prefix:En(e),baseSuffix:St(r,t)}}function qd(e){return{prefix:e,baseSuffix:null}}function Jd(e,t){return Vd(e,t)?"parentConversion":Yd(e,t)?"pasteReference":"noContext"}function Tg(e){return{...e,usedSuffixes:new Set(e.usedSuffixes)}}var xn=class{prefixMap=new Map;processedIds=new Set;_journalPrefixBefore=null;_journalIds=null;beginCustomIdTransaction(){this._journalPrefixBefore=new Map,this._journalIds=[]}commitCustomIdTransaction(){this._journalPrefixBefore=null,this._journalIds=null}rollbackCustomIdTransaction(){let t=this._journalPrefixBefore,r=this._journalIds;if(!(t===null||r===null)){for(let[n,i]of t)i===null?this.prefixMap.delete(n):this.prefixMap.set(n,i);for(let n of[...r].reverse())n.hadId?this.processedIds.add(n.customId):this.processedIds.delete(n.customId);this._journalPrefixBefore=null,this._journalIds=null}}_noteCustomIdBefore(t){if(this._journalPrefixBefore===null||this._journalIds===null)return;let{prefix:r}=this.analyzeCustomId(t);if(!this._journalPrefixBefore.has(r)){let n=this.prefixMap.get(r);this._journalPrefixBefore.set(r,n?Tg(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=Kd(n),r.max=Gd(n),r.quantity=n.length,this._recalculateNext(t)}defaultPrefix;suffixIncrement;constructor(t={}){this.defaultPrefix=t.defaultPrefix??"A",this.suffixIncrement=t.suffixIncrement??"10"}extractPrefix(t){return En(t)}extractSuffix(t){return bn(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=wn(r,n.min),n.max=On(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=wn(n,i.min),i.max=On(n,i.max),i.quantity+=1,this._recalculateNext(r))}else this.prefixMap.set(r,{min:n,max:n,next:St(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}${St(r.max,this.suffixIncrement)}`.length>20}_suffixForUnknownPrefix(t,r){let n=r&&ir(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(;Ln(n,r.max)<0;){if(`${t}${n}`.length>20)return null;if(!r.usedSuffixes.has(n))return n;n=St(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||!ir(r)){let o=St(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=St(a,i)}let s=St(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,St(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=Hd(r),a=Jd(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=St(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 $d(this.defaultPrefix);case"pasteReference":return zd(r,this.suffixIncrement);default:return qd(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=St(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 _g=1,Pg=-1;function Rg(e,t){return!e&&!t?null:e&&t?0:e?_g:Pg}function Xd(e){return e==null}function Zd(e,t){let r=t.indexOf(String(e));return r===-1?t.length:r}function Eg(e,t,r){return e instanceof Date&&t instanceof Date?e.getTime()-t.getTime():typeof e=="number"&&typeof t=="number"?e-t:typeof e=="boolean"&&typeof t=="boolean"?Number(e)-Number(t):Array.isArray(e)&&Array.isArray(t)?e.length-t.length:String(e).localeCompare(String(t),r,{sensitivity:"base",numeric:!0})}function bg(e,t){let r=Ft(e.field);return r===null?null:(n,i)=>{let a=r.extract(n,t),s=r.extract(i,t),o=Rg(Xd(a),Xd(s));if(o!==null)return o;let c=r.valueKind==="enum"?Zd(a,r.order)-Zd(s,r.order):Eg(a,s,t.locale);return e.direction==="desc"?-c:c}}function Qd(e,t){let r=e.rules.map(n=>bg(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 tu(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,pe),Lg(e,r)}function Lg(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 eu(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?ht(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 ru(e){let{state:t,sector:r,scheduler:n,skipAutoSchedule:i,now:a}=e;if(at(t),r.updateDurationForPrimaveraEndDate&&Og(t),xg(t),eu(t),i){a&&(re(t,a),Nt(t,r.statusCriteria));return}let s=await n.schedule({});Ue(t,s),Ng(t),wg(t),await me(t,void 0,!1),a&&(re(t,a),Nt(t,r.statusCriteria))}function wg(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=Rt(t))})}function Og(e){e.forEachActivity(t=>{!t.startDate||!t.endDate||(t.durationHours=e.calculateDuration({startDate:t.startDate,endDate:t.endDate,task:t}))})}function xg(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=Ot(t.constraintDate,i,r))})}function Ng(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=Ot(t.constraintDate,n,r))})}var kt={READY:"ready",DESTROYED:"destroyed",POISONED:"poisoned"};function nu(e){let t=e.clock??null,r=t?.()??null,n=r?Wr(r):null,i=e.reporter??he,a=Rn({sector:e.sector,activities:e.activities,links:e.links,calendars:e.calendars,baseCalendars:e.baseCalendars},i),s=a.sector;s.statusCriteria=ur(e.statusCriteria),s.ganttId=e.ganttId??null;let o=a.calendars,c=a.baseCalendars??[],l=Dn(a.activities,a.links,a.calendars,c),d=g=>Qd(g,Xt(s.hoursPerDay)),u=new xe(l,d);u.hydrateViewState({hiddenIds:a.viewStateSeed.hiddenIds});let f=new Lr(u,i);tu(u);let p=Wd({knownIds:a.activities.map(g=>g.id)}),h=Ud({seed:r?.getTime()??0,knownIds:a.links.map(g=>g.id)}),v=Bd({knownIds:a.activities.map(g=>g.uniqueCorrelativeId)}),I=new xn({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;fn(u,e.baselinePoints,n,i,g)}let T=ru({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:v,customIdTracker:I,calendars:o,baseCalendars:c,clock:t,reporter:i,initPromise:T}}var Fg=()=>({constantStart:null,variableStartOffset:null,constantEnd:null,variableEndOffset:null}),ga=(e,t)=>e===null?t:Math.min(e,t),va=(e,t)=>e===null?t:Math.max(e,t);function au(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=Mg(e,t,n);return Wg(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=Bg(o,s),l=jg(o,s);if(c===null||l===null)throw new Error(`[ScheduleCore] incomplete date gesture bounds for ${String(a)}`);return{startTimeMs:c,endTimeMs:l}}}}function Mg(e,t,r){let n=new Map,i=t.kind==="move"?String(t.anchorActivityId):null,a=i===null?null:iu(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=iu(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 Wg(e,t,r){let n=ei(e,new Set(t));for(let i of n){let a=Fg();for(let s of e.getChildren(i)){let o=r.get(s);if(o){Ug(a,o);continue}let c=e.getActivity(s);if(!c)throw new Error(`[ScheduleCore] missing child ${s} while previewing parent ${i}`);a.constantStart=ga(a.constantStart,c.startDate.getTime()),a.constantEnd=va(a.constantEnd,c.endDate.getTime())}r.set(i,a)}}function iu(e,t){let r=e.getActivity(t);if(!r)throw new Error(`[ScheduleCore] missing date gesture activity ${t}`);if(e.hasChildren(t))throw new Error(`[ScheduleCore] summary activity ${t} cannot be dragged directly`);return r}function Ug(e,t){t.constantStart!==null&&(e.constantStart=ga(e.constantStart,t.constantStart)),t.variableStartOffset!==null&&(e.variableStartOffset=ga(e.variableStartOffset,t.variableStartOffset)),t.constantEnd!==null&&(e.constantEnd=va(e.constantEnd,t.constantEnd)),t.variableEndOffset!==null&&(e.variableEndOffset=va(e.variableEndOffset,t.variableEndOffset))}function Bg(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 jg(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 Hg=new Set(["inline-edit","bulk-edit","dates-batch"]);function Vg(e){for(let t of e.activities)if(t.kind==="deleted"||t.kind==="updated"&&t.fields!==void 0&&"parentId"in t.fields)return!0;return!1}function Yg(e,t){let r=[];for(let n of e.activities){let i=t.getActivity(n.id);if(i===null)return null;r.push(i)}return r}function Kg(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 Nn=class{_activityClipboard={value:null};_status=kt.READY;coreRuntime;_undo=new kn;_opQueue=Promise.resolve();_scheduleRevision=0;_pendingScheduleRevision=0;_criticalPathRevision=-1;_activeCriticalPath=null;constructor(t){let r=nu(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!==kt.DESTROYED&&this._saveTracker.init(this.coreRuntime.state.getAllActivities(),this.getAllLinksView())}),this._criticalPathReady=this._initPromise.then(()=>this._enqueue(async()=>{let i=await this._runCriticalPathAndCapture();return this._criticalPathRevision=this._scheduleRevision,i}));let n=t.criticalPathOnLoad===!0;this._ready=n?this._criticalPathReady.then(()=>{}):this._initPromise}get ready(){return this._ready}get criticalPathReady(){return this._criticalPathReady}get status(){return this._status}getSector(){return B(this.coreRuntime.sector)}getActivityView(t){return this.assertReady(),$l(this.coreRuntime.state,t)}createDateGesturePreview(t){this.assertReady();let r=this._scheduleRevision;return au(this.coreRuntime.state,t,()=>{if(this.assertReady(),this._scheduleRevision!==r)throw new Error("[ScheduleCore] date gesture preview is stale")})}getAllActivitiesView(){return this.assertReady(),zl(this.coreRuntime.state)}getIndentTargetParentIds(t){this.assertReady();let r=dn(t.map(n=>String(n)),this.coreRuntime.state);return[...new Set(r.allowedMoves.map(n=>String(n.newParentId)))]}getChildrenView(t){return this.assertReady(),Xl(this.coreRuntime.state,t)}getLinkView(t){return this.assertReady(),td(this.coreRuntime.state,t)}getAllLinksView(){return this.assertReady(),ed(this.coreRuntime.state)}auditEffectiveGraph(){this.assertReady();let t=this.coreRuntime.state,r=t.getAllLinks(),n=je(t,r),i=kr(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(),ql(this.coreRuntime.state)}forEachActivityId(t){this.assertReady(),Jl(this.coreRuntime.state,t)}getChildrenIds(t){return this.assertReady(),la(this.coreRuntime.state,t)}getSelectedActivityIds(){return this.assertReady(),Zl(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(),Ql(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(),rd(this.coreRuntime.calendars.values())}getModifiedLinks(){return this.assertReady(),this._saveTracker.modifiedLinks(this.getAllLinksView())}getModifiedActivities(){return this.assertReady(),this._saveTracker.modifiedActivities(this.coreRuntime.state.getAllActivities()).map(B)}hasUnsavedChanges(){return this.assertReady(),this._saveTracker.hasUnsavedChanges()}getScheduleRevision(){return this._scheduleRevision}applyPreviewInverse(t){return this._enqueue(async()=>{this.assertReady();let r=this.coreRuntime.state,n=new Map;for(let o of t.activities)o.kind!=="deleted"&&o.after&&n.set(String(o.id),z(o.after));let i=new Map;for(let o of t.links)o.kind!=="deleted"&&o.after&&i.set(String(o.id),{...o.after});let a=er(t,void 0,void 0,n,i);fa(r,a),In(a)&&this._resyncCustomIdTrackerFromModel();let s={...t,activities:t.activities.map(o=>{if(o.kind==="deleted")return{...o,after:null};let c=r.getActivity(String(o.id));return{...o,after:c?z(c):null}}),links:t.links.map(o=>{if(o.kind==="deleted")return{...o,after:null};let c=r.getLink(String(o.id));return{...o,after:c?ut(c):null}})};return this._reapplyViewState(s)??s})}getDeletedActivitiesSinceLastSave(){return this.assertReady(),this._saveTracker.deletedActivities(this.coreRuntime.state.getAllActivities()).map(B)}getDeletedLinksSinceLastSave(){return this.assertReady(),this._saveTracker.deletedLinks(this.getAllLinksView()).map(B)}_enqueue(t){let r=this._opQueue.then(t,t);return this._opQueue=r.then(()=>{},()=>{}),r}_beginScheduleMutation(t){return xi(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=r.preview===!0?!1:this._beginScheduleMutation(t);return this._enqueue(()=>this._dispatchInner(t,r,n))}async applyActivityBatch(t,r={}){let n=r.preview===!0?!1: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(),r.preview===!0&&!Hg.has(t.kind))return{result:{ok:!1,reason:S.PREVIEW_UNSUPPORTED_ACTION},changedState:!1};let n=nd(this.coreRuntime.state,{hoursPerDay:this.coreRuntime.sector.hoursPerDay,dateFormat:this.coreRuntime.sector.dateFormat,...r.inputUnit!==void 0?{inputUnit:r.inputUnit}:{}}),i=ud(t,r),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 Il(t,r,{adapter:this.coreRuntime.state,ctx:n,scheduler:this.coreRuntime.scheduler,sector:this.coreRuntime.sector,calendars:this.coreRuntime.calendars,activityIdGen:this.coreRuntime.activityIdGenerator,linkIdGen:this.coreRuntime.linkIdGenerator,uidGen:this.coreRuntime.uniqueCorrelativeIdGenerator,customIdTracker:this.coreRuntime.customIdTracker,reporter:this.coreRuntime.reporter,activityClipboard:this._activityClipboard,defaultBaseCalendarId:this.coreRuntime.baseCalendars.find(o=>o.baseDefault)?.id??null,now:this.coreRuntime.clock?Wr(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"&&ua(s.changes)){let o=od(this.coreRuntime.state,s.changes);this._undo.record(er(da(s.changes),s.__beforeSnap,s.__beforeLinks,o.afterSnap,o.afterLinks),cd(t),Date.now())}if(s.ok&&(i==="clear-on-success"?(this._saveTracker.snapshotActivities(this.coreRuntime.state.getAllActivities()),this._saveTracker.snapshotLinks(this.getAllLinksView()),this._undo.clear()):t.kind==="activity-lookahead-sync"&&t.acknowledgePersistedLookahead===!0?this._saveTracker.acknowledgePersistedLookahead(t.activityIds,o=>this.coreRuntime.state.getActivity(o)):r.preview!==!0&&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)return{result:s,changedState:!1};if(r.preview===!0){let o=Sn(this.coreRuntime.state,er(da(s.changes)),"before");return{result:{...Aa(s),preview:{inverse:o,revision:this._scheduleRevision}},changedState:!1}}return xi(t)&&ua(s.changes)?(this._recordScheduleMutation(r.skipAutoSchedule!==!0&&r.skipCriticalPath!==!0&&ie(t)),{result:Aa(s),changedState:!0}):{result:Aa(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),!gc(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=Jt(this.coreRuntime.state,c,c);return d.length===0?a:{...s,viewState:[...s.viewState??[],...d]}}_emitTouchedBranchOrder(t){let r=this.coreRuntime.state,n=yd(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=jn(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:Fe(n)};let a=new Set(r);for(let o of t.activities){if(o.kind==="deleted")return{...t,order:Fe(n)};let c=n.getParentId(o.id);a.add(c===null?"0":String(c))}let s=jn(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=Xt(this.coreRuntime.sector.hoursPerDay),a=r.getFilterProjection(),s=Kg(a,n,i),o=Vg(t)?null:Yg(t,r),c,l;if(o===null||!s){let f=cr({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=Ea(a,o,f=>r.getParentId(f)),l=a.visibleIds;let u=Jt(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===kt.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 xe(Dn(this.coreRuntime.state.getAllActivities().map(o=>z(o)),this.coreRuntime.state.getAllLinks().map(o=>({...o})),Array.from(this.coreRuntime.calendars.values()),this.coreRuntime.baseCalendars)),i=()=>!r.cancelled&&this._status!==kt.DESTROYED&&this._scheduleRevision===t&&this._pendingScheduleRevision===this._scheduleRevision,a=(async()=>{let o=await wi(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)Li(this.coreRuntime.state,l,d);c=await U(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===kt.DESTROYED)return{changes:{source:{kind:"init"},activities:[],links:[],calendars:[],trackingEvents:[]}};this.coreRuntime.state.beginWriteCapture(),this.coreRuntime.customIdTracker.beginCustomIdTransaction();let t;try{await Jr(this.coreRuntime.state,this.coreRuntime.sector.hoursPerDay),t=await U(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;fd(this.coreRuntime.state,n),this._recordScheduleMutation(!1),r(!0),In(n)&&this._resyncCustomIdTrackerFromModel(),this._undo.pushRedo(n),this._undo.resetCoalesce();let i=Sn(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;fa(this.coreRuntime.state,r),this._recordScheduleMutation(!1),t(!0),In(r)&&this._resyncCustomIdTrackerFromModel(),this._undo.pushUndo(r),this._undo.resetCoalesce();let n=Sn(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=kt.DESTROYED}_initPromise;_criticalPathReady;_ready;_saveTracker=new _n;assertReady(){if(this._status===kt.DESTROYED)throw new Error("[ScheduleCore] instance is destroyed");if(this._status===kt.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=kt.POISONED,this.coreRuntime.reporter.error("[ScheduleCore] rollback failed \u2014 core poisoned",r),r}}};function Aa(e){let{__beforeSnap:t,__beforeLinks:r,...n}=e;return n}var su=(e=[])=>(e??[]).filter(t=>!t.proplannerId);var ou={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 cu=8;var Y={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",SIR_APPROVE:"sir-approve",ACTIVITY_LOOKAHEAD_SYNC:"activity-lookahead-sync"},Gg={[Y.ACTIVITY_CLIPBOARD_CLEAR]:!0,[Y.ACTIVITY_COPY]:!0,[Y.ACTIVITY_PASTE_COPIED]:!0,[Y.PERSISTENCE_ACKNOWLEDGE]:!0,[Y.BASELINE_APPLY]:!0,[Y.PONDERATOR_CRITERION_SET]:!0,[Y.STATUS_CRITERIA_SET]:!0,[Y.INLINE_EDIT]:!0,[Y.DATES_BATCH]:!0,[Y.BULK_EDIT]:!0,[Y.LINK_CREATE]:!0,[Y.LINK_UPDATE]:!0,[Y.LINK_DELETE]:!0,[Y.LINKS_BATCH]:!0,[Y.ACTIVITY_CREATE]:!0,[Y.ACTIVITY_DELETE]:!0,[Y.ACTIVITY_MOVE]:!0,[Y.ACTIVITY_INDENT]:!0,[Y.ACTIVITY_OUTDENT]:!0,[Y.ACTIVITY_SET_PROGRESS]:!0,[Y.SELECTION_TOGGLE]:!0,[Y.SELECTION_REPLACE]:!0,[Y.VISIBILITY_SET]:!0,[Y.FILTER_SET]:!0,[Y.SORT_SET]:!0,[Y.SIR_SYNC]:!0,[Y.SIR_APPROVE]:!0,[Y.ACTIVITY_LOOKAHEAD_SYNC]:!0},lu=Object.keys(Gg);var du={CHILD:"child",CHILD_CONFIRMED:"child-confirmed",LINE:"line",ROOT:"root"};return gu($g);})();
|
|
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
|