@outbuild-company/schedule-core 1.9.4 → 1.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- "use strict";var ScheduleCore=(()=>{var Wn=Object.defineProperty;var Zd=Object.getOwnPropertyDescriptor;var Qd=Object.getOwnPropertyNames;var tu=Object.prototype.hasOwnProperty;var eu=(e,t)=>{for(var r in t)Wn(e,r,{get:t[r],enumerable:!0})},ru=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Qd(t))!tu.call(e,i)&&i!==r&&Wn(e,i,{get:()=>t[i],enumerable:!(n=Zd(t,i))||n.enumerable});return e};var nu=e=>ru(Wn({},"__esModule",{value:!0}),e);var Qg={};eu(Qg,{ACTIVITY_TYPE:()=>mr,CALENDAR_UNIT:()=>ot,COLUMN:()=>_,CONSTRAINT_TYPE:()=>K,CONSTRAINT_TYPE_TO_LABEL:()=>$d,CREATION_KIND:()=>Jd,DEFAULT_HOURS_PER_DAY:()=>zd,DISPATCH_ACTION_KIND:()=>G,DISPATCH_ACTION_KINDS:()=>qd,DISPATCH_TRACK_EVENT:()=>It,LINK_CODE_TO_TYPE:()=>Qt,LINK_TYPE:()=>W,LINK_TYPE_CODE:()=>ks,NEW_ACTIVITY_DEFAULTS:()=>an,REJECTION_REASON:()=>k,ROOT_PARENT_ID:()=>N,SCHEDULE_CORE_STATUS:()=>kt,STATUS:()=>bt,ScheduleCore:()=>Mn,WORK_TIME_DIRECTION:()=>X,checkNoUpdatedLinks:()=>sd,computeExpectedProgress:()=>fi,expectedProgressFromBaseline:()=>Ee,getActiveBaseline:()=>ut,getUnsavedActivities:()=>Gd,isRootParent:()=>L,normalizeParentKey:()=>Bt,parseFromBackend:()=>Rn,willRunCriticalPath:()=>Wl,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 ur=e=>String(e);function La(e){let{clickedId:t,isChecked:r,currentSelection:n,hierarchy:i,isFrozen:a,exists:s,autoCheckParents:o}=e,c=ur(t),l=new Set([...n].map(String)),d=new Set(l),u=iu(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:su(l,d),parentBlocked:p}}function iu(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=ur(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=ur(c);if(a(l))return;let d=i.getChildrenIds(l).map(ur).filter(s),u=d.some(a),f=d.filter(m=>!a(m)),h=f.length>0&&f.every(m=>o.has(m))&&!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 su(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 k={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 Fa(e,t){let{adapter:r}=t,n=e.activityId;if(!r.getActivity(n))return{ok:!1,reason:k.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 fr(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 xa(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 ou=["Waiting","Done","Doing","Overdue","Advancement"],cu=["mfo","mso","snlt","snet","alap","asap","fnet","fnlt"];function Bn(e,t){return e===null||t<=0?null:e/t}function lu(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)=>Bn(e.durationHours,t.hoursPerDay)},calendarDuration:{valueKind:"number",extract:e=>e.type==="milestone"?0:lu(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)=>Bn(e.freeSlackHours,t.hoursPerDay)},totalSlackDays:{valueKind:"number",extract:(e,t)=>Bn(e.criticalPath?.totalSlackHours??null,t.hoursPerDay)},expectedProgressBaseline:{valueKind:"number",extract:e=>e.expectedProgressBaseline},expectedProgress:{valueKind:"number",extract:e=>e.expectedProgress},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:ou,extract:e=>e.status},constraintType:{valueKind:"enum",order:cu,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 du[e]??null}function jn(e){return e instanceof Date?e:typeof e=="string"||typeof e=="number"?new Date(e):new Date(Number.NaN)}function uu(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 fu(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 pu(e,t,r){return typeof e=="number"&&e>=t&&e<=r}function hu(e,t,r){return e instanceof Date?r==="after"?e.getTime()>t.getTime():r==="before"?e.getTime()<t.getTime():!1:!1}function yu(e,t,r){if(!(e instanceof Date))return!1;let n=e.getTime();return n>=t.getTime()&&n<=r.getTime()}function mu(e,t,r){let i=(Array.isArray(e)?e:[]).some(a=>t.has(String(a)));return r==="someOf"?i:r==="notSomeOf"?!i:!1}function gu(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 a==="between"?n.valueKind==="number"?pu(i,Number(t.value),Number(t.valueTo)):n.valueKind==="date"?yu(i,jn(t.value),jn(t.valueTo)):!1:n.valueKind==="string"?uu(i,String(t.value),a):n.valueKind==="number"?fu(i,Number(t.value),a):n.valueKind==="date"?hu(i,jn(t.value),a):n.valueKind==="id-array"?mu(i,Na(t.value),a):gu(i,Na(t.value),a)}function vu(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 Au(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 Un(e,t,r){let n=vu(e,t,r),i=t.dateRange,a=i===void 0||Au(e,i);return n&&a}function Iu(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)Un(o,n,i)&&(a.add(String(o.id)),s.push(o.id));for(let o of s)Iu(o,r,a);return a}function Cu(e){let{activities:t,parentOf:r,filter:n,context:i}=e,a=new Set,s=new Map,o=new Map,c=new Map;for(let l of t){let d=String(l.id),u=r(d);o.set(d,u),c.set(d,c.get(d)??0),u!==null&&c.set(u,(c.get(u)??0)+1);let f=Un(l,n,i);s.set(d,f?1:0),f&&a.add(d)}return{matchedIds:a,visibleReferenceCounts:s,parentIds:o,remainingChildren:c}}function ku(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 Su(e){let t=new Set;for(let[r,n]of e)n>0&&t.add(r);return t}function pr(e){let t=Cu(e);ku(t);let r=Su(t.visibleReferenceCounts);return{filter:e.filter,context:e.context,matchedIds:t.matchedIds,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=Un(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 Du={string:new Set(["includes","notIncludes","is","isNot"]),number:new Set(["equals","notEquals","greaterThan","lessThan","greaterOrEqual","lessOrEqual","between"]),date:new Set(["after","before","between"]),"id-array":new Set(["someOf","notSomeOf"]),enum:new Set(["someOf","notSomeOf"]),boolean:new Set(["someOf","notSomeOf"]),reference:new Set(["someOf","notSomeOf"])};function ja(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 Ua(e){let t=Wt(e.field);if(t===null)return{ok:!1,reason:"unknown_field"};if(!Du[t.valueKind].has(e.operator))return{ok:!1,reason:"unknown_operator"};if(e.operator==="between")return Tu(e,t.valueKind);if(t.valueKind==="number"){let n=Hn(e.value);return n===null?{ok:!1,reason:"invalid_value"}:{ok:!0,criterion:{...e,value:n}}}if(t.valueKind==="date"){let n=Vn(e.value);return n===null?{ok:!1,reason:"invalid_value"}:{ok:!0,criterion:{...e,value:n}}}let r=_u(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 Tu(e,t){if(t==="number"){let r=Hn(e.value),n=Hn(e.valueTo);return r===null||n===null||r>n?{ok:!1,reason:"invalid_value"}:{ok:!0,criterion:{...e,value:r,valueTo:n}}}if(t==="date"){let r=Vn(e.value),n=Vn(e.valueTo);return r===null||n===null||r.getTime()>n.getTime()?{ok:!1,reason:"invalid_value"}:{ok:!0,criterion:{...e,value:r,valueTo:n}}}return{ok:!1,reason:"unknown_operator"}}function _u(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 Hn(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 Vn(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 Pu(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=pr({activities:n,parentOf:a=>e.getParentId(a),filter:t,context:Zt(r)});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=Ua(u);if(!f.ok)return{ok:!1,reason:f.reason};i.push(f.criterion)}let a=ja(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}=Pu(r,s,n);r.setFilterProjection(c);let l=ye(r,o);return{ok:!0,changes:{source:e,activities:[],links:[],calendars:[],trackingEvents:[],viewState:l}}}var N="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;function gt(e,t){let r=Ue(e,t),n=t.getOrderComparator?.()??null;return r.sort(n===null?hr:(i,a)=>n(i,a)||hr(i,a)),r.map(i=>String(i.id))}function Ka(e){let t=[],r=i=>{t.push(i);let a=gt(String(i.id),e);for(let s of a){let o=e.getActivity(s);o&&r(o)}},n=gt("0",e);for(let i of n){let a=e.getActivity(i);a&&r(a)}return t}function 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&&!bu(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 Ue(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 hr(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 bu(e,t){return e.has(t)?!0:e.has(String(t))}function me(e){let t=[],r=n=>{let i=gt(n,e);i.length>1&&t.push({parentId:n,childIds:i});for(let a of i)r(a)};return r("0"),t}function Gn(e,t){let r=[];for(let n of t){let i=gt(n,e);i.length>1&&r.push({parentId:n,childIds:i})}return r}function Ru(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=Ru(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 Eu={TEXT:"text",DESCRIPTION:"description",DURATION:"duration",PROGRESS:"progress",COST:"cost",USED_COST:"used_cost",HH_WORK_TIME:"hhWorkTime",START_DATE:"start_date",END_DATE:"end_date",CONSTRAINT_TYPE:"constraint_type",CONSTRAINT_DATE:"constraint_date",CALENDAR_ID:"calendar_id",CUSTOM_ID:"custom_id",SUBCONTRACT_ID:"subcontractId",RESPONSABLES:"responsables",TAGS:"tags",CUSTOM_PREDECESSORS:"custom_predecessors",CUSTOM_SUCESSORS:"custom_sucessors"},Lu={REAL_WORK:"real_work",REAL_COST:"real_cost",EXPECTED_PROGRESS:"expected_progress",EXPECTED_PROGRESS_BASE:"expected_progress_base",START_BASE:"start_base",END_BASE:"end_base",DURATION_BASE:"duration_base",COST_BASE:"cost_base",WORK_BASE:"work_base",CALENDAR_DURATION:"calendarDuration",IS_CRITICAL:"is_critical",EARLY_START:"earlyStart",EARLY_FINISH:"earlyFinish",LATE_START:"lateStart",LATE_FINISH:"lateFinish",FREE_SLACK:"freeSlack",TOTAL_SLACK:"totalSlack",CORRELATIVE_ID:"correlative_id",UNIQUE_CORRELATIVE_ID:"unique_correlative_id",PONDERATOR:"ponderator",STATUS:"status"},_={...Eu,...Lu};function qa(e,t){throw new Error(t)}function Ja(e,t){return()=>t()===e}var X={FUTURE:"future",PAST:"past"},ot={HOUR:"hour",DAY:"day"},bt={DONE:"Done",OVERDUE:"Overdue",ADVANCEMENT:"Advancement",WAITING:"Waiting",DOING:"Doing"};var K={ASAP:"asap",ALAP:"alap",SNET:"snet",SNLT:"snlt",FNET:"fnet",FNLT:"fnlt",MSO:"mso",MFO:"mfo"},wu={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 Za(e,t,r){if(!t)return{violated:!1};let n=wu[e];return n?n(t,r)?{violated:!0,constraintType:e,constraintDate:t}:{violated:!1}:{violated:!1}}var Ou=new Set(["mso","snet","snlt"]);function He(e,t,r){return Ou.has(e)?t:r}function Qa(e,t,r){return{type:"constraint",messageKey:"constraint_violation",data:{constraintType:e,constraintDate:t,...r?{projectedDate:r}:{}}}}var Fu={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}},yr=e=>new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate())),Xa=(e,t)=>new Date(e.getTime()+t*864e5),xu=(e,t)=>e.getUTCFullYear()===t.getUTCFullYear()&&e.getUTCMonth()===t.getUTCMonth()&&e.getUTCDate()===t.getUTCDate();function $n(e,t){if(!e.constraintDate||!e.constraintType)return null;let r=Fu[e.constraintType];if(!r)return e.constraintDate;let n=e.constraintDate,i=t.getClosestWorkTime({date:yr(n),dir:X.FUTURE,task:e});if(xu(i,n))return n.getTime()!==yr(n).getTime()?n:r.startOfDay?i:t.getClosestWorkTime({date:Xa(yr(n),1),dir:X.PAST,task:e});let a=yr(t.getClosestWorkTime({date:n,dir:r.direction,task:e}));return r.startOfDay?t.getClosestWorkTime({date:a,dir:X.FUTURE,task:e}):t.getClosestWorkTime({date:Xa(a,1),dir:X.PAST,task:e})}function ts(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=$n(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 zn(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 mr={TASK:"task",PROJECT:"project",MILESTONE:"milestone"},rs={ALAP_DEBOUNCE_MS:1e3,CRITICAL_PATH_DEBOUNCE_MS:1e3,YIELD_SLICE_MS:8};var qn=typeof window>"u",Nu=!qn&&typeof MessageChannel<"u";function Z(){return Nu?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 gr(e,t){return performance.now()-e<rs.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 qn||await Z(),e()?{aborted:!1}:{aborted:!0}}function vr(e,t){let{inDegree:r,successors:n}=Mu(e,t),i=Wu(r),a=Bu(i,r,n),s=a.length<e.length,o=s?ju(e,a):[],c=[...a].reverse();return{ordered:a,reversed:c,hasCycles:s,cycleNodes:o}}function Mu(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 Wu(e){let t=new ht;for(let[r,n]of e)n===0&&t.enqueue(r);return t}function Bu(e,t,r){let n=[];for(;!e.isEmpty();){let i=e.dequeue();n.push(i);for(let a of r.get(i)??[]){let s=(t.get(a)??1)-1;t.set(a,s),s===0&&e.enqueue(a)}}return n}function ju(e,t){let r=new Set(t);return e.filter(n=>!r.has(n))}var Ar=class{cached=null;invalidate(){this.cached=null}get(t,r){return this.cached?this.cached:(this.cached=vr(t,r),this.cached)}};function ns(e,t){let r=[];for(let n of e)t.has(n)&&r.push(n);return r}var Jn={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 is(e){return e==="project"||e==="task"||e==="milestone"}function Lt(e,t){return t||is(e)&&Jn[e].alwaysSummary}function wt(e){return e==="milestone"}function jt(e){return is(e)&&Jn[e].promotesToProjectOnFirstChild}var Xn="project",ve="task";function Ve(e,t){return t===0?"milestone":e===0&&t>0?"task":null}function Ir(e,t){let r=t.getActivity(e);return r?Lt(r.type,t.getChildren(e).length>0):!1}function Cr(e,t,r){let n=String(t),i=r.getActivity(e);for(;i?.parentId&&String(i.parentId)!=="0";){if(String(i.parentId)===n)return!0;i=r.getActivity(i.parentId)}return!1}function Zn(e,t,r){let n=Ir(e,r);return Ir(t,r)&&Cr(e,t,r)||n&&Cr(t,e,r)}function os(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 Uu(e){let t=new Map;for(let r of e)as(t,String(r.source),r),as(t,String(r.target),r);return t}function as(e,t,r){let n=e.get(t);if(n){n.push(r);return}e.set(t,[r])}function Hu(e,t,r,n){if(e.length<=1)return e;let i=new Set(e.map(String)),a=[];for(let s of e)Vu(s,i,t,r,n)||a.push(s);return a.length>0?a:e}function Vu(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(Yu(c,a,s,t,r,i))return!0;return!1}function Yu(e,t,r,n,i,a){if(Ku(e)||!(a?String(e.source)===t:String(e.target)===t))return!1;let o=Gu(e,t);if(!n.has(String(o)))return!1;let c=i.getActivity(o);return!!(c?.autoScheduling!==!1&&c&&$u(e,r,c))}function Ku(e){return e.source===e.target}function Gu(e,t){return String(e.source)===t?e.target:e.source}function $u(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 Sr(e,t){let r=[],n=Uu(e),i=0;for(let a of e){let s=Ir(a.source,t),o=Ir(a.target,t);if(zu(a,s,o,t))continue;if(!s&&!o){r.push(a);continue}let c=ss(a.source,s,t,n,!0),l=ss(a.target,o,t,n,!1);i=ef(r,c,l,a,t,i,n)}return r}function zu(e,t,r,n){return r&&Cr(e.source,e.target,n)||t&&Cr(e.target,e.source,n)}function ss(e,t,r,n,i){return t?Hu(os(e,r),r,n,i):[e]}function qu(e,t,r){let n=os(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 kr(e,t){return qu(e,t,r=>{let n=t.getActivity(r);return n?{startDate:n.startDate,endDate:n.endDate}:null})}function Ju(e,t,r){return e?t?r.calculateDuration({startDate:t.startDate,endDate:t.endDate,task:e}):e.durationHours:0}function Xu(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 Zu(e,t){let r=String(e);return(t.get(r)??[]).some(i=>String(i.target)===r)}function Qu(e,t,r,n,i){if(Zu(e,i))return 0;let a=n.getActivity(e);return!t||!a||!r?0:n.calculateDuration({startDate:t,endDate:a.startDate,task:r})}function tf(e,t){let r=t.getActivity(e.source),n=t.getActivity(e.target),i=kr(e.source,t),a=kr(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?-Ju(n,a,t):0,summarySourceId:e.type===W.START_TO_START&&i?e.source:void 0}}function ef(e,t,r,n,i,a,s){let o=tf(n,i),{source:c,sourceBounds:l,targetStart:d,userLag:u}=o,{sourceEndpointIsStart:f,targetLag:p,summarySourceId:h}=o,m=a;for(let I of t){let T=f?Xu(I,c,l,i):0;for(let v of r){if(String(I)===String(v))continue;let S=Qu(v,d,c,i,s);e.push(rf(n,I,v,m,T,p,u+S,h,S!==0&&p===0?n.target:void 0)),m+=1}}return m}function rf(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 Dr=class{invalidate(){}get(t,r){return Sr(t,r)}};function nf(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 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 cs(e,t){let r=new Map;for(let s of t)r.set(s.id,s);let n=nf(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 ls(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 sf(e,t,r){if(e._summarySourceId===void 0)return null;let n=r.getActivity(e._summarySourceId);if(!n)return null;let i=kr(e._summarySourceId,r);return i?-r.calculateDuration({startDate:i.startDate,endDate:t.endDate,task:n}):null}function of(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 ds(e,t,r,n){let{sourceLag:i,targetLag:a,trueLag:s,isFS:o,isFF:c}=ls(e,t,r),l=sf(r,e,n)??i,d=l+a+s;if(!(t.durationHours===0?d!==0:l!==0||a!==0||s!==0))return of(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 m=new Date(Date.UTC(h.getUTCFullYear(),h.getUTCMonth(),h.getUTCDate()));return{successorStart:n.getClosestWorkTime({date:m,dir:"future",task:t}),link:r}}return{successorStart:n.getClosestWorkTime({date:h,dir:"future",task:t}),link:r}}function us(e,t,r,n){let{sourceLag:i,targetLag:a,trueLag:s}=ls(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 fs(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=ts(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 Tr(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=zn(e.startDate,n):es(i,n)?a=i:a=zn(i,n),t.startDate=a,t.endDate=r.calculateEndDate({startDate:a,durationHours:e.durationHours,task:e})}function ps(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 cf(e,t){return t.length?t.some(r=>String(r)===String(e)):!1}function hs(e,t,r){return Qn(e.id,t,r)?{startDate:e.startDate,endDate:e.endDate}:{startDate:e.startDate,endDate:e.endDate}}function Qn(e,t,r){return t.dragWithMultiple&&cf(e,r)}async function ms(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 gr(d,i);if(f.aborted)return a;d=f.newSliceStart;let p=r.getActivity(u);if(!p||!p.autoScheduling||p.progress===100||lf(p,r))continue;let h=s.get(String(u))??[],m=null,I=null,T=!1;for(let w of h){let A=r.getActivity(w.source);if(!A)continue;let C=o(w.source),R=C.startDate.getTime()!==A.startDate.getTime()||C.endDate.getTime()!==A.endDate.getTime(),x={...A,startDate:C.startDate,endDate:C.endDate},F=hs(x,c,l),z={...x,startDate:F.startDate,endDate:F.endDate},Q=Qn(w.source,c,l)?{...w,lag:0}:w,lt=ds(z,p,Q,r);(!m||lt.successorStart>m)&&(m=lt.successorStart,I=String(w.id),T=w._summaryTargetId!==void 0&&!R)}m!==null&&T&&m<p.startDate&&(m=new Date(p.startDate));let S=a.get(u),g=S?{...S}:{activityId:u,startDate:p.startDate,endDate:p.endDate,drivingLinkId:null,kind:"asap",conflict:!1},P=g.earliestStart||g.latestStart||g.earliestEnd||g.latestEnd;if(!(!m&&!P)){if(m){let w=m;p.type===mr.MILESTONE&&(w=ps(p,m)),g.drivingLinkId=I,g.startDate=w,g.endDate=r.calculateEndDate({startDate:w,durationHours:p.durationHours,task:p}),g.earliestSchedulingStart=w,g.earliestSchedulingEnd=g.endDate}else p.constraintType===K.MSO?g.earliestStart&&(g.startDate=g.earliestStart,g.endDate=g.earliestEnd??r.calculateEndDate({startDate:g.earliestStart,durationHours:p.durationHours,task:p})):p.constraintType===K.MFO&&g.latestStart&&(g.startDate=g.latestStart,g.endDate=g.latestEnd??r.calculateEndDate({startDate:g.latestStart,durationHours:p.durationHours,task:p}));Tr(p,g,r),a.set(u,g)}}return a}function lf(e,t){return Lt(e.type,t.getChildren(e.id).length>0)}async function gs(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 v=String(I.target);u.has(v)||u.set(v,[]),u.get(v).push(I)}let f=I=>{let T=s.get(I);if(T)return{startDate:T.startDate,endDate:T.endDate};let v=n.getActivity(I);return v?{startDate:v.startDate,endDate:v.endDate}:{startDate:new Date,endDate:new Date}},p=I=>!I.parentId||L(I.parentId)?n.getProjectEnd():f(I.parentId).endDate,h=(I,T)=>{let v=I,S=0;for(;v&&!L(v)&&S++<c+1;){if(String(v)===String(T))return!0;let g=n.getActivity(v);if(!g||!g.parentId)break;v=g.parentId}return!1},m=performance.now();for(let I of e){let T=await gr(m,a);if(T.aborted)return s;m=T.newSliceStart;let v=n.getActivity(I);if(!v||v.constraintType!==K.ALAP||!v.autoScheduling||v.progress===100||Lt(v.type,n.getChildren(I).length>0))continue;let S=p(v);if(!S)continue;let g=S,P=null,w=!1,A=d.get(String(I))??[];for(let St of A){if((St.lag??0)<0)continue;let pe=n.getActivity(St.target);if(!pe||pe.autoScheduling===!1)continue;let Ea=f(St.target),Xd={...pe,startDate:Ea.startDate,endDate:Ea.endDate},dr=us(Xd,v,St,n);dr<g&&(g=dr),(P===null||dr<P)&&(P=dr,w=v.parentId&&!L(v.parentId)?h(St.target,v.parentId):!1)}if(P!==null)if(w)g=P;else{let St=f(I).endDate,pe=St.getTime()>S.getTime()?St:S;g=P<pe?P:pe}else g>S&&(g=S);let R=(u.get(String(I))??[]).some(St=>St.type===W.FINISH_TO_START||St.type===W.FINISH_TO_FINISH),x=new Date(Date.UTC(g.getUTCFullYear(),g.getUTCMonth(),g.getUTCDate())),F=()=>n.getClosestWorkTime({date:x,dir:"past",task:v}),z=n.getClosestWorkTime({date:g,dir:"future",task:v}).getTime()===g.getTime(),Q;v.durationHours===0&&P===null?Q=R&&z?F():n.getClosestWorkTime({date:g,dir:"past",task:v}):v.durationHours===0?R?Q=F():Q=n.getClosestWorkTime({date:g,dir:"future",task:v}):Q=n.getClosestWorkTime({date:g,dir:"future",task:v});let lt=n.calculateEndDate({startDate:Q,durationHours:-v.durationHours,task:v}),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:v.durationHours,task:v}),Tr(v,nt,n),s.set(I,nt)}return s}var Ae={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 Ye(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 ti(e,t){let r=String(t.source),n=String(t.target);if(r===n)return!0;let i=new Map;for(let a of e){let s=String(a.source),o=String(a.target),c=i.get(s)??[];c.push(o),i.set(s,c)}return df(i,n,r)}function Ke(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 df(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 _r(e){let t=uf(e);for(let r of t.adjacency.keys())t.records.has(r)||ff(r,t);return t.components}function uf(e){let t=new Map,r=new Set;for(let n of e){let i=String(n.source),a=String(n.target),s=vs(t,i);if(vs(t,a),i===a){r.add(i);continue}s.push(a)}return{adjacency:t,selfLooped:r,records:new Map,componentStack:[],nextIndex:0,components:[]}}function vs(e,t){let r=e.get(t);if(r)return r;let n=[];return e.set(t,n),n}function ff(e,t){let r=[];for(r.push({node:e,record:As(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&&hf(n.node,t)}}function pf(e,t,r,n){let i=n.records.get(t);if(!i){r.push({node:t,record:As(t,n),neighborCursor:0});return}i.onStack&&i.visitIndex<e.record.lowLink&&(e.record.lowLink=i.visitIndex)}function As(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 hf(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 Ge(e,t,r){let n=r?new ei(e,r):e;return Sr([...t],n)}var ei=class{constructor(t,r){this.base=t;for(let[n,i]of r.reparented){let a=String(n),s=i===null||L(i)?null:i,o=t.getActivity(n)?.parentId??null,c=o===null||L(o)?null:String(o),l=s===null?null:String(s);if(c!==l){if(this.reparented.set(a,s),c!==null){let d=this.movedOutByParent.get(c)??new Set;d.add(a),this.movedOutByParent.set(c,d)}if(l!==null){let d=this.movedInByParent.get(l)??[];d.push(n),this.movedInByParent.set(l,d)}}}}base;reparented=new Map;movedOutByParent=new Map;movedInByParent=new Map;withOverride(t){if(!t)return null;let r=this.reparented.get(String(t.id));return r===void 0?t:{...t,parentId:r}}getActivity(t){return this.withOverride(this.base.getActivity(t))}getLiveActivity(t){return this.withOverride(this.base.getLiveActivity(t))}getAllActivities(){return this.base.getAllActivities().map(t=>this.withOverride(t)??t)}getChildren(t){let r=String(t),n=this.movedOutByParent.get(r),i=this.base.getChildren(t),a=n?i.filter(o=>!n.has(String(o))):[...i],s=this.movedInByParent.get(r);return s&&a.push(...s),a}getParent(t){let r=this.reparented.get(String(t));return r===void 0?this.base.getParent(t):r===null?null:this.getActivity(r)}isChildOf(t,r){let n=String(r),i=new Set,a=this.getActivity(t);for(;a;){let s=a.parentId;if(s===null||L(s))return!1;let o=String(s);if(o===n)return!0;if(i.has(o))return!1;i.add(o),a=this.getActivity(s)}return!1}getAllLinks(){return this.base.getAllLinks()}getAllIds(){return this.base.getAllIds()}getLink(t){return this.base.getLink(t)}activityExists(t){return this.base.activityExists(t)}getOutgoingLinkIds(t){return this.base.getOutgoingLinkIds(t)}getIncomingLinkIds(t){return this.base.getIncomingLinkIds(t)}getClosestWorkTime(t){return this.base.getClosestWorkTime(t)}calculateEndDate(t){return this.base.calculateEndDate(t)}calculateDuration(t){return this.base.calculateDuration(t)}batchUpdate(t){this.base.batchUpdate(t)}updateActivity(t){this.base.updateActivity(t)}getFlags(){return this.base.getFlags()}getProjectEnd(){return this.base.getProjectEnd()}};function $e(e){let{port:t,currentLinks:r,proposedLinks:n,proposal:i}=e,a=Ge(t,n,i);if(!Ke(a))return{ok:!0};let s=Ge(t,r),o=Is(s),l=[...Is(a)].filter(d=>!o.has(d));return l.length===0?{ok:!0}:{ok:!1,newlyCyclicActivityIds:l}}function Is(e){let t=new Set;for(let r of _r(e))for(let n of r)t.add(n);return t}function Ut(e,t){switch(e.kind){case"create":return yf(e,t);case"update":return ze(e,t.port);case"delete":return mf(e,t)}}function br(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=Cs(l);n.has(d)||n.set(d,l.id),i.push({source:l.source,target:l.target})}let a=Ke(i),s=null;for(let{operation:l,linkId:d}of e){if(String(l.source)===String(l.target)){s={applied:!1,rejected:"self-link"};break}if(!t.port.getActivity(l.source)||!t.port.getActivity(l.target)){s={applied:!1,rejected:"activity-missing"};break}if(Zn(l.source,l.target,t.port)){s={applied:!1,rejected:"hierarchy-link"};break}let u=Cs(l),f=n.get(u);if(f!==void 0){s={applied:!1,rejected:"duplicate",linkId:f};break}if(n.set(u,d),a&&ti(i,{source:l.source,target:l.target}))return{applied:!1,rejected:"cycle"};i.push({source:l.source,target:l.target})}if(!a&&Ke(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(!$e({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 Cs(e){return JSON.stringify([String(e.source),String(e.target),e.type])}function yf(e,t){let{port:r}=t;if(String(e.source)===String(e.target))return{applied:!1,rejected:"self-link"};let n=r.getActivity(e.source),i=r.getActivity(e.target);if(!n||!i)return{applied:!1,rejected:"activity-missing"};if(Zn(e.source,e.target,r))return{applied:!1,rejected:"hierarchy-link"};let a=r.getAllLinks();for(let d of a)if(String(d.source)===String(e.source)&&String(d.target)===String(e.target)&&d.type===e.type)return{applied:!1,rejected:"duplicate",linkId:d.id};let s=a.map(d=>({source:d.source,target:d.target}));if(ti(s,{source:e.source,target:e.target}))return{applied:!1,rejected:"cycle"};let o=(t.newLinkId??gf)(),c={id:o,source:e.source,target:e.target,type:e.type,lag:e.lag,freeSlackHours:null,isCritical:!1};return $e({port:r,currentLinks:a,proposedLinks:[...a,c]}).ok?(r.addLink(c),{applied:!0,linkId:o}):{applied:!1,rejected:"cycle"}}function ze(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 mf(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 Pr=null;function gf(){return Pr===null&&(Pr=Date.now()),Pr+=1,String(Pr)}var ks={[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},Ss="fs";function Ds(e){if(e in Qt)return Qt[e]}var Ts=";",_s=/^(\d+)(fs|ss|ff|sf)?(?:([+-]?)(\d+(?:\.\d+)?)d?)?$/i;function Rr(e){let t=[],r=[],n=e.replace(/\s+/g,"");if(n.length===0)return{specs:t,errors:r};for(let i of n.split(Ts)){if(i.length===0)continue;let a=vf(i);a?t.push(a):r.push(i)}return{specs:t,errors:r}}function vf(e){let t=e.toLowerCase(),r=_s.exec(t);if(!r)return null;let[,n,i,a,s]=r,o=i?Qt[i]:Qt[Ss],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 Lr(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=Er(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(Er(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 Er(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=Er(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(Er(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 Or(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 Ps={rawInputToConstraintDate(e,t){let r=new Date(e);return r.setUTCHours(0,0,0,0),r.getTime()===e.getTime()?t.getClosestWorkTime({direction:X.FUTURE,date:e,unit:ot.HOUR}):t.isWorkTime(e,ot.HOUR)?e:r},computeLagBetweenTasks(e,t,r){return r.calculateDuration(e,t)}};function ri(e,t,r){switch(r){case"0":return{sourceDate:e.endDate,targetDate:t.startDate};case"1":return{sourceDate:e.startDate,targetDate:t.startDate};case"2":return{sourceDate:e.endDate,targetDate:t.endDate};case"3":return{sourceDate:e.startDate,targetDate:t.endDate}}}var ni=Ps;var Ie=class{adapter;reporter;currentCalculationId=0;topoCache=new Ar;expandedLinksCache=new Dr;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=Ja(r,()=>this.currentCalculationId),i={plans:new Map,updatedIds:[],cycles:[],cancelled:!1};try{Cf(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=kf(t,l,this.adapter),p=f.links,h=f.idSet;Ot(d);let m=Ht("schedule.topologicalSort"),I=Df(this.topoCache,u,l,h);if(Ot(m),I.hasCycles)return Ot(a),{...i,cycles:[I.cycleNodes]};if((await ge(n)).aborted)return{...i,cancelled:!0};let T=Ht("schedule.processConstraints"),v=new Map;if(fs(I.ordered,this.adapter,v),Ot(T),(await ge(n)).aborted)return{...i,cancelled:!0};let S=Ht("schedule.asapPass"),g=await ms(I.ordered,p,this.adapter,t,n,v);if(Ot(S),(await ge(n)).aborted)return{...i,cancelled:!0};let P=Ht("schedule.alapPass"),w=await gs(I.reversed,p,g,this.adapter,t,n);if(Ot(P),(await ge(n)).aborted)return{...i,cancelled:!0};let A=Ht("schedule.diff"),C=[];for(let[R,x]of w){let F=this.adapter.getActivity(R);if(!F)continue;let z=F.startDate.getTime()!==x.startDate.getTime(),Q=F.endDate.getTime()!==x.endDate.getTime();(z||Q)&&C.push(R)}return Ot(A),Ot(a),{plans:w,updatedIds:C,cycles:[],cancelled:!1}}catch(a){return this.reporter.error("[AutoScheduler] Error during scheduling",a),i}}},Af=!1;function If(){let e=globalThis.__SCHEDULER_PHASE_LOG__;return typeof e=="boolean"?e:Af}function Ht(e){return{name:e,startedAt:performance.now()}}function Cf(e){let t=e;typeof t.clearCalendarCache=="function"&&t.clearCalendarCache()}function Ot(e){if(!If())return;let t=performance.now()-e.startedAt;console.log(`[scheduler] ${e.name} ${t.toFixed(1)}ms`)}function kf(e,t,r){let n=e.triggerId;if(n==null)return{idSet:null,links:t};let i=cs(n,t);return Sf(i,t,r)}function Sf(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 Df(e,t,r,n){let i=e.get(t,r);if(i.hasCycles){let s=n?Array.from(n):t;return vr(s,r)}if(!n)return i;let a=ns(i.ordered,n);return{ordered:a,reversed:[...a].reverse(),hasCycles:!1,cycleNodes:[]}}function bs(e,t,r){let n=t.getActivity(e);if(!n)return;let i=r?{...n,endDate:r.endDate}:n,a=t.calendarReader.getCalendar(String(n.calendarId));for(let s of t.getIncomingLinkIds(e)){let o=t.getLink(s);if(!o)continue;let c=t.getActivity(o.source);if(!c||c.constraintType==="alap"||wt(n.type)&&(o.type===W.START_TO_FINISH||o.type===W.FINISH_TO_FINISH))continue;let{sourceDate:d,targetDate:u}=ri(c,i,o.type),f=ni.computeLagBetweenTasks(d,u,a);f!==o.lag&&ze({kind:"update",linkId:o.id,lag:f},t)}}function Rs(e,t){let r=t.getActivity(e);r&&wt(r.type)&&(r.durationHours=0)}function Fr(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 Es(e){return Number(e.toFixed(2))}function qe(e){for(let t of Tf(e))ws(t,e)}function Ls(e,t){for(let r of e)ws(r,t)}function Tf(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,_f(n,e));return[...t].sort((n,i)=>(r.get(i)??0)-(r.get(n)??0))}function _f(e,t){let r=0,n=e;for(;n&&n!=="0"&&t.getActivity(n);)r+=1,n=t.getParentId(n);return r}function ws(e,t){let r=t.getChildren(e);if(r.length===0)return;let n=[];for(let i of r){let a=t.getActivity(i);a&&n.push({progress:Number(a.progress??0),ponderator:Number(a.ponderator??0)})}ii(e,n,t)}function ii(e,t,r){let n=r.getActivity(e);if(!n)return;let i=Fr(t);if(i===null){let a=r.getProgressFallback(e);a!==null&&r.setActivityField(e,_.PROGRESS,a);return}r.getProgressFallback(e)===null&&r.setProgressFallback(e,Number(n.progress??0)),r.setActivityField(e,_.PROGRESS,Es(i))}function Os(e,t,r){let n=[e];for(;n.length>0;){let i=n.pop();if(i===void 0)continue;let a=r.getChildren(i);a.length!==0&&(r.setProgressFallback(i,t),n.push(...a))}}function dt(e,t){return(Number(e)||0)*(Number(t)||0)/100}async function Ce(e,t,r=!0,n={}){let i=t?Je(e,t):wf(e),a=r?n.progressMode??"freeze-when-no-contribution":"skip";await Pf(i,e,a,{recomputeRealWork:n.recomputeRealWork??!1})}function xr(e,t){Fs(e,t,"skip")}async function Pf(e,t,r,n={recomputeRealWork:!1}){let a=0;for(let s of e)Fs(s,t,r,n.recomputeRealWork),a+=1,a%200===0&&await Z()}function Je(e,t){let r=new Set,n=new Map;for(let s of t)bf(s,e,r,n);if(r.size===0)return[];let i=Array.from(r),a=Rf(i,n);return xs(i,a)}function bf(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 Rf(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 Ef(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+=Lf(c,t.getChildren(o).length>0)),s.push({progress:Number(c.progress??0),ponderator:Number(c.ponderator??0)})}return{minStart:n,maxEnd:i,realWorkSum:a,weightedChildren:s}}function Fs(e,t,r="freeze-when-no-contribution",n=!1){let i=t.getActivity(e);if(!i)return;let a=t.getChildren(e);if(a.length===0)return;let s=Ef(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),r!=="skip"&&ii(e,s.weightedChildren,t),n&&t.setActivityField(e,"realWorkHours",s.realWorkSum)}function Lf(e,t){return t?Number(e.realWorkHours)||0:dt(e.workHours,e.progress)}function wf(e){let t=Of(e),r=Ff(t,e);return xs(t,r)}function Of(e){let t=new Set;return e.forEachActivity(r=>{r.parentId!==null&&t.add(r.parentId)}),Array.from(t)}function Ff(e,t){let r=new Map;for(let n of e)r.set(n,xf(n,t));return r}function xf(e,t){let r=0,n=e;for(;n&&!L(n)&&t.getActivity(n);)r+=1,n=t.getParentId(n);return r}function xs(e,t){return[...e].sort((r,n)=>(t.get(n)??0)-(t.get(r)??0))}var Ns={updateActivityDuration:Rs,updateTaskTiming:Mf("updateTaskTiming"),adjustLinkLagOnTaskMove:bs,recordLastStartDate:Nf};function Nf(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 Ns?Ns[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 Mf(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 U(){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 j(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 Ms={targetField:"name",canEdit(){return H()},parseInput(e){return typeof e!="string"?M("not_a_string"):O(e)},validate(){return U()},transform(e,t){return j({name:t},{autoSchedule:!1,postProcessors:[]})},trackEvent:"activity_name_entry"};var Ws={targetField:"description",canEdit(){return H()},parseInput(e){return typeof e!="string"?M("not_a_string"):O(e.trim())},validate(){return U()},transform(e,t){return j({description:t},{autoSchedule:!1,postProcessors:[]})},trackEvent:"activity_description_entry"};function Dt(e){return e.constraintType??K.ASAP}var Nr=100;function ke(e){return e.progress>=Nr}function et(e,t){return Lt(e.type,t.hasChildren(e.id))}function Bs(e){return e.progress>0}function js(e){return e.hasLookaheadTasks}function te(e,t){return Math.round(Math.ceil(e*t*60)/60)}var Se=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 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 Wf(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 ai(e,t){return e.getClosestWorkTime({direction:X.FUTURE,date:t,unit:ot.HOUR})}function si(e,t){let r=Wf(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"]),oi=new Set(["fnet","fnlt","mfo"]),Kt=new Set(["asap","alap"]),Br="snet";function Ft(e,t,r){let n=Yt(e,"UTC");if(!Mr.has(r)&&!oi.has(r))return n;let i=Mr.has(r)?ai(t,n):si(t,n),a=new Date(n);return a.setUTCHours(i.getUTCHours(),i.getUTCMinutes(),i.getUTCSeconds(),i.getUTCMilliseconds()),a}var Gt=()=>({constraintType:Br});var ee=e=>({constraintDate:e}),Us=e=>({constraintDate:e});var Hs={UPDATE_TASK_TIMING:"updateTaskTiming",ADJUST_LINK_LAG_ON_TASK_MOVE:"adjustLinkLagOnTaskMove",RECORD_LAST_START_DATE:"recordLastStartDate"};var Vs={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 De(e,t,r){return Za(e,t,r)}function Te(e,t,r){return Qa(e,t,r)}var Ks={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 Ys(r)?tt(Vs.NEGATIVE_DURATION):Bf(t,r)?tt("unchanged"):U()},transform(e,t,r){if(Ys(t))return j({},{autoSchedule:!1,postProcessors:[]});let n=jf(e,t,r),i=Uf(e,t,r,n.violated);return{...j(i,{autoSchedule:!0,postProcessors:[Hs.RECORD_LAST_START_DATE]}),...n.violated?{constraintWarning:Te(n.constraintType,n.constraintDate,Gs(e,t,r)??void 0)}:{}}},trackEvent:"activity_duration_entry"};function Ys(e){return Math.sign(e)===-1}function Bf(e,t){return e===t}function jf(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 De(i,e.constraintDate,a)}function Uf(e,t,r,n=!1){let i={};n&&Object.assign(i,Gt(),ee(e.startDate));let a=Ve(e.durationHours,t);a&&(i.type=a),i.durationHours=t;let s=Gs(e,t,r);return s&&Object.assign(i,Se(s)),i}function Gs(e,t,r){let n=r.calendars.getCalendar(e.calendarId);return n?n.calculateEndDate(e.startDate,t):null}var _e=e=>({realWorkHours:e});var Hf=0,Vf=Nr,$s=0,zs={targetField:"progress",canEdit(e,t){return js(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 Yf(r)?tt("out_of_range"):U()},transform(e,t,r){let n=Kf(t),i=Gf(t),a=qf(e,t,r.hierarchy),s={progress:t,autoScheduling:n,..._e(a.get(e.id)??0)},o=i?$f(e,t,n,r.hierarchy,a):[],c=i?Xf(e,t,r.hierarchy):[],l=o.length+c.length>0?[...o,...c]:void 0,d=[],u=i?Qf(e,t):void 0;return j(s,{autoSchedule:!1,postProcessors:d,cascadeMutations:l,trackingEvents:u})},trackEvent:"activity_progress_entry"};function Yf(e){return e<Hf||e>Vf}function Kf(e){return e===$s}function Gf(e){return e===Nr||e===$s}function $f(e,t,r,n,i){return n.getDescendantIds(e.id).map(s=>({activityId:s,fields:zf(t,r,i.get(s)??0)}))}function zf(e,t,r){return{progress:e,autoScheduling:t,..._e(r)}}function qf(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 Jf(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 Xf(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=[...Jf(e,r),...r.getAncestorIds(e.id)],a=[];for(let s of i){let o=Zf(s,n,r);o!==null&&(n.set(s,o),a.push({activityId:s,fields:{progress:o}}))}return a}function Zf(e,t,r){let n=r.getChildProgressInfo(e).map(a=>({progress:t.has(a.id)?t.get(a.id):a.progress,ponderator:a.ponderator??0})),i=Fr(n);return i===null?null:Number(i.toFixed(2))}function Qf(e,t){return[{name:"activity_progress_update_radio_button",properties:{activity_id:e.id,activity_name:e.name,progress_updated:t}}]}var qs={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 U()},transform(e,t,r){let n=tp(e,t,r.hierarchy);return j({cost:t},{autoSchedule:!1,postProcessors:[],cascadeMutations:n})},trackEvent:"activity_cost_budgeted_entry"};function tp(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 Js={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 U()},transform(e,t,r){let n=ep(e,t,r.hierarchy);return j({usedCost:t},{autoSchedule:!1,postProcessors:[],cascadeMutations:n})},trackEvent:"activity_cost_spent_entry"};function ep(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 Xs={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 U()},transform(e,t,r,n){let i=Zs(t,e.progress),a=String(n).trim()===""?[]:rp(e,t,i,r.hierarchy);return j({workHours:t,..._e(i)},{autoSchedule:!1,postProcessors:[],cascadeMutations:a})},trackEvent:"activity_labor_hours_budgeted_entry"};function Zs(e,t){return dt(e,t)}function rp(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??Zs(d.workHours,d.progress);c+=u,l+=f}i.set(o,c),a.set(o,l),s.push({activityId:o,fields:{workHours:c,..._e(l)}})}return s}function jr(e,t){return e.getUTCFullYear()===t.getUTCFullYear()&&e.getUTCMonth()===t.getUTCMonth()&&e.getUTCDate()===t.getUTCDate()}function ci(e,t){return e.getTime()<t.getTime()}function Pe(e){return e instanceof Date&&!Number.isNaN(e.getTime())}var Ur=e=>({durationHours:e});var Qs={targetField:"startDate",canEdit(e,t){return et(e,t)?q("summary","summary_column_value"):Bs(e)?q("has_progress","cant_edit_activity_with_progress"):H()},parseInput(e,t,r){return Pe(e)?O(Yt(e,"UTC")):M("invalid_date")},validate(e,t,r,n){if(jr(t,r))return tt("unchanged");let i=np(e,r,n);return i||U()},transform(e,t,r){let n=r.calendars.getCalendar(e.calendarId);if(!n)throw new Error("startDatePipeline: no calendar resolved (integrity)");let i=ai(n,t),a=e.type==="milestone",s=a?i:n.calculateEndDate(i,e.durationHours),o=i;return{...j({startDate:i,...Se(s),...a?Ur(0):{},...Gt(),...ee(o)},{autoSchedule:!0,postProcessors:["adjustLinkLagOnTaskMove"]}),constraintWarning:ip(e,i,n)}},trackEvent:"activity_start_date_entry"};function np(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 ip(e,t,r){let n=r.calculateEndDate(t,e.durationHours),i=He(Dt(e),t,n),a=De(Dt(e),e.constraintDate,i);if(a.violated)return Te(a.constraintType,a.constraintDate,i)}var ap=99.999,eo={targetField:"endDate",canEdit(e,t){return et(e,t)?q("summary","summary_column_value"):sp(e)?q("completed","cant_edit_completed_activity"):H()},parseInput(e,t,r){if(!Pe(e))return M("invalid_date");let n=Yt(e,"UTC"),i=r.calendars.getCalendar(t.calendarId);return i?i.isWorkTime(n,ot.DAY)?O(si(i,n)):O(i.getClosestWorkTime({direction:"past",date:n,unit:ot.HOUR})):O(n)},validate(e,t,r,n){if(jr(e.endDate,r))return tt("unchanged");if(op(r,e))return tt("before_date_origin");if(cp(r,e))return tt("before_start_date");let i=lp(r,e,n);return i||U()},transform(e,t,r){let n=dp(e,t),i=up(e,t,r,!!n);return{...j(i,{autoSchedule:!0,postProcessors:["updateTaskTiming"]}),...n?{constraintWarning:n}:{}}},trackEvent:"activity_end_date_entry"};function sp(e){return e.progress>=ap}function op(e,t){return t.dateOrigin?ci(e,t.dateOrigin):!1}function cp(e,t){return ci(e,t.startDate)}function lp(e,t,r){let n=r.calendars.getCalendar(t.calendarId);return n?n.isWorkTime(e,ot.DAY)?null:tt("not_working_day"):null}function dp(e,t){if(Dt(e)===K.MSO)return;let n=He(Dt(e),e.startDate,t),i=De(Dt(e),e.constraintDate,n);if(i.violated)return Te(i.constraintType,i.constraintDate,n)}function up(e,t,r,n=!1){let i={};wt(e.type)&&!n&&to(e)?Object.assign(i,ee(e.startDate)):(n||to(e))&&Object.assign(i,Gt(),ee(e.startDate));let o=fp(e,t,r),c=Ve(e.durationHours,o);return c&&(i.type=c),Object.assign(i,Ur(o)),i.endDate=t,i}function to(e){return Kt.has(Dt(e))}function fp(e,t,r){let n=r.calendars.getCalendar(e.calendarId);return n?n.calculateDuration(e.startDate,t):e.durationHours}var pp=new Set(Object.values(K)),ro={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 hp(t)?O(t):M("invalid_constraint_type")},validate(){return U()},transform(e,t,r){let n=yp(e,t,r);return j(n,{autoSchedule:!0})}};function hp(e){return pp.has(e)}function yp(e,t,r){let n=gp(e,t);return{constraintType:t,...Us(mp(e,t,n,r))}}function mp(e,t,r,n){if(e.type!=="milestone"||!r)return r;let i=n.calendars.getCalendar(String(e.calendarId));return i?Ft(r,i,t):r}function gp(e,t){return Kt.has(t)?null:Mr.has(t)?e.startDate:oi.has(t)?e.endDate:e.constraintDate}var no={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 Pe(e)?O(e):M("invalid_date")},validate(){return U()},transform(e,t,r){let n=io(e)?Br:Dt(e),i=r.calendars.getCalendar(e.calendarId);if(!i)throw new Error("constraintDatePipeline: no calendar resolved (integrity)");let a=Ft(t,i,n),s=vp(e,a);return j(s,{autoSchedule:!0})}};function vp(e,t){return{constraintDate:t,...io(e)?Gt():{}}}function io(e){return Kt.has(Dt(e))||!e.constraintType}var ao={targetField:"calendarId",canEdit(){return H()},parseInput(e){let t=String(e).trim();return Ap(t)?M("empty_calendar"):O(t)},validate(e,t,r,n){return Ip(e.calendarId,r)?tt("unchanged"):n.calendars.getCalendar(r)?U():tt("unknown_calendar")},transform(e,t,r){return j(Cp(e,t,r),{autoSchedule:!0,postProcessors:[]})},trackEvent:"activity_calendar_assignment"};function Ap(e){return e===""}function Ip(e,t){return e===t}function Cp(e,t,r){let n={calendarId:t,assignedDefaultCalendar:!1},i=r.calendars.getCalendar(t);if(i){let a=e.durationHours===0,s=a?kp(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,Se(i.calculateEndDate(c,e.durationHours)))}return n}function kp(e){return new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()))}var so={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 U()},transform(e,t){return j({customId:t},{autoSchedule:!1,postProcessors:[]})},trackEvent:"schedule_custom_id_edition"};var oo={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 U()},transform(e,t){return j({subcontractId:t},{autoSchedule:!1,postProcessors:[]})}};function Xe(e){if(e==null)return null;if(typeof e=="object"){if(!("id"in e))return null;let t=e.id;return t==null?null:String(t)}return String(e)}function Hr(e){return e.some(t=>Xe(t)===null)}var co={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 Hr(r)?tt("missing_id"):U()},transform(e,t){let r=t.map(Xe).filter(n=>n!==null);return j({responsableIds:r},{autoSchedule:!1,postProcessors:[]})}};var lo={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 Hr(r)?tt("missing_id"):U()},transform(e,t){let r=t.map(Xe).filter(n=>n!==null);return j({tagIds:r},{autoSchedule:!1,postProcessors:[]})}};var Sp=new Map([[_.TEXT,Ms],[_.DESCRIPTION,Ws],[_.DURATION,Ks],[_.PROGRESS,zs],[_.COST,qs],[_.USED_COST,Js],[_.HH_WORK_TIME,Xs],[_.START_DATE,Qs],[_.END_DATE,eo],[_.CONSTRAINT_TYPE,ro],[_.CONSTRAINT_DATE,no],[_.CALENDAR_ID,ao],[_.CUSTOM_ID,so],[_.SUBCONTRACT_ID,oo],[_.RESPONSABLES,co],[_.TAGS,lo]]);function $t(e){return Sp.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 Dp=["name","description","type","startDate","endDate","durationHours","constraintType","constraintDate","calendarId","assignedDefaultCalendar","autoScheduling","progress","cost","usedCost","workHours","realWorkHours","customId","subcontractId","responsableIds","tagIds"],uo=new Set(Dp);var E={ID:"id",PROPLANNER_ID:"proplannerId",PARENT:"parentId",NAME:"name",DESCRIPTION:"description",TYPE:"type",START_DATE:"startDate",END_DATE:"endDate",DURATION_HOURS:"durationHours",CONSTRAINT_TYPE:"constraintType",CONSTRAINT_DATE:"constraintDate",AUTO_SCHEDULING:"autoScheduling",CALENDAR_ID:"calendarId",ASSIGNED_DEFAULT_CALENDAR:"assignedDefaultCalendar",DATE_ORIGIN:"dateOrigin",PROGRESS:"progress",COST:"cost",USED_COST:"usedCost",REAL_COST:"realCost",WORK_HOURS:"workHours",REAL_WORK_HOURS:"realWorkHours",PONDERATOR:"ponderator",HAS_CUSTOM_PONDERATOR:"hasCustomPonderator",CORRELATIVE_ID:"correlativeId",UNIQUE_CORRELATIVE_ID:"uniqueCorrelativeId",CUSTOM_ID:"customId",SUBCONTRACT_ID:"subcontractId",IS_LOOKAHEAD:"isLookahead",HAS_LOOKAHEAD_TASKS:"hasLookaheadTasks",NEW_ACTIVITIES_ARRAY:"newActivityIds",HAS_NEW_ACTIVITIES:"hasNewActivities",IS_NEW_ACTIVITY:"isNewActivity",PENDING_REQUEST_IDS:"pendingRequestIds",RESPONSABLE_IDS:"responsableIds",TAG_IDS:"tagIds",BASELINE_POINTS:"baselinePoints",BASELINE_SNAPSHOT:"baselineSnapshot",SUM_OF_DURATION_RECURSIVELY:"recursiveDurationHours",CALENDAR_DURATION:"calendarDuration",IS_CRITICAL:"isCritical",FREE_SLACK_HOURS:"freeSlackHours",EXPECTED_PROGRESS:"expectedProgress",EXPECTED_PROGRESS_BASELINE:"expectedProgressBaseline",STATUS:"status",CRITICAL_PATH:"criticalPath"},Ze={ID:"id",SOURCE:"source",TARGET:"target",TYPE:"type",LAG:"lag",FREE_SLACK_HOURS:"freeSlackHours",IS_CRITICAL:"isCritical",SOURCE_LAG:"_sourceLag",TARGET_LAG:"_targetLag",TRUE_LAG:"_trueLag",SUMMARY_SOURCE_ID:"_summarySourceId",SUMMARY_TARGET_ID:"_summaryTargetId",GANTT_ID:"ganttId",SECTOR_ID:"sectorId",PROPLANNER_ID:"proplannerId"};function rt(e,t,r,n){e.setActivityFieldDynamic(t,r,n)}function fo(e,t,r,n){e.setLinkFieldDynamic(t,r,n)}function xt(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:Tp(e.baselineSnapshot),criticalPath:_p(e.criticalPath)}}function Et(e){return e===null?null:new Date(e)}function Tp(e){return e===null?null:{...e,startDate:Et(e.startDate),endDate:Et(e.endDate)}}function _p(e){return e===null?null:{...e,earlyStart:Et(e.earlyStart),earlyFinish:Et(e.earlyFinish),lateStart:Et(e.lateStart),lateFinish:Et(e.lateFinish)}}var yo=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%yo===0&&await Z();let a=e.getActivity(i);a&&r.set(i,J(a))}return r}function J(e){return xt(e)}function Vr(e,t){let r=e.getActivity(t);return r?xt(r):null}function qt(e,t,r){po(e,t,r.patch);for(let n of r.cascadeMutations??[])po(e,n.activityId,n.fields)}function po(e,t,r){for(let[n,i]of Object.entries(r)){if(!uo.has(n))throw new Error(`applyFieldChanges: column write to non-writable field "${n}"`);rt(e,t,n,i)}}async function Yr(e,t,r,n){let i=[],a=0;for(let s of r){a+=1,a%yo===0&&await Z();let o=Pp(e,t,s,n);o&&i.push(o)}return i}function Pp(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 bp(r,n.get(r),i);let s=di(a,i);return Rp(s,n,r,i),a&&Object.keys(s).length===0?null:{id:r,kind:a?"updated":"created",fields:s,after:J(i)}}function bp(e,t,r){return t===r.correlativeId?null:{id:e,kind:"updated",fields:{correlativeId:{before:t,after:r.correlativeId}},after:J(r)}}function Rp(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 di(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)||!li(n[s],i[s]))&&(r[s]={before:ho(n[s]),after:ho(i[s])});return r}function ho(e){return e===null||typeof e!="object"?e:b(e)}function li(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)=>li(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)&&li(r[s],n[s]))}function Kr(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 ui(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 Re(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 Ep=/^(\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(Ep);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 Ee(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 Lp=e=>e.type==="project",wp=(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 Ee(a(e.startDate),a(e.endDate),t,i)};function Op(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(!Lp(o)){let d=wp(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)}),Op(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 Fp=e=>e.type==="project",xp=e=>ut(e),Np=(e,t,r,n)=>{let i=xp(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:Ee(i.startDate,i.endDate,t,a)};function fi(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(!Fp(c)){let u=Np(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 Le(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)}),fi(i,t,n,r)}var pi="Baseline";function Gr(e){return e==="Actual"?"Actual":pi}var mo=e=>Math.round(e*100)/100;function Mp(e,t){return(t==="Baseline"?e.expectedProgressBaseline:e.expectedProgress)??void 0}function Wp(e,t){let r=mo(e),n=mo(t);return r>99.99?bt.DONE:n>r?bt.OVERDUE:e>0&&r>n?bt.ADVANCEMENT:e===0&&t===0?bt.WAITING:e>0&&r<n?bt.DOING:bt.WAITING}function Mt(e,t){let r=[];return e.forEachActivity((n,i)=>{let a=typeof n.progress=="number"?n.progress:0,s=Wp(a,Mp(n,t));n.status!==s&&(rt(e,i,_.STATUS,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 Bp(e){return e&&e.constructor===Date?!!(e.getFullYear&&e.getMonth&&e.getDate):!1}function $r(e){return Bp(e)&&!isNaN(e.getTime())}function D(e,t,r,n){if(!$r(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(!$r(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 jp=e=>e?e.$level===1:!1,Up=e=>e.type==="project",Hp=e=>e.$level!==0,Vp=e=>e.type==="task",Yp=e=>e.type==="task"||e.type==="milestone",ct={byFirstLevel:jp,filterByParentType:Up,avoidSubproject:Hp,byTaskType:Vp,byTaskTypeAndMilestone:Yp};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 go(e){let{gantt:t,pendingParentsWithNoLinks:r,calculations:n,linkProperty:i}=e;try{let a=Kp({gantt:t,pendingParentsWithNoLinks:r});if(a.length===0)return new Set;let s=Gp({gantt:t,subprojectsWithNoLinks:a}),o=$p({gantt:t,childrenIds:s,linkProperty:i,getArrayOfLinkedActivities:zp,calculations:n});return new Set(o.map(c=>c.id))}catch(a){throw a}}function Kp(e){let{gantt:t,pendingParentsWithNoLinks:r}=e;return t.getTaskByTime().filter(ct.filterByParentType).filter(n=>r.has(n.id)).map(n=>n.id)}function Gp(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 $p(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 zp(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 vo({gantt:e,linkProperty:t,direction:r}){try{let n=qp(e,t);if(r==="forward")return{chainStartActivities:n,activitiesStartChainButChildrenOfLinkedParents:null};if(r==="backward")return Jp(n,e,t)}catch(n){throw console.log("Critical Path",n),n}}function qp(e,t){return e.getTaskByTime().filter(ct.avoidSubproject).filter(ct.byTaskTypeAndMilestone).filter(r=>!r[t].length)}function Jp(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 Ao({gantt:e,direction:t,linkProperty:r}){try{let n=Xp(e),i=new Set,a=new Set,s=new Set;t==="backward"&&th(n).forEach(d=>{i.add(d.id)});let o=Zp(n,t,r),c=Qp(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 Xp(e){return e.getTaskByTime().filter(ct.filterByParentType).filter(ct.avoidSubproject)}function Zp(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 Qp(e,t){let r=new Set(t.map(n=>n.id));return e.filter(n=>!r.has(n.id))}function th(e){return e.filter(t=>{let r=Number(t.progress);return Number.isNaN(r)?!1:r===100})}function Io({pendingParentsWithLinks:e,gantt:t,direction:r}){try{let n=new Set;return e.forEach(i=>{let a=t.getTask(i),s=eh(r),o=rh(r),c=a[s];if(!Array.isArray(c))return;nh(t,c,o).forEach(d=>{n.add(d)})}),n}catch(n){throw n}}function eh(e){return e==="forward"?"$source":"$target"}function rh(e){return e==="forward"?"target":"source"}function nh(e,t,r){return t.map(n=>{let a=e.getLink(n)[r];return Number(a)})}var Qe={identifySecondLevelActivities:go,identifyInitialActivities:vo,identifyParentsWithAndWithoutLinks:Ao,identifyForbiddenActivities:Io};function zr(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}):tr(r,e,n,i)}function Co({duration:e,constraintDate:t,activityCalendar:r,activity:n}){let i=new Date(t);return{es:D(r,i,e,n),ef:i}}function ko({duration:e,constraintDate:t,activityCalendar:r,activity:n}){let i=new Date(t),a=D(r,i,e,n);return{es:i,ef:a}}function tr(e,t,r,n){if(![V.FS,V.SS,V.FF].includes(t))return e;let a=[V.FS,V.SS].includes(t)?"future":"past";return yt({dateBaseToCalculate:e,activityCalendar:r,direction:a,activity:n})}var 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=zr(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=ko({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=Co({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=tr(i,"ss",this.activityCalendar,this.activity));let a=D(this.activityCalendar,i,this.activity.duration,this.activity);return{es:i,ef:a}}calculateFFLink({lag:t,predecessorEf:r}){let n=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=tr(a,"ff",this.activityCalendar,this.activity)),{es:a,ef:i}}calculateFSLink({lag:t,predecessorEf:r}){let n=r;t===0&&(n=yt({dateBaseToCalculate:r,activityCalendar:this.activityCalendar,direction:"future",activity:this.activity}));let i=D(this.activityCalendar,n,t,this.activity),a=D(this.activityCalendar,i,this.activity.duration,this.activity);return{es:i,ef:a}}calculateSFLink({lag:t,predecessorEs:r}){let n=D(this.activityCalendar,r,t,this.activity),i=D(this.activityCalendar,n,-this.activity.duration,this.activity);return t>0&&(i=tr(i,"sf",this.activityCalendar,this.activity)),{es:i,ef:n}}},So=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)}},Do=gi;function To(e){let{parent:t,linkProperty:r,linkDirection:n,calculations:i,gantt:a,direction:s,linkCandidates:o}=e,c=t[r],l=ih(t),d=null;if(s==="forward"){let u=ah(c,n,i,a);d=new So(u,t,a,o),d=d.calculate()}else{let u=sh(c,n,i,a);d=new Do({linksWithActivityData:u,activity:t,parentData:l,gantt:a}).calculate()}return d}function ih(e){return{duration:e.duration,calendarId:e.calendar_id}}function ah(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 sh(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 bo(e){let{activityData:t,calculations:r,singleParents:n,direction:i}=e;if(oh(t.id,r))return null;let a=ch(t.id,n),s=lh(a,r);return s.length===0?null:dh(s,i)}function oh(e,t){return t.has(e)}function ch(e,t){let r=t.get(e);return r?r.childrens:[]}function lh(e,t){return e.filter(r=>t.has(r)).map(r=>t.get(r))}function dh(e,t){if(t==="forward"){let r=_o(e,"es"),n=Po(e,"ef");return{es:r,ef:n}}else{let r=_o(e,"ls"),n=Po(e,"lf");return{ls:r,lf:n}}}function _o(e,t){return e.reduce((r,n)=>n[t]<r[t]?n:r)[t]}function Po(e,t){return e.reduce((r,n)=>n[t]>r[t]?n:r)[t]}var vi={parentWithLinks:To,parentWithNoLinks:bo};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)})}},Ro=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}}},Eo=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}=Qe.identifyParentsWithAndWithoutLinks({gantt:this.gantt,direction:this.direction,linkProperty:this.linkProperty});this.parentsWithFullProgress=t,this.pendingParentsWithNoLinks=r,this.pendingParentsWithLinks=n}catch(t){throw t}}identifyForbiddenActivitiesLinkedToParentsWithLinks(){try{this.forbiddenActivitiesLinkedToParentsWithLinks=Qe.identifyForbiddenActivities({pendingParentsWithLinks:this.pendingParentsWithLinks,gantt:this.gantt,direction:this.direction})}catch(t){throw t}}getArrayOfIdOfLinkedActivities(t,r=!1){return t.map(n=>{let a=this.gantt.getLink(n)[r||this.linkDirection];return Number(a)})}async identifyThirdLevelActivities(){try{let{structureOfParents:t,singleParents:r}=new Eo({gantt:this.gantt,linkProperty:this.linkProperty}).identifyThirdLevelActivities();this.structureOfParents=t,this.singleParents=r}catch(t){throw t}}processEachActivity(t){let r=new Set,n=new Set,i=new Map,a=new Map;return this.singleParents.set(Number(t.id),{level:t.$level,hasLink:!!t[this.linkProperty].length,childrens:[]}),new Promise((s,o)=>{this.gantt.eachTask(function(c){let l=Number(c.parent);if(n.add(c.id),c.type==="project"){let u={level:c.$level,hasLink:!!c[this.linkProperty].length,childrens:[]};r.add(c.id),this.singleParents.set(Number(c.id),u)}l&&this.singleParents.has(l)&&this.singleParents.get(l).childrens.push(c.id),i.has(c.$level)||i.set(c.$level,new Map);let d=i.get(c.$level);d.has(Number(c.parent))||d.set(Number(c.parent),[]),d.get(Number(c.parent)).push({id:c.id,isParent:c.type==="project",calculated:!1})}.bind(this),t.id),s({parentsIds:r,allTasks:n,activitiesByLevel:i,singleParents:a})})}identifySecondLevelActivities(){try{let t=Qe.identifySecondLevelActivities({gantt:this.gantt,pendingParentsWithNoLinks:this.pendingParentsWithNoLinks,calculations:this.calculations,linkProperty:this.linkProperty});this.secondLevelActivities=new Set([...this.secondLevelActivities,...t])}catch(t){throw t}}identifyInitialActivities(){try{let{chainStartActivities:t,activitiesStartChainButChildrenOfLinkedParents:r}=Qe.identifyInitialActivities({gantt:this.gantt,linkProperty:this.linkProperty,direction:this.direction});this.chainStartActivities=t,r&&(this.activitiesStartChainButChildrenOfLinkedParents=r)}catch(t){throw new Error("Error in identifyInitialActivities",{cause:t})}}calculateSecondLevelActivities(){try{this.direction==="forward"?this.recursiveCalculateEfAndEs(Array.from(this.secondLevelActivities),0,"secondLevel"):this.recursiveCalculateLfAndLs(Array.from(this.secondLevelActivities))}catch(t){throw t}}calculateStartAndFinishOfActivitiesThatStartChain(){try{this.chainStartActivities.forEach(t=>{if(!t||t.progress>100||t.type==="project")return;let r=this.calculateStartAndFinishOfChainOrigin(t,this.direction);if(this.direction==="forward"){let{es:n,ef:i}=r;this.calculations.set(t.id,{es:n,ef:i,text:t.text}),this.activitiesWaitingForCalculation.delete(t.id)}else{let{ls:n,lf:i}=r;this.calculations.set(t.id,{ls:n,lf:i,text:t.text}),this.activitiesWaitingForCalculation.delete(t.id)}})}catch(t){throw t}}buildDependencyGraph(t){let r=new Map,n=new Set(this.calculations.keys()),i=new Map;return t.forEach(a=>{a&&i.set(a.id,a)}),i.forEach((a,s)=>{if(n.has(s))return;let o=[];(a[this.linkDirection]||[]).forEach(l=>{let d=this.gantt.getLink(l);if(d){let u=Number(d[this.linkProperty]);o.push(u)}}),o=o.filter(l=>i.has(l)||n.has(l)),r.set(s,o)}),{graph:r,activityMap:i,calculatedActivities:n}}topologicalSort(t,r){let n=new Set,i=new Set,a=[],s=o=>{if(i.has(o))throw new Error("Cyclical dependency detected",{cause:{nodeId:o}});if(!n.has(o)&&!r.has(o)){i.add(o);let c=t.get(o)||[];for(let l of c)s(l);i.delete(o),n.add(o),a.push(o)}};for(let o of t.keys())!n.has(o)&&!r.has(o)&&s(o);return a.reverse()}calculateStartAndFinishOfChainOrigin(t=null,r=null){try{let n=t,i=Number(n.progress);i==="0.00"&&(i=0);let a=this.gantt.getCalendar(n.calendar_id);if(!a)throw new Error(`Error trying to get calendar with id: ${n.calendar_id}`);if((r||this.direction)==="forward"){let o=n.start_date,c=n.end_date;return{es:o,ef:c}}else{if(i>=100)return{ls:At(n.start_date).clone(),lf:At(n.end_date).clone()};if(i===0)return this.calculateBackwardWhenZeroProgress(n,a);if(i<100&&i>0)return this.calculateWhenProgressIsBetweenZeroAndOneHundred(n,a)}}catch(n){throw n}}calculateBackwardWhenZeroProgress(t,r){let n=At(t.start_date).clone(),i=At(t.end_date).clone(),a=t.duration,s=[y.ASAP,y.ALAP,y.SNET,y.FNET],o=t.constraint_type||y.ASAP;if(s.includes(o))i=this.projectDates.end_date,n=D(r,i,-a,t);else{let c=[y.SNLT,y.MSO],l=[y.FNLT,y.MFO];c.includes(o)&&(n=t.constraint_date,i=D(r,n,a,t)),l.includes(o)&&(i=t.constraint_date,n=D(r,i,-a,t))}return{ls:n,lf:i}}calculateWhenProgressIsBetweenZeroAndOneHundred(t){let r=t.start_date,n=null,i=t.constraint_type||y.ASAP,a=this.projectDates.end_date,s=[y.ASAP,y.ALAP,y.SNET,y.FNET],o=[y.SNLT,y.FNLT];if(s.includes(i))n=Math.max(t.end_date,a);else if(i===y.MSO)n=t.end_date;else if(i===y.MFO||o.includes(i)){let c=Math.min(a,t.constraint_date);n=Math.max(c,t.end_date)}return{ls:r,lf:new Date(n)}}initializeActivitiesWithFullProgress(){try{Array.from(this.activitiesWaitingForCalculation).filter(n=>Number(this.gantt.getTask(n).progress)===100).map(n=>this.gantt.getTask(n)).forEach(n=>{let i=n.type==="project";this.setDatesForActivityWithFullProgress(n),this.activitiesWaitingForCalculation.delete(n.id),i&&this.pendingParentsWithLinks.has(n.id)&&(this.parentCalculationFromChildren.add(n.id),this.calculationsOfParentThatImpactChildrens.set(n.id,{[this.direction==="forward"?"es":"ls"]:n.start_date,[this.direction==="forward"?"ef":"lf"]:n.end_date}),this.calculationOfParentsFromLinks.add(n.id))})}catch(t){throw t}}doCalculationForParentType(t){let r=new Ro({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 uh(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 qr=uh;var ki=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})}},Lo=ki;var er=class extends Lo{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 zr(t)}calculateLink(t){return{0:()=>this.calculateFS(t),1:()=>this.calculateSS(t),2:()=>this.calculateFF(t),3:()=>this.calculateSF(t)}[t.type]()}};var Si=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}},Jr=Si;var Di=(e,t)=>()=>t()===e;var Ti=e=>!e?.fullyParsed||typeof window<"u"&&window.to_use_react_gantt?.conversionMode?.isActive;var fh=16,ae=async e=>performance.now()-e>fh?(await Z(),performance.now()):e;var rr=async({pending:e,activityCalculator:t,calculateFn:r,shouldKeepPending:n,isCalculated:i,onActivityProcessed:a,isCurrent:s})=>{let o=new Set(e),c=performance.now();for(;o.size>0;){if(!s())return;c=await 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 Jr({gantt:this.gantt,direction:this.direction,pendingParentsWithNoLinks:this.pendingParentsWithNoLinks,pendingParentsWithLinks:this.pendingParentsWithLinks,calculationOfParentsFromLinks:this.calculationOfParentsFromLinks,singleParents:this.singleParents,calculations:this.calculations,activitiesStartChainButChildrenOfLinkedParents:this.activitiesStartChainButChildrenOfLinkedParents,linkProperty:this.linkProperty,linkDirection:this.linkDirection});await rr({pending:this.activitiesWaitingForCalculation,activityCalculator:r,calculateFn:n=>this.calculateStartAndFinishTimes(n),shouldKeepPending:n=>this.calculationOfParentsFromLinks.has(n)&&!this.calculations.has(n),isCalculated:n=>this.calculations.has(n),onActivityProcessed:n=>this.activitiesWaitingForCalculation.delete(n),isCurrent:t})}calculateStartAndFinishTimes(t){t.forEach(r=>{let n=this.gantt.getTask(r);if(n.type==="project")return this.doCalculationForParentType(n);if(!n)throw new Error("Error trying to get activity",{cause:{activityId:r}});let i=n.$target,a=n.constraint_type||y.ASAP,s=[y.SNET,y.SNLT,y.FNLT,y.FNET],o=[y.ASAP,y.ALAP,y.SNET,y.FNET,y.SNLT,y.FNLT],c=this.gantt.getCalendar(n.calendar_id);if(!c)throw new Error(`Error trying to get calendar with id: ${n.calendar_id}`);let l=Number(n.progress),d=null,u=null,f=null;if(l===100){this.setDatesForActivityWithFullProgress(n);return}l>0&&o.includes(a)?({es:d,ef:u}=this.getDatesForActivityWithZeroProgress(n),f=new er({links:i,activity:n,calculatedActivitiesMap:this.calculations,calculatedAlapsMap:this.alapMap,constraint:a,parentsWithLinks:this.pendingParentsWithLinks,parentsCalculations:this.calculationsOfParentThatImpactChildrens,ganttInstance:this.gantt,linkCandidates:this.linkCandidates}).calculate(),a===y.ASAP&&this.totalFloatForAsap.set(r,{es:f.es,ef:f.ef,text:n.text})):{es:d,ef:u}=new er({links:i,activity:n,calculatedActivitiesMap:this.calculations,calculatedAlapsMap:this.alapMap,constraint:a,parentsWithLinks:this.pendingParentsWithLinks,parentsCalculations:this.calculationsOfParentThatImpactChildrens,ganttInstance:this.gantt,linkCandidates:this.linkCandidates}).calculate(),a===y.ALAP&&this.alapMap.set(r,{es:n.start_date,ef:n.end_date,text:n.text});let p=qr(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)}},wo=_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})}},Oo=Pi;var bi=class extends Oo{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))}},Fo=bi;function ph(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 xo=ph;var Ri=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 Jr({gantt:this.gantt,direction:this.direction,pendingParentsWithNoLinks:this.pendingParentsWithNoLinks,pendingParentsWithLinks:this.pendingParentsWithLinks,calculationOfParentsFromLinks:this.calculationOfParentsFromLinks,singleParents:this.singleParents,calculations:this.calculations,activitiesStartChainButChildrenOfLinkedParents:this.activitiesStartChainButChildrenOfLinkedParents,linkProperty:this.linkProperty,linkDirection:this.linkDirection});await rr({pending:this.activitiesWaitingForCalculation,activityCalculator:r,calculateFn:n=>this.calculateStartAndFinishTimes(n),shouldKeepPending:n=>this.calculationOfParentsFromLinks.has(n)&&!this.calculations.has(n),isCalculated:n=>this.calculations.has(n),onActivityProcessed:n=>this.activitiesWaitingForCalculation.delete(n),isCurrent:t})}setDatesToParentsWithLinks(t){if(!t)throw new Error("Error trying to get parent",{cause:{receivedParentData:t}});let r=this.singleParents.get(t.id).childrens,i=Array.from(this.calculations).filter(o=>r.includes(o[0])).map(o=>o[1]),{minLs:a,maxLf:s}=i.reduce((o,{ls:c,lf:l})=>({minLs:new Date(Math.min(o.minLs.getTime(),new Date(c).getTime())),maxLf:new Date(Math.max(o.maxLf.getTime(),new Date(l).getTime()))}),{minLs:new Date(i[0].ls),maxLf:new Date(i[0].lf)});this.calculations.set(t.id,{ls:a,lf:s})}calculateStartAndFinishTimes(t){t.forEach(r=>{let n=this.gantt.getTask(r);if(!n)throw new Error("Activity not found",{cause:{activityId:r}});let i=n.$source,a=n.constraint_type||y.ASAP,s=Number(n.progress);if(this.activitiesStartChainButChildrenOfLinkedParents.has(r)){if(this.calculationsOfParentThatImpactChildrens.has(Number(n.parent))&&this.calculationsOfParentThatImpactChildrens.get(Number(n.parent))===!1){let{ls:d,lf:u}=this.calculateStartAndFinishOfChainOrigin(n,this.direction);this.setCalculations(n,d,u);return}return this.doCalculationForActivitiesThatStartLinkButHisParentIsLinked(n)}if(n.type==="project")return this.doCalculationForParentType(n);if(s===100){this.setDatesForActivityWithFullProgress(n);return}if(this.allLinkedActivitiesHasProgress(i,n)){this.setWhenAllLinkedActivitiesHasProgress(n);return}if(s>0&&s<100&&(a===y.MSO||a===y.MFO)){this.setWhenActivitiesHasProgressButLessThanOneHundred(n,a);return}if(a===y.MSO||a===y.MFO){this.recalculateInBaseRestriction(n,a);return}let{ls:o,lf:c,minFromLinks:l}=this.calculateLfandLsFromLinks(i,n,a,this.parentsWithFullProgress,this.calculationsOfParentThatImpactChildrens);(a===y.SNLT||a===y.FNLT)&&({ls:o,lf:c}=this.getTheLessLateInBasEsEfConstraint(n.id,{ls:o,lf:c},a)),this.setCalculations(n,o,c),this.minFromLinks.set(n.id,{ls:l.ls,lf:l.lf})})}getTheLessLateInBasEsEfConstraint(t,r,n){let i=this.forwardConstraintsMap.get(t);if(!i){let a=this.gantt.getTask(t),s=this.gantt.getCalendar(a.calendar_id);i=qr(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 Fo({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=xo(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}},No=Ri;function Mo(){return null}var Wo=({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)})}},Bo=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)}},jo=Li;var Uo=e=>({totalFloat:new Bo(e.totalFloat).getTotalFloat(),freeFloat:new jo(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=Wo({forward:t,backward:r,id:l,activity:d,gantt:n,projectDates:i}),{totalFloat:f,freeFloat:p}=Uo(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||Mo(),Ti(this.gantt))return!1;let o=new wo(this.gantt);if(await o.calculateAsync(a),!a())return!1;let c=o.calculations,l=o.constraintsMap,d=new No(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}}},Ho=Oi;var hh=e=>e==="fnet"||e==="fnlt"||e==="mfo",yh=e=>new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()));function mh(e,t){let r=e.constraintDate;if(!r||!hh(e.constraintType))return r;let n=yh(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()?$n(e,t):r}function gh(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 vh(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 Ah(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 Ih(e,t){let r=vh(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:mh(i,e)})}),n}function Ch(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 kh(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 Vo(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=gh(f);return r.set(d,p),p},i=kh(e);await Z();let a=Ah(e),s=Ih(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=Ch(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 Ko=1e3;function Sh(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 Dh(e,t,r,n,i){let a=new Map,s=0;for(let o of t.forward?.keys()??[]){if(++s>=Ko&&(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),_h(o,Number(l.progress??0),t,r))}return i()?a:null}async function Th(e,t,r,n){let i=new Map,a=0;for(let s of e.getAllLinks()){if(++a>=Ko&&(a=0,await Z(),!n()))return null;i.set(String(s.id),Sh(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 Yo=(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 _h(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=Yo(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:Yo(r.freeFloat.get(e)?.activityFreeFloat,n)}}var Xr=(e,t)=>e===t||e!==null&&t!==null&&e.getTime()===t.getTime();function Fi(e,t,r){let n=e.getActivity(t),i=n?.criticalPath,a=r.criticalPath;n&&i&&Xr(i.earlyStart,a.earlyStart)&&Xr(i.earlyFinish,a.earlyFinish)&&Xr(i.lateStart,a.lateStart)&&Xr(i.lateFinish,a.lateFinish)&&Object.is(i.totalSlackHours,a.totalSlackHours)&&Object.is(n.isCritical,r.isCritical)&&Object.is(n.freeSlackHours,r.freeSlackHours)||e.setActivityFields(t,r)}function xi(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 Vo(e,t);if(!r())return null;let i=new Ho(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 Dh(e,s,t,n.getCanonicalActivityId,r);if(!o)return null;let c=await Th(e,i.linkResidualHours,o,r);return c?{activities:o,links:c}:null}async function Zr(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;Fi(e,i,a)}for(let[i,a]of n.links){if(!r())return!1;xi(e,i,a)}return!0}function we(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 Go=new Set;var $o=new Set(["activity-outdent","activity-indent"]);var nr=new Set([_.TEXT,_.DESCRIPTION,_.COST,_.USED_COST,_.CUSTOM_ID,_.RESPONSABLES,_.SUBCONTRACT_ID,_.TAGS]),Ph=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"]),bh=new Set(["activity-clipboard-clear","activity-copy","selection-toggle","selection-replace","visibility-set","filter-set","sort-set"]);function qo(e){return!bh.has(e.kind)}var Rh=new Set;function Eh(e){return e.kind==="inline-edit"?nr.has(e.column):e.kind==="bulk-edit"?e.edits.every(t=>nr.has(t.column)):!1}function Mi(e,t){return!(Ph.has(e.kind)||t.has(e.kind)||Eh(e))}function Wi(e){return e.kind==="activity-lookahead-sync"?e.persistedProgress!==void 0:Mi(e,Rh)}function se(e){return e.kind==="activity-lookahead-sync"?e.persistedProgress!==void 0:Mi(e,Go)}function Jo(e){return Mi(e,$o)}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 Lh(e){return Jo(e)&&Bi(e)}var zo=new Set([_.PROGRESS,_.HH_WORK_TIME,_.DURATION,_.COST,_.USED_COST,_.REAL_COST]);function wh(e){return e.kind==="activity-set-progress"?!0:e.kind==="inline-edit"?zo.has(e.column):e.kind==="bulk-edit"?e.edits.some(t=>zo.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 Xo(e,t,r){let n=new Set;t.ran&&n.add(it.AUTOSCHEDULE),n.add(it.PARENT_BOUNDS),wh(e)&&n.add(it.PARENT_PROGRESS),Bi(e)&&n.add(it.REAL_WORK);let i=!r.skipAutoSchedule;return i&&Jo(e)&&n.add(it.EXPECTED_PROGRESS),i&&Lh(e)&&n.add(it.REAL_COST),i&&se(e)&&!r.skipCriticalPath&&n.add(it.CRITICAL_PATH),n}async function Y(e,t){let r=Fh(e.adapter),n=Oh(t,r);n.has(it.AUTOSCHEDULE)&&await jh(e.adapter,t);let i=n.has(it.AUTOSCHEDULE)?await Mh(e,t.autoscheduleFrom):Bh();return await Uh(e.adapter,t,i.scheduledIds,n,r),await Vh(e,n,t.now),i}function Oh(e,t){let r=e.autoscheduleFrom!==null,n=!e.options.skipAutoSchedule&&r,i=new Set(Xo(e.action,{requested:r,ran:n},e.options));return(e.recomputeParentProgress||t.affectedParents.size>0)&&i.add(it.PARENT_PROGRESS),i}function Fh(e){let t=new Set,r=new Set,n=e.peekWriteCapture();if(!n)return{affectedParents:t,dirtySeeds:r};let i=a=>{if(a===null||L(a))return;let s=String(a);t.add(s);let o=e.getChildren(s)[0];o!==void 0&&r.add(o)};return xh(e,n.ops,i),Nh(e,n.before,r,i),{affectedParents:t,dirtySeeds:r}}function xh(e,t,r){for(let n of t)if(n.kind==="insert"){let i=e.getActivity(n.activityId);i&&r(i.parentId)}else n.kind==="remove"&&r(n.before.parentId)}function Nh(e,t,r,n){for(let[i,a]of t){let s=e.getActivity(i);if(!s)continue;let o=!Object.is(a.progress,s.progress),c=!Object.is(a.ponderator,s.ponderator),l=!Object.is(a.parentId,s.parentId);(o||c)&&(n(s.parentId),r.add(String(i))),l&&(n(a.parentId),n(s.parentId),r.add(String(i)))}}async function Mh(e,t){let r=t==="roots"?{}:{triggerId:t},n=await e.scheduler.schedule(r),i=Wh(e.adapter,n.updatedIds);return Ye(e.adapter,n),i}function Wh(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 Bh(){return{scheduledIds:[]}}async function jh(e,t){let r=t.collectDirty?t.collectDirty([]):ui(t.recomputeParentsFrom,[]);r.size!==0&&await Ce(e,r,!1)}async function Uh(e,t,r,n,i){n.has(it.PARENT_PROGRESS)&&Hh(e,i.affectedParents);let a=t.collectDirty?t.collectDirty(r):ui(t.recomputeParentsFrom,r);for(let s of i.dirtySeeds)a.add(s);await Ce(e,a,n.has(it.PARENT_PROGRESS),{recomputeRealWork:n.has(it.REAL_WORK),progressMode:"freeze-when-no-contribution"})}function Hh(e,t){for(let r of t){if(e.hasChildren(r))continue;let n=e.getProgressFallback(r);n!==null&&(e.setActivityField(r,"progress",n),e.setProgressFallback(r,null))}}async function Vh(e,t,r){t.has(it.EXPECTED_PROGRESS)&&r!==null&&(Yh(e.adapter)&&Le(e.adapter,r,e.defaultBaseCalendarId??null),ne(e.adapter,r),Mt(e.adapter,e.sector.statusCriteria)),t.has(it.REAL_COST)&&we(e.adapter),t.has(it.CRITICAL_PATH)&&await Zr(e.adapter,e.sector.hoursPerDay)}function Yh(e){let t=!1;return e.forEachActivity(r=>{ut(r)&&(t=!0)}),t}var Kh=new Set([_.CONSTRAINT_TYPE,_.CONSTRAINT_DATE]),Gh=new Set(["mso","mfo"]);function Qr(e){return Kh.has(e)}function tn(e){return e===_.CONSTRAINT_DATE}function en(e,t,r,n){let i=r.getActivity(e);if(!i)return!1;let a=i.constraintType;if(!a||Kt.has(a)||Gh.has(a))return!1;let s=ji(i.startDate),o=ji(r.getLastStartDate(e));if(!o||!s||s.getTime()!==o.getTime())return!1;let c=$h(t,a,String(i.calendarId??""),n),l=ji(i.constraintDate);return zh(l,c)?!1:(r.setActivityField(e,"constraintDate",c),!0)}function $h(e,t,r,n){if(e===null)return null;let i=n.getCalendar(r);return i?Ft(e,i,t):e}function ji(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 rn(e,{postMutationArgs:t,revertTargets:r,revert:n}){let{scheduledIds:i}=await Y(e,Zo(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,Zo(t));i=Jh(i,s.scheduledIds)}return se(t.action)&&await Y(e,qh(t)),{scheduledIds:i}}function Zo(e){return{...e,options:{...e.options,skipCriticalPath:!0}}}function qh(e){return{action:e.action,autoscheduleFrom:null,recomputeParentsFrom:[],now:null,options:e.options}}function Jh(e,t){let r=new Set(e);for(let n of t)r.add(n);return[...r]}function Xh(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 Ui(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&&!Xh(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=ey(e,t),n=new Map(t.beforeSnap),i=e.peekWriteCapture();if(i){let f=ny(i);ry(e,i,f,n,r)}let a=t.sirDetection,s=a==="before-diff"?Ui(n,e,r):[],o=ty(t.correlativeShifts,r),c=await Yr(e,n,r,o),l=a==="after-diff"?Ui(n,e,r):s,d=t.warnings??[],u=Qh(t.links??[],i?Zh(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 Zh(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 Qh(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 ty(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 ey(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 ry(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(di(s,o)).length!==0&&(n.set(a,s),i.add(a))}}function ny(e){return new Set(e.ops.filter(t=>t.kind==="insert").map(t=>t.activityId))}function Oe(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 xe(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 nn(e,t){typeof e=="string"&&e.length>0&&t.releaseCustomId(e)}async function Qo(e,t,r){let{adapter:n,ctx:i,scheduler:a,sector:s}=r,o=$t(e.column);if(!o)return{ok:!1,reason:k.NO_PIPELINE_FOR_COLUMN};e.column===_.DURATION&&a.invalidateExpandedLinksCache();let c=i.activityReader.getActivity(e.activityId);if(!c)return{ok:!1,reason:k.ACTIVITY_NOT_FOUND};let l=o.canEdit(c,i.hierarchy);if(!l.allowed)return{ok:!1,reason:l.reason??k.CANNOT_EDIT,alertKey:l.alertKey};let d=o.parseInput(e.newValue,c,i);if(!d.ok)return{ok:!1,reason:d.reason??k.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??k.INVALID,alertKey:f.notification?.messageKey};if(e.column===_.CUSTOM_ID&&d.value!==null){let C=n.getActivity(e.activityId),R=C?C.customId:null,x=typeof R=="string"?R:null;if(r.customIdTracker.isCustomIdInUse(String(d.value),x))return{ok:!1,reason:k.CUSTOM_ID_DUPLICATE}}let p=o.transform(c,d.value,i,d.raw),h=zt(e.activityId,p),m=await $(n,h),I=Fe(n,String(e.activityId)),T=c.constraintDate;qt(n,e.activityId,p),Vt(e.activityId,p.postProcessors??[],n,m.get(String(e.activityId))??null);let v=xe(I,n,String(e.activityId));if(e.column===_.CUSTOM_ID){let C=m.get(String(e.activityId)),R=C?C.customId:null,x=typeof R=="string"?R:null,F=typeof d.value=="string"?d.value:null;x!==F&&r.customIdTracker.trackCustomIdChange(x,F)}let S=()=>({action:e,autoscheduleFrom:p.needsAutoSchedule?String(e.activityId):null,recomputeParentsFrom:[],collectDirty:C=>Kr(e.activityId,h,C),now:r.now,options:t}),g=Qr(e.column),{scheduledIds:P}=await(g?rn({adapter:n,scheduler:a,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{postMutationArgs:S(),revertTargets:tn(e.column)?[]:[{activityId:e.activityId,priorConstraintDate:T}],revert:(C,R)=>en(C,R,n,i.calendars)}):Y({adapter:n,scheduler:a,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},S())),w=(p.trackingEvents??[]).map(C=>({name:C.name,properties:C.properties??{}})),A=be(e.activityId,p.constraintWarning);return{ok:!0,changes:await B(n,{source:e,beforeSnap:m,touchedIds:h,scheduledIds:P,sirDetection:"before-diff",links:v,trackingEvents:w,...A?{warnings:[A]}:{},hoursPerDay:s.hoursPerDay})}}function iy(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 ay(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 sy(e){return new Map([...e].map(([t,r])=>[String(t),r]))}async function tc(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:k.INVALID_LINK_TYPE};let i=e.lag;if(i!==void 0&&!Number.isFinite(i))return{ok:!1,reason:k.INVALID_LINK_LAG}}return Hi([fy(e,r.sector.hoursPerDay)],e,t,r,e.kind==="link-create"&&e.linkId?new Map([[0,e.linkId]]):void 0)}async function ec(e,t,r){let{hoursPerDay:n}=r.sector,i=e.operations.map(s=>ly(s,n)),a=oy(e.operations);return Hi(i,e,t,r,a)}function oy(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 cy(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 ly(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}=iy(e,a),u=await $(a,l),f=ay(e,a,c,cy(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=dy(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}),m=Oe(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:sy(d),changes:await B(a,{source:t,beforeSnap:u,touchedIds:l,scheduledIds:h,links:m,hoursPerDay:o.hoursPerDay})}}function dy(e,t,r){for(let n of e){if(n.rejected!==null)continue;let i=uy(n.op,t,r);if(i!==null)return r.hasChildren(i)?"roots":String(i)}return null}function uy(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 fy(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 rc(e,t,r){let{adapter:n,sector:i}=r;if(typeof e.newValue!="string")return{ok:!1,reason:k.INVALID_VALUE};if(!n.getActivity(e.activityId))return{ok:!1,reason:k.ACTIVITY_NOT_FOUND};let s=e.column===_.CUSTOM_PREDECESSORS,{specs:o}=Rr(e.newValue),c=o.map(h=>({...h,lag:vt(Or(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 m=n.getLink(h);m&&f.push(m)}let p=s?Lr({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(ac);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),py(a,i)}i+=1;let s=Ue(String(a.id),e);s.sort(ac),nc(r,s)}return n}function nc(e,t){for(let r=t.length-1;r>=0;r-=1)e.push(t[r])}function ic(e){let t=e.correlativeId,r=typeof t=="number"?t:Number(t);return Number.isFinite(r)?r:Yn}var ac=(e,t)=>ic(e)-ic(t);function py(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}=cc(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 sc(e,t){let r=t.getActivity(e);if(!r)return;let n=r.parentId;!n||L(n)||Vi(n,t)}function oc(e,t,r){for(let n of e){if(r.hasChildren(n))continue;let i=r.getActivity(n);i&&r.setActivityField(n,E.REAL_WORK_HOURS,dt(ir(i,E.WORK_HOURS),ir(i,E.PROGRESS)))}for(let n of t)r.setActivityField(n,E.REAL_WORK_HOURS,cc(n,r).realWorkHours)}function cc(e,t){let r=0,n=0;for(let i of t.getChildren(e)){let a=t.getActivity(i);if(!a)continue;let s=ir(a,E.WORK_HOURS);r+=s,n+=hy(i,a,s,t)}return{workHours:r,realWorkHours:n}}function ir(e,t){let r=e[t];return typeof r=="number"&&Number.isFinite(r)?r:0}function hy(e,t,r,n){return n.hasChildren(e)?ir(t,E.REAL_WORK_HOURS):dt(r,ir(t,E.PROGRESS))}function 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+=yy(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 lc(e,t){let r=t.getActivity(e);if(!r)return;let n=r.parentId;!n||L(n)||Yi(n,t)}function yy(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+=my(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 dc(e,t){let r=t.getActivity(e);if(!r)return;let n=r.parentId;!n||L(n)||Ki(n,t)}function my(e,t){let r=e[t];return typeof r=="number"&&Number.isFinite(r)?r:0}var an=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}),uc="New Master Plan",fc="New Activity";var gy=["name","description","type","startDate","durationHours","constraintType","constraintDate","calendarId","assignedDefaultCalendar","autoScheduling","progress","cost","usedCost","realCost","workHours","realWorkHours","ponderator","hasCustomPonderator","customId","subcontractId","responsableIds","tagIds","isLookahead"],sn=new Set(gy);function vy(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"||!sn.has(r))throw new Error(`activity-create: rejected override key "${String(r)}" \u2014 not a creation-writable canonical field`);return e}function pc(e,t){let r=e.parentId!=null?t.getActivity(e.parentId):null,n=vy(e.activityOverrides??{}),i=e.numTasksInGantt===0?uc:fc,a=n.name??i,s=n.durationHours??e.sector.hoursPerDay,o=n.calendarId??e.sector.defaultCalendar,c=Ay(r,e.fallbackStartDate,n.startDate),l={...an,...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:Rt({type:l.type,startDate:d,endDate:u}),newActivityIds:[...l.newActivityIds],pendingRequestIds:[...l.pendingRequestIds],responsableIds:[...l.responsableIds],tagIds:[...l.tagIds],baselinePoints:[...l.baselinePoints]}}}function Ay(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 Ne(e){let t=e.getParent(e.parentId);if(!t)return null;let r=e.isCurrentlyLeaf!==void 0?e.isCurrentlyLeaf&&jt(t.type):Cy(t),n=Array.isArray(t.newActivityIds)?t.newActivityIds:[],a={isLookahead:!1,hasNewActivities:!0,newActivityIds:n.some(s=>String(s)===String(e.newChildId))?[...n]:[...n,e.newChildId]};return t.customId!=null&&t.customId!==""&&(a.customId=null),r&&(a.type=Xn,(e.promotionSource??"create")==="create"&&(a.constraintType=K.ASAP,a.constraintDate=null)),{parentId:e.parentId,fields:a,promotionSnapshot:Iy(t)}}function Cy(e){return jt(e.type)&&(!Array.isArray(e.newActivityIds)||e.newActivityIds.length===0)}function on(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,hc=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 Ue(t,e)}function yc(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 cn(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 mc(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 ky=new Set([...[...sn].filter(e=>e!=="durationHours"),"durationDays"]);function ln(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:k.INVALID_VALUE};for(let a of Reflect.ownKeys(e))if(typeof a=="symbol"||!ky.has(a))return{ok:!1,reason:k.INVALID_VALUE};let{durationDays:n,...i}=e;return n!==void 0&&(!Number.isFinite(n)||n<0)?{ok:!1,reason:k.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 ar(e,t,r={}){let{adapter:n,scheduler:i,sector:a,calendars:s,activityIdGen:o,uidGen:c}=t;r.skipCacheInvalidation||i.invalidateAllCaches();let l=Sy(e,n);if(!l.ok)return l;let{parent:d,anchorSiblingId:u,isRoot:f}=l,p=Ty(e.activityId,n,o,t.isActivityIdReserved),h=c.next(),m={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=pc(m,{getActivity:A=>n.getActivity(A),calculateEndDate:A=>n.calculateEndDate(A),getClosestWorkTime:A=>n.getClosestWorkTime(A)}).newTask;T.realWorkHours=dt(T.workHours,T.progress),Py(T,e,t,u,d,r);let v=r.insertionCorrelativeId??on(n,f?"0":e.parentId,e.afterSiblingId,e.beforeSiblingId);T.correlativeId=v;let S=new Set([p]);d&&S.add(d.id);let g=d!==null&&n.getChildren(d.id).length===0,P=g?d?.customId:null,w=r.skipBeforeSnap?new Map:await $(n,S);return n.addActivity(T),by(e,p,d,n,g),P&&t.customIdTracker.releaseCustomId(P),r.skipRollupCascades||(sc(p,n),lc(p,n),dc(p,n)),Ry(n,p,w,S,r),{ok:!0,newId:p,parent:d,newActivity:T,beforeSnap:w,initialTouched:S}}function Sy(e,t){let r=L(e.parentId),n=r?null:t.getActivity(e.parentId);if(!r&&!n)return{ok:!1,reason:k.PARENT_NOT_FOUND};if(n!==null&&he(n))return{ok:!1,reason:k.PARENT_FROZEN_BY_SIR};if(e.afterSiblingId!==void 0&&e.beforeSiblingId!==void 0)return{ok:!1,reason:k.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:k.ANCHOR_SIBLING_NOT_FOUND};let a=r?"0":e.parentId;return(i.parentId==null?"0":String(i.parentId))!==a?{ok:!1,reason:k.ANCHOR_SIBLING_WRONG_PARENT}:null}function Ty(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 _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 by(e,t,r,n,i){if(!r)return;let a=Ne({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 Ry(e,t,r,n,i){if(i.skipCorrelativeRecompute)return;let a=at(e);i.skipBeforeSnap||Re(e,a,new Set([String(t)]),r,n)}async function Ey(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 gc(e,t,r){let{adapter:n,scheduler:i,sector:a}=r,s=ln(e.overrides,a.hoursPerDay);if(!s.ok)return s;let o=await ar({...e,overrides:s.value},r);if(!o.ok)return o;let{newId:c}=o,l=o.newActivity.autoScheduling;n.setActivityField(c,"autoScheduling",!1);let d;try{d=await Y({adapter:n,scheduler:i,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:"roots",recomputeParentsFrom:[c],now:r.now,options:t})}finally{n.setActivityField(c,"autoScheduling",l)}let{scheduledIds:u}=d;return{ok:!0,changes:await Ey(n,e,o,u,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 Tt(e,t){Vi(e,t),Yi(e,t),Ki(e,t)}function vc(e,t){let r=new Set,n=[];for(let i of e){let a=String(i);r.has(a)||(r.add(a),n.push(a))}for(;n.length>0;){let i=n.pop(),a=t.getChildren(i);for(let s of a){let o=String(s);r.has(o)||(r.add(o),n.push(o))}}return r}function Ac(e,t){let r=new Set;for(let n of e){for(let i of t.getOutgoingLinkIds(n))r.add(String(i));for(let i of t.getIncomingLinkIds(n))r.add(String(i))}return[...r]}function 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 Me(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:ve,durationHours:r,progress:0,autoScheduling:!0,constraintType:"asap",constraintDate:null,hasNewActivities:!1,...Oy(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 Ic(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 Cc=200;async function kc(e,t,r){let{adapter:n,scheduler:i,customIdTracker:a,sector:s}=r;if(i.invalidateAllCaches(),e.activityIds.length===0)return{ok:!1,reason:k.ACTIVITY_IDS_EMPTY};for(let A of e.activityIds)if(!n.getActivity(A))return{ok:!1,reason:k.ACTIVITY_NOT_FOUND};let o=vc(e.activityIds,n),c=Ac(o,n),l=new Set;for(let A of e.activityIds){let C=n.getActivity(A);if(!C)continue;let R=C.parentId;if(L(R))continue;let x=String(R);o.has(x)||l.add(x)}let d=new Set([...o,...l]),u=await $(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%Cc===0&&await Z();let C=n.getActivity(A);if(!C)continue;let R=L(C.parentId)?null:n.getActivity(String(C.parentId)),x=R?.hasNewActivities===!0&&R.newActivityIds.some(z=>String(z)===String(A));(C.isNewActivity===!0||x)&&p.add(A);let F=C.customId;typeof F=="string"&&F.length>0&&a.releaseCustomId(F)}for(let A of c)n.removeLink(A);let m=$i(n,o),I=0;for(let A of o)I+=1,I%Cc===0&&await Z(),n.removeActivity(A);for(let A of l){let C=n.getActivity(A);if(!C)continue;Fy(C,p,n);let R=n.getChildren(A),x=Me({parent:C,remainingChildIds:R.map(String),defaultDurationHours:s.hoursPerDay,promotionSnapshot:n.getPromotionSnapshot(A),computeEndDate:(F,z)=>n.calculateEndDate({startDate:F,durationHours:z,task:C}),idsRemoved:o});if(!x){xr(A,n);continue}for(let[F,z]of Object.entries(x.fields))rt(n,A,F,z);if(C.customId==null||C.customId===""){let F=Xt(A,n),z=F?n.getActivity(F)?.customId:null,Q=a.generateCustomIdForRestoredChild(typeof z=="string"&&z?z:null);n.setActivityField(A,E.CUSTOM_ID,Q)}}for(let A of l)Tt(A,n);let T=at(n),{scheduledIds:v}=await Y({adapter:n,scheduler:i,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:"roots",recomputeParentsFrom:l,now:r.now,options:t}),S={name:It.ACTIVITY_DELETION,properties:{activity_ids:[...e.activityIds],cascade_count:o.size}};e.eventSource!==void 0&&(S.properties.event_source=e.eventSource);let g=new Map;for(let[A,C]of f)g.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 w=await B(n,{source:e,beforeSnap:u,touchedIds:d,scheduledIds:v,sirDetection:"after-diff",links:xy(f),trackingEvents:[S],hoursPerDay:s.hoursPerDay,correlativeShifts:T});return{ok:!0,changes:m.length>0?{...w,viewState:m}:w,__beforeSnap:P,__beforeLinks:g}}function Fy(e,t,r){let n=Ic({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 xy(e){let t=[];for(let[r,n]of e.entries())t.push({id:r,kind:"deleted",fields:{source:{before:String(n.source),after:void 0},target:{before:String(n.target),after:void 0},type:{before:n.type,after:void 0},lag:{before:Number(n.lag),after:void 0}},after:null});return t}async function Tc(e,t,r){let n=Ny(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(g=>String(g))):new Set,s=e.mode==="replace"?await $(r.adapter,a):new Map,o=e.mode==="replace"?Yy(r):new Map,c=e.mode==="replace"?$i(r.adapter,a):[];r.scheduler.invalidateAllCaches();let l=[];if(e.mode==="replace"){for(let g of o.keys()){let P=Ut({kind:"delete",linkId:g},{port:r.adapter});if(!P.applied)return{ok:!1,reason:P.rejected??k.INVALID};l.push({op:{kind:"delete",linkId:g},finalLinkId:g,rejected:null})}for(let g of a){let P=r.adapter.getActivity(g)?.customId;typeof P=="string"&&P.length>0&&r.customIdTracker.releaseCustomId(P),r.adapter.removeActivity(g)}}let d=await Vy(e,i.plan.items,r);if(!d.ok)return d;let u=_c(e)?[]:at(r.adapter),f=new Set(i.plan.items.map(g=>String(g.activityId))),p=u.filter(g=>!f.has(g.activityId)),h=e.mode==="replace"?new Set(a):new Set;Re(r.adapter,u,f,s,h);for(let g of i.plan.items)h.add(String(g.activityId));let m=i.plan.links.map(g=>({operation:{kind:"create",source:g.source,target:g.target,type:g.type,lag:vt(g.lag,r.sector.hoursPerDay)},linkId:g.linkId})),I=br(m,{port:r.adapter,preserved:o});if(!I.applied)return{ok:!1,reason:I.rejected??k.INVALID};for(let{operation:g,linkId:P}of m)l.push({op:g,finalLinkId:P,rejected:null});let T=i.plan.items.map(g=>g.activityId),{scheduledIds:v}=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}),S=await B(r.adapter,{source:e,beforeSnap:s,touchedIds:h,scheduledIds:v,links:Oe(l,o,r.adapter),hoursPerDay:r.sector.hoursPerDay,correlativeShifts:p,...e.mode==="replace"?{sirDetection:"after-diff"}:{}});return{ok:!0,changes:c.length>0?{...S,viewState:c}:S,...e.mode==="replace"?{__beforeSnap:s,__beforeLinks:Ky(o)}:{}}}function Ny(e,t){if(e.mode!=="append"&&e.mode!=="replace")return k.INVALID;let r=new Set,n=new Set;for(let a of e.items){if(a.batchId.length===0||r.has(a.batchId))return k.INVALID;if(r.add(a.batchId),a.index!==void 0&&(!Number.isInteger(a.index)||a.index<0))return k.INVALID;if(a.activityId!==void 0){let s=String(a.activityId);if(s.length===0||s==="0"||n.has(s))return k.INVALID;n.add(s)}}for(let a of e.items)if(!zi(a.parent,!0,e.mode,r,t))return k.PARENT_NOT_FOUND;if(My(e.items))return k.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)?k.INVALID_LINK_TYPE:k.INVALID_LINK_LAG;if(!zi(a.source,!1,e.mode,r,t)||!zi(a.target,!1,e.mode,r,t))return k.ACTIVITY_NOT_FOUND;if(a.linkId!==void 0){let s=String(a.linkId);if(s.length===0||i.has(s))return k.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 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){let r=new Map;for(let d of e.items){let u=ln(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=By(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=jy(d.linkId,e.mode,a,t);return a.add(String(u)),u}),o=Uy(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:k.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:k.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=Dc(u.source,n),p=Dc(u.target,n),h=s[d];if(f===null||p===null||h===void 0)return{ok:!1,reason:k.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 By(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 jy(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 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)?[]:Gi(r.adapter,d).sort((m,I)=>st(m)-st(I)||String(m.id).localeCompare(String(I.id))).map(m=>String(m.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?Sc(c[d-1],r):null,p=l<c.length?Sc(c[l],r):null;for(let h=0;h<u;h+=1){let m=c[d+h],I=s.get(m);I!==void 0&&a.set(I,Hy(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 Sc(e,t){let r=t.adapter.getActivity(e);return r?st(r):0}function Hy(e,t,r,n){return e!==null&&t!==null&&t>e?e+(t-e)*r/(n+1):e!==null?e+r:t!==null?t-(n-r+1):r-1}async function Vy(e,t,r){let n=new Map,i=[];for(let s of t){if(s.parentBatchId===null){i.push(s);continue}let o=n.get(s.parentBatchId)??[];o.push(s),n.set(s.parentBatchId,o)}for(let s=0;s<i.length;s+=1){let o=i[s],c=await ar({kind:"activity-create",parentId:o.parentId,activityId:o.activityId,overrides:o.overrides,...e.eventSource===void 0?{}:{eventSource:e.eventSource}},r,{skipCorrelativeRecompute:!0,skipBeforeSnap:!0,skipCacheInvalidation:!0,skipRollupCascades:!0,insertionCorrelativeId:o.insertionCorrelativeId});if(!c.ok)return c;for(let l of n.get(o.input.batchId)??[])i.push(l)}if(i.length!==t.length)return{ok:!1,reason:k.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 Dc(e,t){return typeof e=="string"?e:t.get(e.batchId)??null}function Yy(e){return new Map(e.adapter.getAllLinks().map(t=>[String(t.id),{...t}]))}function Ky(e){return new Map(Array.from(e,([t,r])=>[String(t),r]))}function Pc(e,t){let{adapter:r}=t,n=e.activityId,i=r.getActivity(n);if(!i)return{ok:!1,reason:k.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:k.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 bc(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 Rc(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 Gy(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 Ec(e,t,r,n){let i=new Set,a=new Set;for(let s of e)Gy(s,t,r,n,i,a)}async function Lc(e,t){let r=e.filter(o=>{let c=t.adapter.getActivity(String(o.activityId));return c!==null&&c.progress!==o.progress}),n=new Set(r.map(o=>String(o.activityId))),i=Je(t.adapter,n),a=new Set(n);for(let o of i)a.add(String(o));let s=await $(t.adapter,a);return t.adapter.batchUpdate(()=>{for(let o of r)t.adapter.setActivityField(String(o.activityId),"progress",o.progress);Ls(i,t.adapter),oc(n,i,t.adapter)}),[...await Yr(t.adapter,s,a)]}async function wc(e,t){let r=e.activities??[],n=e.links??[],i=t.adapter.getAllActivities(),a=t.adapter.getAllLinks(),s=e.checkpoint?.activities??i,o=e.checkpoint?.links??a,c=new Map(s.map(h=>[String(h.id),h])),l=new Map(o.map(h=>[String(h.id),h])),d=bc(s),u=bc(o);Ec(r,"activity",h=>{let m=c.get(h);return{exists:m!==void 0,current:m?.proplannerId??null}},d),Ec(n,"link",h=>{let m=l.get(h);return{exists:m!==void 0,current:m?.proplannerId??null}},u),Rc(s,r,"activity"),Rc(o,n,"link");let f=[],p=[];return t.adapter.batchUpdate(()=>{for(let h of r){let m=t.adapter.getActivity(h.id);if(!m||m.proplannerId===h.proplannerId)continue;let I=m.proplannerId;t.adapter.setActivityField(h.id,"proplannerId",h.proplannerId),f.push({id:h.id,kind:"updated",fields:{proplannerId:{before:I,after:h.proplannerId}},after:{...m,proplannerId:h.proplannerId}})}for(let h of n){let m=t.adapter.getLink(h.id);if(!m||m.proplannerId===h.proplannerId)continue;let I=m.proplannerId;t.adapter.setLinkProplannerId(h.id,h.proplannerId),p.push({id:h.id,kind:"updated",fields:{proplannerId:{before:I,after:h.proplannerId}},after:{...m,proplannerId:h.proplannerId}})}}),{ok:!0,changes:{source:e,activities:f,links:p,calendars:[],trackingEvents:[]}}}async function Oc(e,t,r){if($y(e))return{ok:!1,reason:k.INVALID_VALUE};let n=[...new Set(e.activityIds.map(String))];if(e.acknowledgePersistedLookahead===!0&&n.some(o=>!r.isActivityIdReserved(o)))return{ok:!1,reason:k.INVALID};let a=n.map(o=>r.adapter.getActivity(o));if(a.some(o=>!o))return{ok:!1,reason:k.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 Lc([{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 $y(e){let t=e.persistedProgress;return t!==void 0&&(e.activityIds.length!==1||!Number.isFinite(t)||t<0||t>100)}function dn(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)||(Fc(s,a,t)||Fc(a,s,t))&&n.push(String(i.id))}return n}function Fc(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 un(e,t){let r=e.getAllLinks();return!$e({port:e,currentLinks:r,proposedLinks:r,proposal:{reparented:t}}).ok}function fn(e,t){let r=new Set;if(e.length===0)return r;let n=new Map(e.map(a=>[a.activityId,a.newParentId]));if(!un(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),un(t,s)){r.add(a.activityId);continue}i.set(a.activityId,a.newParentId)}return r}async function xc(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:k.ACTIVITY_NOT_FOUND};let o=L(e.parentId);if(!o&&!n.getActivity(e.parentId))return{ok:!1,reason:k.PARENT_NOT_FOUND};if(!o&&(e.parentId===e.activityId||n.isChildOf(e.parentId,e.activityId)))return{ok:!1,reason:k.CANNOT_MOVE_INTO_OWN_DESCENDANT};if(e.afterSiblingId!==void 0&&e.beforeSiblingId!==void 0)return{ok:!1,reason:k.ANCHOR_SIBLING_CONFLICT};let c=e.afterSiblingId??e.beforeSiblingId;if(c!==void 0){let P=n.getActivity(c);if(!P)return{ok:!1,reason:k.ANCHOR_SIBLING_NOT_FOUND};if((P.parentId===null?"0":String(P.parentId))!==e.parentId)return{ok:!1,reason:k.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(un(n,P))return{ok:!1,reason:k.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 m=on(n,e.parentId,e.afterSiblingId,e.beforeSiblingId);if(n.setActivityField(e.activityId,E.CORRELATIVE_ID,m),f){if(!o){let P=n.getActivity(e.parentId);if(P){let w=P.customId,A=jt(P.type)&&n.getChildren(e.parentId).filter(R=>R!==e.activityId).length===0,C=Ne({parentId:e.parentId,newChildId:e.activityId,getParent:R=>n.getActivity(R)??null,isCurrentlyLeaf:A,promotionSource:"reparent"});if(C){for(let[R,x]of Object.entries(C.fields))rt(n,C.parentId,R,x);C.promotionSnapshot&&n.setPromotionSnapshot(C.parentId,C.promotionSnapshot),C.fields.customId===null&&nn(w,r.customIdTracker)}}}if(d!=="0"){let P=n.getActivity(d);if(P){let w=n.getChildren(d),A=Me({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(A){for(let[z,Q]of Object.entries(A.fields))rt(n,d,z,Q);let C=Xt(d,n),R=C?n.getActivity(C)?.customId:null,x=typeof R=="string"&&R?R:null,F=r.customIdTracker.generateCustomIdForRestoredChild(x);n.setActivityField(d,E.CUSTOM_ID,F)}}}}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 A=J(w);P.before!==void 0&&(A.correlativeId=P.before),h.set(P.activityId,A)}let T=f&&d!=="0"?n.getChildren(d).map(String):[],{scheduledIds:v}=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}),S=f?dn([e.activityId],n):[],g={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:S.map(String)}};return e.eventSource!==void 0&&(g.properties.event_source=e.eventSource),{ok:!0,changes:await B(n,{source:e,beforeSnap:h,touchedIds:p,scheduledIds:v,sirDetection:"before-diff",trackingEvents:[g],hoursPerDay:a.hoursPerDay})}}function pn(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,m=p?st(p):oe;return h-m});for(let d of o){if(!t.getActivity(d)){n.push({activityId:d,reason:k.ACTIVITY_NOT_FOUND}),s.delete(d);continue}if(cn(d,a,t))continue;let f=Ga(d,s,t);if(f==null){n.push({activityId:d,reason:k.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=fn(i,t);for(let d of c)n.push({activityId:d,reason:k.HIERARCHY_CYCLE});let l=i.filter(d=>!c.has(d.activityId));return{moves:i,cyclicMoveIds:c,allowedMoves:l,failed:n}}async function Nc(e,t,r){let{adapter:n,scheduler:i,sector:a}=r;if(i.invalidateAllCaches(),e.activityIds.length===0)return{ok:!1,reason:k.ACTIVITY_IDS_EMPTY};let s=new Set,o=[],c=pn(e.activityIds,n),l=[...c.failed];for(let v of c.moves)s.add(String(v.activityId)),s.add(String(v.newParentId)),v.oldParentId!=="0"&&s.add(String(v.oldParentId));let d=c.allowedMoves,u=await $(n,s);for(let{activityId:v,newParentId:S}of d)n.setActivityField(v,E.PARENT,S),n.setActivityField(v,E.CORRELATIVE_ID,hc),o.push(v);let f=new Set;for(let{activityId:v,newParentId:S}of d){if(f.has(S))continue;f.add(S);let g=n.getActivity(S);if(!g)continue;let P=g.customId,w=jt(g.type)&&n.getChildren(S).filter(R=>!o.includes(R)).length===0,A=g.hasNewActivities&&g.newActivityIds.some(R=>String(R)===String(v)),C=Ne({parentId:S,newChildId:v,getParent:R=>n.getActivity(R)??null,isCurrentlyLeaf:w,promotionSource:"reparent"});if(C){for(let[R,x]of Object.entries(C.fields))rt(n,C.parentId,R,x);C.promotionSnapshot&&n.setPromotionSnapshot(C.parentId,C.promotionSnapshot),A||(n.setActivityField(S,E.HAS_NEW_ACTIVITIES,!1),n.setActivityField(S,E.NEW_ACTIVITIES_ARRAY,[]))}n.setActivityField(S,E.CONSTRAINT_TYPE,"asap"),n.setActivityField(S,E.CONSTRAINT_DATE,null),n.setActivityField(S,E.CUSTOM_ID,null),nn(P,r.customIdTracker)}let p=new Set;for(let v of d)v.oldParentId!=="0"&&p.add(v.oldParentId),p.add(v.newParentId);for(let v of p)Tt(v,n);let h=at(n);for(let v of h){if(s.add(v.activityId),u.has(v.activityId))continue;let S=n.getActivity(v.activityId);if(!S)continue;let g=J(S);v.before!==void 0&&(g.correlativeId=v.before),u.set(v.activityId,g)}let{scheduledIds:m}=await Y({adapter:n,scheduler:i,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:null,recomputeParentsFrom:o,now:r.now,options:t}),I=dn(o,n),T={name:It.ACTIVITY_INDENT,properties:{activity_ids:o,failed:l.map(v=>({activity_id:v.activityId,reason:v.reason})),invalid_link_ids:I}};return e.eventSource!==void 0&&(T.properties.event_source=e.eventSource),{ok:!0,activityVerdicts:e.activityIds.map(v=>{let S=l.find(g=>String(g.activityId)===String(v));return S?{activityId:String(v),ok:!1,reason:S.reason}:{activityId:String(v),ok:!0}}),changes:await B(n,{source:e,beforeSnap:u,touchedIds:s,scheduledIds:m,trackingEvents:[T],hoursPerDay:a.hoursPerDay})}}async function Mc(e,t,r){let{adapter:n,scheduler:i,sector:a}=r;if(i.invalidateAllCaches(),e.activityIds.length===0)return{ok:!1,reason:k.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,Kn(C,n)),c.set(C,yc(C,s,n)))}let l=new Set,d=[],u=[],f=new Set,p=[],h=new Set,m=[...e.activityIds].sort((A,C)=>{let R=n.getActivity(A),x=n.getActivity(C),F=R?st(R):oe,z=x?st(x):oe;return F-z});for(let A of m){let C=A,R=n.getActivity(C);if(!R){d.push({activityId:C,reason:k.ACTIVITY_NOT_FOUND});continue}if(cn(C,h,n))continue;let x=R.parentId;if(L(x)){d.push({activityId:C,reason:k.OUTDENT_ROOT_LEVEL_NOT_EDITABLE});continue}let F=String(x),z=n.getActivity(F);if(!z){d.push({activityId:C,reason:k.ACTIVITY_NOT_FOUND});continue}let Q=z.parentId;if(L(Q)){d.push({activityId:C,reason:k.OUTDENT_ROOT_LEVEL_NOT_EDITABLE});continue}let lt=String(Q),pt=Kn(F,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:F,targetIndexInGrandparent:pt}),h.add(C),l.add(String(C)),l.add(String(F)),lt!=="0"&&l.add(String(lt)),f.add(F)}let I=fn(p.map(A=>({activityId:A.activityId,newParentId:A.grandparentKey})),n);for(let A of I)d.push({activityId:A,reason:k.HIERARCHY_CYCLE});let T=p.filter(A=>!I.has(A.activityId)),v=await $(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),x=Me({parent:C,remainingChildIds:R.map(String),defaultDurationHours:a.hoursPerDay,promotionSnapshot:n.getPromotionSnapshot(A),computeEndDate:(pt,nt)=>n.calculateEndDate({startDate:pt,durationHours:nt,task:C}),idsRemoved:new Set(T.filter(pt=>pt.oldParentKey===A).map(pt=>pt.activityId))});if(!x){xr(A,n);continue}for(let[pt,nt]of Object.entries(x.fields))rt(n,A,pt,nt);let F=Xt(A,n),z=F?n.getActivity(F)?.customId:null,Q=typeof z=="string"&&z?z:null,lt=r.customIdTracker.generateCustomIdForRestoredChild(Q);n.setActivityField(A,E.CUSTOM_ID,lt)}let S=new Set;for(let A of f)S.add(String(A));for(let A of T)A.grandparentKey!=="0"&&S.add(String(A.grandparentKey));for(let A of S)Tt(A,n);let g=at(n);for(let A of g){if(l.add(A.activityId),v.has(A.activityId))continue;let C=n.getActivity(A.activityId);if(!C)continue;let R=J(C);A.before!==void 0&&(R.correlativeId=A.before),v.set(A.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(A=>({activity_id:String(A.activityId),reason:A.reason}))}};return e.eventSource!==void 0&&(w.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 B(n,{source:e,beforeSnap:v,touchedIds:l,scheduledIds:P,trackingEvents:[w],hoursPerDay:a.hoursPerDay})}}async function Wc(e,t,r){let{adapter:n,ctx:i,scheduler:a,sector:s}=r;if(e.newValue!==0&&e.newValue!==100)return{ok:!1,reason:k.INVALID_PROGRESS_VALUE};let o=i.activityReader.getActivity(e.activityId);if(!o)return{ok:!1,reason:k.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),Os(e.activityId,e.newValue,n),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:m=>Kr(e.activityId,u,m),now:r.now,options:t}),h=(d.trackingEvents??[]).map(m=>({name:m.name,properties:m.properties??{}}));return{ok:!0,changes:await B(n,{source:e,beforeSnap:f,touchedIds:u,scheduledIds:p,trackingEvents:h,hoursPerDay:s.hoursPerDay})}}async function Bc(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 m=zy(h,r);if(s.push(m.verdict),!m.verdict.ok||!m.changes)continue;let I=zt(h.activityId,m.changes);qy(o,I,r);for(let g of I)c.add(g);let T=Fe(n,h.activityId),v=Vr(n,String(h.activityId));qt(n,h.activityId,m.changes),Vt(h.activityId,m.changes.postProcessors??[],n,v),d.push(...xe(T,n,h.activityId)),f||=!!m.changes.needsAutoSchedule;for(let g of m.changes.trackingEvents??[])l.push({name:g.name,properties:g.properties??{}});let S=be(h.activityId,m.changes.constraintWarning);S&&u.push(S)}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 zy(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??k.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??k.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??k.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 qy(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 qi=_.CUSTOM_ID;async function jc(e,t,r){let{adapter:n,scheduler:i,sector:a}=r;e.edits.some(S=>S.column===_.DURATION)&&i.invalidateExpandedLinksCache();let o=[],c=new Map,l=new Map,d=new Set,u=new Set,f=[],p=[],h=[],m=!1;for(let S of e.edits){let g=Jy(S,r);if(o.push(g.verdict),!g.verdict.ok||!g.changes)continue;let P=be(S.activityId,g.changes.constraintWarning);P&&h.push(P);let w=zt(S.activityId,g.changes);tm(c,w,r);for(let F of w)u.add(F);Qy(l,S,c),tn(S.column)&&d.add(String(S.activityId));let A=Fe(n,S.activityId),C=Vr(n,String(S.activityId)),R=Xy(S,r),x=g.changes;qt(n,S.activityId,x),Vt(S.activityId,g.changes.postProcessors??[],n,C),Zy(S,R,r),p.push(...xe(A,n,S.activityId)),m||=!!g.changes.needsAutoSchedule;for(let F of g.changes.trackingEvents??[])f.push({name:F.name,properties:F.properties??{}})}let I={action:e,autoscheduleFrom:m?"roots":null,recomputeParentsFrom:u,now:r.now,options:t},T=l.size>0,{scheduledIds:v}=await(T?rn({adapter:n,scheduler:i,sector:a,defaultBaseCalendarId:r.defaultBaseCalendarId},{postMutationArgs:I,revertTargets:[...l].filter(([S])=>!d.has(S)).map(([S,g])=>({activityId:S,priorConstraintDate:g})),revert:(S,g)=>en(S,g,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:v,sirDetection:"before-diff",links:p,trackingEvents:f,warnings:h,hoursPerDay:a.hoursPerDay})}}function Jy(e,t){let{ctx:r}=t,n=e.activityId,i=$t(e.column);if(!i)return{verdict:{activityId:n,ok:!1,reason:k.NO_PIPELINE_FOR_COLUMN},changes:null};let a=r.activityReader.getActivity(e.activityId);if(!a)return{verdict:{activityId:n,ok:!1,reason:k.ACTIVITY_NOT_FOUND},changes:null};let s=i.canEdit(a,r.hierarchy);if(!s.allowed)return{verdict:{activityId:n,ok:!1,reason:s.reason??k.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??k.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??k.INVALID,...l.notification?.messageKey?{alertKey:l.notification.messageKey}:{}},changes:null};if(e.column===qi&&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:k.CUSTOM_ID_DUPLICATE},changes:null}}let d=i.transform(a,o.value,r,o.raw);return{verdict:{activityId:n,ok:!0},changes:d}}function Xy(e,t){if(e.column!==qi)return null;let r=t.adapter.getActivity(e.activityId),n=r?r.customId:null;return typeof n=="string"?n:null}function Zy(e,t,r){if(e.column!==qi)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 Qy(e,t,r){if(!Qr(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 tm(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 Uc(e){return typeof e=="string"&&e.length>0?Nt(e):e instanceof Date?e:null}function Ji(e){let t=typeof e=="number"?e:typeof e=="string"&&e.trim()!==""?Number(e):Number.NaN;return!Number.isFinite(t)||t<0?null:t}function hn(e,t){let r=Ji(e.duration),n=Ji(e.cost),i=Ji(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:Uc(e.start_date),endDate:Uc(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 Hc(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=>hn(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 em(e){let t=ut(e);return t?{startDate:t.startDate,endDate:t.endDate,durationDays:t.durationDays,cost:t.cost,workHours:t.workHours}:null}function Vc(e){let t=[];return e.forEachActivity((r,n)=>{let i=em(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 yn(e,t,r,n,i=null){let a=new Set;for(let s of Hc(e,t,n))a.add(s);if(r)for(let s of Le(e,r,i))a.add(s);for(let s of Vc(e))a.add(s);for(let s of we(e))a.add(s);return[...a]}function Yc(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=rm(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 rm(e,t,r){let n=r.getActivity(e);if(!n)return 0;let i=ut(n);if(!i)return 0;if(t==="COST")return mn(i.cost);if(t==="HH")return mn(i.workHours);let a=n.type;return a==="project"?Kc(e,r):a==="milestone"?0:mn(i.durationDays)}function Kc(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+=Kc(String(n),t):s!=="milestone"&&(r+=mn(a.durationDays))}return r}function mn(e){let t=typeof e=="string"?parseFloat(e):e;return typeof t=="number"&&Number.isFinite(t)?t:0}function Gc(e,t){t.forEachActivity((r,n)=>{t.setActivityField(n,_.PONDERATOR,0)}),t.forEachActivity((r,n)=>{t.getChildren(n).length>0&&Yc(String(n),e,t)})}function gn(e,t){Gc(t,e.adapter),qe(e.adapter),e.now&&(Le(e.adapter,e.now,e.defaultBaseCalendarId??null),ne(e.adapter,e.now)),we(e.adapter),e.now&&Mt(e.adapter,e.sector.statusCriteria)}function $c(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 zc(e,t){let r=await $(t.adapter,new Set(t.adapter.getAllIds())),n=$c(t),i=yn(t.adapter,e.points,t.now,t.reporter,t.defaultBaseCalendarId??null);return $c(t)!==n&&gn(t,t.sector.activityCreter??"DURATION"),{ok:!0,changes:await B(t.adapter,{source:e,beforeSnap:r,touchedIds:i,scheduledIds:[],hoursPerDay:t.sector.hoursPerDay})}}function nm(e){if(!(e==="DURATION"||e==="COST"||e==="HH"))throw new Error(`ponderator-criterion-set: invalid criterion "${String(e)}"`)}async function qc(e,t){nm(e.criterion);let r=new Set(t.adapter.getAllIds()),n=await $(t.adapter,r);return gn(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 Jc(e,t){let r=Gr(e.criteria),n=new Set(t.adapter.getAllIds()),i=await $(t.adapter,n),a=Mt(t.adapter,r);return t.sector.statusCriteria=r,{ok:!0,changes:await B(t.adapter,{source:e,beforeSnap:i,touchedIds:a,scheduledIds:[],hoursPerDay:t.sector.hoursPerDay})}}var Xc=["name","description","type","startDate","durationHours","constraintType","constraintDate","calendarId","cost","hasCustomPonderator","subcontractId","responsableIds","tagIds"];function im(e){let t={};for(let r of Xc)Object.assign(t,{[r]:b(e[r])});return t}function am(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 Zc(e,t){let r=new Set(t.adapter.checkedIds().map(String));if(r.size===0)return{ok:!1,reason:k.NO_ACTIVITY_SELECTION};let n=am(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:im(s)}}),links:t.adapter.getAllLinks().filter(a=>r.has(String(a.source))&&r.has(String(a.target))).map(a=>b(a))};let i=fr({kind:"selection-replace",activityIds:[]},{adapter:t.adapter});return i.ok?{...i,changes:{...i.changes,source:e}}:i}function Qc(e,t){return t.value=null,{ok:!0,changes:{source:e,activities:[],links:[],calendars:[],trackingEvents:[]}}}function sm(e,t){let r=t.getActivity(e);return r?{ok:!0,parentId:r.parentId==null?"0":String(r.parentId)}:{ok:!1,reason:k.ANCHOR_SIBLING_NOT_FOUND}}var tl=()=>({ok:!1,reason:k.ACTIVITY_PASTE_INVARIANT_FAILED});async function el(e,t,r){let n=r.activityClipboard.value;if(n===null)return{ok:!1,reason:k.CLIPBOARD_EMPTY};let i=sm(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 m of n.activities){let I=o.get(m.originalParentId),T=await ar({kind:"activity-create",parentId:I??i.parentId,...I===void 0?{afterSiblingId:l??e.destination.afterSiblingId}:{},overrides:b(m.overrides),eventSource:e.eventSource},r,{skipCorrelativeRecompute:!0,skipBeforeSnap:!0,customIdReferenceId:e.destination.afterSiblingId});if(!T.ok)return T;o.set(m.originalId,T.newId),c.push(T.newId),I===void 0&&(l=T.newId)}let d=at(r.adapter),u=new Set(c.map(String));Re(r.adapter,d,u,a,s);for(let m of c)s.add(String(m));let f=[];for(let m of n.links){let I=o.get(m.source),T=o.get(m.target);if(I===void 0||T===void 0)return tl();let v={kind:"create",source:I,target:T,type:m.type,lag:m.lag},S=Ut(v,{port:r.adapter,newLinkId:r.linkIdGen.next});if(!S.applied)return tl();f.push({op:v,finalLinkId:S.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=Oe(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 rl(e,t,r){return e.kind==="activity-copy"?Zc(e,{adapter:r.adapter,clipboard:r.activityClipboard}):e.kind==="activity-clipboard-clear"?Qc(e,r.activityClipboard):e.kind==="activity-paste-copied"?el(e,t,r):e.kind==="activity-batch"?Tc(e,t,r):e.kind==="persistence-acknowledge"?wc(e,r):e.kind==="baseline-apply"?zc(e,r):e.kind==="ponderator-criterion-set"?qc(e,r):e.kind==="status-criteria-set"?Jc(e,r):e.kind==="link-create"||e.kind==="link-update"||e.kind==="link-delete"?tc(e,t,r):e.kind==="links-batch"?ec(e,t,r):e.kind==="activity-create"?gc(e,t,r):e.kind==="activity-delete"?kc(e,t,r):e.kind==="activity-move"?xc(e,t,r):e.kind==="activity-indent"?Nc(e,t,r):e.kind==="activity-outdent"?Mc(e,t,r):e.kind==="activity-set-progress"?Wc(e,t,r):e.kind==="dates-batch"?Bc(e,t,r):e.kind==="bulk-edit"?jc(e,t,r):e.kind==="selection-toggle"?Fa(e,Xi(r)):e.kind==="selection-replace"?fr(e,Xi(r)):e.kind==="visibility-set"?xa(e,Xi(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"?Pc(e,r):e.kind==="activity-lookahead-sync"?Oc(e,t,r):e.kind==="inline-edit"&&(e.column===_.CUSTOM_PREDECESSORS||e.column===_.CUSTOM_SUCESSORS)?rc(e,t,r):e.kind!=="inline-edit"?qa(e,`[ScheduleCore] dispatch kind "${e.kind}" not supported yet`):Qo(e,t,r)}function Xi(e){return{adapter:e.adapter}}var om=new Set(["startDate","endDate","constraintDate"]);function nl(e,t){return om.has(e)&&typeof t=="string"?new Date(t):t}function il(e,t={}){let r=t.defaultUnit??"hour";return{getCalendar(n){let i=e.getCalendar(String(n));return i?cm(i,r):null}}}function cm(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 lm(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 dm={}.constructor.toString();function um(e){var t=e.constructor.toString();return t!==dm}function fm(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 lm(e):for(r=new Array(e.length),t=0;t<e.length;t++)r[t]=_t(e[t]);break;default:if(um(e))r=Object.create(e);else{if(fm(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 We(e,t,r){for(var n in t)(e[n]===void 0||r)&&(e[n]=t[n]);return e}function al(e){return typeof e<"u"}var vn;function Zi(){return vn||(vn=new Date().valueOf()),vn++,vn}function mt(e,t){return e.bind?e.bind(t):function(){return e.apply(t,arguments)}}var hm=(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)},ym=(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)},sl={date_to_str:hm,str_to_date:ym},mm=(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}}),gm=(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])},ol={date_to_str:mm,str_to_date:gm};function cl(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=sl;return a()&&(l=ol),l.date_to_str(o,c,e)},str_to_date:function(o,c){var l=sl;return a()&&(l=ol),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 Qi(e,t,r,n,i){return this.date=e,this.unit=t,this.task=r,this.id=n,this.calendar=i,this}function ta(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 ea(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 vm(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 ll=function(e){return{getWorkHoursArguments:function(){var t=arguments[0];if(ce(t)?t={date:t}:t=We({},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 Qi)return t;var r;if(t.date?r=new Qi(t.date,t.unit,t.task,null,t.calendar):r=new Qi(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 ta)return r;var n;if(ce(r)?n=new ta(r):n=new ta(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=vm,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 ea)return a;var s;if(ce(a)?s=new ea(arguments[0],arguments[1],arguments[2],void 0,arguments[3],void 0,arguments[4]):s=new ea(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 dl(){}dl.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 m=Array.isArray(h)?h:d.hours;s.dates[u]=this._toHoursArray(this._mergeHoursConfig(f,m))}}}};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 ra=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}},na=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={}}},ia=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 Am(){return typeof Map<"u"?new ra:new na}var aa=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 sa(e,t){this.argumentsHelper=t,this.$gantt=e,this._workingUnitsCache=Am(),this._largeUnitsCache=new ia(this),this._dateDurationCache=new aa,this._worktime=null,this._cached_timestamps={},this._cached_timestamps_count=0}sa.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),m=this.units[h-1];m&&!this._isWorkTime(a,m)&&(c=this._getClosestWorkTimeFuture(a,m))}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 sa))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 m=!1,I=null,T=null,v=c.length-1;v>=0;v--)if(c[v].start<h-1&&c[v].end>=h-1){m=!0,I=c[v],T=c[v-1];break}if(m)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 S=this._getMinutesPerHour(n);S<=p?(i+=S,n=this._nextDate(n,"hour",r)):(s=this._subtractMinutesUntilHourStart(n,p),i+=s.added,n=s.end)}else if(n.getUTCHours()===0&&n.getUTCMinutes()===0&&n.getUTCSeconds()===0){var g=this._getClosestWorkTimePast(n,"hour");if(g.valueOf()===n.valueOf()){var g=this.$gantt.date.add(n,-1,"day"),P=this._getWorkHours(g);if(P.length){var w=P[P.length-1];g.setUTCSeconds(w.durationSeconds)}}n=g}else n=this._getClosestWorkTimePast(new Date(n-1),"hour")}if(i<t){var A=t-i;s=this._subtractMinutesUntilHourStart(n,A),i+=s.added,n=s.end}return n},_calculateMinuteEndDate:function(e,t,r){var n=new Date(e),i=0;r=r||1,t=Math.abs(t*1),t=Math.round(t);var a=this._addMinutesUntilHourEnd(n,t);i+=a.added,n=a.end;for(var s=0,o=[],c=0,l=this._isMinutePrecision(n);i<t;){var d=this.$gantt.date.day_start(new Date(n)).valueOf();d!==s&&(o=this._getWorkHours(n),c=this._getMinutesPerDay(n),s=d);var u=t-i,f=this._getTimeOfDayStamp(n);if(!o.length||!c){n=this.$gantt.date.add(this.$gantt.date.day_start(n),1,"day");continue}if(o[0].start>=f&&u>=c){if(i+=c,u==c){n=new Date(Date.UTC(n.getUTCFullYear(),n.getUTCMonth(),n.getUTCDate(),0,0,o[o.length-1].end));break}else n=this.$gantt.date.add(n,1,"day"),n=this.$gantt.date.day_start(n);continue}for(var p=!1,h=null,m=0;m<o.length;m++)if(o[m].start<=f&&o[m].end>f){p=!0,h=o[m];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 sr={isLegacyResourceCalendarFormat:function(e){if(!e)return!1;for(var t in e)if(e[t]&&typeof e[t]=="object")return!0;return!1},getResourceProperty:function(e){var t=e.resource_calendars,r=e.resource_property;if(this.isLegacyResourceCalendarFormat(t))for(var n in e){r=n;break}return r},getCalendarIdFromLegacyConfig:function(e,t){if(t)for(var r in t){var n=t[r];if(e[r]){var i=n[e[r]];if(i)return i}}return null}};function 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 Cm=Im();function ul(e){this.$gantt=e,this._calendars={},this._legacyConfig=void 0,this.$gantt.attachEvent("onGanttReady",(function(){this.$gantt.config.resource_calendars&&(this._isLegacyConfig=sr.isLegacyResourceCalendarFormat(this.$gantt.config.resource_calendars))}).bind(this)),this.$gantt.attachEvent("onBeforeGanttReady",(function(){this.createDefaultCalendars()}).bind(this)),this.$gantt.attachEvent("onBeforeGanttRender",(function(){this.createDefaultCalendars()}).bind(this))}ul.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 dl,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 sa(this.$gantt,ll(this.$gantt));t.id=String(Zi());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 We(t,r),this._createCalendarFromConfig(t)},getCalendar:function(e){e=e||"global";var t=this._calendars[e];return t||(this.createDefaultCalendars(),t=this._calendars[e]),t},getCalendars:function(){var e=[];for(var t in this._calendars)e.push(this.getCalendar(t));return e},_getOwnCalendar:function(e){var t=this.$gantt.config;if(e[t.calendar_property])return this.getCalendar(e[t.calendar_property]);if(t.resource_calendars){var r,n,i;if(this._legacyConfig===!1?i=t.resource_property:i=sr.getResourceProperty(t),Array.isArray(e[i])&&e[i].length)t.dynamic_resource_calendars?n=Cm.getCalendarIdFromMultipleResources(e[i],this):r=this.getResourceCalendar(e[i]);else if(this._legacyConfig===void 0&&(this._legacyConfig=sr.isLegacyResourceCalendarFormat(t.resource_calendars)),this._legacyConfig)var n=sr.getCalendarIdFromLegacyConfig(e,t.resource_calendars);else if(i&&e[i]&&t.resource_calendars[e[i]])var r=this.getResourceCalendar(e[i]);if(n&&(r=this.getCalendar(n)),r)return r}return null},getResourceCalendar:function(e){if(e==null)return this.getCalendar();var t=null;typeof e=="number"||typeof e=="string"?t=e:t=e.id||e.key;var r=this.$gantt.config,n=r.resource_calendars,i=null;if(Array.isArray(e)&&e.length===1&&(typeof e[0]=="object"?t=e[0].resource_id:t=e[0]),n){if(this._legacyConfig===void 0&&(this._legacyConfig=sr.isLegacyResourceCalendarFormat(r.resource_calendars)),this._legacyConfig){for(var a in n)if(n[a][t]){i=n[a][t];break}}else var i=n[t];if(i)return this.getCalendar(i)}return this.getCalendar()},getTaskCalendar:function(e){var t=this.$gantt,r;if(e==null)return this.getCalendar();if((typeof e=="number"||typeof e=="string")&&t.isTaskExists(e)?r=t.getTask(e):r=e,!r)return this.getCalendar();var n=this._getOwnCalendar(r),i=!!t.getState().group_mode;if(!n&&t.config.inherit_calendar&&t.isTaskExists(r.parent)){for(var a=r;t.isTaskExists(a.parent)&&(a=t.getTask(a.parent),!(t.isSummaryTask(a)&&(n=this._getOwnCalendar(a),n))););i&&!n&&e.$effective_calendar&&(n=this.getCalendar(e.$effective_calendar))}return n||this.getCalendar()},addCalendar:function(e){if(!this.isCalendar(e)){var t=e.id;e=this.createCalendar(e),e.id=t}if(e._tryChangeCalendarSettings(function(){})){var r=this.$gantt.config;return e.id=e.id||Zi(),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 oa(e,t){this.argumentsHelper=t,this.$gantt=e}oa.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 oa},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 fl(e){this.$gantt=e.$gantt,this.argumentsHelper=ll(this.$gantt),this.calendarManager=e,this.$disabledCalendar=new oa(this.$gantt,this.argumentsHelper)}fl.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: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)}},Sm={create:km};function pl(e){var t=new ul(e),r=new fl(t),n=Sm.create(t,r);We(e,n)}var hl={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 yl(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||hl,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:al,mixin:We,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=cl(r),r.date.init(),pl(r),r}function Dm(e={}){let t=yl(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 ml={createCalendar:Dm};var RO=3600*1e3;function Il(e){return{getActivity(t){return e.getActivity(t)}}}var{createCalendar:Tm}=ml,or="__replay_default__";function _m(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 gl={hours:["8:00-16:00"],days:[!1,!0,!0,!0,!0,!0,!1]},vl="__main_global__",Pm={hours:["8:00-12:00","13:00-17:00"],days:[!1,!0,!0,!0,!0,!0,!1]};function Al(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 bm(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:_m(e.hours),dates:t};return e.customWeeks&&(r.customWeeks=e.customWeeks),r}function Cl(e){let t=Tm({config:{work_time:!0}});t.addCalendar({id:or,worktime:gl}),t.addCalendar({id:vl,worktime:Pm});let r=new Set(e.filter(d=>!Al(d.worktime)).map(d=>String(d.id))),n=e.filter(d=>Al(d.worktime));for(let d of n)t.addCalendar({id:d.id,worktime:d.worktime?bm(d.worktime):gl});let i=il(t),a=i.getCalendar(or),s=i.getCalendar(vl);if(!a||!s)throw new Error("[replay-calendar] fallback calendars failed to register in work-calendar instance");let o=new Set([or]);for(let d of n)o.add(String(d.id));let c=new Map;return{reader:{getCalendar(d){let u=String(d),f=c.get(u);if(f)return f;let p=a;return o.has(u)?p=i.getCalendar(d)??a:r.has(u)&&(p=s),c.set(u,p),p}}}}function kl(e){return{hasChildren(t){return e.hasChildren(t)},getParentStartDateIfHasPredecessors(t){let r=e.getActivity(t);if(!r)return null;let n=e.getParent(r.id);return!n||e.getIncomingLinkIds(n.id).length===0?null:n.startDate},getDescendantIds(t){return Rm(e,t).map(r=>String(r))},getAncestorIds(t){let r=[],n=e.getActivity(t);for(;n;){let i=n.parentId;if(i===null)break;let a=e.getActivity(i);if(!a)break;r.push(String(i)),n=a}return r},getChildProgressInfo(t){return e.getChildren(t).map(n=>{let i=e.getActivity(n);return{id:n,progress:Number(i?.progress??0),ponderator:Number(i?.ponderator??0)}})},getChildHhInfo(t){return e.getChildren(t).map(n=>{let i=e.getActivity(n);return{id:n,workHours:Number(i?.workHours??0),progress:Number(i?.progress??0),realWorkHours:Number(i?.realWorkHours??0)}})},getChildUsedCostInfo(t){return e.getChildren(t).map(n=>{let i=e.getActivity(n);return{id:n,usedCost:Number(i?.usedCost??0)}})},getChildCostInfo(t){return e.getChildren(t).map(n=>{let i=e.getActivity(n);return{id:n,cost:Number(i?.cost??0)}})}}}function Rm(e,t){let r=[],n=new 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 An=class{_journal=null;begin(){this._journal={dirty:new Set,before:new Map,ops:[],linkFieldCaptured:new Set,correlativeBefore:new Map,scheduledBefore:new Map,progressFallbackBefore:new Map}}peek(){return this._journal}end(){this._journal=null}note(t,r){let n=this._journal;n&&(n.before.has(t)||n.before.set(t,xt(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:xt(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:Sl(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=xt(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:Sl(r)}))}noteProgressFallback(t,r){let n=this._journal;!n||n.progressFallbackBefore.has(t)||n.progressFallbackBefore.set(t,r)}};function Sl(e){return{...e}}var In=class{_cache={closestWorkTime:new Map,endDate:new Map,duration:new Map};reader;constructor(t){this.reader=t.reader}resolveCalendar(t){let r=Dl(t);return this.reader.getCalendar(r??or)}getClosestWorkTime(t){let r=`${la(t.task)}|${t.dir}|${t.date.getTime()}`;return ca(this._cache.closestWorkTime,r,()=>this.resolveCalendar(t.task).getClosestWorkTime({direction:t.dir,date:t.date,unit:ot.HOUR}))}calculateEndDate(t){let r=`${la(t.task)}|${t.startDate.getTime()}|${t.durationHours}`;return ca(this._cache.endDate,r,()=>this.resolveCalendar(t.task).calculateEndDate(t.startDate,t.durationHours))}calculateDuration(t){let r=`${la(t.task)}|${t.startDate.getTime()}|${t.endDate.getTime()}`;return ca(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 ca(e,t,r){let n=e.get(t);if(n!==void 0)return n;let i=r();return e.set(t,i),i}var Em="__default__";function Dl(e){if(!e)return null;let t=e.calendarId;return t==null?null:String(t)}function la(e){return Dl(e)??Em}var Cn=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?hr(i,a):String(r).localeCompare(String(n))};this._roots.sort(t);for(let r of this._childrenByParent.values())r.sort(t)}};var kn=class{checkedSet=new Set;hiddenSet=new Set;activeFilter=null;activeOrder=null;isChecked(t){return this.checkedSet.has(t)}isVisible(t){return!this.hiddenSet.has(t)}hiddenIds(){return[...this.hiddenSet]}getActiveFilter(){return this.activeFilter}setActiveFilter(t){this.activeFilter=t}getActiveOrder(){return this.activeOrder}setActiveOrder(t){this.activeOrder=t}checkedIds(){return[...this.checkedSet]}checkedCount(){return this.checkedSet.size}setChecked(t,r){return r===this.checkedSet.has(t)?!1:(r?this.checkedSet.add(t):this.checkedSet.delete(t),!0)}setVisible(t,r){return r===!this.hiddenSet.has(t)?!1:(r?this.hiddenSet.delete(t):this.hiddenSet.add(t),!0)}forget(t){this.checkedSet.delete(t),this.hiddenSet.delete(t)}hydrate(t){this.checkedSet=new Set(t.checkedIds??[]),this.hiddenSet=new Set(t.hiddenIds??[]),this.activeFilter=null,this.activeOrder=null}snapshot(){return{checked:new Set(this.checkedSet),hidden:new Set(this.hiddenSet),activeFilter:this.activeFilter,activeOrder:this.activeOrder}}restore(t){this.checkedSet=new Set(t.checked),this.hiddenSet=new Set(t.hidden),this.activeFilter=t.activeFilter,this.activeOrder=t.activeOrder}};var Be=class e{_activities=new Map;_lastStartDate=new Map;_promotionSnapshot=new Map;_progressFallback=new Map;_links=new Map;_outgoing=new Map;_incoming=new Map;_hierarchy;_buildOrderComparator;_cache={ids:null,visualOrderIds:null,orderComparator:null};_writeCapture=new An;_viewState=new kn;_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 In(Cl(this._calendarSnapshot)),this._flags=wm(t),this._hierarchy=new Cn(this._activities),this._hierarchy.rebuild()}fork(){let t=new e({activities:this.getAllActivities().map(xt),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._progressFallback=new Map(this._progressFallback),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)}getProgressFallback(t){return this._progressFallback.get(String(t))??null}setProgressFallback(t,r){let n=String(t),i=this._progressFallback.get(n)??null;Object.is(i,r)||(this._writeCapture.noteProgressFallback(n,i),r===null?this._progressFallback.delete(n):this._progressFallback.set(n,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))??Tl}getIncomingLinkIds(t){return this._incoming.get(String(t))??Tl}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,ua(i,r),r===E.PARENT&&this._hierarchy.markDirty(),da(r)&&(this._cache.visualOrderIds=null))}setActivityFieldDynamic(t,r,n){let i=this.getActivity(t);if(i){if(!Object.hasOwn(i,r))throw new Error(`setActivityFieldDynamic: unknown CoreActivity field "${r}"`);this._writeCapture.note(String(t),i),Reflect.set(i,r,nl(r,n)),ua(i,r),r===E.PARENT&&this._hierarchy.markDirty(),da(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)),ua(n,a),a===E.PARENT&&(i=!0),da(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){Pl(this._outgoing,String(t.source),t.id),Pl(this._incoming,String(t.target),t.id)}_deindexLink(t){let r=this._outgoing.get(String(t.source));r&&this._outgoing.set(String(t.source),_l(r,t.id));let n=this._incoming.get(String(t.target));n&&this._incoming.set(String(t.target),_l(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(!Lm(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.setProgressFallback(n,null),(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,progressFallbackBefore:s}=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._restoreProgressFallbacks(s),this._viewStateBefore!==null&&(this._viewState.restore(this._viewStateBefore),this._filterProjection=null,this.invalidateDerivedOrder()),this._promotionSnapshotBefore!==null&&(this._promotionSnapshot=this._promotionSnapshotBefore),this._lastStartDateBefore!==null&&(this._lastStartDate=this._lastStartDateBefore),this._cache.ids=null,this._cache.visualOrderIds=null,this._hierarchy.markDirty()}_restoreProgressFallbacks(t){for(let[r,n]of t)n===null?this._progressFallback.delete(r):this._progressFallback.set(r,n)}_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))}},Tl=[];function Lm(e){return e===Ze.LAG||e===Ze.TYPE||e===Ze.FREE_SLACK_HOURS||e===Ze.IS_CRITICAL}function da(e){return e===E.PARENT||e===E.CORRELATIVE_ID}function ua(e,t){t!==E.START_DATE&&t!==E.END_DATE&&t!==E.TYPE||(e.calendarDuration=Rt(e))}function _l(e,t){return e.filter(r=>String(r)!==String(t))}function Pl(e,t,r){let n=e.get(t);n?n.push(r):e.set(t,[r])}function wm(e){let t=e.runtimeFlags??{};return{isPasting:!!t.isPasting,isBulkOperation:!!t.isBulkOperation,dragWithMultiple:!!t.dragWithMultiple,draggingSingleMilestone:!!t.draggingSingleMilestone,creatingActivity:!1,avoidAutoScheduleBeforeDrag:!1,maxPerformance:!!t.maxPerformance,allCheckedTaskIds:[]}}function bl(e,t){let r=e.getActivity(t);return r?b(r):null}function Rl(e){return e.getAllActivities().map(b)}function El(e){return e.getAllIds().map(String)}function Ll(e,t){e.forEachActivity((r,n)=>t(n))}function wl(e,t){let r=t==="0"?fa(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 fa(e,t){return gt(t,e)}function Ol(e){return e.checkedIds().map(String)}function Fl(e,t){if(t==="0"){let r=!1;return e.forEachActivity(n=>{r||=L(n.parentId)}),r}return e.getChildren(t).length>0}function pa(e,t){let r=e.getLink(t);return r?ft(r):null}function xl(e){return e.getAllLinks().map(t=>ft(t))}function Sn(e){let[t,r]=e.split(":");return Number(t)*60+Number(r??0)}function Om(e){return e.reduce((t,r)=>Sn(r)<Sn(t)?r:t)}function Fm(e){return e.reduce((t,r)=>Sn(r)>Sn(t)?r:t)}function xm(e){return e.worktime.days.flatMap(t=>Array.isArray(t)?t:t===!0?e.worktime.hours:[])}function Nl(e){let t=[...e].find(a=>a.is_default);if(!t)return null;let r=xm(t);if(r.length===0)return null;let n=r.map(a=>a.split("-")[0]),i=r.map(a=>a.split("-")[1]);return{startHour:Om(n),endHour:Fm(i)}}function Ml(e,t){return{calendars:e.calendarReader,hierarchy:kl(e),activityReader:Il(e),dateFormat:t.dateFormat??"YYYY-MM-DD",customHours:t.customHours??{},hoursPerDay:t.hoursPerDay}}function Wl(e){return se(e)}var Nm=new Set(["freeSlackHours","isCritical"]);function Mm(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 Hl(e){let t=e.activities.map(i=>({...i,after:null})),r=e.links.map(i=>Mm(i,Nm)).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 ha(e,t,r,n,i,a,s){return{changeSet:e,beforeSnap:t,beforeLinks:Bl(r),afterSnap:n,afterLinks:Bl(i),progressFallbackBefore:a,progressFallbackAfter:s}}function Bl(e){if(e)return new Map(Array.from(e,([t,r])=>[t,{...r,freeSlackHours:null,isCritical:!1}]))}function Vl(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 Yl(e){return e.kind!=="inline-edit"||!nr.has(e.column)?null:`inline-edit:${String(e.activityId)}:${e.column}`}function jl(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 Kl(e,t){if(!jl(e)||!jl(t))return!1;let r=e.changeSet.activities[0],n=t.changeSet.activities[0];return!!r&&!!n&&String(r.id)===String(n.id)}function Gl(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 ha(o)}function $l(e){return e.kind==="persistence-acknowledge"?"checkpoint-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 ya(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 ma(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:Ul(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:Ul(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"?Wm(s):s);return{source:{kind:r==="before"?"undo":"redo"},activities:n,links:i,calendars:[],trackingEvents:[],effects:[],viewState:a}}function Ul(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 Wm(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 ga(e){return e.activities.length>0||e.links.length>0||(e.viewState?.length??0)>0||(e.effects?.length??0)>0}function zl(e,t){Jl(e,t,"before")}function ql(e,t){Jl(e,t,"after")}function Jl(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))fo(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.progressFallbackBefore:t.progressFallbackAfter;for(let[a,s]of i??[])e.setProgressFallback(a,s)}var Bm=100,jm=600,Dn=class e{constructor(t=Bm){this.maxDepth=t}maxDepth;undoStack=[];redoStack=[];sequence=0;_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.sequence=this.sequence,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<=jm&&i!==void 0&&Kl(i.entry,t)?(i.entry=Gl(i.entry,t),i.touchedAt=this.touch()):(this.undoStack.push({entry:t,touchedAt:this.touch()}),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()?.entry??null}takeRedo(){return this.redoStack.pop()?.entry??null}pushRedo(t){this.redoStack.push({entry:t,touchedAt:this.touch()})}pushUndo(t){this.undoStack.push({entry:t,touchedAt:this.touch()})}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}undoDepth(){return this.undoStack.length}capturePersistenceBoundary(){return this.resetCoalesce(),this.sequence}discardThrough(t){this.removeEntriesThrough(this.undoStack,t),this.removeEntriesThrough(this.redoStack,t),this.resetCoalesce()}applyPersistedIdentities(t,r){let n=new Map(t.map(({id:a,proplannerId:s})=>[String(a),s])),i=new Map(r.map(({id:a,proplannerId:s})=>[String(a),s]));for(let a of[...this.undoStack,...this.redoStack])a.entry=this.withPersistedIdentities(a.entry,n,i)}clear(){this.undoStack.length=0,this.redoStack.length=0,this.resetCoalesce()}touch(){return this.sequence+=1,this.sequence}removeEntriesThrough(t,r){let n=t.filter(({touchedAt:i})=>i>r);t.splice(0,t.length,...n)}withPersistedIdentities(t,r,n){let i=s=>s===void 0?void 0:new Map(Array.from(s,([o,c])=>[o,r.has(o)?{...c,proplannerId:r.get(o)}:c])),a=s=>s===void 0?void 0:new Map(Array.from(s,([o,c])=>[o,n.has(o)?{...c,proplannerId:n.get(o)}:c]));return{...t,beforeSnap:i(t.beforeSnap),afterSnap:i(t.afterSnap),beforeLinks:a(t.beforeLinks),afterLinks:a(t.afterLinks)}}};var Um=["parentId","correlativeId"];function Zl(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(Xl(c.parentId?.before));continue}let s=i.fields;!s||!Um.some(c=>c in s)||(n(a),"parentId"in s&&r.add(Xl(s.parentId?.before)))}return r}function Xl(e){return e==null?"0":String(e)}function Hm(e){return{...e,id:String(e.id),source:String(e.source),target:String(e.target),type:e.type,lag:Number(e.lag)}}function Vm(e){return{days:e.days,hours:e.hours,...e.dates?{dates:e.dates}:{},...e.customWeeks?{customWeeks:e.customWeeks}:{}}}function Ql(e){return{id:String(e.id),worktime:Vm(e.worktime)}}function Tn(e,t,r,n=[]){let i=t.map(Hm),a=[...r.map(Ql),...n.map(Ql)];return{activities:[...e],links:i,calendars:a}}var td={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"},ed=Object.keys(td).filter(e=>td[e]==="tracked"),rd=new Set(["startDate","endDate","constraintDate","dateOrigin"]),nd=new Set(["newActivityIds","responsableIds","tagIds"]);function id(e){let t=ed.map(r=>[r,Ym(r,e[r])]);return Object.fromEntries(t)}function Ym(e,t){return rd.has(e)?t instanceof Date?new Date(t):null:nd.has(e)?Array.isArray(t)?[...t]:[]:t}function cr(e,t){return va(e,t).length>0}function va(e,t){return ed.filter(r=>!Km(r,e[r],t[r]))}function Km(e,t,r){return rd.has(e)?Gm(t,r):nd.has(e)?$m(t,r):(t??null)===(r??null)}function Gm(e,t){let r=e instanceof Date?e.getTime():null,n=t instanceof Date?t.getTime():null;return r===n}function $m(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 ad={id:"ignored",source:"tracked",target:"tracked",type:"tracked",lag:"tracked",freeSlackHours:"ignored",isCritical:"ignored",ganttId:"ignored",sectorId:"ignored",proplannerId:"ignored"},zm=Object.keys(ad).filter(e=>ad[e]==="tracked");function _n(e,t){return zm.some(r=>e[r]!==t[r])}function sd(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?_n(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 od(e,t){for(let r of e)Pt(r.proplannerId);for(let r of t)Pt(r.proplannerId)}var Pn=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){od(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,n=[],i=[],a,s){if(!this.trackingEnabled)return;let o=new Map(n.map(({id:p,proplannerId:h})=>[String(p),h])),c=new Map(i.map(({id:p,proplannerId:h})=>[String(p),h])),l=t.map(p=>({...p,proplannerId:o.get(String(p.id))??p.proplannerId})),d=r.map(p=>{let h=c.get(String(p.id));return h===void 0?{...p}:{...p,proplannerId:h}});if(od(l,d),this.snapshotActivities(l),this.snapshotLinks(d),!a||!s)return;let u=new Map(a.map(p=>[String(p.id),p])),f=new Map(s.map(p=>[String(p.id),p]));for(let p of l){let h=String(p.id);this.activityIsDirty(h,u.get(h)??null)&&this.dirtyActivityIds.add(h)}for(let p of a){let h=String(p.id);this.activityIsDirty(h,p)&&this.dirtyActivityIds.add(h)}for(let p of d){let h=String(p.id);this.linkIsDirty(h,f.get(h)??null)&&this.dirtyLinkIds.add(h)}for(let p of s){let h=String(p.id);this.linkIsDirty(h,p)&&this.dirtyLinkIds.add(h)}}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=id(r);this.activitiesAtLastSave.set(String(r.id),{persistable:i,deletedSnapshot:{id:r.id,proplannerId:r.proplannerId,parentId:r.parentId,hadBaseline:r.baselineSnapshot!==null||r.baselinePoints.length>0}}),cr(r,i)&&this.dirtyActivityIds.add(n)}}}snapshotLinks(t){if(this.trackingEnabled){this.linksAtLastSave.clear(),this.dirtyLinkIds.clear();for(let r of t){let n=String(r.id);if(!Pt(r.proplannerId)){this.dirtyLinkIds.add(n);continue}this.linksAtLastSave.set(String(r.id),{id:r.id,proplannerId:r.proplannerId,source:r.source,target:r.target,lag:r.lag,type:r.type})}}}recordChanges(t,r,n,i){if(!(!this.trackingEnabled||!this.initialized)){for(let a of t){let s=String(a.id),o=n(s);this.activityIsDirty(s,o)?this.dirtyActivityIds.add(s):this.dirtyActivityIds.delete(s)}for(let a of r){let s=String(a.id),o=i(s);this.linkIsDirty(s,o)?this.dirtyLinkIds.add(s):this.dirtyLinkIds.delete(s)}}}activityIsDirty(t,r){let n=this.activitiesAtLastSave.get(t);return r===null?n!==void 0:this.initialCalendarRepairIds.has(t)||!Pt(r.proplannerId)||n===void 0||cr(r,n.persistable)}linkIsDirty(t,r){let n=this.linksAtLastSave.get(t);return r===null?n!==void 0:!Pt(r.proplannerId)||n===void 0||_n(n,r)}acknowledgePersistedLookahead(t,r){if(!this.trackingEnabled||!this.initialized)return;let n=t.map(i=>{let a=typeof i=="string"?i:String(i.id),s=r(a),o=this.activitiesAtLastSave.get(a);if(s===null||o===void 0)throw new Error(`unknown persisted activity "${a}"`);return{activityId:a,acknowledgesLookahead:typeof i=="string"||!!i.fields?.isLookahead,acknowledgesProgress:typeof i!="string"&&!!i.fields?.progress,current:s,saved:o}});for(let{activityId:i,acknowledgesLookahead:a,acknowledgesProgress:s,current:o,saved:c}of n){let l={...c.persistable,...a?{isLookahead:o.isLookahead}:{},...s?{progress:o.progress}:{}};this.activitiesAtLastSave.set(i,{...c,persistable:l}),this.initialCalendarRepairIds.has(i)||!Pt(o.proplannerId)||cr(o,l)?this.dirtyActivityIds.add(i):this.dirtyActivityIds.delete(i)}}hasCheckpointActivityId(t){return this.activitiesAtLastSave.has(t)}hasCheckpointLinkId(t){return this.linksAtLastSave.has(t)}hasUnsavedChanges(){return this.trackingEnabled&&this.initialized&&(this.dirtyActivityIds.size>0||this.dirtyLinkIds.size>0)}newActivities(t){if(!this.trackingEnabled||!this.initialized)return[];let r=[];for(let n of this.dirtyActivityIds){let i=t(n);i!==null&&!Pt(i.proplannerId)&&r.push(i)}return r}newLinks(t){if(!this.trackingEnabled||!this.initialized)return[];let r=[];for(let n of this.dirtyLinkIds){let i=t(n);i!==null&&!Pt(i.proplannerId)&&r.push(i)}return r}deletedActivities(t){if(!this.trackingEnabled||!this.initialized)return[];let r=[];for(let n of this.dirtyActivityIds){let i=this.activitiesAtLastSave.get(n);i&&t(n)===null&&r.push({...i.deletedSnapshot})}return r}deletedLinks(t){if(!this.trackingEnabled||!this.initialized)return[];let r=[];for(let n of this.dirtyLinkIds){let i=this.linksAtLastSave.get(n);i&&t(n)===null&&r.push({...i})}return r}modifiedActivities(t){if(!this.trackingEnabled||!this.initialized)return[];let r=[];for(let n of this.dirtyActivityIds){let i=t(n);if(i===null||!Pt(i.proplannerId))continue;let a=this.activitiesAtLastSave.get(n);(a===void 0||this.initialCalendarRepairIds.has(n)||cr(i,a.persistable))&&r.push(i)}return r}modifiedActivityFields(t){let r=new Map;if(!this.trackingEnabled||!this.initialized)return r;for(let n of this.dirtyActivityIds){let i=t(n),a=this.activitiesAtLastSave.get(n);if(!i||!a)continue;let s=va(i,a.persistable);s.length>0&&r.set(n,s)}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||_n(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 cd=/^(\d{4})[/-](\d{1,2})[/-](\d{1,2})/;var Aa=[!1,!0,!0,!0,!0,!0,!1],ld=new Set(["1","true"]),Ia="DURATION",dd="asap",ud={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 fd(e,t){let r=[],n=e.map(a=>{let s=ag(a,t);return a.should_be_showed===!1&&r.push(s.id),s});og(n);let i=new Set(n.map(a=>a.id));return cg(n,i,t.reporter),{activities:n,activityIds:i,hiddenIds:r}}function qm(e){return e===0}function Jm(e,t){if(!e)return null;let r=ud[e.toUpperCase()];return r===void 0?(t.warn(`[parseFromBackend] unknown constraint label "${e}" \u2014 defaulting to "asap"`),dd):r}function Xm(e,t){let r=Jm(e.constraint,t),i=r!=="asap"&&r!=="alap"&&e.constraint_date?Nt(e.constraint_date):null;return{constraintType:r,constraintDate:i}}function Zm(e,t,r){if(e==null)return r;let n=String(e);return t.has(n)?n:r}function Qm(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 tg(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)tg(r)&&t.push(String(r.id));return t}function eg(e){return e==="0"?null:String(e)}function rg(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 ng(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 ig(e,t){return Array.isArray(e)?e.map(r=>hn(r,t)).filter(r=>r!==null):[]}function ag(e,t){let r=Zm(e.calendarId,t.knownCalendarIds,t.defaultCalendarId),n=e.calendarId==null||!t.knownCalendarIds.has(String(e.calendarId)),i=Number(e.progress),{constraintType:a,constraintDate:s}=Xm(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=ng(e,t.reporter);return{id:String(e.unique_id),proplannerId:rg(e.id),parentId:eg(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:qm(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:sg(e),subcontractId:e.subcontractId,isLookahead:e.isOnLookahead,hasLookaheadTasks:Array.isArray(e.tasks)&&e.tasks.length>0,newActivityIds:Qm(e.newActivitiesArray),hasNewActivities:e.hasNewActivities??!1,...e.isNewActivity===!0?{isNewActivity:!0}:{},pendingRequestIds:Ca(e.pendingRequests),responsableIds:Ca(e.responsables),tagIds:Ca(e.tags),baselinePoints:ig(e.baseline_points,t.reporter),baselineSnapshot:null,recursiveDurationHours:te(Number(e.sumOfDurationRecursively??0),t.hoursPerDay),calendarDuration:Rt({type:e.type,startDate:c,endDate:l}),isCritical:u,freeSlackHours:null,expectedProgress:null,expectedProgressBaseline:null,status:null,criticalPath:null}}function sg(e){return e.has_childs?null:e.custom_id}function og(e){let t=e.find(r=>r.correlativeId===0&&r.type==="project");t&&(t.parentId=null)}function cg(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 md(e,t,r,n=null){let s=(e!==void 0&&e.length>0?e:t??[]).map(c=>ug(c,n)),o=(r??[]).map(c=>fg(c,n));return{calendars:s,baseCalendars:o,knownCalendarIds:new Set(s.map(c=>c.id)),defaultCalendarId:dg(s)}}function dg(e){let t=e.find(n=>n.is_default);if(t)return t.id;let r=e[0];return r?r.id:null}function gd(e,t){let r=vg(e.working_days),{days:n,hours:i}=gg(e,r),a=pg(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 ug(e,t){let r=e.baseDefault,n=typeof r=="boolean"?r:void 0;return gd(e,{idSuffix:"",isDefault:!!e.is_default,baseDefault:n,exceptionsSource:e.exceptiondays,exceptionRange:t})}function fg(e,t){return gd(e,{idSuffix:"-base",isDefault:!1,baseDefault:!!e.is_default,exceptionsSource:e.baseexceptiondays??e.exceptiondays,exceptionRange:t})}function pg(e,t){if(!Array.isArray(e)||e.length===0)return null;let r={};for(let n of e){if(!n)continue;let i=hg(n.from_date,n.to_date,t);if(i.length===0)continue;let a=yg(n);if(a!==void 0)for(let s of i)r[s]=a}return Object.keys(r).length>0?r:null}function hg(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=cd.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 yg(e){if(e.workable===!1)return!1;let t=e.shifts;if(Array.isArray(t)&&t.length>0){let r=mg(t);if(r.length>0)return r}}var hd=/^\d{1,2}:\d{2}$/;function mg(e){let t=[];for(let r of e){let n=Id(r?.shift_string);if(!n)continue;if(!n.startsCsv.includes(",")&&!n.endsCsv.includes(",")){let o=n.startsCsv.trim(),c=n.endsCsv.trim();!bn(o)&&!bn(c)&&hd.test(o)&&hd.test(c)&&t.push(`${o}-${c}`);continue}let s=Ad(n.startsCsv,n.endsCsv).find(o=>o!==null);s&&t.push(s)}return t.sort(vd),t}function yd(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 vd(e,t){return yd(e)-yd(t)}function gg(e,t){let r=Array.from({length:7},()=>[]),n=(l,d)=>{let u=Ad(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=Id(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(vd);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 Ad(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];bn(c)||bn(l)||(s[o]=`${c}-${l}`)}return s}function Id(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 vg(e){if(typeof e!="string")return[...Aa];let t=e.split(",").map(r=>r.trim());return t.length!==7?[...Aa]:t.map(r=>ld.has(r))}var Ag=new Set(["false","null"]);function bn(e){return!e||Ag.has(e)}function Ig(e){return e==="0"||e==="1"||e==="2"||e==="3"}function Cg(e){if(typeof e!="string")return null;let t=Ds(e);return t||(Ig(e)?e:null)}function kg(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 kd(e,t){let r=[];for(let n of e)try{r.push(Sg(n,t.knownActivityIds,t.hoursPerDay))}catch(i){t.reporter.warn("[parseFromBackend] dropping invalid link",i)}return Dg(r)}function Sg(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=Cg(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=kg(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 Dg(e){let t=new Map;for(let r of e){let n=`${r.source}-${r.target}-${r.type}`,i=t.get(n);(!i||Cd(r)>Cd(i))&&t.set(n,r)}return[...t.values()]}function Cd(e){let t=Number(e.id);return Number.isFinite(t)?t:-1/0}function Tg(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 _g(e){let t=e.custom_id_prefix;return typeof t=="string"&&t.length>0?t:void 0}function Pg(e){let t=e.custom_id_increment;return typeof t=="string"?t:typeof t=="number"&&Number.isFinite(t)?String(t):void 0}function Sd(e){let t=_g(e),r=Pg(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:Tg(e.activity_creter),statusCriteria:pi,ganttId:null}}function Rn(e,t=Ae){let r=Sd(e.sector),{calendars:n,baseCalendars:i,knownCalendarIds:a,defaultCalendarId:s}=md(e.calendars,e.sector.calendars,e.baseCalendars,bg(e.activities)),{activities:o,activityIds:c,hiddenIds:l}=fd(e.activities,{knownCalendarIds:a,defaultCalendarId:s,hoursPerDay:r.hoursPerDay,reporter:t}),d=kd(e.links,{knownActivityIds:c,hoursPerDay:r.hoursPerDay,reporter:t});return{sector:r,activities:o,links:d,calendars:n,baseCalendars:i,viewStateSeed:{hiddenIds:l}}}function bg(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 Sa(e={}){let t=e.seed??0,r=n=>{n>t&&(t=n)};if(e.knownIds)for(let n of e.knownIds){let i=typeof n=="number"?n:Number(n);Number.isFinite(i)&&r(i)}return{fork(){return Sa({seed:t})},next(){return t+=1,String(t)},bump(n){let i=typeof n=="number"?n:Number(n);Number.isFinite(i)&&r(i)},snapshot(){return t},restore(n){t=n}}}function 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 Dd(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 Ln(e){if(!e||typeof e!="string"||e.trim().length===0)return"";let t=e.match(/(\d+)$/);return t?t[1]??"":""}function Td(e){if(!e||typeof e!="object")return"";let t=e.customId;return typeof t=="string"?t:""}function _d(e,t){return!t&&Dd(e)}function Pd(e,t){return t&&Dd(e)}function lr(e){return typeof e=="string"&&e.length>0&&/^\d+$/.test(e)}function wn(e){if(!lr(e))return 0n;try{return BigInt(e)}catch{return 0n}}function Rg(e,t){if(typeof e!="bigint")return"";let r=e.toString();if(!lr(t))return r;let n=t.length;return r.padStart(n,"0")}function Ct(e,t){let r=wn(e),n=wn(t),i=r+n;return Rg(i,e)}function On(e,t){let r=wn(e),n=wn(t);return r<n?-1:r>n?1:0}function Fn(e,t){return On(e,t)<=0?e:t}function xn(e,t){return On(e,t)>=0?e:t}function bd(e){if(!e||e.length===0)throw new Error("minSuffixFromArray requires non-empty array");return e.reduce((t,r)=>Fn(t,r))}function Rd(e){if(!e||e.length===0)throw new Error("maxSuffixFromArray requires non-empty array");return e.reduce((t,r)=>xn(t,r))}function Ed(e){return{prefix:e,baseSuffix:null}}function Ld(e,t){let r=Ln(e);return{prefix:En(e),baseSuffix:Ct(r,t)}}function wd(e){return{prefix:e,baseSuffix:null}}function Od(e,t){return _d(e,t)?"parentConversion":Pd(e,t)?"pasteReference":"noContext"}function Fd(e){return{...e,usedSuffixes:new Set(e.usedSuffixes)}}var Nn=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?Fd(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=bd(n),r.max=Rd(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,Fd(n));for(let r of this.processedIds)t.processedIds.add(r);return t}extractPrefix(t){return En(t)}extractSuffix(t){return Ln(t)}analyzeCustomId(t){return{prefix:this.extractPrefix(t),suffix:this.extractSuffix(t)}}_updatePrefixStats(t,r){if(this._ensureFreshBounds(t),!this.prefixMap.has(t)){this.prefixMap.set(t,{min:r,max:r,next:r,quantity:1,usedSuffixes:new Set([r])}),this._recalculateNext(t);return}let n=this.prefixMap.get(t);n.usedSuffixes.has(r)||(n.usedSuffixes.add(r),n.min=Fn(r,n.min),n.max=xn(r,n.max),n.quantity+=1,this._recalculateNext(t))}_recalculateNext(t){let r=this.prefixMap.get(t);if(!r)return;let n=this.getNextAvailableSuffix(t);r.next=n??this.suffixIncrement}getPrefixStats(t){this._ensureFreshBounds(t);let r=this.prefixMap.get(t);return r?{min:r.min,max:r.max,next:r.next,quantity:r.quantity}:null}getNextSuffix(t){this._ensureFreshBounds(t);let r=this.prefixMap.get(t);return r?r.next:this.suffixIncrement}getAllPrefixes(){return Array.from(this.prefixMap.keys())}registerCustomId(t){if(!t||typeof t!="string")return{prefix:"",suffix:""};let{prefix:r,suffix:n}=this.analyzeCustomId(t);if(!r&&!n)return{prefix:r,suffix:n};if(this._noteCustomIdBefore(t),this._ensureFreshBounds(r),this.prefixMap.has(r)){let i=this.prefixMap.get(r);i.usedSuffixes.has(n)||(i.usedSuffixes.add(n),i.min=Fn(n,i.min),i.max=xn(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&&lr(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(;On(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||!lr(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=Td(r),a=Od(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 Ed(this.defaultPrefix);case"pasteReference":return Ld(r,this.suffixIncrement);default:return wd(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 Eg=1,Lg=-1;function wg(e,t){return!e&&!t?null:e&&t?0:e?Eg:Lg}function xd(e){return e==null}function Nd(e,t){let r=t.indexOf(String(e));return r===-1?t.length:r}function Og(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 Fg(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=wg(xd(a),xd(s));if(o!==null)return o;let c=r.valueKind==="enum"?Nd(a,r.order)-Nd(s,r.order):Og(a,s,t.locale);return e.direction==="desc"?-c:c}}function Md(e,t){let r=e.rules.map(n=>Fg(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 Wd(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),xg(e,r)}function xg(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 Bd(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 jd(e){let{state:t,sector:r,scheduler:n,skipAutoSchedule:i,now:a}=e;if(at(t),r.updateDurationForPrimaveraEndDate&&Mg(t),Wg(t),Bd(t),i){qe(t),a&&(ne(t,a),Mt(t,r.statusCriteria));return}let s=await n.schedule({});Ye(t,s),Bg(t),Ng(t),await Ce(t,void 0,!1),qe(t),a&&(ne(t,a),Mt(t,r.statusCriteria))}function Ng(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 Mg(e){e.forEachActivity(t=>{!t.startDate||!t.endDate||(t.durationHours=e.calculateDuration({startDate:t.startDate,endDate:t.endDate,task:t}))})}function Wg(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=Ft(t.constraintDate,i,r))})}function Bg(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=Ft(t.constraintDate,n,r))})}var kt={READY:"ready",DESTROYED:"destroyed",POISONED:"poisoned"};function Ud(e){let t=e.clock??null,r=t?.()??null,n=r?Wr(r):null,i=e.reporter??Ae,a=Rn({sector:e.sector,activities:e.activities,links:e.links,calendars:e.calendars,baseCalendars:e.baseCalendars},i),s=a.sector;s.statusCriteria=Gr(e.statusCriteria),s.ganttId=e.ganttId??null;let o=a.calendars,c=a.baseCalendars??[],l=Tn(a.activities,a.links,a.calendars,c),d=v=>Md(v,Zt(s.hoursPerDay)),u=new Be(l,d);u.hydrateViewState({hiddenIds:a.viewStateSeed.hiddenIds});let f=new Ie(u,i);Wd(u);let p=Sa({knownIds:a.activities.map(v=>v.id)}),h=Da({seed:r?.getTime()??0,knownIds:a.links.map(v=>v.id)}),m=Ta({knownIds:a.activities.map(v=>v.uniqueCorrelativeId)}),I=new Nn({defaultPrefix:s.customIdPrefix,suffixIncrement:s.customIdIncrement});if(I.populateFromActivities(a.activities),e.baselinePoints&&e.baselinePoints.length>0){let v=c.find(S=>S.baseDefault)?.id??null;yn(u,e.baselinePoints,n,i,v)}let T=jd({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:m,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=jg(o,c);Object.keys(l).length>0&&a.push({id:s,kind:"updated",fields:l,after:b(c)})}return a}function jg(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 Ug(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 Hd(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:Ug(e,t),...r?{order:b(e.order)}:{}}}var Hg=()=>({constantStart:null,variableStartOffset:null,constantEnd:null,variableEndOffset:null}),Pa=(e,t)=>e===null?t:Math.min(e,t),ba=(e,t)=>e===null?t:Math.max(e,t);function Yd(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=Vg(e,t,n);return Yg(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=Gg(o,s),l=$g(o,s);if(c===null||l===null)throw new Error(`[ScheduleCore] incomplete date gesture bounds for ${String(a)}`);return{startTimeMs:c,endTimeMs:l}}}}function Vg(e,t,r){let n=new Map,i=t.kind==="move"?String(t.anchorActivityId):null,a=i===null?null:Vd(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=Vd(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 Yg(e,t,r){let n=Je(e,new Set(t));for(let i of n){let a=Hg();for(let s of e.getChildren(i)){let o=r.get(s);if(o){Kg(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=ba(a.constantEnd,c.endDate.getTime())}r.set(i,a)}}function Vd(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 Kg(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=ba(e.constantEnd,t.constantEnd)),t.variableEndOffset!==null&&(e.variableEndOffset=ba(e.variableEndOffset,t.variableEndOffset))}function Gg(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 $g(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 Ra=Symbol("ScheduleCore.fork.source");function zg(e){return e.kind==="persistence-acknowledge"||e.kind==="activity-lookahead-sync"&&e.acknowledgePersistedLookahead===!0}function qg(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 Jg(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 Xg(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 Mn=class e{_activityClipboard={value:null};_status=kt.READY;coreRuntime;_isFork;_undo=new Dn;_opQueue=Promise.resolve();_scheduleRevision=0;_pendingScheduleRevision=0;_criticalPathRevision=-1;_activeCriticalPath=null;constructor(t){if(Ra in t){this._isFork=!0;let i=t[Ra],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=Ud(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}fork(){return this._enqueue(async()=>(await this._ready,this.assertReady(),new e({[Ra]:this})))}get criticalPathReady(){return this._criticalPathReady}get status(){return this._status}getSector(){return b(this.coreRuntime.sector)}getActivityView(t){return this.assertReady(),bl(this.coreRuntime.state,t)}createDateGesturePreview(t){this.assertReady();let r=this._scheduleRevision;return Yd(this.coreRuntime.state,t,()=>{if(this.assertReady(),this._scheduleRevision!==r)throw new Error("[ScheduleCore] date gesture preview is stale")})}getAllActivitiesView(){return this.assertReady(),Rl(this.coreRuntime.state)}getIndentTargetParentIds(t){this.assertReady();let r=pn(t.map(n=>String(n)),this.coreRuntime.state);return[...new Set(r.allowedMoves.map(n=>String(n.newParentId)))]}getChildrenView(t){return this.assertReady(),wl(this.coreRuntime.state,t)}getLinkView(t){return this.assertReady(),pa(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=pa(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(),xl(this.coreRuntime.state)}auditEffectiveGraph(){this.assertReady();let t=this.coreRuntime.state,r=t.getAllLinks(),n=Ge(t,r),i=_r(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(),El(this.coreRuntime.state)}forEachActivityId(t){this.assertReady(),Ll(this.coreRuntime.state,t)}getChildrenIds(t){return this.assertReady(),fa(this.coreRuntime.state,t)}getSelectedActivityIds(){return this.assertReady(),Ol(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(),Fl(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(),Nl(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)}getModifiedActivityFields(){return this.assertReady(),b(this._saveTracker.modifiedActivityFields(t=>this.coreRuntime.state.getActivity(t)))}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}capturePersistenceHistoryBoundary(){return this.assertReady(),this._undo.capturePersistenceBoundary()}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 Hd(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&&zg(t))return{result:{ok:!1,reason:k.SANDBOX_PERSISTENCE_FORBIDDEN},changedState:!1};let n=Ml(this.coreRuntime.state,{hoursPerDay:this.coreRuntime.sector.hoursPerDay,dateFormat:this.coreRuntime.sector.dateFormat}),i=$l(t),a=[this.coreRuntime.activityIdGenerator.snapshot(),this.coreRuntime.linkIdGenerator.snapshot(),this.coreRuntime.uniqueCorrelativeIdGenerator.snapshot()];this.coreRuntime.state.beginWriteCapture(),this.coreRuntime.customIdTracker.beginCustomIdTransaction();let s,o;try{s=await rl(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?Wr(this.coreRuntime.clock()):null});let c=this.coreRuntime.state.peekWriteCapture()?.progressFallbackBefore;c&&c.size>0&&(o=new Map(c)),s.ok||this._rollback(a)}catch(c){throw this._rollback(a),c}finally{this.coreRuntime.state.endWriteCapture(),this.coreRuntime.customIdTracker.commitCustomIdTransaction()}if(s.ok&&i==="record"&&ga(s.changes)){let c=Vl(this.coreRuntime.state,s.changes),l=o?new Map(Array.from(o.keys(),d=>[d,this.coreRuntime.state.getProgressFallback(d)])):void 0;this._undo.record(ha(Hl(s.changes),s.__beforeSnap,s.__beforeLinks,c.afterSnap,c.afterLinks,o,l),Yl(t),Date.now())}if(s.ok)if(i==="checkpoint-on-success"){if(t.kind!=="persistence-acknowledge")throw new Error("checkpoint-on-success requires persistence acknowledge");let c=this.coreRuntime.state.getAllActivities(),l=this.coreRuntime.state.getAllLinks(),d=t.checkpoint,u=d?.historyBoundary??this._undo.capturePersistenceBoundary();this._saveTracker.acknowledge(d?.activities??c,d?.links??l,t.activities,t.links,c,l),this._undo.discardThrough(u),this._undo.applyPersistedIdentities(t.activities??[],t.links??[])}else t.kind==="activity-lookahead-sync"&&t.acknowledgePersistedLookahead===!0?(this._saveTracker.acknowledgePersistedLookahead(s.changes.activities,c=>this.coreRuntime.state.getActivity(c)),t.persistedProgress!==void 0&&this._undo.clear()):this._saveTracker.recordChanges(s.changes.activities,s.changes.links,c=>this.coreRuntime.state.getActivity(c),c=>this.coreRuntime.state.getLink(c));return s=this._withReappliedViewState(t,s),s.ok?Wi(t)&&ga(s.changes)?(this._recordScheduleMutation(r.skipAutoSchedule!==!0&&r.skipCriticalPath!==!0&&se(t)),{result:Kd(s),changedState:!0}):{result:Kd(s),changedState:!1}:{result:s,changedState:!1}}recomputeCriticalPath(){let t=this._enqueue(async()=>({job:this._startCriticalPathForCurrentRevision()})).then(({job:r})=>r);return this._criticalPathReady=t,t}isCriticalPathSettled(){return this._criticalPathRevision===this._scheduleRevision&&this._pendingScheduleRevision===this._scheduleRevision&&this._activeCriticalPath===null}async whenCriticalPathSettled(){for(;!this.isCriticalPathSettled();)await this.recomputeCriticalPath()}_withReappliedViewState(t,r){if(!r.ok||(t.kind==="visibility-set"&&this.coreRuntime.state.setFilterProjection(null),!qo(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);return this._reapplyActiveOrder(n.changes??r??t,n.touchedParents)??n.changes??r}_emitTouchedBranchOrder(t){let r=this.coreRuntime.state,n=Zl(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=Xg(a,n,i),o=qg(t)?null:Jg(t,r),c,l;if(o===null||!s){let f=pr({activities:r.getAllActivities(),parentOf:p=>r.getParentId(p),filter:n,context:i});r.setFilterProjection(f),l=f.visibleIds,c=r.getAllIds()}else c=Ba(a,o,f=>r.getParentId(f)),l=a.visibleIds;let u=ye(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 Be(Tn(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!==kt.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)Fi(this.coreRuntime.state,l,d);for(let[l,d]of o.links)xi(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===kt.DESTROYED)return{changes:{source:{kind:"init"},activities:[],links:[],calendars:[],trackingEvents:[]}};this.coreRuntime.state.beginWriteCapture(),this.coreRuntime.customIdTracker.beginCustomIdTransaction();let t;try{await Zr(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;zl(this.coreRuntime.state,n),this._recordScheduleMutation(!1),r(!0),ya(n)&&this._resyncCustomIdTrackerFromModel(),this._undo.pushRedo(n),this._undo.resetCoalesce();let i=ma(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;ql(this.coreRuntime.state,r),this._recordScheduleMutation(!1),t(!0),ya(r)&&this._resyncCustomIdTrackerFromModel(),this._undo.pushUndo(r),this._undo.resetCoalesce();let n=ma(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 Pn;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 Kd(e){let{__beforeSnap:t,__beforeLinks:r,...n}=e;return n}var Gd=(e=[])=>(e??[]).filter(t=>!t.proplannerId);var $d={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 zd=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"},Zg={[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},qd=Object.keys(Zg);var Jd={CHILD:"child",CHILD_CONFIRMED:"child-confirmed",LINE:"line",ROOT:"root"};return nu(Qg);})();
1
+ "use strict";var ScheduleCore=(()=>{var jn=Object.defineProperty;var Qd=Object.getOwnPropertyDescriptor;var tu=Object.getOwnPropertyNames;var eu=Object.prototype.hasOwnProperty;var ru=(e,t)=>{for(var r in t)jn(e,r,{get:t[r],enumerable:!0})},nu=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of tu(t))!eu.call(e,i)&&i!==r&&jn(e,i,{get:()=>t[i],enumerable:!(n=Qd(t,i))||n.enumerable});return e};var iu=e=>nu(jn({},"__esModule",{value:!0}),e);var Zg={};ru(Zg,{ACTIVITY_TYPE:()=>Ae,CALENDAR_UNIT:()=>ct,COLUMN:()=>P,CONSTRAINT_TYPE:()=>G,CONSTRAINT_TYPE_TO_LABEL:()=>zd,CREATION_KIND:()=>Xd,DEFAULT_HOURS_PER_DAY:()=>qd,DISPATCH_ACTION_KIND:()=>$,DISPATCH_ACTION_KINDS:()=>Jd,DISPATCH_TRACK_EVENT:()=>It,LINK_CODE_TO_TYPE:()=>ee,LINK_TYPE:()=>W,LINK_TYPE_CODE:()=>Ds,NEW_ACTIVITY_DEFAULTS:()=>on,REJECTION_REASON:()=>C,ROOT_PARENT_ID:()=>N,SCHEDULE_CORE_STATUS:()=>kt,STATUS:()=>bt,ScheduleCore:()=>Bn,WORK_TIME_DIRECTION:()=>Z,checkNoUpdatedLinks:()=>od,computeExpectedProgress:()=>hi,expectedProgressFromBaseline:()=>we,getActiveBaseline:()=>ut,getUnsavedActivities:()=>$d,isRootParent:()=>L,normalizeParentKey:()=>jt,parseFromBackend:()=>Ln,willRunCriticalPath:()=>Bl,yieldToBrowser:()=>Q});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 Oa(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=au(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||su({id:c,isChecked:r,autoCheckParents:o,hierarchy:i,isFrozen:a,exists:s,next:d}),{nextSelection:d,changed:ou(l,d),parentBlocked:p}}function au(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 su(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(g=>!a(g)),h=f.length>0&&f.every(g=>o.has(g))&&!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 ou(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 me(e){return(e.pendingRequestIds?.length??0)>0}var C={CANNOT_EDIT:"cannot_edit",PARSE_ERROR:"parse_error",INVALID:"invalid",CUSTOM_ID_DUPLICATE:"custom_id_duplicate",INVALID_LINK_TYPE:"invalid_link_type",INVALID_LINK_LAG:"invalid_link_lag",INVALID_VALUE:"invalid_value",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 Fa=(e,t)=>{let r=e.getActivity(t);return r!=null&&me(r)},xa=(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 Na(e,t){let{adapter:r}=t,n=e.activityId;if(!r.getActivity(n))return{ok:!1,reason:C.ACTIVITY_NOT_FOUND};let i=e.frozenIds?new Set(e.frozenIds):null,a=i?o=>i.has(o):o=>Fa(r,o),s=Oa({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:xa(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=>!Fa(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:xa(e,r,a)}}function ge(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 Ma(e,t){let{adapter:r}=t,n=new Set(e.visibleIds.map(String)),i=ge(r,n);return{ok:!0,changes:{source:e,activities:[],links:[],calendars:[],trackingEvents:[],viewState:i}}}var cu=["Waiting","Done","Doing","Overdue","Advancement"],lu=["mfo","mso","snlt","snet","alap","asap","fnet","fnlt"];function Un(e,t){return e===null||t<=0?null:e/t}function du(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 uu={name:{valueKind:"string",extract:e=>e.name},description:{valueKind:"string",extract:e=>e.description},customId:{valueKind:"string",extract:e=>e.customId},correlativeId:{valueKind:"number",extract:e=>e.correlativeId},uniqueCorrelativeId:{valueKind:"number",extract:e=>{let t=Number(e.uniqueCorrelativeId);return Number.isFinite(t)?t:null}},progress:{valueKind:"number",extract:e=>e.progress},durationDays:{valueKind:"number",extract:(e,t)=>Un(e.durationHours,t.hoursPerDay)},calendarDuration:{valueKind:"number",extract:e=>e.type==="milestone"?0:du(e.startDate,e.endDate)},cost:{valueKind:"number",extract:e=>e.cost},usedCost:{valueKind:"number",extract:e=>e.usedCost},realCost:{valueKind:"number",extract:e=>e.realCost},workHours:{valueKind:"number",extract:e=>e.workHours},realWorkHours:{valueKind:"number",extract:e=>e.realWorkHours},ponderator:{valueKind:"number",extract:e=>e.ponderator},freeSlackDays:{valueKind:"number",extract:(e,t)=>Un(e.freeSlackHours,t.hoursPerDay)},totalSlackDays:{valueKind:"number",extract:(e,t)=>Un(e.criticalPath?.totalSlackHours??null,t.hoursPerDay)},expectedProgressBaseline:{valueKind:"number",equalityPrecision:2,extract:e=>e.expectedProgressBaseline},expectedProgress:{valueKind:"number",extract:e=>e.expectedProgress},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:cu,extract:e=>e.status},constraintType:{valueKind:"enum",order:lu,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 Bt(e){return uu[e]??null}function Hn(e){return e instanceof Date?e:typeof e=="string"||typeof e=="number"?new Date(e):new Date(Number.NaN)}function Lt(e){return Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate())}function fu(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,n){if(e===null||typeof e!="number")return r==="notEquals";let i=n===void 0?e:Number(e.toFixed(n));return r==="equals"?i===t:r==="notEquals"?i!==t:r==="greaterThan"?e>t:r==="lessThan"?e<t:r==="greaterOrEqual"?e>=t:r==="lessOrEqual"?e<=t:!1}function hu(e,t,r){return typeof e=="number"&&e>=t&&e<=r}function yu(e,t,r){if(!(e instanceof Date))return!1;let n=Lt(e),i=Lt(t);return r==="after"?n>i:r==="before"?n<i:!1}function mu(e,t,r){if(!(e instanceof Date))return!1;let n=Lt(e);return n>=Lt(t)&&n<=Lt(r)}function gu(e,t,r){let i=(Array.isArray(e)?e:[]).some(a=>t.has(String(a)));return r==="someOf"?i:r==="notSomeOf"?!i:!1}function vu(e,t,r){let n=e!==null&&t.has(String(e));return r==="someOf"?n:r==="notSomeOf"?!n:!1}function Wa(e){let t=Array.isArray(e)?e:[e];return new Set(t.map(r=>String(r)))}function Ba(e,t,r){let n=Bt(t.field);if(n===null)return!1;let i=n.extract(e,r),{operator:a}=t;return a==="between"?n.valueKind==="number"?hu(i,Number(t.value),Number(t.valueTo)):n.valueKind==="date"?mu(i,Hn(t.value),Hn(t.valueTo)):!1:n.valueKind==="string"?fu(i,String(t.value),a):n.valueKind==="number"?pu(i,Number(t.value),a,n.equalityPrecision):n.valueKind==="date"?yu(i,Hn(t.value),a):n.valueKind==="id-array"?gu(i,Wa(t.value),a):vu(i,Wa(t.value),a)}function Au(e,t,r){return t.criteria.length===0?!0:t.logic==="or"?t.criteria.some(n=>Ba(e,n,r)):t.criteria.every(n=>Ba(e,n,r))}function Iu(e,t){let r=Lt(e.startDate),n=Lt(e.endDate),i=Lt(t.start),a=Lt(t.end),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=Au(e,t,r),i=t.dateRange,a=i===void 0||Iu(e,i);return n&&a}function Cu(e,t,r){let n=t(e);for(;n!==null&&!r.has(String(n));)r.add(String(n)),n=t(n)}function ja(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)Cu(o,r,a);return a}function ku(e){let{activities:t,parentOf:r,filter:n,context:i}=e,a=new Set,s=new Map,o=new Map,c=new Map;for(let l of t){let d=String(l.id),u=r(d);o.set(d,u),c.set(d,c.get(d)??0),u!==null&&c.set(u,(c.get(u)??0)+1);let f=Vn(l,n,i);s.set(d,f?1:0),f&&a.add(d)}return{matchedIds:a,visibleReferenceCounts:s,parentIds:o,remainingChildren:c}}function Su(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 Du(e){let t=new Set;for(let[r,n]of e)n>0&&t.add(r);return t}function yr(e){let t=ku(e);Su(t);let r=Du(t.visibleReferenceCounts);return{filter:e.filter,context:e.context,matchedIds:t.matchedIds,visibleIds:r,visibleReferenceCounts:t.visibleReferenceCounts}}function Ua(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 Qt(e){return{hoursPerDay:e,locale:"en"}}var Tu={string:new Set(["includes","notIncludes","is","isNot"]),number:new Set(["equals","notEquals","greaterThan","lessThan","greaterOrEqual","lessOrEqual","between"]),date:new Set(["after","before","between"]),"id-array":new Set(["someOf","notSomeOf"]),enum:new Set(["someOf","notSomeOf"]),boolean:new Set(["someOf","notSomeOf"]),reference:new Set(["someOf","notSomeOf"])};function Ha(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 Va(e){let t=Bt(e.field);if(t===null)return{ok:!1,reason:"unknown_field"};if(!Tu[t.valueKind].has(e.operator))return{ok:!1,reason:"unknown_operator"};if(e.operator==="between")return _u(e,t.valueKind);if(t.valueKind==="number"){let n=Yn(e.value);return n===null?{ok:!1,reason:"invalid_value"}:{ok:!0,criterion:{...e,value:n}}}if(t.valueKind==="date"){let n=Kn(e.value);return n===null?{ok:!1,reason:"invalid_value"}:{ok:!0,criterion:{...e,value:n}}}let r=Pu(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 _u(e,t){if(t==="number"){let r=Yn(e.value),n=Yn(e.valueTo);return r===null||n===null||r>n?{ok:!1,reason:"invalid_value"}:{ok:!0,criterion:{...e,value:r,valueTo:n}}}if(t==="date"){let r=Kn(e.value),n=Kn(e.valueTo);return r===null||n===null||r.getTime()>n.getTime()?{ok:!1,reason:"invalid_value"}:{ok:!0,criterion:{...e,value:r,valueTo:n}}}return{ok:!1,reason:"unknown_operator"}}function Pu(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 Yn(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 Kn(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 R(e){return structuredClone(e)}function Ya(e){return e.criteria.length===0&&e.dateRange===void 0}function bu(e,t,r){let n=e.getAllActivities();if(Ya(t))return{visibleIds:ja({activities:n,parentOf:a=>e.getParentId(a),filter:t,context:Qt(r)}),projection:null};let i=yr({activities:n,parentOf:a=>e.getParentId(a),filter:t,context:Qt(r)});return{visibleIds:i.visibleIds,projection:i}}function Ka(e,t){let{adapter:r,hoursPerDay:n}=t,i=[];for(let u of e.criteria){let f=Va(u);if(!f.ok)return{ok:!1,reason:f.reason};i.push(f.criterion)}let a=Ha(e.dateRange);if(!a.ok)return{ok:!1,reason:a.reason};let s=R(a.dateRange===void 0?{criteria:i,logic:e.logic}:{criteria:i,logic:e.logic,dateRange:a.dateRange});r.setActiveFilter(Ya(s)?null:s);let{visibleIds:o,projection:c}=bu(r,s,n);r.setFilterProjection(c);let l=ge(r,o);return{ok:!0,changes:{source:e,activities:[],links:[],calendars:[],trackingEvents:[],viewState:l}}}var N="0";function L(e){return e==null||e===0||e==="0"}function jt(e){return L(e)?"0":String(e)}var Gn=Number.MAX_SAFE_INTEGER;function gt(e,t){let r=Ve(e,t),n=t.getOrderComparator?.()??null;return r.sort(n===null?mr:(i,a)=>n(i,a)||mr(i,a)),r.map(i=>String(i.id))}function $a(e){let t=[],r=i=>{t.push(i);let a=gt(String(i.id),e);for(let s of a){let o=e.getActivity(s);o&&r(o)}},n=gt("0",e);for(let i of n){let a=e.getActivity(i);a&&r(a)}return t}function za(e,t,r){let n=r.getActivity(e);if(!n)return null;let i=qa(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&&!Ru(t,c))return c}return null}function $n(e,t){let r=t.getActivity(e);if(!r)return-1;let n=qa(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 mr(e,t){let r=Ga(e),n=Ga(t);return r!==n?r-n:String(e.id).localeCompare(String(t.id))}function Ga(e){let t=e.correlativeId,r=typeof t=="number"?t:Number(t);return Number.isFinite(r)?r:Gn}function qa(e){let t=e.parentId;return t===null?"0":t}function Ru(e,t){return e.has(t)?!0:e.has(String(t))}function ve(e){let t=[],r=n=>{let i=gt(n,e);i.length>1&&t.push({parentId:n,childIds:i});for(let a of i)r(a)};return r("0"),t}function zn(e,t){let r=[];for(let n of t){let i=gt(n,e);i.length>1&&r.push({parentId:n,childIds:i})}return r}function Eu(e){return Bt(e.field)===null?"unknown_field":e.direction!=="asc"&&e.direction!=="desc"?"unknown_operator":null}function Ja(e,t){let{adapter:r}=t;for(let a of e.rules){let s=Eu(a);if(s!==null)return{ok:!1,reason:s}}let n=e.rules.length===0?null:R({rules:e.rules});return r.setActiveOrder(n),{ok:!0,changes:{source:e,activities:[],links:[],calendars:[],trackingEvents:[],order:ve(r)}}}var Lu={TEXT:"text",DESCRIPTION:"description",DURATION:"duration",PROGRESS:"progress",COST:"cost",USED_COST:"used_cost",HH_WORK_TIME:"hhWorkTime",START_DATE:"start_date",END_DATE:"end_date",CONSTRAINT_TYPE:"constraint_type",CONSTRAINT_DATE:"constraint_date",CALENDAR_ID:"calendar_id",CUSTOM_ID:"custom_id",SUBCONTRACT_ID:"subcontractId",RESPONSABLES:"responsables",TAGS:"tags",CUSTOM_PREDECESSORS:"custom_predecessors",CUSTOM_SUCESSORS:"custom_sucessors"},wu={REAL_WORK:"real_work",REAL_COST:"real_cost",EXPECTED_PROGRESS:"expected_progress",EXPECTED_PROGRESS_BASE:"expected_progress_base",START_BASE:"start_base",END_BASE:"end_base",DURATION_BASE:"duration_base",COST_BASE:"cost_base",WORK_BASE:"work_base",CALENDAR_DURATION:"calendarDuration",IS_CRITICAL:"is_critical",EARLY_START:"earlyStart",EARLY_FINISH:"earlyFinish",LATE_START:"lateStart",LATE_FINISH:"lateFinish",FREE_SLACK:"freeSlack",TOTAL_SLACK:"totalSlack",CORRELATIVE_ID:"correlative_id",UNIQUE_CORRELATIVE_ID:"unique_correlative_id",PONDERATOR:"ponderator",STATUS:"status"},P={...Lu,...wu};function Xa(e,t){throw new Error(t)}function Za(e,t){return()=>t()===e}var Z={FUTURE:"future",PAST:"past"},ct={HOUR:"hour",DAY:"day"},bt={DONE:"Done",OVERDUE:"Overdue",ADVANCEMENT:"Advancement",WAITING:"Waiting",DOING:"Doing"};var G={ASAP:"asap",ALAP:"alap",SNET:"snet",SNLT:"snlt",FNET:"fnet",FNLT:"fnlt",MSO:"mso",MFO:"mfo"},Ou={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 ts(e,t,r){if(!t)return{violated:!1};let n=Ou[e];return n?n(t,r)?{violated:!0,constraintType:e,constraintDate:t}:{violated:!1}:{violated:!1}}var Fu=new Set(["mso","snet","snlt"]);function Ye(e,t,r){return Fu.has(e)?t:r}function es(e,t,r){return{type:"constraint",messageKey:"constraint_violation",data:{constraintType:e,constraintDate:t,...r?{projectedDate:r}:{}}}}var xu={snet:{startOfDay:!0,direction:Z.FUTURE},snlt:{startOfDay:!0,direction:Z.PAST},fnet:{startOfDay:!1,direction:Z.FUTURE},fnlt:{startOfDay:!1,direction:Z.PAST},mso:{startOfDay:!0,direction:Z.FUTURE},mfo:{startOfDay:!1,direction:Z.PAST}},gr=e=>new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate())),Qa=(e,t)=>new Date(e.getTime()+t*864e5),Nu=(e,t)=>e.getUTCFullYear()===t.getUTCFullYear()&&e.getUTCMonth()===t.getUTCMonth()&&e.getUTCDate()===t.getUTCDate();function qn(e,t){if(!e.constraintDate||!e.constraintType)return null;let r=xu[e.constraintType];if(!r)return e.constraintDate;let n=e.constraintDate,i=t.getClosestWorkTime({date:gr(n),dir:Z.FUTURE,task:e});if(Nu(i,n))return n.getTime()!==gr(n).getTime()?n:r.startOfDay?i:t.getClosestWorkTime({date:Qa(gr(n),1),dir:Z.PAST,task:e});let a=gr(t.getClosestWorkTime({date:n,dir:r.direction,task:e}));return r.startOfDay?t.getClosestWorkTime({date:a,dir:Z.FUTURE,task:e}):t.getClosestWorkTime({date:Qa(a,1),dir:Z.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=qn(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 ns(e,t){return!(t.earliestStart&&e<t.earliestStart||t.latestStart&&e>t.latestStart)}function Jn(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 Ae={TASK:"task",PROJECT:"project",MILESTONE:"milestone"},is={ALAP_DEBOUNCE_MS:1e3,CRITICAL_PATH_DEBOUNCE_MS:1e3,YIELD_SLICE_MS:8};var Xn=typeof window>"u",Mu=!Xn&&typeof MessageChannel<"u";function Q(){return Mu?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 vr(e,t){return performance.now()-e<is.YIELD_SLICE_MS?{aborted:!1,newSliceStart:e}:(await Q(),t()?{aborted:!1,newSliceStart:performance.now()}:{aborted:!0,newSliceStart:performance.now()})}async function Ie(e){return Xn||await Q(),e()?{aborted:!1}:{aborted:!0}}function Ar(e,t){let{inDegree:r,successors:n}=Wu(e,t),i=Bu(r),a=ju(i,r,n),s=a.length<e.length,o=s?Uu(e,a):[],c=[...a].reverse();return{ordered:a,reversed:c,hasCycles:s,cycleNodes:o}}function Wu(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 Bu(e){let t=new ht;for(let[r,n]of e)n===0&&t.enqueue(r);return t}function ju(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 Uu(e,t){let r=new Set(t);return e.filter(n=>!r.has(n))}var Ir=class{cached=null;invalidate(){this.cached=null}get(t,r){return this.cached?this.cached:(this.cached=Ar(t,r),this.cached)}};function as(e,t){let r=[];for(let n of e)t.has(n)&&r.push(n);return r}var Zn={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 ss(e){return e==="project"||e==="task"||e==="milestone"}function wt(e,t){return t||ss(e)&&Zn[e].alwaysSummary}function Ot(e){return e==="milestone"}function Ut(e){return ss(e)&&Zn[e].promotesToProjectOnFirstChild}var Qn="project",Ce="task";function Ke(e,t){return t===0?"milestone":e===0&&t>0?"task":null}function Cr(e,t){let r=t.getActivity(e);return r?wt(r.type,t.getChildren(e).length>0):!1}function kr(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=Cr(e,r);return Cr(t,r)&&kr(e,t,r)||n&&kr(t,e,r)}function ls(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 Hu(e){let t=new Map;for(let r of e)os(t,String(r.source),r),os(t,String(r.target),r);return t}function os(e,t,r){let n=e.get(t);if(n){n.push(r);return}e.set(t,[r])}function Vu(e,t,r,n){if(e.length<=1)return e;let i=new Set(e.map(String)),a=[];for(let s of e)Yu(s,i,t,r,n)||a.push(s);return a.length>0?a:e}function Yu(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(Ku(c,a,s,t,r,i))return!0;return!1}function Ku(e,t,r,n,i,a){if(Gu(e)||!(a?String(e.source)===t:String(e.target)===t))return!1;let o=$u(e,t);if(!n.has(String(o)))return!1;let c=i.getActivity(o);return!!(c?.autoScheduling!==!1&&c&&zu(e,r,c))}function Gu(e){return e.source===e.target}function $u(e,t){return String(e.source)===t?e.target:e.source}function zu(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 Dr(e,t){let r=[],n=Hu(e),i=0;for(let a of e){let s=Cr(a.source,t),o=Cr(a.target,t);if(qu(a,s,o,t))continue;if(!s&&!o){r.push(a);continue}let c=cs(a.source,s,t,n,!0),l=cs(a.target,o,t,n,!1);i=rf(r,c,l,a,t,i,n)}return r}function qu(e,t,r,n){return r&&kr(e.source,e.target,n)||t&&kr(e.target,e.source,n)}function cs(e,t,r,n,i){return t?Vu(ls(e,r),r,n,i):[e]}function Ju(e,t,r){let n=ls(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 Sr(e,t){return Ju(e,t,r=>{let n=t.getActivity(r);return n?{startDate:n.startDate,endDate:n.endDate}:null})}function Xu(e,t,r){return e?t?r.calculateDuration({startDate:t.startDate,endDate:t.endDate,task:e}):e.durationHours:0}function Zu(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 Qu(e,t){let r=String(e);return(t.get(r)??[]).some(i=>String(i.target)===r)}function tf(e,t,r,n,i){if(Qu(e,i))return 0;let a=n.getActivity(e);return!t||!a||!r?0:n.calculateDuration({startDate:t,endDate:a.startDate,task:r})}function ef(e,t){let r=t.getActivity(e.source),n=t.getActivity(e.target),i=Sr(e.source,t),a=Sr(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?-Xu(n,a,t):0,summarySourceId:e.type===W.START_TO_START&&i?e.source:void 0,finishAnchoredSummaryTargetId:o&&a?e.target:void 0}}function rf(e,t,r,n,i,a,s){let o=ef(n,i),{source:c,sourceBounds:l,targetStart:d,userLag:u}=o,{sourceEndpointIsStart:f,targetLag:p,summarySourceId:h,finishAnchoredSummaryTargetId:g}=o,I=a;for(let _ of t){let v=f?Zu(_,c,l,i):0;for(let k of r){if(String(_)===String(k))continue;let m=tf(k,d,c,i,s);e.push(nf(n,_,k,I,v,p,u+m,h,g??(m!==0&&p===0?n.target:void 0))),I+=1}}return I}function nf(e,t,r,n,i,a,s,o,c){return{id:`virtual_${e.id}_${n}`,source:t,target:r,type:e.type,lag:e.lag,freeSlackHours:null,isCritical:!1,_sourceLag:i,_targetLag:a,_trueLag:s,...o===void 0?{}:{_summarySourceId:o},...c===void 0?{}:{_summaryTargetId:c}}}var Tr=class{invalidate(){}get(t,r){return Dr(t,r)}};function af(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 sf(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 ds(e,t){let r=new Map;for(let s of t)r.set(s.id,s);let n=af(t),i=sf(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 te(e){return e===0}function us(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 of(e,t,r){if(e._summarySourceId===void 0)return null;let n=r.getActivity(e._summarySourceId);if(!n)return null;let i=Sr(e._summarySourceId,r);return i?-r.calculateDuration({startDate:i.startDate,endDate:t.endDate,task:n}):null}function cf(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 fs(e,t,r,n){let{sourceLag:i,targetLag:a,trueLag:s,isFS:o,isFF:c}=us(e,t,r),l=of(r,e,n)??i,d=l+a+s;if(!(t.durationHours===0?d!==0:l!==0||a!==0||s!==0))return cf(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 g=new Date(Date.UTC(h.getUTCFullYear(),h.getUTCMonth(),h.getUTCDate()));return{successorStart:n.getClosestWorkTime({date:g,dir:"future",task:t}),link:r}}return{successorStart:n.getClosestWorkTime({date:h,dir:"future",task:t}),link:r}}function ps(e,t,r,n){let{sourceLag:i,targetLag:a,trueLag:s}=us(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 hs(e,t,r){for(let n of e){let i=t.getActivity(n);if(!i)continue;let a=i.constraintType;if(!a||a===G.ASAP||a===G.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 _r(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=Jn(e.startDate,n):ns(i,n)?a=i:a=Jn(i,n),t.startDate=a,t.endDate=r.calculateEndDate({startDate:a,durationHours:e.durationHours,task:e})}function ys(e,t){if(!e||!t)return new Date;let{constraintType:r,constraintDate:n}=e;if(!r||!n)return t;switch(r){case G.MSO:case G.MFO:return new Date(n);case G.SNET:case G.FNET:return n>t?new Date(n):t;case G.SNLT:case G.FNLT:return n<t?new Date(n):t;default:return t}}function lf(e,t){return t.length?t.some(r=>String(r)===String(e)):!1}function ms(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&&lf(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 vr(d,i);if(f.aborted)return a;d=f.newSliceStart;let p=r.getActivity(u);if(!p||!p.autoScheduling||p.progress===100||df(p,r))continue;let h=s.get(String(u))??[],g=null,I=null,_=!1;for(let w of h){let S=r.getActivity(w.source);if(!S)continue;let A=o(w.source),T=A.startDate.getTime()!==S.startDate.getTime()||A.endDate.getTime()!==S.endDate.getTime(),x={...S,startDate:A.startDate,endDate:A.endDate},F=ms(x,c,l),q={...x,startDate:F.startDate,endDate:F.endDate},K=ei(w.source,c,l)?{...w,lag:0}:w,at=fs(q,p,K,r);(!g||at.successorStart>g)&&(g=at.successorStart,I=String(w.id),_=w._summaryTargetId!==void 0&&!T&&(w._targetLag===0||n.preventSummaryTargetPullback===!0))}g!==null&&_&&g<p.startDate&&(g=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},b=m.earliestStart||m.latestStart||m.earliestEnd||m.latestEnd;if(!(!g&&!b)){if(g){let w=g;p.type===Ae.MILESTONE&&(w=ys(p,g)),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===G.MSO?m.earliestStart&&(m.startDate=m.earliestStart,m.endDate=m.earliestEnd??r.calculateEndDate({startDate:m.earliestStart,durationHours:p.durationHours,task:p})):p.constraintType===G.MFO&&m.latestStart&&(m.startDate=m.latestStart,m.endDate=m.latestEnd??r.calculateEndDate({startDate:m.latestStart,durationHours:p.durationHours,task:p}));_r(p,m,r),a.set(u,m)}}return a}function df(e,t){return wt(e.type,t.getChildren(e.id).length>0)}async function As(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===G.ALAP&&l.push(I.id);if(l.length===0)return s;let d=new Map,u=new Map;for(let I of t){let _=String(I.source);d.has(_)||d.set(_,[]),d.get(_).push(I);let v=String(I.target);u.has(v)||u.set(v,[]),u.get(v).push(I)}let f=I=>{let _=s.get(I);if(_)return{startDate:_.startDate,endDate:_.endDate};let v=n.getActivity(I);return v?{startDate:v.startDate,endDate:v.endDate}:{startDate:new Date,endDate:new Date}},p=I=>!I.parentId||L(I.parentId)?n.getProjectEnd():f(I.parentId).endDate,h=(I,_)=>{let v=I,k=0;for(;v&&!L(v)&&k++<c+1;){if(String(v)===String(_))return!0;let m=n.getActivity(v);if(!m||!m.parentId)break;v=m.parentId}return!1},g=performance.now();for(let I of e){let _=await vr(g,a);if(_.aborted)return s;g=_.newSliceStart;let v=n.getActivity(I);if(!v||v.constraintType!==G.ALAP||!v.autoScheduling||v.progress===100||wt(v.type,n.getChildren(I).length>0))continue;let k=p(v);if(!k)continue;let m=k,b=null,w=!1,S=d.get(String(I))??[];for(let St of S){if((St.lag??0)<0)continue;let ye=n.getActivity(St.target);if(!ye||ye.autoScheduling===!1)continue;let wa=f(St.target),Zd={...ye,startDate:wa.startDate,endDate:wa.endDate},fr=ps(Zd,v,St,n);fr<m&&(m=fr),(b===null||fr<b)&&(b=fr,w=v.parentId&&!L(v.parentId)?h(St.target,v.parentId):!1)}if(b!==null)if(w)m=b;else{let St=f(I).endDate,ye=St.getTime()>k.getTime()?St:k;m=b<ye?b:ye}else m>k&&(m=k);let T=(u.get(String(I))??[]).some(St=>St.type===W.FINISH_TO_START||St.type===W.FINISH_TO_FINISH),x=new Date(Date.UTC(m.getUTCFullYear(),m.getUTCMonth(),m.getUTCDate())),F=()=>n.getClosestWorkTime({date:x,dir:"past",task:v}),q=n.getClosestWorkTime({date:m,dir:"future",task:v}).getTime()===m.getTime(),K;v.durationHours===0&&b===null?K=T&&q?F():n.getClosestWorkTime({date:m,dir:"past",task:v}):v.durationHours===0?T?K=F():K=n.getClosestWorkTime({date:m,dir:"future",task:v}):K=n.getClosestWorkTime({date:m,dir:"future",task:v});let at=n.calculateEndDate({startDate:K,durationHours:-v.durationHours,task:v}),pt=s.get(I),nt=pt?{...pt}:{activityId:I,startDate:at,endDate:K,drivingLinkId:null,kind:"alap",conflict:!1};nt.startDate=at,nt.endDate=K,nt.drivingLinkId=null,nt.kind="alap";let pe=nt.earliestSchedulingStart??null;nt.earliestSchedulingStart=null,nt.earliestSchedulingEnd=null;let he=pe!==null&&pe.getTime()>at.getTime()?pe:at;nt.latestSchedulingStart=he,nt.latestSchedulingEnd=he===at?K:n.calculateEndDate({startDate:he,durationHours:v.durationHours,task:v}),_r(v,nt,n),s.set(I,nt)}return s}var ke={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 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=Rt(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 uf(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 uf(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 Pr(e){let t=ff(e);for(let r of t.adjacency.keys())t.records.has(r)||pf(r,t);return t.components}function ff(e){let t=new Map,r=new Set;for(let n of e){let i=String(n.source),a=String(n.target),s=Is(t,i);if(Is(t,a),i===a){r.add(i);continue}s.push(a)}return{adjacency:t,selfLooped:r,records:new Map,componentStack:[],nextIndex:0,components:[]}}function Is(e,t){let r=e.get(t);if(r)return r;let n=[];return e.set(t,n),n}function pf(e,t){let r=[];for(r.push({node:e,record:Cs(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;hf(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&&yf(n.node,t)}}function hf(e,t,r,n){let i=n.records.get(t);if(!i){r.push({node:t,record:Cs(t,n),neighborCursor:0});return}i.onStack&&i.visitIndex<e.record.lowLink&&(e.record.lowLink=i.visitIndex)}function Cs(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 yf(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 Dr([...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=ks(s),l=[...ks(a)].filter(d=>!o.has(d));return l.length===0?{ok:!0}:{ok:!1,newlyCyclicActivityIds:l}}function ks(e){let t=new Set;for(let r of Pr(e))for(let n of r)t.add(n);return t}function Ht(e,t){switch(e.kind){case"create":return mf(e,t);case"update":return Je(e,t.port);case"delete":return gf(e,t)}}function Rr(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=Ss(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=Ss(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 Ss(e){return JSON.stringify([String(e.source),String(e.target),e.type])}function mf(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??vf)(),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 gf(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 br=null;function vf(){return br===null&&(br=Date.now()),br+=1,String(br)}var Ds={[W.FINISH_TO_START]:"fs",[W.START_TO_START]:"ss",[W.FINISH_TO_FINISH]:"ff",[W.START_TO_FINISH]:"sf"},ee={fs:W.FINISH_TO_START,ss:W.START_TO_START,ff:W.FINISH_TO_FINISH,sf:W.START_TO_FINISH},Ts="fs";function _s(e){if(e in ee)return ee[e]}var Ps=";",bs=/^(\d+)(fs|ss|ff|sf)?(?:([+-]?)(\d+(?:\.\d+)?)d?)?$/i;function Er(e){let t=[],r=[],n=e.replace(/\s+/g,"");if(n.length===0)return{specs:t,errors:r};for(let i of n.split(Ps)){if(i.length===0)continue;let a=Af(i);a?t.push(a):r.push(i)}return{specs:t,errors:r}}function Af(e){let t=e.toLowerCase(),r=bs.exec(t);if(!r)return null;let[,n,i,a,s]=r,o=i?ee[i]:ee[Ts],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 wr(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=Lr(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(Lr(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 Lr(e,t){return`${String(e)}::${t}`}function Or(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=Lr(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(Lr(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 Fr(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 Rs={rawInputToConstraintDate(e,t){let r=new Date(e);return r.setUTCHours(0,0,0,0),r.getTime()===e.getTime()?t.getClosestWorkTime({direction:Z.FUTURE,date:e,unit:ct.HOUR}):t.isWorkTime(e,ct.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=Rs;var Se=class{adapter;reporter;currentCalculationId=0;topoCache=new Ir;expandedLinksCache=new Tr;constructor(t,r=ke){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=Za(r,()=>this.currentCalculationId),i={plans:new Map,updatedIds:[],cycles:[],cancelled:!1};try{kf(this.adapter);let a=Vt("schedule.total"),s=Vt("schedule.expandParentLinks"),o=this.adapter.getAllLinks(),c=this.expandedLinksCache.get(o,this.adapter);Ft(s);let l=c;if((await Ie(n)).aborted)return{...i,cancelled:!0};let d=Vt("schedule.scoping"),u=this.adapter.getAllIds(),f=Sf(t,l,this.adapter),p=f.links,h=f.idSet;Ft(d);let g=Vt("schedule.topologicalSort"),I=Tf(this.topoCache,u,l,h);if(Ft(g),I.hasCycles)return Ft(a),{...i,cycles:[I.cycleNodes]};if((await Ie(n)).aborted)return{...i,cancelled:!0};let _=Vt("schedule.processConstraints"),v=new Map;if(hs(I.ordered,this.adapter,v),Ft(_),(await Ie(n)).aborted)return{...i,cancelled:!0};let k=Vt("schedule.asapPass"),m=await vs(I.ordered,p,this.adapter,t,n,v);if(Ft(k),(await Ie(n)).aborted)return{...i,cancelled:!0};let b=Vt("schedule.alapPass"),w=await As(I.reversed,p,m,this.adapter,t,n);if(Ft(b),(await Ie(n)).aborted)return{...i,cancelled:!0};let S=Vt("schedule.diff"),A=[];for(let[T,x]of w){let F=this.adapter.getActivity(T);if(!F)continue;let q=F.startDate.getTime()!==x.startDate.getTime(),K=F.endDate.getTime()!==x.endDate.getTime();(q||K)&&A.push(T)}return Ft(S),Ft(a),{plans:w,updatedIds:A,cycles:[],cancelled:!1}}catch(a){return this.reporter.error("[AutoScheduler] Error during scheduling",a),i}}},If=!1;function Cf(){let e=globalThis.__SCHEDULER_PHASE_LOG__;return typeof e=="boolean"?e:If}function Vt(e){return{name:e,startedAt:performance.now()}}function kf(e){let t=e;typeof t.clearCalendarCache=="function"&&t.clearCalendarCache()}function Ft(e){if(!Cf())return;let t=performance.now()-e.startedAt;console.log(`[scheduler] ${e.name} ${t.toFixed(1)}ms`)}function Sf(e,t,r){let n=e.triggerId;if(n==null)return{idSet:null,links:t};let i=ds(n,t);return Df(i,t,r)}function Df(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===G.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 Tf(e,t,r,n){let i=e.get(t,r);if(i.hasCycles){let s=n?Array.from(n):t;return Ar(s,r)}if(!n)return i;let a=as(i.ordered,n);return{ordered:a,reversed:[...a].reverse(),hasCycles:!1,cycleNodes:[]}}function Es(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"||Ot(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 Ls(e,t){let r=t.getActivity(e);r&&Ot(r.type)&&(r.durationHours=0)}function xr(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 ws(e){return Number(e.toFixed(2))}function Xe(e){for(let t of _f(e))Fs(t,e)}function Os(e,t){for(let r of e)Fs(r,t)}function _f(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,Pf(n,e));return[...t].sort((n,i)=>(r.get(i)??0)-(r.get(n)??0))}function Pf(e,t){let r=0,n=e;for(;n&&n!=="0"&&t.getActivity(n);)r+=1,n=t.getParentId(n);return r}function Fs(e,t){let r=t.getChildren(e);if(r.length===0)return;let n=[];for(let i of r){let a=t.getActivity(i);a&&n.push({progress:Number(a.progress??0),ponderator:Number(a.ponderator??0)})}si(e,n,t)}function si(e,t,r){let n=r.getActivity(e);if(!n)return;let i=xr(t);if(i===null){let a=r.getProgressFallback(e);a!==null&&r.setActivityField(e,P.PROGRESS,a);return}r.getProgressFallback(e)===null&&r.setProgressFallback(e,Number(n.progress??0)),r.setActivityField(e,P.PROGRESS,ws(i))}function xs(e,t,r){let n=[e];for(;n.length>0;){let i=n.pop();if(i===void 0)continue;let a=r.getChildren(i);a.length!==0&&(r.setProgressFallback(i,t),n.push(...a))}}function dt(e,t){return(Number(e)||0)*(Number(t)||0)/100}async function De(e,t,r=!0,n={}){let i=t?Ze(e,t):Of(e),a=r?n.progressMode??"freeze-when-no-contribution":"skip";await bf(i,e,a,{recomputeRealWork:n.recomputeRealWork??!1})}function Nr(e,t){Ns(e,t,"skip")}async function bf(e,t,r,n={recomputeRealWork:!1}){let a=0;for(let s of e)Ns(s,t,r,n.recomputeRealWork),a+=1,a%200===0&&await Q()}function Ze(e,t){let r=new Set,n=new Map;for(let s of t)Rf(s,e,r,n);if(r.size===0)return[];let i=Array.from(r),a=Ef(i,n);return Ms(i,a)}function Rf(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 Ef(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 Lf(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+=wf(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 Ns(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=Lf(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),r!=="skip"&&si(e,s.weightedChildren,t),n&&t.setActivityField(e,"realWorkHours",s.realWorkSum)}function wf(e,t){return t?Number(e.realWorkHours)||0:dt(e.workHours,e.progress)}function Of(e){let t=Ff(e),r=xf(t,e);return Ms(t,r)}function Ff(e){let t=new Set;return e.forEachActivity(r=>{r.parentId!==null&&t.add(r.parentId)}),Array.from(t)}function xf(e,t){let r=new Map;for(let n of e)r.set(n,Nf(n,t));return r}function Nf(e,t){let r=0,n=e;for(;n&&!L(n)&&t.getActivity(n);)r+=1,n=t.getParentId(n);return r}function Ms(e,t){return[...e].sort((r,n)=>(t.get(n)??0)-(t.get(r)??0))}var Ws={updateActivityDuration:Ls,updateTaskTiming:Wf("updateTaskTiming"),adjustLinkLagOnTaskMove:Es,recordLastStartDate:Mf};function Mf(e,t){let r=t.getActivity(e);r&&t.setLastStartDate(e,r.startDate)}function Yt(e,t,r,n){for(let i of t){let a=i in Ws?Ws[i]:void 0;if(!a){console.warn(`[replay post-processors] unknown: ${i} \u2014 skipping. Add an entry in POST_PROCESSORS if a fixture needs it.`);continue}a(e,r,n??null)}}function Wf(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 U(){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 j(e,t={}){return{patch:e,needsAutoSchedule:t.autoSchedule??!1,postProcessors:t.postProcessors??[],...t.cascadeMutations!==void 0?{cascadeMutations:t.cascadeMutations}:{},...t.trackingEvents!==void 0?{trackingEvents:t.trackingEvents}:{}}}var Bs={targetField:"name",canEdit(){return H()},parseInput(e){return typeof e!="string"?M("not_a_string"):O(e)},validate(){return U()},transform(e,t){return j({name:t},{autoSchedule:!1,postProcessors:[]})},trackEvent:"activity_name_entry"};var js={targetField:"description",canEdit(){return H()},parseInput(e){return typeof e!="string"?M("not_a_string"):O(e.trim())},validate(){return U()},transform(e,t){return j({description:t},{autoSchedule:!1,postProcessors:[]})},trackEvent:"activity_description_entry"};function Dt(e){return e.constraintType??G.ASAP}var Mr=100;function Te(e){return e.progress>=Mr}function et(e,t){return wt(e.type,t.hasChildren(e.id))}function Us(e){return e.progress>0}function Hs(e){return e.hasLookaheadTasks}function re(e,t){return Math.round(Math.ceil(e*t*60)/60)}var _e=e=>({endDate:e});function Kt(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 Br(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 Bf(e,t){let r=Kt(t,"UTC");for(;!e.isWorkTime(r,ct.DAY);)r=new Date(r),r.setUTCDate(r.getUTCDate()+1),r=Kt(r,"UTC");return r}function oi(e,t){return e.getClosestWorkTime({direction:Z.FUTURE,date:t,unit:ct.HOUR})}function ci(e,t){let r=Bf(e,t),n=new Date(r);return n.setUTCDate(n.getUTCDate()+1),n.setUTCHours(0,0,0,0),e.getClosestWorkTime({direction:Z.PAST,date:n,unit:ct.HOUR})}var Wr=new Set(["snet","snlt","mso"]),li=new Set(["fnet","fnlt","mfo"]),Gt=new Set(["asap","alap"]),jr="snet";function xt(e,t,r){let n=Kt(e,"UTC");if(!Wr.has(r)&&!li.has(r))return n;let i=Wr.has(r)?oi(t,n):ci(t,n),a=new Date(n);return a.setUTCHours(i.getUTCHours(),i.getUTCMinutes(),i.getUTCSeconds(),i.getUTCMilliseconds()),a}var $t=()=>({constraintType:jr});var ne=e=>({constraintDate:e}),Vs=e=>({constraintDate:e});var Ys={UPDATE_TASK_TIMING:"updateTaskTiming",ADJUST_LINK_LAG_ON_TASK_MOVE:"adjustLinkLagOnTaskMove",RECORD_LAST_START_DATE:"recordLastStartDate"};var Ks={UNCHANGED:"unchanged",OUT_OF_RANGE:"out_of_range",NEGATIVE_DURATION:"negative_duration",NOT_WORKING_DAY:"not_working_day",BEFORE_PARENT_START:"before_parent_start",BEFORE_START_DATE:"before_start_date",BEFORE_DATE_ORIGIN:"before_date_origin",CONSTRAINT_VIOLATION:"constraint_violation",MISSING_ID:"missing_id",UNKNOWN_CALENDAR:"unknown_calendar"};function Pe(e,t,r){return ts(e,t,r)}function be(e,t,r){return es(e,t,r)}var $s={targetField:"durationHours",canEdit(e,t){return Te(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)?O(re(n,r.hoursPerDay)):M("not_a_number")},validate(e,t,r){return Gs(r)?tt(Ks.NEGATIVE_DURATION):jf(t,r)?tt("unchanged"):U()},transform(e,t,r){if(Gs(t))return j({},{autoSchedule:!1,postProcessors:[]});let n=Uf(e,t,r),i=Hf(e,t,r,n.violated);return{...j(i,{autoSchedule:!0,postProcessors:[Ys.RECORD_LAST_START_DATE]}),...n.violated?{constraintWarning:be(n.constraintType,n.constraintDate,zs(e,t,r)??void 0)}:{}}},trackEvent:"activity_duration_entry"};function Gs(e){return Math.sign(e)===-1}function jf(e,t){return e===t}function Uf(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 Pe(i,e.constraintDate,a)}function Hf(e,t,r,n=!1){let i={};n&&Object.assign(i,$t(),ne(e.startDate));let a=Ke(e.durationHours,t);a&&(i.type=a),i.durationHours=t;let s=zs(e,t,r);return s&&Object.assign(i,_e(s)),i}function zs(e,t,r){let n=r.calendars.getCalendar(e.calendarId);return n?n.calculateEndDate(e.startDate,t):null}var Re=e=>({realWorkHours:e});var Vf=0,Yf=Mr,qs={targetField:"progress",canEdit(e,t){return Hs(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)?M("not_a_number"):O(t)},validate(e,t,r){return Kf(r)?tt("out_of_range"):U()},transform(e,t,r){let n=te(t),i=e.progress!==t&&n,a=Gf(t),s=qf(e,t,r.hierarchy),o={progress:t,autoScheduling:n,...Re(s.get(e.id)??0)},c=a?$f(e,t,n,r.hierarchy,s):[],l=a?Xf(e,t,r.hierarchy):[],d=c.length+l.length>0?[...c,...l]:void 0,u=[],f=a?Qf(e,t):void 0;return j(o,{autoSchedule:i,postProcessors:u,cascadeMutations:d,trackingEvents:f})},trackEvent:"activity_progress_entry"};function Kf(e){return e<Vf||e>Yf}function Gf(e){return e===Mr||te(e)}function $f(e,t,r,n,i){return n.getDescendantIds(e.id).map(s=>({activityId:s,fields:zf(t,r,i.get(s)??0)}))}function zf(e,t,r){return{progress:e,autoScheduling:t,...Re(r)}}function qf(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 Jf(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 Xf(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=[...Jf(e,r),...r.getAncestorIds(e.id)],a=[];for(let s of i){let o=Zf(s,n,r);o!==null&&(n.set(s,o),a.push({activityId:s,fields:{progress:o}}))}return a}function Zf(e,t,r){let n=r.getChildProgressInfo(e).map(a=>({progress:t.has(a.id)?t.get(a.id):a.progress,ponderator:a.ponderator??0})),i=xr(n);return i===null?null:Number(i.toFixed(2))}function Qf(e,t){return[{name:"activity_progress_update_radio_button",properties:{activity_id:e.id,activity_name:e.name,progress_updated:t}}]}var Js={targetField:"cost",canEdit(e,t){return et(e,t)?J("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 U()},transform(e,t,r){let n=tp(e,t,r.hierarchy);return j({cost:t},{autoSchedule:!1,postProcessors:[],cascadeMutations:n})},trackEvent:"activity_cost_budgeted_entry"};function tp(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 Xs={targetField:"usedCost",canEdit(e,t){return et(e,t)?J("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 U()},transform(e,t,r){let n=ep(e,t,r.hierarchy);return j({usedCost:t},{autoSchedule:!1,postProcessors:[],cascadeMutations:n})},trackEvent:"activity_cost_spent_entry"};function ep(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 Zs={targetField:"workHours",canEdit(e,t){return et(e,t)?J("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 U()},transform(e,t,r,n){let i=Qs(t,e.progress),a=String(n).trim()===""?[]:rp(e,t,i,r.hierarchy);return j({workHours:t,...Re(i)},{autoSchedule:!1,postProcessors:[],cascadeMutations:a})},trackEvent:"activity_labor_hours_budgeted_entry"};function Qs(e,t){return dt(e,t)}function rp(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??Qs(d.workHours,d.progress);c+=u,l+=f}i.set(o,c),a.set(o,l),s.push({activityId:o,fields:{workHours:c,...Re(l)}})}return s}function Ur(e,t){return e.getUTCFullYear()===t.getUTCFullYear()&&e.getUTCMonth()===t.getUTCMonth()&&e.getUTCDate()===t.getUTCDate()}function di(e,t){return e.getTime()<t.getTime()}function Ee(e){return e instanceof Date&&!Number.isNaN(e.getTime())}var Hr=e=>({durationHours:e});var to={targetField:"startDate",canEdit(e,t){return et(e,t)?J("summary","summary_column_value"):Us(e)?J("has_progress","cant_edit_activity_with_progress"):H()},parseInput(e,t,r){return Ee(e)?O(Kt(e,"UTC")):M("invalid_date")},validate(e,t,r,n){if(Ur(t,r))return tt("unchanged");let i=np(e,r,n);return i||U()},transform(e,t,r){let n=r.calendars.getCalendar(e.calendarId);if(!n)throw new Error("startDatePipeline: no calendar resolved (integrity)");let i=oi(n,t),a=e.type==="milestone",s=a?i:n.calculateEndDate(i,e.durationHours),o=i;return{...j({startDate:i,..._e(s),...a?Hr(0):{},...$t(),...ne(o)},{autoSchedule:!0,postProcessors:["adjustLinkLagOnTaskMove"]}),constraintWarning:ip(e,i,n)}},trackEvent:"activity_start_date_entry"};function np(e,t,r){let n=r.hierarchy.getParentStartDateIfHasPredecessors(e.id);if(!n)return null;let i=Kt(n,"UTC");return t.getTime()<i.getTime()?tt("before_parent_start"):null}function ip(e,t,r){let n=r.calculateEndDate(t,e.durationHours),i=Ye(Dt(e),t,n),a=Pe(Dt(e),e.constraintDate,i);if(a.violated)return be(a.constraintType,a.constraintDate,i)}var ap=99.999,ro={targetField:"endDate",canEdit(e,t){return et(e,t)?J("summary","summary_column_value"):sp(e)?J("completed","cant_edit_completed_activity"):H()},parseInput(e,t,r){if(!Ee(e))return M("invalid_date");let n=Kt(e,"UTC"),i=r.calendars.getCalendar(t.calendarId);return i?i.isWorkTime(n,ct.DAY)?O(ci(i,n)):O(i.getClosestWorkTime({direction:"past",date:n,unit:ct.HOUR})):O(n)},validate(e,t,r,n){if(Ur(e.endDate,r))return tt("unchanged");if(op(r,e))return tt("before_date_origin");if(cp(r,e))return tt("before_start_date");let i=lp(r,e,n);return i||U()},transform(e,t,r){let n=dp(e,t),i=up(e,t,r,!!n);return{...j(i,{autoSchedule:!0,postProcessors:["updateTaskTiming"]}),...n?{constraintWarning:n}:{}}},trackEvent:"activity_end_date_entry"};function sp(e){return e.progress>=ap}function op(e,t){return t.dateOrigin?di(e,t.dateOrigin):!1}function cp(e,t){return di(e,t.startDate)}function lp(e,t,r){let n=r.calendars.getCalendar(t.calendarId);return n?n.isWorkTime(e,ct.DAY)?null:tt("not_working_day"):null}function dp(e,t){if(Dt(e)===G.MSO)return;let n=Ye(Dt(e),e.startDate,t),i=Pe(Dt(e),e.constraintDate,n);if(i.violated)return be(i.constraintType,i.constraintDate,n)}function up(e,t,r,n=!1){let i={};Ot(e.type)&&!n&&eo(e)?Object.assign(i,ne(e.startDate)):(n||eo(e))&&Object.assign(i,$t(),ne(e.startDate));let o=fp(e,t,r),c=Ke(e.durationHours,o);return c&&(i.type=c),Object.assign(i,Hr(o)),i.endDate=t,i}function eo(e){return Gt.has(Dt(e))}function fp(e,t,r){let n=r.calendars.getCalendar(e.calendarId);return n?n.calculateDuration(e.startDate,t):e.durationHours}var pp=new Set(Object.values(G)),no={targetField:"constraintType",canEdit(e,t){return Te(e)?J("completed","cant_edit_completed_activity"):et(e,t)?J("summary","summary_column_value"):H()},parseInput(e){let t=String(e).toLowerCase();return hp(t)?O(t):M("invalid_constraint_type")},validate(){return U()},transform(e,t,r){let n=yp(e,t,r);return j(n,{autoSchedule:!0})}};function hp(e){return pp.has(e)}function yp(e,t,r){let n=gp(e,t);return{constraintType:t,...Vs(mp(e,t,n,r))}}function mp(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 gp(e,t){return Gt.has(t)?null:Wr.has(t)?e.startDate:li.has(t)?e.endDate:e.constraintDate}var io={targetField:"constraintDate",canEdit(e,t){return Te(e)?J("completed","cant_edit_completed_activity"):et(e,t)?J("summary","summary_column_value"):H()},parseInput(e){return Ee(e)?O(e):M("invalid_date")},validate(){return U()},transform(e,t,r){let n=ao(e)?jr: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=vp(e,a);return j(s,{autoSchedule:!0})}};function vp(e,t){return{constraintDate:t,...ao(e)?$t():{}}}function ao(e){return Gt.has(Dt(e))||!e.constraintType}var so={targetField:"calendarId",canEdit(){return H()},parseInput(e){let t=String(e).trim();return Ap(t)?M("empty_calendar"):O(t)},validate(e,t,r,n){return Ip(e.calendarId,r)?tt("unchanged"):n.calendars.getCalendar(r)?U():tt("unknown_calendar")},transform(e,t,r){return j(Cp(e,t,r),{autoSchedule:!0,postProcessors:[]})},trackEvent:"activity_calendar_assignment"};function Ap(e){return e===""}function Ip(e,t){return e===t}function Cp(e,t,r){let n={calendarId:t,assignedDefaultCalendar:!1},i=r.calendars.getCalendar(t);if(i){let a=e.durationHours===0,s=a?kp(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,_e(i.calculateEndDate(c,e.durationHours)))}return n}function kp(e){return new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()))}var oo={targetField:"customId",canEdit(e,t){return et(e,t)?J("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 U()},transform(e,t){return j({customId:t},{autoSchedule:!1,postProcessors:[]})},trackEvent:"schedule_custom_id_edition"};var co={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 U()},transform(e,t){return j({subcontractId:t},{autoSchedule:!1,postProcessors:[]})}};function Qe(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 Vr(e){return e.some(t=>Qe(t)===null)}var lo={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 Vr(r)?tt("missing_id"):U()},transform(e,t){let r=t.map(Qe).filter(n=>n!==null);return j({responsableIds:r},{autoSchedule:!1,postProcessors:[]})}};var uo={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 Vr(r)?tt("missing_id"):U()},transform(e,t){let r=t.map(Qe).filter(n=>n!==null);return j({tagIds:r},{autoSchedule:!1,postProcessors:[]})}};var Sp=new Map([[P.TEXT,Bs],[P.DESCRIPTION,js],[P.DURATION,$s],[P.PROGRESS,qs],[P.COST,Js],[P.USED_COST,Xs],[P.HH_WORK_TIME,Zs],[P.START_DATE,to],[P.END_DATE,ro],[P.CONSTRAINT_TYPE,no],[P.CONSTRAINT_DATE,io],[P.CALENDAR_ID,so],[P.CUSTOM_ID,oo],[P.SUBCONTRACT_ID,co],[P.RESPONSABLES,lo],[P.TAGS,uo]]);function zt(e){return Sp.get(e)}function Le(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 Dp=["name","description","type","startDate","endDate","durationHours","constraintType","constraintDate","calendarId","assignedDefaultCalendar","autoScheduling","progress","cost","usedCost","workHours","realWorkHours","customId","subcontractId","responsableIds","tagIds"],fo=new Set(Dp);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"},tr={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 po(e,t,r,n){e.setLinkFieldDynamic(t,r,n)}function Nt(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:Tp(e.baselineSnapshot),criticalPath:_p(e.criticalPath)}}function Et(e){return e===null?null:new Date(e)}function Tp(e){return e===null?null:{...e,startDate:Et(e.startDate),endDate:Et(e.endDate)}}function _p(e){return e===null?null:{...e,earlyStart:Et(e.earlyStart),earlyFinish:Et(e.earlyFinish),lateStart:Et(e.lateStart),lateFinish:Et(e.lateFinish)}}var mo=200;function qt(e,t){let r=new Set([String(e)]);for(let n of t.cascadeMutations??[])r.add(String(n.activityId));return r}async function z(e,t){let r=new Map,n=0;for(let i of t){n+=1,n%mo===0&&await Q();let a=e.getActivity(i);a&&r.set(i,X(a))}return r}function X(e){return Nt(e)}function Yr(e,t){let r=e.getActivity(t);return r?Nt(r):null}function Jt(e,t,r){ho(e,t,r.patch);for(let n of r.cascadeMutations??[])ho(e,n.activityId,n.fields)}function ho(e,t,r){for(let[n,i]of Object.entries(r)){if(!fo.has(n))throw new Error(`applyFieldChanges: column write to non-writable field "${n}"`);rt(e,t,n,i)}}async function Kr(e,t,r,n){let i=[],a=0;for(let s of r){a+=1,a%mo===0&&await Q();let o=Pp(e,t,s,n);o&&i.push(o)}return i}function Pp(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 bp(r,n.get(r),i);let s=fi(a,i);return Rp(s,n,r,i),a&&Object.keys(s).length===0?null:{id:r,kind:a?"updated":"created",fields:s,after:X(i)}}function bp(e,t,r){return t===r.correlativeId?null:{id:e,kind:"updated",fields:{correlativeId:{before:t,after:r.correlativeId}},after:X(r)}}function Rp(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 fi(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)||!ui(n[s],i[s]))&&(r[s]={before:yo(n[s]),after:yo(i[s])});return r}function yo(e){return e===null||typeof e!="object"?e:R(e)}function ui(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)=>ui(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)&&ui(r[s],n[s]))}function Gr(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 pi(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 $r(e,t,r,n,i){for(let a of t){if(r.has(a.activityId)||(i.add(a.activityId),n.has(a.activityId)))continue;let s=e.getActivity(a.activityId);if(!s)continue;let o=X(s);a.before!==void 0&&(o.correlativeId=a.before),n.set(a.activityId,o)}}var Ep=/^(\d{4})\/(\d{1,2})\/(\d{1,2})\s+(\d{1,2}):(\d{2})$/;function Mt(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(Ep);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 we(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 Lp=e=>e.type==="project",wp=(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:Mt(String(s));return we(a(e.startDate),a(e.endDate),t,i)};function Op(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(!Lp(o)){let d=wp(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 ae(e,t){let r=[];e.forEachActivity((n,i)=>{n.parentId===null&&r.push(i)}),Op(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 Fp=e=>e.type==="project",xp=e=>ut(e),Np=(e,t,r,n)=>{let i=xp(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:we(i.startDate,i.endDate,t,a)};function hi(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(!Fp(c)){let u=Np(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 Oe(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)}),hi(i,t,n,r)}var yi="Baseline";function zr(e){return e==="Actual"?"Actual":yi}var go=e=>Math.round(e*100)/100;function Mp(e,t){return(t==="Baseline"?e.expectedProgressBaseline:e.expectedProgress)??void 0}function Wp(e,t){let r=go(e),n=go(t);return r>99.99?bt.DONE:n>r?bt.OVERDUE:e>0&&r>n?bt.ADVANCEMENT:e===0&&t===0?bt.WAITING:e>0&&r<n?bt.DOING:bt.WAITING}function Wt(e,t){let r=[];return e.forEachActivity((n,i)=>{let a=typeof n.progress=="number"?n.progress:0,s=Wp(a,Mp(n,t));n.status!==s&&(rt(e,i,P.STATUS,s),r.push(i))}),r}function mi(e){let t=e instanceof Date?new Date(e.getTime()):e&&typeof e=="object"&&typeof e.valueOf=="function"?new Date(e.valueOf()):new Date(e),r=(i,a)=>s=>s===void 0?t[i]():(t[a](s),n),n={__isMomentShim:!0,clone:()=>mi(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}mi.isMoment=e=>!!e&&typeof e=="object"&&e.__isMomentShim===!0;var At=mi;function Bp(e){return e&&e.constructor===Date?!!(e.getFullYear&&e.getMonth&&e.getDate):!1}function qr(e){return Bp(e)&&!isNaN(e.getTime())}function D(e,t,r,n){if(!qr(new Date(t)))throw new Error(`Invalid date argument for calculateEndDate method. Date: ${t}, Activity: ${JSON.stringify(n)}`);let i=t;return e.calculateEndDate({start_date:new Date(i),duration:r,unit:"hour",task:n})}function yt(e){if(!qr(new Date(e.dateBaseToCalculate)))throw new Error("Invalid date argument for getClosestWorkTime method");let{dateBaseToCalculate:t,activityCalendar:r,direction:n,activity:i}=e;return r.$gantt.getClosestWorkTime({date:new Date(t),dir:n,unit:"hour",task:i})}var jp=e=>e?e.$level===1:!1,Up=e=>e.type==="project",Hp=e=>e.$level!==0,Vp=e=>e.type==="task",Yp=e=>e.type==="task"||e.type==="milestone",lt={byFirstLevel:jp,filterByParentType:Up,avoidSubproject:Hp,byTaskType:Vp,byTaskTypeAndMilestone:Yp};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 se(e){return{0:"fs",1:"ss",2:"ff",3:"sf"}[Number(e)]||"sf"}function vo(e){let{gantt:t,pendingParentsWithNoLinks:r,calculations:n,linkProperty:i}=e;try{let a=Kp({gantt:t,pendingParentsWithNoLinks:r});if(a.length===0)return new Set;let s=Gp({gantt:t,subprojectsWithNoLinks:a}),o=$p({gantt:t,childrenIds:s,linkProperty:i,getArrayOfLinkedActivities:zp,calculations:n});return new Set(o.map(c=>c.id))}catch(a){throw a}}function Kp(e){let{gantt:t,pendingParentsWithNoLinks:r}=e;return t.getTaskByTime().filter(lt.filterByParentType).filter(n=>r.has(n.id)).map(n=>n.id)}function Gp(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=lt.byTaskTypeAndMilestone(c),d=Number(c.progress)<100;return l&&d}).forEach(o=>n.add(o));return[...n]}function $p(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 zp(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 Ao({gantt:e,linkProperty:t,direction:r}){try{let n=qp(e,t);if(r==="forward")return{chainStartActivities:n,activitiesStartChainButChildrenOfLinkedParents:null};if(r==="backward")return Jp(n,e,t)}catch(n){throw console.log("Critical Path",n),n}}function qp(e,t){return e.getTaskByTime().filter(lt.avoidSubproject).filter(lt.byTaskTypeAndMilestone).filter(r=>!r[t].length)}function Jp(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 Io({gantt:e,direction:t,linkProperty:r}){try{let n=Xp(e),i=new Set,a=new Set,s=new Set;t==="backward"&&th(n).forEach(d=>{i.add(d.id)});let o=Zp(n,t,r),c=Qp(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 Xp(e){return e.getTaskByTime().filter(lt.filterByParentType).filter(lt.avoidSubproject)}function Zp(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 Qp(e,t){let r=new Set(t.map(n=>n.id));return e.filter(n=>!r.has(n.id))}function th(e){return e.filter(t=>{let r=Number(t.progress);return Number.isNaN(r)?!1:r===100})}function Co({pendingParentsWithLinks:e,gantt:t,direction:r}){try{let n=new Set;return e.forEach(i=>{let a=t.getTask(i),s=eh(r),o=rh(r),c=a[s];if(!Array.isArray(c))return;nh(t,c,o).forEach(d=>{n.add(d)})}),n}catch(n){throw n}}function eh(e){return e==="forward"?"$source":"$target"}function rh(e){return e==="forward"?"target":"source"}function nh(e,t,r){return t.map(n=>{let a=e.getLink(n)[r];return Number(a)})}var er={identifySecondLevelActivities:vo,identifyInitialActivities:Ao,identifyParentsWithAndWithoutLinks:Io,identifyForbiddenActivities:Co};function Jr(e){return e.length?e.reduce((t,r)=>r.ef>t.ef?r:t):!1}function gi({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}):rr(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 So({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 rr(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 vi=class{constructor(t,r,n,i){if(this.linkedActivitiesData=t,this.activity=r,this.gantt=n,this.linkCandidates=i,this.activityCalendar=this.gantt.getCalendar(this.activity.calendar_id),!this.activityCalendar)throw new Error(`Error trying to get calendar with id: ${this.activity.calendar_id}`)}calculate(){let t=this.calculateLinks(),r=Jr(t),n=this.activity.constraint_type;return n==="snet"?this.handleSNETConstraint(r):n==="fnlt"?this.handleFNLTConstraint(r):r}calculateLinks(){let t=[];for(let r of this.linkedActivitiesData){let n=r.linkType,i=se(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=So({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=gi({linkType:"ss",lag:t,predecessorTime:r,activityCalendar:this.activityCalendar,activity:this.activity}),i=D(this.activityCalendar,n,t,this.activity);t>0&&(i=rr(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=gi({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=rr(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=rr(i,"sf",this.activityCalendar,this.activity)),{es:i,ef:n}}},Do=vi;var Ai=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=se(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)}},To=Ai;function _o(e){let{parent:t,linkProperty:r,linkDirection:n,calculations:i,gantt:a,direction:s,linkCandidates:o}=e,c=t[r],l=ih(t),d=null;if(s==="forward"){let u=ah(c,n,i,a);d=new Do(u,t,a,o),d=d.calculate()}else{let u=sh(c,n,i,a);d=new To({linksWithActivityData:u,activity:t,parentData:l,gantt:a}).calculate()}return d}function ih(e){return{duration:e.duration,calendarId:e.calendar_id}}function ah(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 sh(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 Ro(e){let{activityData:t,calculations:r,singleParents:n,direction:i}=e;if(oh(t.id,r))return null;let a=ch(t.id,n),s=lh(a,r);return s.length===0?null:dh(s,i)}function oh(e,t){return t.has(e)}function ch(e,t){let r=t.get(e);return r?r.childrens:[]}function lh(e,t){return e.filter(r=>t.has(r)).map(r=>t.get(r))}function dh(e,t){if(t==="forward"){let r=Po(e,"es"),n=bo(e,"ef");return{es:r,ef:n}}else{let r=Po(e,"ls"),n=bo(e,"lf");return{ls:r,lf:n}}}function Po(e,t){return e.reduce((r,n)=>n[t]<r[t]?n:r)[t]}function bo(e,t){return e.reduce((r,n)=>n[t]>r[t]?n:r)[t]}var Ii={parentWithLinks:_o,parentWithNoLinks:Ro};var Ci=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=Ii.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=Ii.parentWithNoLinks({activityData:this.activity,gantt:this.gantt,singleParents:this.singleParents,calculations:this.calculations,direction:this.direction});t&&this.calculations.set(this.activity.id,t)}setDatesToParentsWithLinks(){if(!this.activity)throw new Error("Error trying to get parent",{cause:{parentActivity:this.activity}});let t=this.singleParents.get(this.activity.id)?.childrens,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)})}},Eo=Ci;var ki=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(lt.byFirstLevel).filter(lt.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}}},Lo=ki;var Si=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(lt.avoidSubproject).forEach(t=>{this.activitiesWaitingForCalculation.add(t.id)})}catch(t){throw t}}identifyParentsWithAndWithoutLinks(){try{let{parentsWithFullProgress:t,pendingParentsWithNoLinks:r,pendingParentsWithLinks:n}=er.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=er.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 Lo({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=er.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}=er.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 Eo({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()}},Xt=Si;function uh(e,t,r){let n={es:null,ef:null};if(!e)return n;if([y.SNET,y.SNLT].includes(t)){let i=new Date(e.constraint_date);n.es=i,n.ef=D(r,i,e.duration,e)}else if([y.FNLT,y.FNET].includes(t)){let i=new Date(e.constraint_date);n.es=D(r,i,-e.duration,e),n.ef=i}else if(t===y.MSO){let i=new Date(e.constraint_date);n.es=i,n.ef=D(r,i,e.duration,e)}else if(t===y.MFO){let i=new Date(e.constraint_date);n.es=D(r,i,-e.duration,e),n.ef=i}return n}var Xr=uh;var Di=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})}},wo=Di;var nr=class extends wo{constructor(t){super(t)}calculate(){if(this.links.length===0)return new Xt(this.gantt,"forward").calculateStartAndFinishOfChainOrigin(this.referenceActivity);let t=this.links.map(n=>{let i=this.gantt.getLink(n);if(!i)throw new Error("Link data not found",{cause:{linkId:n}});let a=this.calculateLink(i);return this.linkCandidates?.set(String(i.id),{targetId:String(this.referenceActivity.id),...a}),a}),r=Number(this.referenceActivity.parent);if(this.parentsWithLinks.has(r)){let n=this.gantt.getCalendar(this.referenceActivity.calendar_id),i=this.parentsCalculations.get(r).es,a=D(n,i,this.referenceActivity.duration,this.referenceActivity);t.push({es:i,ef:a})}return Jr(t)}calculateLink(t){return{0:()=>this.calculateFS(t),1:()=>this.calculateSS(t),2:()=>this.calculateFF(t),3:()=>this.calculateSF(t)}[t.type]()}};var Ti=class{constructor(t){this.gantt=t.gantt,this.direction=t.direction,this.pendingParentsWithNoLinks=t.pendingParentsWithNoLinks,this.pendingParentsWithLinks=t.pendingParentsWithLinks,this.calculationOfParentsFromLinks=t.calculationOfParentsFromLinks,this.singleParents=t.singleParents,this.calculations=t.calculations,this.activitiesStartChainButChildrenOfLinkedParents=t.activitiesStartChainButChildrenOfLinkedParents,this.linkProperty=t.linkProperty,this.linkDirection=t.linkDirection}checkActivitiesThatNowCanBeCalculated(t){let r=new Set,n=new Set(t);for(let i of t){let a=this.gantt.getTask(i);a.type==="project"?this.handleProjectActivity(i,a,r,n):this.handleNonProjectActivity(i,a,r,n)}return{activitiesThatCanBeCalculated:r,pendingActivities:n}}handleProjectActivity(t,r,n,i){let a=this.pendingParentsWithNoLinks.has(t),s=this.pendingParentsWithLinks.has(t),o=this.calculationOfParentsFromLinks.has(t);if(a){let c=this.singleParents.get(t)?.childrens;if(!c)return;c.every(d=>this.calculations.has(d))&&(n.add(t),i.delete(t));return}if(s&&o){let c=this.singleParents.get(t)?.childrens;if(!c)return;c.every(d=>this.calculations.has(d))&&(n.add(t),i.delete(t));return}s&&!o&&this.canCalculateParentActivity(r)&&(n.add(t),i.delete(t))}canCalculateParentActivity(t){let r=(t[this.linkProperty]||[]).length===0,n=t.constraint_type;return(this.direction==="forward"?n==="fnlt"||n==="snlt":n==="fnlt")&&r?!0:this.getArrayOfLinkedActivities(t[this.linkProperty]).every(s=>this.calculations.has(s))}handleNonProjectActivity(t,r,n,i){let a=Number(r.parent),s=this.pendingParentsWithLinks.has(a),o=this.calculationOfParentsFromLinks.has(a);if(s&&!o||this.direction==="backward"&&this.activitiesStartChainButChildrenOfLinkedParents.has(t)&&!o)return;if(r.$target.length===0&&r.$source.length===0){n.add(t),i.delete(t);return}let c=this.getLinkedActivities(r[this.linkProperty]),l=c.every(d=>this.calculations.has(d.id));if(this.direction==="backward"&&(c.length===0||l)&&o){n.add(t),i.delete(t);return}l&&(n.add(t),i.delete(t))}getLinkedActivities(t){if(!Array.isArray(t))return[];let r=[];for(let n of t){let i=this.gantt.getLink(n);if(!i)continue;let a=i[this.linkDirection],s=this.gantt.getTask(a);s&&r.push(s)}return r}getArrayOfLinkedActivities(t){if(!Array.isArray(t))return[];let r=[];for(let n of t){let i=this.gantt.getLink(n);i&&r.push(Number(i[this.linkDirection]))}return r}},Zr=Ti;var _i=(e,t)=>()=>t()===e;var Pi=e=>!e?.fullyParsed||typeof window<"u"&&window.to_use_react_gantt?.conversionMode?.isActive;var fh=16,oe=async e=>performance.now()-e>fh?(await Q(),performance.now()):e;var ir=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 oe(c);let{activitiesThatCanBeCalculated:l,pendingActivities:d}=t.checkActivitiesThatNowCanBeCalculated(o);if(l.size===0)break;for(let u of l){if(!s())return;c=await oe(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 bi=class extends Xt{constructor(t){super(t,"forward"),this.gantt=t,this.chainStartActivities=new Set,this.secondLevelActivities=new Set,this.pendingParentsWithLinks=new Set,this.pendingParentsWithNoLinks=new Set,this.structureOfParents=new Map,this.singleParents=new Map,this.calculations=new Map,this.calculationsOfParentThatImpactChildrens=new Map,this.alapMap=new Map,this.activitiesWaitingForCalculation=new Set,this.constraintsMap=new Map,this.totalFloatSnltFnlt=new Map,this.totalFloatForMsoMfo=new Map,this.totalFloatForAsap=new Map,this.linkCandidates=new Map,this.calculationOfParentsFromLinks=new Set,this.parentCalculationFromChildren=new Set,this.forbiddenActivitiesLinkedToParentsWithLinks=new Set,this.activitiesStartChainButChildrenOfLinkedParents=new Set,this.identifyInitialActivities(),this.initActivitiesWaitingForCalculation()}async calculateAsync(t){this.identifyParentsWithAndWithoutLinks(),t()&&(this.identifyForbiddenActivitiesLinkedToParentsWithLinks(),t()&&(this.initializeActivitiesWithFullProgress(),t()&&(this.calculateStartAndFinishOfActivitiesThatStartChain(),t()&&(this.identifySecondLevelActivities(),t()&&(this.identifyThirdLevelActivities(),t()&&await this.iterativeCalculateEfAndEs(t))))))}async iterativeCalculateEfAndEs(t){let r=new Zr({gantt:this.gantt,direction:this.direction,pendingParentsWithNoLinks:this.pendingParentsWithNoLinks,pendingParentsWithLinks:this.pendingParentsWithLinks,calculationOfParentsFromLinks:this.calculationOfParentsFromLinks,singleParents:this.singleParents,calculations:this.calculations,activitiesStartChainButChildrenOfLinkedParents:this.activitiesStartChainButChildrenOfLinkedParents,linkProperty:this.linkProperty,linkDirection:this.linkDirection});await ir({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 nr({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 nr({links:i,activity:n,calculatedActivitiesMap:this.calculations,calculatedAlapsMap:this.alapMap,constraint:a,parentsWithLinks:this.pendingParentsWithLinks,parentsCalculations:this.calculationsOfParentThatImpactChildrens,ganttInstance:this.gantt,linkCandidates:this.linkCandidates}).calculate(),a===y.ALAP&&this.alapMap.set(r,{es:n.start_date,ef:n.end_date,text:n.text});let p=Xr(n,a,c);if(s.includes(a)&&(this.constraintsMap.set(r,p),this.totalFloatSnltFnlt.set(r,{es:d,ef:u}),{es:d,ef:u}=this.recalculateInBaseConstraint(a,p,{es:d,ef:u})),[y.MSO,y.MFO].includes(a))if(this.totalFloatForMsoMfo.set(r,{es:d,ef:u}),this.constraintsMap.set(r,p),n.progress===0)d=p.es,u=p.ef;else{let h=n.end_date;a===y.MFO&&(h=Math.max(p.ef,n.end_date)),d=n.start_date,u=h}this.calculations.set(r,{es:d,ef:u}),this.activitiesWaitingForCalculation.delete(r)})}getTheGreatesDateBetweenRestrictionAndEsEf(t,r,n="greater"){if(n==="greater")return r.ef>t.ef?r:t;if(n==="less")return r.ef<t.ef?r:t}setDatesForActivityWithFullProgress(t){this.calculations.set(t.id,{es:t.start_date,ef:t.end_date})}getDatesForActivityWithZeroProgress(t){return{es:t.start_date,ef:t.end_date}}recalculateInBaseConstraint(t,r,n){let i=[y.SNET,y.FNET].includes(t)?"greater":"less",{es:a,ef:s}=this.getTheGreatesDateBetweenRestrictionAndEsEf(r,n,i);return{es:a,ef:s}}cleanAllActivityParentsFromLinks(t){return t.map(r=>{let n=this.gantt.getLink(r);if(!n)throw new Error("Error trying to get link",{cause:{linkId:r}});let i=n.source,a=n.target;if(!(!this.gantt.getTask(i)||this.gantt.getTask(i)?.type==="project")&&!(!this.gantt.getTask(a)||this.gantt.getTask(a)?.type==="project"))return r}).filter(Boolean)}},Oo=bi;var Ri=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})}},Fo=Ri;var Ei=class extends Fo{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 Xt(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))}},xo=Ei;function ph(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 No=ph;var Li=class extends Xt{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 ir({pending:this.activitiesWaitingForCalculation,activityCalculator:r,calculateFn:n=>this.calculateStartAndFinishTimes(n),shouldKeepPending:n=>this.calculationOfParentsFromLinks.has(n)&&!this.calculations.has(n),isCalculated:n=>this.calculations.has(n),onActivityProcessed:n=>this.activitiesWaitingForCalculation.delete(n),isCurrent:t})}setDatesToParentsWithLinks(t){if(!t)throw new Error("Error trying to get parent",{cause:{receivedParentData:t}});let r=this.singleParents.get(t.id).childrens,i=Array.from(this.calculations).filter(o=>r.includes(o[0])).map(o=>o[1]),{minLs:a,maxLf:s}=i.reduce((o,{ls:c,lf:l})=>({minLs:new Date(Math.min(o.minLs.getTime(),new Date(c).getTime())),maxLf:new Date(Math.max(o.maxLf.getTime(),new Date(l).getTime()))}),{minLs:new Date(i[0].ls),maxLf:new Date(i[0].lf)});this.calculations.set(t.id,{ls:a,lf:s})}calculateStartAndFinishTimes(t){t.forEach(r=>{let n=this.gantt.getTask(r);if(!n)throw new Error("Activity not found",{cause:{activityId:r}});let i=n.$source,a=n.constraint_type||y.ASAP,s=Number(n.progress);if(this.activitiesStartChainButChildrenOfLinkedParents.has(r)){if(this.calculationsOfParentThatImpactChildrens.has(Number(n.parent))&&this.calculationsOfParentThatImpactChildrens.get(Number(n.parent))===!1){let{ls:d,lf:u}=this.calculateStartAndFinishOfChainOrigin(n,this.direction);this.setCalculations(n,d,u);return}return this.doCalculationForActivitiesThatStartLinkButHisParentIsLinked(n)}if(n.type==="project")return this.doCalculationForParentType(n);if(s===100){this.setDatesForActivityWithFullProgress(n);return}if(this.allLinkedActivitiesHasProgress(i,n)){this.setWhenAllLinkedActivitiesHasProgress(n);return}if(s>0&&s<100&&(a===y.MSO||a===y.MFO)){this.setWhenActivitiesHasProgressButLessThanOneHundred(n,a);return}if(a===y.MSO||a===y.MFO){this.recalculateInBaseRestriction(n,a);return}let{ls:o,lf:c,minFromLinks:l}=this.calculateLfandLsFromLinks(i,n,a,this.parentsWithFullProgress,this.calculationsOfParentThatImpactChildrens);(a===y.SNLT||a===y.FNLT)&&({ls:o,lf:c}=this.getTheLessLateInBasEsEfConstraint(n.id,{ls:o,lf:c},a)),this.setCalculations(n,o,c),this.minFromLinks.set(n.id,{ls:l.ls,lf:l.lf})})}getTheLessLateInBasEsEfConstraint(t,r,n){let i=this.forwardConstraintsMap.get(t);if(!i){let a=this.gantt.getTask(t),s=this.gantt.getCalendar(a.calendar_id);i=Xr(a,n,s)}return r.lf<i.ef?r:{ls:i.es,lf:i.ef}}allLinkedActivitiesHasProgress(t){try{let r=!0;for(let n of t){let i=this.gantt.getLink(n);if(!i)continue;let a=this.gantt.getTask(i.target);a&&(a.type==="project"&&(r=!1),a.progress===0&&(r=!1))}return r}catch(r){throw new Error(r.message)}}setDatesForActivityWithFullProgress(t){this.setCalculations(t,t.start_date,t.end_date)}setWhenAllLinkedActivitiesHasProgress(t){let r=Number(t.parent),{ls:n,lf:i}=this.calculateStartAndFinishOfChainOrigin(t,"backward");if(this.calculationsOfParentThatImpactChildrens.has(r)){n=t.start_date;let a=this.calculationsOfParentThatImpactChildrens.get(r);a&&typeof a=="object"&&a.lf!=null&&(i=new Date(Math.min(i,a.lf)))}this.setCalculations(t,n,i)}setWhenActivitiesHasProgressButLessThanOneHundred(t,r){if(r===y.MSO){this.setCalculations(t,t.start_date,t.end_date);return}if(r===y.MFO){let n=Math.min(t.constraint_date,this.projectDates.end_date),i=new Date(Math.max(n,t.end_date));this.setCalculations(t,t.start_date,i);return}}setCalculations(t,r,n){this.calculations.set(t.id,{ls:r,lf:n,text:t.text})}calculateLfandLsFromLinks(t,r,n,i,a){return new xo({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=No(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}},Mo=Li;function Wo(){return null}var Bo=({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 wi=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)})}},jo=wi;var Oi=class{constructor(t){this.gantt=t.gantt,this.activity=t.activity,this.forwardMap=t.forwardMap,this.backwardMap=t.backwardMap,this.projectDates=t.projectDates,this.linksFreeFloatArray=[],this.linksFreeFloatObject={},this.durationCache=new Map}getFreeFloat(){let t=Number(this.activity.progress),r=this.getConstraintType();return this.calculateFreeFloatOfLink(r),{activityFreeFloat:t===100?0:this.getFreeFloatBaseConstraint(r),linksFreeFloat:this.linksFreeFloatObject}}getFreeFloatBaseConstraint(t){return t===y.MSO||t===y.MFO?this.calculateMsoMfo(t):this.calculateGeneral(t)}calculateFreeFloatOfLink(t=y.ASAP){let r=this.activity.$source.map(n=>{let{LINK:i,LINK_TYPE:a}=this.getLinkData(n),s=this.gantt.getTask(i.target);if(!s)return{linkId:i.id,freeFloat:null,hasProgress:!1};let o=Number(s.progress)>0,{sucessorDateToCalculate:c,predecessorDateToCalculate:l}=this.getDatesFromSucessorAndPredecessor(a,t,s),d=this.calculationWithCalendar(c,l),u=this.parseHoursToDays(d)-this.parseHoursToDays(i.lag),f=Math.max(0,u);return this.linksFreeFloatObject[i.id]=f,{linkId:i.id,freeFloat:f,hasProgress:o}}).filter(n=>n.freeFloat!==null&&n.freeFloat!==void 0);return this.linksFreeFloatArray=r,r}calculateGeneral(t=y.ASAP){let r=this.getMinFloat(this.linksFreeFloatArray),n=this.calculateFreeFloatForEndOfProject(t),i=0;return[y.SNLT,y.FNLT].includes(t)?i=this.doCalculationForSnltFnlt(t,n,r):i=this.doGeneralCalculation(n,r),Math.max(0,i)}getConstraintType(){let{constraint_type:t}=this.activity;return t||(t=y.ASAP),t}getDatesFromSucessorAndPredecessor(t,r,n){let i=n.constraint_type===y.ALAP,a=this.getSucessorAndPredecessorDates({constraint:r,isSuscessorAlap:i,sucessorId:n.id,predecessorId:this.activity.id}),s=new Date,o=new Date;return s=a[t].sucessor,o=a[t].predecessor,{sucessorDateToCalculate:s,predecessorDateToCalculate:o}}doGeneralCalculation(t,r){return r===null?t:this.getMinValue(r,t)}doCalculationForSnltFnlt(t,r,n){let i=this.calculateFreeFloatOfRestriction(t);return this.getMinValue(n,r,i)}calculateFreeFloatForEndOfProject(t){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=se(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)}},Uo=Oi;var Ho=e=>({totalFloat:new jo(e.totalFloat).getTotalFloat(),freeFloat:new Uo(e.freeFloat).getFreeFloat()});var Fi=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=Bo({forward:t,backward:r,id:l,activity:d,gantt:n,projectDates:i}),{totalFloat:f,freeFloat:p}=Ho(u);o.set(l,f),c.set(l,p),s=await oe(s)}return{totalFloatMap:o,freeFloatMap:c}};var xi=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=_i(n,this.getCurrentCalculationId),a=()=>i()&&r();try{let s=t||this.gantt;if(this.gantt=s||Wo(),Pi(this.gantt))return!1;let o=new Oo(this.gantt);if(await o.calculateAsync(a),!a())return!1;let c=o.calculations,l=o.constraintsMap,d=new Mo(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 oe(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 Fi({activityIds:a,forward:t,backward:r,gantt:this.gantt,projectDates:i,isCurrent:n})}catch(i){throw this.forwardPathCalculations?.size,i}}},Vo=xi;var hh=e=>e==="fnet"||e==="fnlt"||e==="mfo",yh=e=>new Date(Date.UTC(e.getUTCFullYear(),e.getUTCMonth(),e.getUTCDate()));function mh(e,t){let r=e.constraintDate;if(!r||!hh(e.constraintType))return r;let n=yh(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()?qn(e,t):r}function gh(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 vh(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 Ah(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 Ih(e,t){let r=vh(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:mh(i,e)})}),n}function Ch(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 kh(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 Yo(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=gh(f);return r.set(d,p),p},i=kh(e);await Q();let a=Ah(e),s=Ih(e,a);await Q();let o=[...s.values()].sort((l,d)=>(l.start_date?.getTime()??0)-(d.start_date?.getTime()??0));await Q();let c=Ch(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 Go=1e3;function Sh(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 Dh(e,t,r,n,i){let a=new Map,s=0;for(let o of t.forward?.keys()??[]){if(++s>=Go&&(s=0,await Q(),!i()))return null;let c=n(o);if(c===null)continue;let l=e.getActivity(c);l&&a.set(String(c),_h(o,Number(l.progress??0),t,r))}return i()?a:null}async function Th(e,t,r,n){let i=new Map,a=0;for(let s of e.getAllLinks()){if(++a>=Go&&(a=0,await Q(),!n()))return null;i.set(String(s.id),Sh(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 Ko=(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 _h(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=Ko(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:Ko(r.freeFloat.get(e)?.activityFreeFloat,n)}}var Qr=(e,t)=>e===t||e!==null&&t!==null&&e.getTime()===t.getTime();function Ni(e,t,r){let n=e.getActivity(t),i=n?.criticalPath,a=r.criticalPath;n&&i&&Qr(i.earlyStart,a.earlyStart)&&Qr(i.earlyFinish,a.earlyFinish)&&Qr(i.lateStart,a.lateStart)&&Qr(i.lateFinish,a.lateFinish)&&Object.is(i.totalSlackHours,a.totalSlackHours)&&Object.is(n.isCritical,r.isCritical)&&Object.is(n.freeSlackHours,r.freeSlackHours)||e.setActivityFields(t,r)}function Mi(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 Wi(e,t,r=()=>!0){if(!r())return null;let n=await Yo(e,t);if(!r())return null;let i=new Vo(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 Dh(e,s,t,n.getCanonicalActivityId,r);if(!o)return null;let c=await Th(e,i.linkResidualHours,o,r);return c?{activities:o,links:c}:null}async function tn(e,t,r=()=>!0){let n=await Wi(e,t,r);if(!n||!r())return!1;for(let[i,a]of n.activities){if(!r())return!1;Ni(e,i,a)}for(let[i,a]of n.links){if(!r())return!1;Mi(e,i,a)}return!0}function Fe(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 $o=new Set;var zo=new Set(["activity-outdent","activity-indent"]);var ar=new Set([P.TEXT,P.DESCRIPTION,P.COST,P.USED_COST,P.CUSTOM_ID,P.RESPONSABLES,P.SUBCONTRACT_ID,P.TAGS]),Ph=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"]),bh=new Set(["activity-clipboard-clear","activity-copy","selection-toggle","selection-replace","visibility-set","filter-set","sort-set"]);function Jo(e){return!bh.has(e.kind)}var Rh=new Set;function Eh(e){return e.kind==="inline-edit"?ar.has(e.column):e.kind==="bulk-edit"?e.edits.every(t=>ar.has(t.column)):!1}function Bi(e,t){return!(Ph.has(e.kind)||t.has(e.kind)||Eh(e))}function ji(e){return e.kind==="activity-lookahead-sync"?e.persistedProgress!==void 0:Bi(e,Rh)}function ce(e){return e.kind==="activity-lookahead-sync"?e.persistedProgress!==void 0:Bi(e,$o)}function Xo(e){return Bi(e,zo)}function Ui(e){return e.kind==="activity-set-progress"?!0:e.kind==="inline-edit"?e.column===P.PROGRESS:e.kind==="bulk-edit"?e.edits.some(t=>t.column===P.PROGRESS):!1}function Lh(e){return Xo(e)&&Ui(e)}var qo=new Set([P.PROGRESS,P.HH_WORK_TIME,P.DURATION,P.COST,P.USED_COST,P.REAL_COST]);function wh(e){return e.kind==="activity-set-progress"?!0:e.kind==="inline-edit"?qo.has(e.column):e.kind==="bulk-edit"?e.edits.some(t=>qo.has(t.column)):!1}var 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 Zo(e,t,r){let n=new Set;t.ran&&n.add(it.AUTOSCHEDULE),n.add(it.PARENT_BOUNDS),wh(e)&&n.add(it.PARENT_PROGRESS),Ui(e)&&n.add(it.REAL_WORK);let i=!r.skipAutoSchedule;return i&&Xo(e)&&n.add(it.EXPECTED_PROGRESS),i&&Lh(e)&&n.add(it.REAL_COST),i&&ce(e)&&!r.skipCriticalPath&&n.add(it.CRITICAL_PATH),n}async function Y(e,t){let r=Fh(e.adapter),n=Oh(t,r);n.has(it.AUTOSCHEDULE)&&await jh(e.adapter,t);let i=n.has(it.AUTOSCHEDULE)?await Mh(e,t.autoscheduleFrom,t.preventSummaryTargetPullback):Bh();return await Uh(e.adapter,t,i.scheduledIds,n,r),await Vh(e,n,t.now),i}function Oh(e,t){let r=e.autoscheduleFrom!==null,n=!e.options.skipAutoSchedule&&r,i=new Set(Zo(e.action,{requested:r,ran:n},e.options));return(e.recomputeParentProgress||t.affectedParents.size>0)&&i.add(it.PARENT_PROGRESS),i}function Fh(e){let t=new Set,r=new Set,n=e.peekWriteCapture();if(!n)return{affectedParents:t,dirtySeeds:r};let i=a=>{if(a===null||L(a))return;let s=String(a);t.add(s);let o=e.getChildren(s)[0];o!==void 0&&r.add(o)};return xh(e,n.ops,i),Nh(e,n.before,r,i),{affectedParents:t,dirtySeeds:r}}function xh(e,t,r){for(let n of t)if(n.kind==="insert"){let i=e.getActivity(n.activityId);i&&r(i.parentId)}else n.kind==="remove"&&r(n.before.parentId)}function Nh(e,t,r,n){for(let[i,a]of t){let s=e.getActivity(i);if(!s)continue;let o=!Object.is(a.progress,s.progress),c=!Object.is(a.ponderator,s.ponderator),l=!Object.is(a.parentId,s.parentId);(o||c)&&(n(s.parentId),r.add(String(i))),l&&(n(a.parentId),n(s.parentId),r.add(String(i)))}}async function Mh(e,t,r=!1){let n=t==="roots"?{}:{triggerId:t};r&&(n.preventSummaryTargetPullback=!0);let i=await e.scheduler.schedule(n),a=Wh(e.adapter,i.updatedIds);return Ge(e.adapter,i),a}function Wh(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 Bh(){return{scheduledIds:[]}}async function jh(e,t){let r=t.collectDirty?t.collectDirty([]):pi(t.recomputeParentsFrom,[]);r.size!==0&&await De(e,r,!1)}async function Uh(e,t,r,n,i){n.has(it.PARENT_PROGRESS)&&Hh(e,i.affectedParents);let a=t.collectDirty?t.collectDirty(r):pi(t.recomputeParentsFrom,r);for(let s of i.dirtySeeds)a.add(s);await De(e,a,n.has(it.PARENT_PROGRESS),{recomputeRealWork:n.has(it.REAL_WORK),progressMode:"freeze-when-no-contribution"})}function Hh(e,t){for(let r of t){if(e.hasChildren(r))continue;let n=e.getProgressFallback(r);n!==null&&(e.setActivityField(r,"progress",n),e.setProgressFallback(r,null))}}async function Vh(e,t,r){t.has(it.EXPECTED_PROGRESS)&&r!==null&&(Yh(e.adapter)&&Oe(e.adapter,r,e.defaultBaseCalendarId??null),ae(e.adapter,r),Wt(e.adapter,e.sector.statusCriteria)),t.has(it.REAL_COST)&&Fe(e.adapter),t.has(it.CRITICAL_PATH)&&await tn(e.adapter,e.sector.hoursPerDay)}function Yh(e){let t=!1;return e.forEachActivity(r=>{ut(r)&&(t=!0)}),t}var Kh=new Set([P.CONSTRAINT_TYPE,P.CONSTRAINT_DATE]),Gh=new Set(["mso","mfo"]);function en(e){return Kh.has(e)}function rn(e){return e===P.CONSTRAINT_DATE}function nn(e,t,r,n){let i=r.getActivity(e);if(!i)return!1;let a=i.constraintType;if(!a||Gt.has(a)||Gh.has(a))return!1;let s=Hi(i.startDate),o=Hi(r.getLastStartDate(e));if(!o||!s||s.getTime()!==o.getTime())return!1;let c=$h(t,a,String(i.calendarId??""),n),l=Hi(i.constraintDate);return zh(l,c)?!1:(r.setActivityField(e,"constraintDate",c),!0)}function $h(e,t,r,n){if(e===null)return null;let i=n.getCalendar(r);return i?xt(e,i,t):e}function Hi(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 an(e,{postMutationArgs:t,revertTargets:r,revert:n}){let{scheduledIds:i}=await Y(e,Qo(t)),a=!1;for(let{activityId:s,priorConstraintDate:o}of r){let c=n(s,o);a=a||c}if(a){let s=await Y(e,Qo(t));i=Jh(i,s.scheduledIds)}return ce(t.action)&&await Y(e,qh(t)),{scheduledIds:i}}function Qo(e){return{...e,options:{...e.options,skipCriticalPath:!0}}}function qh(e){return{action:e.action,autoscheduleFrom:null,recomputeParentsFrom:[],now:null,options:e.options}}function Jh(e,t){let r=new Set(e);for(let n of t)r.add(n);return[...r]}function Vi(e,t,r){let n=[];for(let i of r){let a=e.get(i);if(!a)continue;let s=a.pendingRequestIds??[];if(me({pendingRequestIds:s})&&t.getActivity(i)==null)for(let o of s)n.push({kind:"sir-auto-reject",activityId:i,sirId:o,reason:"activity_deleted"})}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=ty(e,t),n=new Map(t.beforeSnap),i=e.peekWriteCapture();if(i){let f=ry(i);ey(e,i,f,n,r)}let a=t.sirDetection,s=a==="before-diff"?Vi(n,e,r):[],o=Qh(t.correlativeShifts,r),c=await Kr(e,n,r,o),l=a==="after-diff"?Vi(n,e,r):s,d=t.warnings??[],u=Zh(t.links??[],i?Xh(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 Xh(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 Zh(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 Qh(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 ty(e,t){let r=new Set;for(let n of t.touchedIds)r.add(n);for(let n of t.scheduledIds)r.add(n);if(t.includeAllIds)for(let n of e.getAllIds())r.add(n);return r}function ey(e,t,r,n,i){for(let a of t.dirty){if(r.has(a)||n.has(a))continue;let s=t.before.get(a),o=e.getActivity(a);!s||!o||Object.keys(fi(s,o)).length!==0&&(n.set(a,s),i.add(a))}}function ry(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 Ne(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 Me(e,t,r){let n=[];if(!t.getActivity(r))return n;for(let i of t.getIncomingLinkIds(r)){let a=t.getLink(i);if(!a)continue;let s=e.get(String(a.id));s===void 0||s===Number(a.lag)||n.push({id:String(a.id),kind:"updated",fields:{lag:{before:s,after:Number(a.lag)}},after:ft(a)})}return n}function sn(e,t){typeof e=="string"&&e.length>0&&t.releaseCustomId(e)}async function tc(e,t,r){let{adapter:n,ctx:i,scheduler:a,sector:s}=r,o=zt(e.column);if(!o)return{ok:!1,reason:C.NO_PIPELINE_FOR_COLUMN};e.column===P.DURATION&&a.invalidateExpandedLinksCache();let c=i.activityReader.getActivity(e.activityId);if(!c)return{ok:!1,reason:C.ACTIVITY_NOT_FOUND};let l=o.canEdit(c,i.hierarchy);if(!l.allowed)return{ok:!1,reason:l.reason??C.CANNOT_EDIT,alertKey:l.alertKey};let d=o.parseInput(e.newValue,c,i);if(!d.ok)return{ok:!1,reason:d.reason??C.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??C.INVALID,alertKey:f.notification?.messageKey};if(e.column===P.CUSTOM_ID&&d.value!==null){let A=n.getActivity(e.activityId),T=A?A.customId:null,x=typeof T=="string"?T:null;if(r.customIdTracker.isCustomIdInUse(String(d.value),x))return{ok:!1,reason:C.CUSTOM_ID_DUPLICATE}}let p=o.transform(c,d.value,i,d.raw),h=qt(e.activityId,p),g=await z(n,h),I=Ne(n,String(e.activityId)),_=c.constraintDate;Jt(n,e.activityId,p),Yt(e.activityId,p.postProcessors??[],n,g.get(String(e.activityId))??null);let v=Me(I,n,String(e.activityId));if(e.column===P.CUSTOM_ID){let A=g.get(String(e.activityId)),T=A?A.customId:null,x=typeof T=="string"?T:null,F=typeof d.value=="string"?d.value:null;x!==F&&r.customIdTracker.trackCustomIdChange(x,F)}let k=()=>({action:e,autoscheduleFrom:p.needsAutoSchedule?String(e.activityId):null,recomputeParentsFrom:[],collectDirty:A=>Gr(e.activityId,h,A),now:r.now,options:t}),m=en(e.column),{scheduledIds:b}=await(m?an({adapter:n,scheduler:a,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{postMutationArgs:k(),revertTargets:rn(e.column)?[]:[{activityId:e.activityId,priorConstraintDate:_}],revert:(A,T)=>nn(A,T,n,i.calendars)}):Y({adapter:n,scheduler:a,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},k())),w=(p.trackingEvents??[]).map(A=>({name:A.name,properties:A.properties??{}})),S=Le(e.activityId,p.constraintWarning);return{ok:!0,changes:await B(n,{source:e,beforeSnap:g,touchedIds:h,scheduledIds:b,sirDetection:"before-diff",links:v,trackingEvents:w,...S?{warnings:[S]}:{},hoursPerDay:s.hoursPerDay})}}function ny(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 iy(e,t,r,n){return e.map((i,a)=>{let s=i.kind==="create"?n?.get(a):void 0,o=Ht(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 ay(e){return new Map([...e].map(([t,r])=>[String(t),r]))}async function ec(e,t,r){if(e.kind==="link-create"||e.kind==="link-update"){let n=e.type;if(n!==void 0&&!Object.values(W).some(a=>a===n))return{ok:!1,reason:C.INVALID_LINK_TYPE};let i=e.lag;if(i!==void 0&&!Number.isFinite(i))return{ok:!1,reason:C.INVALID_LINK_LAG}}return Yi([uy(e,r.sector.hoursPerDay)],e,t,r,e.kind==="link-create"&&e.linkId?new Map([[0,e.linkId]]):void 0)}async function rc(e,t,r){let{hoursPerDay:n}=r.sector,i=e.operations.map(s=>cy(s,n)),a=sy(e.operations);return Yi(i,e,t,r,a)}function sy(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 oy(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 cy(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 Yi(e,t,r,n,i){let{adapter:a,scheduler:s,sector:o,linkIdGen:c}=n;s.invalidateAllCaches();let{activityIds:l,links:d}=ny(e,a),u=await z(a,l),f=iy(e,a,c,oy(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=ly(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}),g=xe(f,d,a);return{ok:!0,linkVerdicts:f.map((I,_)=>I.rejected===null?{operationIndex:_,kind:I.op.kind,ok:!0,linkId:String(I.finalLinkId)}:{operationIndex:_,kind:I.op.kind,ok:!1,reason:I.rejected}),__beforeLinks:ay(d),changes:await B(a,{source:t,beforeSnap:u,touchedIds:l,scheduledIds:h,links:g,hoursPerDay:o.hoursPerDay})}}function ly(e,t,r){for(let n of e){if(n.rejected!==null)continue;let i=dy(n.op,t,r);if(i!==null)return r.hasChildren(i)?"roots":String(i)}return null}function dy(e,t,r){return e.kind==="create"?e.target:e.kind==="delete"?t.get(e.linkId)?.target??null:r.getLink(e.linkId)?.target??null}function uy(e,t){return e.kind==="link-create"?{kind:"create",source:e.source,target:e.target,type:e.type,lag:vt(e.lag,t)}:e.kind==="link-update"?{kind:"update",linkId:e.linkId,type:e.type,lag:e.lag===void 0?void 0:vt(e.lag,t)}:{kind:"delete",linkId:e.linkId}}async function nc(e,t,r){let{adapter:n,sector:i}=r;if(typeof e.newValue!="string")return{ok:!1,reason:C.INVALID_VALUE};if(!n.getActivity(e.activityId))return{ok:!1,reason:C.ACTIVITY_NOT_FOUND};let s=e.column===P.CUSTOM_PREDECESSORS,{specs:o}=Er(e.newValue),c=o.map(h=>({...h,lag:vt(Fr(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 g=n.getLink(h);g&&f.push(g)}let p=s?wr({targetActivityId:e.activityId,currentLinks:f,desiredSpecs:c,resolveActivityByCorrelative:d}):Or({sourceActivityId:e.activityId,currentLinks:f,desiredSpecs:c,resolveActivityByCorrelative:d});return Yi(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 st(e){e.invalidateVisualOrderIds?.();let t=[];e.forEachActivity(a=>{L(a.parentId)&&t.push(a)}),t.sort(sc);let r=[];ic(r,t);let n=[],i=0;for(;r.length>0;){let a=r.pop();if(a.correlativeId!==i){let o=typeof a.correlativeId=="number"?a.correlativeId:void 0;n.push({activityId:String(a.id),before:o}),o!==void 0&&e.noteCorrelativeBefore?.(String(a.id),o),fy(a,i)}i+=1;let s=Ve(String(a.id),e);s.sort(sc),ic(r,s)}return n}function ic(e,t){for(let r=t.length-1;r>=0;r-=1)e.push(t[r])}function ac(e){let t=e.correlativeId,r=typeof t=="number"?t:Number(t);return Number.isFinite(r)?r:Gn}var sc=(e,t)=>ac(e)-ac(t);function fy(e,t){e.correlativeId=t}function Ki(e,t){if(!e||e==="0")return;let r=String(e);for(;r!==null;){let{workHours:n,realWorkHours:i}=lc(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 oc(e,t){let r=t.getActivity(e);if(!r)return;let n=r.parentId;!n||L(n)||Ki(n,t)}function cc(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(sr(i,E.WORK_HOURS),sr(i,E.PROGRESS)))}for(let n of t)r.setActivityField(n,E.REAL_WORK_HOURS,lc(n,r).realWorkHours)}function lc(e,t){let r=0,n=0;for(let i of t.getChildren(e)){let a=t.getActivity(i);if(!a)continue;let s=sr(a,E.WORK_HOURS);r+=s,n+=py(i,a,s,t)}return{workHours:r,realWorkHours:n}}function sr(e,t){let r=e[t];return typeof r=="number"&&Number.isFinite(r)?r:0}function py(e,t,r,n){return n.hasChildren(e)?sr(t,E.REAL_WORK_HOURS):dt(r,sr(t,E.PROGRESS))}function Gi(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+=hy(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 dc(e,t){let r=t.getActivity(e);if(!r)return;let n=r.parentId;!n||L(n)||Gi(n,t)}function hy(e,t){let r=e[t];return typeof r=="number"&&Number.isFinite(r)?r:0}function $i(e,t){if(!e||e==="0")return;let r=String(e);for(;r!==null;){let n=t.getChildren(r),i=0;for(let o of n){let c=t.getActivity(o);c&&(i+=yy(c,E.COST))}t.setActivityField(r,E.COST,i);let a=t.getActivity(r);if(!a)break;let s=a.parentId;if(!s||L(s))break;r=s}}function uc(e,t){let r=t.getActivity(e);if(!r)return;let n=r.parentId;!n||L(n)||$i(n,t)}function yy(e,t){let r=e[t];return typeof r=="number"&&Number.isFinite(r)?r:0}var on=Object.freeze({proplannerId:null,description:"",type:"task",progress:0,constraintType:"asap",constraintDate:null,autoScheduling:!0,assignedDefaultCalendar:!1,dateOrigin:null,cost:0,usedCost:0,realCost:0,workHours:0,realWorkHours:0,ponderator:0,hasCustomPonderator:!1,correlativeId:0,customId:null,subcontractId:null,isLookahead:!1,hasLookaheadTasks:!1,newActivityIds:[],hasNewActivities:!1,pendingRequestIds:[],responsableIds:[],tagIds:[],baselinePoints:[],baselineSnapshot:null,recursiveDurationHours:0,isCritical:!1,freeSlackHours:null,expectedProgress:null,expectedProgressBaseline:null,status:null,criticalPath:null}),fc="New Master Plan",pc="New Activity";var my=["name","description","type","startDate","durationHours","constraintType","constraintDate","calendarId","assignedDefaultCalendar","autoScheduling","progress","cost","usedCost","realCost","workHours","realWorkHours","ponderator","hasCustomPonderator","customId","subcontractId","responsableIds","tagIds","isLookahead"],cn=new Set(my);function gy(e){let t=Object.getPrototypeOf(e);if(t!==null&&t!==Object.prototype)throw new Error("activity-create: override bag must be a plain object with no custom prototype");for(let r of Reflect.ownKeys(e))if(typeof r=="symbol"||!cn.has(r))throw new Error(`activity-create: rejected override key "${String(r)}" \u2014 not a creation-writable canonical field`);return e}function hc(e,t){let r=e.parentId!=null?t.getActivity(e.parentId):null,n=gy(e.activityOverrides??{}),i=e.numTasksInGantt===0?fc:pc,a=n.name??i,s=n.durationHours??e.sector.hoursPerDay,o=n.calendarId??e.sector.defaultCalendar,c=vy(r,e.fallbackStartDate,n.startDate),l={...on,...n,id:e.id,parentId:e.parentId,uniqueCorrelativeId:e.nextUniqueCorrelativeId,name:a,durationHours:s,calendarId:o,startDate:c,endDate:c},d=n.startDate?new Date(l.startDate):t.getClosestWorkTime({date:l.startDate,dir:Z.FUTURE,task:l});if(!n.startDate&&r&&Ot(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:Z.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 vy(e,t,r){return r?new Date(r):e?new Date(e.startDate):t?new Date(t):new Date}function Ay(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 We(e){let t=e.getParent(e.parentId);if(!t)return null;let r=e.isCurrentlyLeaf!==void 0?e.isCurrentlyLeaf&&Ut(t.type):Iy(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=G.ASAP,a.constraintDate=null)),{parentId:e.parentId,fields:a,promotionSnapshot:Ay(t)}}function Iy(e){return Ut(e.type)&&(!Array.isArray(e.newActivityIds)||e.newActivityIds.length===0)}function ln(e,t,r,n){let i=t,a=i==="0",s=zi(e,i);if(n!==void 0){let c=s.find(l=>l.id===n);if(c){let l=ot(c),d=s.map(ot).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=ot(c),d=s.map(ot).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(ot))+1}var le=Number.MAX_SAFE_INTEGER,yc=Number.MAX_SAFE_INTEGER-1;function ot(e){let t=e.correlativeId,r=typeof t=="number"?t:Number(t);return Number.isFinite(r)?r:le}function zi(e,t){return Ve(t,e)}function mc(e,t,r){let n=e,i=Zt(e,r);for(;i!=null&&t.has(i);)n=i,i=Zt(i,r);return n}function dn(e,t,r){let n=new Set([e]),i=jt(r.getActivity(e)?.parentId);for(;i!=="0"&&!n.has(i);){if(t.has(i))return!0;n.add(i),i=jt(r.getActivity(i)?.parentId)}return!1}function Zt(e,t){let r=t.getActivity(e);if(!r)return null;let n=jt(r.parentId),i=gt(n,t),a=i.findIndex(s=>String(s)===String(e));return a<=0?null:i[a-1]??null}function gc(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(ot);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 Cy=new Set([...[...cn].filter(e=>e!=="durationHours"),"durationDays"]);function un(e,t){if(e===void 0)return{ok:!0,value:{}};let r=Object.getPrototypeOf(e);if(r!==null&&r!==Object.prototype)return{ok:!1,reason:C.INVALID_VALUE};for(let a of Reflect.ownKeys(e))if(typeof a=="symbol"||!Cy.has(a))return{ok:!1,reason:C.INVALID_VALUE};let{durationDays:n,...i}=e;return n!==void 0&&(!Number.isFinite(n)||n<0)?{ok:!1,reason:C.INVALID_VALUE}:{ok:!0,value:{...i,...n===0&&(i.type===void 0||i.type==="task")?{type:"milestone"}:{},...n===void 0?{}:{durationHours:re(n,t)}}}}async function or(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=Dy(e.activityId,n,o,t.isActivityIdReserved),h=c.next(),g={id:p,parentId:f?null:e.parentId,sector:{id:a.id,hoursPerDay:a.hoursPerDay,defaultCalendar:Ey(s)},numTasksInGantt:n.activityCount(),nextUniqueCorrelativeId:h,activityOverrides:e.overrides??{}},_=hc(g,{getActivity:A=>n.getActivity(A),calculateEndDate:A=>n.calculateEndDate(A),getClosestWorkTime:A=>n.getClosestWorkTime(A)}).newTask;_.realWorkHours=dt(_.workHours,_.progress),_y(_,e,t,u,d,r);let v=r.insertionCorrelativeId??ln(n,f?"0":e.parentId,e.afterSiblingId,e.beforeSiblingId);_.correlativeId=v;let k=new Set([p]);d&&k.add(d.id);let m=d!==null&&n.getChildren(d.id).length===0,b=m?d?.customId:null,w=r.skipBeforeSnap?new Map:await z(n,k);n.addActivity(_),Py(e,p,d,n,m),b&&t.customIdTracker.releaseCustomId(b),r.skipRollupCascades||(oc(p,n),dc(p,n),uc(p,n));let S=by(n,p,k,r);return{ok:!0,newId:p,parent:d,newActivity:_,beforeSnap:w,initialTouched:k,correlativeShifts:S}}function ky(e,t){let r=L(e.parentId),n=r?null:t.getActivity(e.parentId);if(!r&&!n)return{ok:!1,reason:C.PARENT_NOT_FOUND};if(n!==null&&me(n))return{ok:!1,reason:C.PARENT_FROZEN_BY_SIR};if(e.afterSiblingId!==void 0&&e.beforeSiblingId!==void 0)return{ok:!1,reason:C.ANCHOR_SIBLING_CONFLICT};let s=e.afterSiblingId??e.beforeSiblingId,o=Sy(e,t,r,s);return o||{ok:!0,parent:n,anchorSiblingId:s,isRoot:r}}function Sy(e,t,r,n){if(n===void 0)return null;let i=t.getActivity(n);if(!i)return{ok:!1,reason:C.ANCHOR_SIBLING_NOT_FOUND};let a=r?"0":e.parentId;return(i.parentId==null?"0":String(i.parentId))!==a?{ok:!1,reason:C.ANCHOR_SIBLING_WRONG_PARENT}:null}function Dy(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 Ty(e){let t=e.overrides?.customId;return typeof t=="string"?t:void 0}function _y(e,t,r,n,i,a){let{adapter:s,customIdTracker:o}=r,c=Ty(t);if(c!==void 0){if(c.length===0)return;if(!o.isCustomIdInUse(c)){o.registerCustomId(c);return}}let l=a.customIdReferenceId??n,d=l!==void 0,u=d?s.getActivity(l):i;e.customId=o.generateCustomIdForNewChild({activity:u??{},useActivityCustomIdAsReference:d})}function Py(e,t,r,n,i){if(!r)return;let a=We({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 by(e,t,r,n){if(n.skipCorrelativeRecompute)return[];let i=st(e).filter(a=>a.activityId!==String(t));for(let a of i)r.add(a.activityId);return i}async function Ry(e,t,r,n,i){let{newId:a,newActivity:s,beforeSnap:o,initialTouched:c,correlativeShifts:l}=r,d={name:It.ACTIVITY_CREATION,properties:{parent_id:t.parentId,activity_id:a,created_duration:s.durationHours}};return t.eventSource!==void 0&&(d.properties.event_source=t.eventSource),B(e,{source:t,beforeSnap:o,touchedIds:c,scheduledIds:n,correlativeShifts:l,trackingEvents:[d],hoursPerDay:i})}async function vc(e,t,r){let{adapter:n,scheduler:i,sector:a}=r,s=un(e.overrides,a.hoursPerDay);if(!s.ok)return s;let o=await or({...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:c,recomputeParentsFrom:[c],preventSummaryTargetPullback:!0,now:r.now,options:t})}finally{n.setActivityField(c,"autoScheduling",l)}let{scheduledIds:u}=d;return{ok:!0,changes:await Ry(n,e,o,u,a.hoursPerDay)}}function Ey(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){Ki(e,t),Gi(e,t),$i(e,t)}function Ac(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 Ic(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 Ly(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 wy(e,t,r){let n=e.startDate;return!r||!(n instanceof Date)?{}:{endDate:r(n,t)}}function Be(e){if(e.remainingChildIds.length>0)return null;let t=e.parent,r=e.defaultDurationHours,n=Number.isFinite(r),i=Ly(e.promotionSnapshot)??(n?{type:Ce,durationHours:r,progress:0,autoScheduling:!0,constraintType:"asap",constraintDate:null,hasNewActivities:!1,...wy(t,r,e.computeEndDate)}:{type:Ce});if(e.idsRemoved&&e.idsRemoved.size>0){let a=Array.isArray(t.newActivityIds)?t.newActivityIds:[];if(a.length>0){let s=a.filter(o=>!e.idsRemoved.has(o)&&!e.idsRemoved.has(String(o)));s.length!==a.length&&(i.newActivityIds=s)}}return t.hasLookaheadTasks&&(i.isLookahead=!0),{parentId:String(t.id),fields:i}}function Cc(e){if(e.idsRemoved.size===0)return null;let t=e.parent.newActivityIds;if(!Array.isArray(t)||t.length===0)return null;let r=t,n=r.filter(i=>!e.idsRemoved.has(i)&&!e.idsRemoved.has(String(i)));return n.length===r.length?null:{parentId:String(e.parent.id),fields:{newActivityIds:[...n],hasNewActivities:n.length>0}}}var kc=200;async function Sc(e,t,r){let{adapter:n,scheduler:i,customIdTracker:a,sector:s}=r;if(i.invalidateAllCaches(),e.activityIds.length===0)return{ok:!1,reason:C.ACTIVITY_IDS_EMPTY};for(let A of e.activityIds)if(!n.getActivity(A))return{ok:!1,reason:C.ACTIVITY_NOT_FOUND};let o=e.activityIds.filter(A=>{let T=n.getActivity(A);return!(T?.correlativeId===0&&T.type===Ae.PROJECT)}),c=Ac(o,n),l=Ic(c,n),d=new Set;for(let A of e.activityIds){let T=n.getActivity(A);if(!T)continue;let x=T.parentId;if(L(x))continue;let F=String(x);c.has(F)||d.add(F)}let u=new Set([...c,...d]),f=await z(n,u),p=new Map;for(let A of l){let T=n.getLink(A);T&&p.set(A,{...T})}let h=new Set,g=0;for(let A of c){g+=1,g%kc===0&&await Q();let T=n.getActivity(A);if(!T)continue;let x=L(T.parentId)?null:n.getActivity(String(T.parentId)),F=x?.hasNewActivities===!0&&x.newActivityIds.some(K=>String(K)===String(A));(T.isNewActivity===!0||F)&&h.add(A);let q=T.customId;typeof q=="string"&&q.length>0&&a.releaseCustomId(q)}for(let A of l)n.removeLink(A);let I=qi(n,c),_=0;for(let A of c)_+=1,_%kc===0&&await Q(),n.removeActivity(A);for(let A of d){let T=n.getActivity(A);if(!T)continue;Fy(T,h,n);let x=n.getChildren(A),F=Be({parent:T,remainingChildIds:x.map(String),defaultDurationHours:s.hoursPerDay,promotionSnapshot:n.getPromotionSnapshot(A),computeEndDate:(q,K)=>n.calculateEndDate({startDate:q,durationHours:K,task:T}),idsRemoved:c});if(!F){Nr(A,n);continue}for(let[q,K]of Object.entries(F.fields))rt(n,A,q,K);if(T.customId==null||T.customId===""){let q=Zt(A,n),K=q?n.getActivity(q)?.customId:null,at=a.generateCustomIdForRestoredChild(typeof K=="string"&&K?K:null);n.setActivityField(A,E.CUSTOM_ID,at)}}for(let A of d)Tt(A,n);let v=st(n),{scheduledIds:k}=await Y({adapter:n,scheduler:i,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:"roots",recomputeParentsFrom:d,now:r.now,options:t}),m={name:It.ACTIVITY_DELETION,properties:{activity_ids:[...e.activityIds],cascade_count:c.size}};e.eventSource!==void 0&&(m.properties.event_source=e.eventSource);let b=new Map;for(let[A,T]of p)b.set(A,T);let w=new Map;for(let A of c){let T=f.get(String(A));T&&w.set(String(A),T)}let S=await B(n,{source:e,beforeSnap:f,touchedIds:u,scheduledIds:k,sirDetection:"after-diff",links:xy(p),trackingEvents:[m],hoursPerDay:s.hoursPerDay,correlativeShifts:v});return{ok:!0,changes:I.length>0?{...S,viewState:I}:S,__beforeSnap:w,__beforeLinks:b}}function Fy(e,t,r){let n=Cc({parent:e,idsRemoved:t});if(n)for(let[i,a]of Object.entries(n.fields))rt(r,n.parentId,i,a)}function qi(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 xy(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 _c(e,t,r){let n=Ny(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 z(r.adapter,a):new Map,o=e.mode==="replace"?Yy(r):new Map,c=e.mode==="replace"?qi(r.adapter,a):[];r.scheduler.invalidateAllCaches();let l=[];if(e.mode==="replace"){for(let m of o.keys()){let b=Ht({kind:"delete",linkId:m},{port:r.adapter});if(!b.applied)return{ok:!1,reason:b.rejected??C.INVALID};l.push({op:{kind:"delete",linkId:m},finalLinkId:m,rejected:null})}for(let m of a){let b=r.adapter.getActivity(m)?.customId;typeof b=="string"&&b.length>0&&r.customIdTracker.releaseCustomId(b),r.adapter.removeActivity(m)}}let d=await Vy(e,i.plan.items,r);if(!d.ok)return d;let u=Pc(e)?[]:st(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;$r(r.adapter,u,f,s,h);for(let m of i.plan.items)h.add(String(m.activityId));let g=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=Rr(g,{port:r.adapter,preserved:o});if(!I.applied)return{ok:!1,reason:I.rejected??C.INVALID};for(let{operation:m,linkId:b}of g)l.push({op:m,finalLinkId:b,rejected:null});let _=i.plan.items.map(m=>m.activityId),{scheduledIds:v}=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:_,now:r.now,options:t}),k=await B(r.adapter,{source:e,beforeSnap:s,touchedIds:h,scheduledIds:v,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:Ky(o)}:{}}}function Ny(e,t){if(e.mode!=="append"&&e.mode!=="replace")return C.INVALID;let r=new Set,n=new Set;for(let a of e.items){if(a.batchId.length===0||r.has(a.batchId))return C.INVALID;if(r.add(a.batchId),a.index!==void 0&&(!Number.isInteger(a.index)||a.index<0))return C.INVALID;if(a.activityId!==void 0){let s=String(a.activityId);if(s.length===0||s==="0"||n.has(s))return C.INVALID;n.add(s)}}for(let a of e.items)if(!Ji(a.parent,!0,e.mode,r,t))return C.PARENT_NOT_FOUND;if(My(e.items))return C.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)?C.INVALID_LINK_TYPE:C.INVALID_LINK_LAG;if(!Ji(a.source,!1,e.mode,r,t)||!Ji(a.target,!1,e.mode,r,t))return C.ACTIVITY_NOT_FOUND;if(a.linkId!==void 0){let s=String(a.linkId);if(s.length===0||i.has(s))return C.INVALID;i.add(s)}}return null}function Ji(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){let r=new Map;for(let d of e.items){let u=un(d.overrides,t.sector.hoursPerDay);if(!u.ok)return u;r.set(d.batchId,u.value)}let n=new Map,i=new Set;for(let d of e.items){let u=By(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=jy(d.linkId,e.mode,a,t);return a.add(String(u)),u}),o=Uy(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:C.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:C.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=Tc(u.source,n),p=Tc(u.target,n),h=s[d];if(f===null||p===null||h===void 0)return{ok:!1,reason:C.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 By(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 jy(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 Uy(e,t,r){if(Pc(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)?[]:zi(r.adapter,d).sort((g,I)=>ot(g)-ot(I)||String(g.id).localeCompare(String(I.id))).map(g=>String(g.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?Dc(c[d-1],r):null,p=l<c.length?Dc(c[l],r):null;for(let h=0;h<u;h+=1){let g=c[d+h],I=s.get(g);I!==void 0&&a.set(I,Hy(f,p,h+1,u))}}}return a}function Pc(e){return e.mode==="append"&&e.items.every(t=>t.parent==="0"&&t.index===void 0)}function Dc(e,t){let r=t.adapter.getActivity(e);return r?ot(r):0}function Hy(e,t,r,n){return e!==null&&t!==null&&t>e?e+(t-e)*r/(n+1):e!==null?e+r:t!==null?t-(n-r+1):r-1}async function Vy(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 or({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:C.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 Tc(e,t){return typeof e=="string"?e:t.get(e.batchId)??null}function Yy(e){return new Map(e.adapter.getAllLinks().map(t=>[String(t.id),{...t}]))}function Ky(e){return new Map(Array.from(e,([t,r])=>[String(t),r]))}function bc(e,t){let{adapter:r}=t,n=e.activityId,i=r.getActivity(n);if(!i)return{ok:!1,reason:C.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:C.ACTIVITY_NOT_FOUND};let c={id:n,kind:"updated",fields:{pendingRequestIds:{before:a,after:s}},after:X(o)};return{ok:!0,changes:{source:e,activities:[c],links:[],calendars:[],trackingEvents:[]}}}function Rc(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 Ec(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 Gy(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 Lc(e,t,r,n){let i=new Set,a=new Set;for(let s of e)Gy(s,t,r,n,i,a)}async function wc(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=Ze(t.adapter,n),a=new Set(n);for(let o of i)a.add(String(o));let s=await z(t.adapter,a);return t.adapter.batchUpdate(()=>{for(let o of r){let c=String(o.activityId);t.adapter.setActivityField(c,"progress",o.progress),t.adapter.setActivityField(c,"autoScheduling",te(o.progress))}Os(i,t.adapter),cc(n,i,t.adapter)}),[...await Kr(t.adapter,s,a)]}async function Oc(e,t){let r=e.activities??[],n=e.links??[],i=t.adapter.getAllActivities(),a=t.adapter.getAllLinks(),s=e.checkpoint?.activities??i,o=e.checkpoint?.links??a,c=new Map(s.map(h=>[String(h.id),h])),l=new Map(o.map(h=>[String(h.id),h])),d=Rc(s),u=Rc(o);Lc(r,"activity",h=>{let g=c.get(h);return{exists:g!==void 0,current:g?.proplannerId??null}},d),Lc(n,"link",h=>{let g=l.get(h);return{exists:g!==void 0,current:g?.proplannerId??null}},u),Ec(s,r,"activity"),Ec(o,n,"link");let f=[],p=[];return t.adapter.batchUpdate(()=>{for(let h of r){let g=t.adapter.getActivity(h.id);if(!g||g.proplannerId===h.proplannerId)continue;let I=g.proplannerId;t.adapter.setActivityField(h.id,"proplannerId",h.proplannerId),f.push({id:h.id,kind:"updated",fields:{proplannerId:{before:I,after:h.proplannerId}},after:{...g,proplannerId:h.proplannerId}})}for(let h of n){let g=t.adapter.getLink(h.id);if(!g||g.proplannerId===h.proplannerId)continue;let I=g.proplannerId;t.adapter.setLinkProplannerId(h.id,h.proplannerId),p.push({id:h.id,kind:"updated",fields:{proplannerId:{before:I,after:h.proplannerId}},after:{...g,proplannerId:h.proplannerId}})}}),{ok:!0,changes:{source:e,activities:f,links:p,calendars:[],trackingEvents:[]}}}async function Fc(e,t,r){if($y(e))return{ok:!1,reason:C.INVALID_VALUE};let n=[...new Set(e.activityIds.map(String))];if(e.acknowledgePersistedLookahead===!0&&n.some(o=>!r.isActivityIdReserved(o)))return{ok:!1,reason:C.INVALID};let a=n.map(o=>r.adapter.getActivity(o));if(a.some(o=>!o))return{ok:!1,reason:C.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 wc([{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:e.persistedProgress===0?n[0]: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 $y(e){let t=e.persistedProgress;return t!==void 0&&(e.activityIds.length!==1||!Number.isFinite(t)||t<0||t>100)}function fn(e,t){let r=new Set;for(let i of e)r.add(String(i));let n=[];for(let i of t.getAllLinks()){let a=String(i.source),s=String(i.target);!r.has(a)&&!r.has(s)||(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||L(s))return!1;let o=s;if(o===t)return!0;n=o}return!1}function pn(e,t){let r=e.getAllLinks();return!qe({port:e,currentLinks:r,proposedLinks:r,proposal:{reparented:t}}).ok}function hn(e,t){let r=new Set;if(e.length===0)return r;let n=new Map(e.map(a=>[a.activityId,a.newParentId]));if(!pn(t,n))return r;let i=new Map;for(let a of e){let s=new Map(i);if(s.set(a.activityId,a.newParentId),pn(t,s)){r.add(a.activityId);continue}i.set(a.activityId,a.newParentId)}return r}async function Nc(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:C.ACTIVITY_NOT_FOUND};let o=L(e.parentId);if(!o&&!n.getActivity(e.parentId))return{ok:!1,reason:C.PARENT_NOT_FOUND};if(!o&&(e.parentId===e.activityId||n.isChildOf(e.parentId,e.activityId)))return{ok:!1,reason:C.CANNOT_MOVE_INTO_OWN_DESCENDANT};if(e.afterSiblingId!==void 0&&e.beforeSiblingId!==void 0)return{ok:!1,reason:C.ANCHOR_SIBLING_CONFLICT};let c=e.afterSiblingId??e.beforeSiblingId;if(c!==void 0){let b=n.getActivity(c);if(!b)return{ok:!1,reason:C.ANCHOR_SIBLING_NOT_FOUND};if((b.parentId===null?"0":String(b.parentId))!==e.parentId)return{ok:!1,reason:C.ANCHOR_SIBLING_WRONG_PARENT}}let l=s.parentId,d=jt(l),u=String(e.parentId),f=d!==u;if(f){let b=new Map([[e.activityId,o?null:e.parentId]]);if(pn(n,b))return{ok:!1,reason:C.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 z(n,p);f&&n.setActivityField(e.activityId,E.PARENT,u);let g=ln(n,e.parentId,e.afterSiblingId,e.beforeSiblingId);if(n.setActivityField(e.activityId,E.CORRELATIVE_ID,g),f){if(!o){let b=n.getActivity(e.parentId);if(b){let w=b.customId,S=Ut(b.type)&&n.getChildren(e.parentId).filter(T=>T!==e.activityId).length===0,A=We({parentId:e.parentId,newChildId:e.activityId,getParent:T=>n.getActivity(T)??null,isCurrentlyLeaf:S,promotionSource:"reparent"});if(A){for(let[T,x]of Object.entries(A.fields))rt(n,A.parentId,T,x);A.promotionSnapshot&&n.setPromotionSnapshot(A.parentId,A.promotionSnapshot),A.fields.customId===null&&sn(w,r.customIdTracker)}}}if(d!=="0"){let b=n.getActivity(d);if(b){let w=n.getChildren(d),S=Be({parent:b,remainingChildIds:w.map(String),defaultDurationHours:a.hoursPerDay,promotionSnapshot:n.getPromotionSnapshot(d),computeEndDate:(A,T)=>n.calculateEndDate({startDate:A,durationHours:T,task:b}),idsRemoved:new Set([e.activityId])});if(S){for(let[q,K]of Object.entries(S.fields))rt(n,d,q,K);let A=Zt(d,n),T=A?n.getActivity(A)?.customId:null,x=typeof T=="string"&&T?T:null,F=r.customIdTracker.generateCustomIdForRestoredChild(x);n.setActivityField(d,E.CUSTOM_ID,F)}}}}f&&(d!=="0"&&Tt(d,n),o||Tt(e.parentId,n));let I=st(n);for(let b of I){if(p.add(b.activityId),h.has(b.activityId))continue;let w=n.getActivity(b.activityId);if(!w)continue;let S=X(w);b.before!==void 0&&(S.correlativeId=b.before),h.set(b.activityId,S)}let _=f&&d!=="0"?n.getChildren(d).map(String):[],{scheduledIds:v}=await Y({adapter:n,scheduler:i,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:e.activityId,recomputeParentsFrom:[e.activityId,e.parentId,..._],now:r.now,options:t,recomputeParentProgress:f}),k=f?fn([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:v,sirDetection:"before-diff",trackingEvents:[m],hoursPerDay:a.hoursPerDay})}}function yn(e,t){let r=new Set(e),n=[],i=[],a=new Set,s=new Set(r),o=[...e].sort((d,u)=>{let f=t.getActivity(d),p=t.getActivity(u),h=f?ot(f):le,g=p?ot(p):le;return h-g});for(let d of o){if(!t.getActivity(d)){n.push({activityId:d,reason:C.ACTIVITY_NOT_FOUND}),s.delete(d);continue}if(dn(d,a,t))continue;let f=za(d,s,t);if(f==null){n.push({activityId:d,reason:C.INDENT_NO_ELIGIBLE_SIBLING}),s.delete(d);continue}let p=t.getActivity(d)?.parentId,h=L(p)?"0":String(p);i.push({activityId:d,newParentId:f,oldParentId:h}),a.add(d)}let c=hn(i,t);for(let d of c)n.push({activityId:d,reason:C.HIERARCHY_CYCLE});let l=i.filter(d=>!c.has(d.activityId));return{moves:i,cyclicMoveIds:c,allowedMoves:l,failed:n}}async function Mc(e,t,r){let{adapter:n,scheduler:i,sector:a}=r;if(i.invalidateAllCaches(),e.activityIds.length===0)return{ok:!1,reason:C.ACTIVITY_IDS_EMPTY};let s=new Set,o=[],c=yn(e.activityIds,n),l=[...c.failed];for(let v of c.moves)s.add(String(v.activityId)),s.add(String(v.newParentId)),v.oldParentId!=="0"&&s.add(String(v.oldParentId));let d=c.allowedMoves,u=await z(n,s);for(let{activityId:v,newParentId:k}of d)n.setActivityField(v,E.PARENT,k),n.setActivityField(v,E.CORRELATIVE_ID,yc),o.push(v);let f=new Set;for(let{activityId:v,newParentId:k}of d){if(f.has(k))continue;f.add(k);let m=n.getActivity(k);if(!m)continue;let b=m.customId,w=Ut(m.type)&&n.getChildren(k).filter(T=>!o.includes(T)).length===0,S=m.hasNewActivities&&m.newActivityIds.some(T=>String(T)===String(v)),A=We({parentId:k,newChildId:v,getParent:T=>n.getActivity(T)??null,isCurrentlyLeaf:w,promotionSource:"reparent"});if(A){for(let[T,x]of Object.entries(A.fields))rt(n,A.parentId,T,x);A.promotionSnapshot&&n.setPromotionSnapshot(A.parentId,A.promotionSnapshot),S||(n.setActivityField(k,E.HAS_NEW_ACTIVITIES,!1),n.setActivityField(k,E.NEW_ACTIVITIES_ARRAY,[]))}n.setActivityField(k,E.CONSTRAINT_TYPE,"asap"),n.setActivityField(k,E.CONSTRAINT_DATE,null),n.setActivityField(k,E.CUSTOM_ID,null),sn(b,r.customIdTracker)}let p=new Set;for(let v of d)v.oldParentId!=="0"&&p.add(v.oldParentId),p.add(v.newParentId);for(let v of p)Tt(v,n);let h=st(n);for(let v of h){if(s.add(v.activityId),u.has(v.activityId))continue;let k=n.getActivity(v.activityId);if(!k)continue;let m=X(k);v.before!==void 0&&(m.correlativeId=v.before),u.set(v.activityId,m)}let{scheduledIds:g}=await Y({adapter:n,scheduler:i,sector:r.sector,defaultBaseCalendarId:r.defaultBaseCalendarId},{action:e,autoscheduleFrom:null,recomputeParentsFrom:o,now:r.now,options:t}),I=fn(o,n),_={name:It.ACTIVITY_INDENT,properties:{activity_ids:o,failed:l.map(v=>({activity_id:v.activityId,reason:v.reason})),invalid_link_ids:I}};return e.eventSource!==void 0&&(_.properties.event_source=e.eventSource),{ok:!0,activityVerdicts:e.activityIds.map(v=>{let k=l.find(m=>String(m.activityId)===String(v));return k?{activityId:String(v),ok:!1,reason:k.reason}:{activityId:String(v),ok:!0}}),changes:await B(n,{source:e,beforeSnap:u,touchedIds:s,scheduledIds:g,trackingEvents:[_],hoursPerDay:a.hoursPerDay})}}async function Wc(e,t,r){let{adapter:n,scheduler:i,sector:a}=r;if(i.invalidateAllCaches(),e.activityIds.length===0)return{ok:!1,reason:C.ACTIVITY_IDS_EMPTY};let s=new Set(e.activityIds),o=new Map,c=new Map;for(let S of e.activityIds){let A=S;n.getActivity(A)&&(o.set(A,$n(A,n)),c.set(A,mc(A,s,n)))}let l=new Set,d=[],u=[],f=new Set,p=[],h=new Set,g=[...e.activityIds].sort((S,A)=>{let T=n.getActivity(S),x=n.getActivity(A),F=T?ot(T):le,q=x?ot(x):le;return F-q});for(let S of g){let A=S,T=n.getActivity(A);if(!T){d.push({activityId:A,reason:C.ACTIVITY_NOT_FOUND});continue}if(dn(A,h,n))continue;let x=T.parentId;if(L(x)){d.push({activityId:A,reason:C.OUTDENT_ROOT_LEVEL_NOT_EDITABLE});continue}let F=String(x),q=n.getActivity(F);if(!q){d.push({activityId:A,reason:C.ACTIVITY_NOT_FOUND});continue}let K=q.parentId;if(L(K)){d.push({activityId:A,reason:C.OUTDENT_ROOT_LEVEL_NOT_EDITABLE});continue}let at=String(K),pt=$n(F,n)+1,nt=c.get(A);if(nt!=null&&s.has(nt)){let pe=o.get(nt)??-1,he=o.get(A)??-1;pe>=0&&he>=0&&(pt+=he-pe)}p.push({activityId:A,grandparentKey:at,oldParentKey:F,targetIndexInGrandparent:pt}),h.add(A),l.add(String(A)),l.add(String(F)),at!=="0"&&l.add(String(at)),f.add(F)}let I=hn(p.map(S=>({activityId:S.activityId,newParentId:S.grandparentKey})),n);for(let S of I)d.push({activityId:S,reason:C.HIERARCHY_CYCLE});let _=p.filter(S=>!I.has(S.activityId)),v=await z(n,l);for(let S of _){n.setActivityField(S.activityId,E.PARENT,S.grandparentKey);let A=gc(n,S.grandparentKey,S.targetIndexInGrandparent,S.activityId);n.setActivityField(S.activityId,E.CORRELATIVE_ID,A),u.push(S.activityId)}for(let S of f){let A=n.getActivity(S);if(!A)continue;let T=n.getChildren(S),x=Be({parent:A,remainingChildIds:T.map(String),defaultDurationHours:a.hoursPerDay,promotionSnapshot:n.getPromotionSnapshot(S),computeEndDate:(pt,nt)=>n.calculateEndDate({startDate:pt,durationHours:nt,task:A}),idsRemoved:new Set(_.filter(pt=>pt.oldParentKey===S).map(pt=>pt.activityId))});if(!x){Nr(S,n);continue}for(let[pt,nt]of Object.entries(x.fields))rt(n,S,pt,nt);let F=Zt(S,n),q=F?n.getActivity(F)?.customId:null,K=typeof q=="string"&&q?q:null,at=r.customIdTracker.generateCustomIdForRestoredChild(K);n.setActivityField(S,E.CUSTOM_ID,at)}let k=new Set;for(let S of f)k.add(String(S));for(let S of _)S.grandparentKey!=="0"&&k.add(String(S.grandparentKey));for(let S of k)Tt(S,n);let m=st(n);for(let S of m){if(l.add(S.activityId),v.has(S.activityId))continue;let A=n.getActivity(S.activityId);if(!A)continue;let T=X(A);S.before!==void 0&&(T.correlativeId=S.before),v.set(S.activityId,T)}let{scheduledIds:b}=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(S=>({activity_id:String(S.activityId),reason:S.reason}))}};return e.eventSource!==void 0&&(w.properties.event_source=e.eventSource),{ok:!0,activityVerdicts:e.activityIds.map(S=>{let A=d.find(T=>String(T.activityId)===String(S));return A?{activityId:String(S),ok:!1,reason:A.reason}:{activityId:String(S),ok:!0}}),changes:await B(n,{source:e,beforeSnap:v,touchedIds:l,scheduledIds:b,trackingEvents:[w],hoursPerDay:a.hoursPerDay})}}async function Bc(e,t,r){let{adapter:n,ctx:i,scheduler:a,sector:s}=r;if(e.newValue!==0&&e.newValue!==100)return{ok:!1,reason:C.INVALID_PROGRESS_VALUE};let o=i.activityReader.getActivity(e.activityId);if(!o)return{ok:!1,reason:C.ACTIVITY_NOT_FOUND};let c=zt(P.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=qt(e.activityId,d),f=await z(n,u);Jt(n,e.activityId,d),xs(e.activityId,e.newValue,n),Yt(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:g=>Gr(e.activityId,u,g),now:r.now,options:t}),h=(d.trackingEvents??[]).map(g=>({name:g.name,properties:g.properties??{}}));return{ok:!0,changes:await B(n,{source:e,beforeSnap:f,touchedIds:u,scheduledIds:p,trackingEvents:h,hoursPerDay:s.hoursPerDay})}}async function jc(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 g=zy(h,r);if(s.push(g.verdict),!g.verdict.ok||!g.changes)continue;let I=qt(h.activityId,g.changes);qy(o,I,r);for(let m of I)c.add(m);let _=Ne(n,h.activityId),v=Yr(n,String(h.activityId));Jt(n,h.activityId,g.changes),Yt(h.activityId,g.changes.postProcessors??[],n,v),d.push(...Me(_,n,h.activityId)),f||=!!g.changes.needsAutoSchedule;for(let m of g.changes.trackingEvents??[])l.push({name:m.name,properties:m.properties??{}});let k=Le(h.activityId,g.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 zy(e,t){let{ctx:r}=t,n=e.activityId,i=zt(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??C.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??C.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??C.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 qy(e,t,r){let n=new Set;for(let i of t)e.has(i)||n.add(i);if(n.size!==0)for(let i of n){let a=r.adapter.getActivity(i);a&&e.set(i,X(a))}}var Xi=P.CUSTOM_ID;async function Uc(e,t,r){let{adapter:n,scheduler:i,sector:a}=r;e.edits.some(k=>k.column===P.DURATION)&&i.invalidateExpandedLinksCache();let o=[],c=new Map,l=new Map,d=new Set,u=new Set,f=[],p=[],h=[],g=!1;for(let k of e.edits){let m=Jy(k,r);if(o.push(m.verdict),!m.verdict.ok||!m.changes)continue;let b=Le(k.activityId,m.changes.constraintWarning);b&&h.push(b);let w=qt(k.activityId,m.changes);tm(c,w,r);for(let F of w)u.add(F);Qy(l,k,c),rn(k.column)&&d.add(String(k.activityId));let S=Ne(n,k.activityId),A=Yr(n,String(k.activityId)),T=Xy(k,r),x=m.changes;Jt(n,k.activityId,x),Yt(k.activityId,m.changes.postProcessors??[],n,A),Zy(k,T,r),p.push(...Me(S,n,k.activityId)),g||=!!m.changes.needsAutoSchedule;for(let F of m.changes.trackingEvents??[])f.push({name:F.name,properties:F.properties??{}})}let I={action:e,autoscheduleFrom:g?"roots":null,recomputeParentsFrom:u,now:r.now,options:t},_=l.size>0,{scheduledIds:v}=await(_?an({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)=>nn(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:v,sirDetection:"before-diff",links:p,trackingEvents:f,warnings:h,hoursPerDay:a.hoursPerDay})}}function Jy(e,t){let{ctx:r}=t,n=e.activityId,i=zt(e.column);if(!i)return{verdict:{activityId:n,ok:!1,reason:C.NO_PIPELINE_FOR_COLUMN},changes:null};let a=r.activityReader.getActivity(e.activityId);if(!a)return{verdict:{activityId:n,ok:!1,reason:C.ACTIVITY_NOT_FOUND},changes:null};let s=i.canEdit(a,r.hierarchy);if(!s.allowed)return{verdict:{activityId:n,ok:!1,reason:s.reason??C.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??C.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??C.INVALID,...l.notification?.messageKey?{alertKey:l.notification.messageKey}:{}},changes:null};if(e.column===Xi&&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:C.CUSTOM_ID_DUPLICATE},changes:null}}let d=i.transform(a,o.value,r,o.raw);return{verdict:{activityId:n,ok:!0},changes:d}}function Xy(e,t){if(e.column!==Xi)return null;let r=t.adapter.getActivity(e.activityId),n=r?r.customId:null;return typeof n=="string"?n:null}function Zy(e,t,r){if(e.column!==Xi)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 Qy(e,t,r){if(!en(t.column))return;let n=String(t.activityId);if(e.has(n))return;let i=r.get(n);i&&e.set(n,i.constraintDate??null)}function tm(e,t,r){let n=new Set;for(let i of t)e.has(i)||n.add(i);if(n.size!==0)for(let i of n){let a=r.adapter.getActivity(i);a&&e.set(i,X(a))}}function Hc(e){return typeof e=="string"&&e.length>0?Mt(e):e instanceof Date?e:null}function Zi(e){let t=typeof e=="number"?e:typeof e=="string"&&e.trim()!==""?Number(e):Number.NaN;return!Number.isFinite(t)||t<0?null:t}function mn(e,t){let r=Zi(e.duration),n=Zi(e.cost),i=Zi(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:Hc(e.start_date),endDate:Hc(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 Vc(e,t,r){let n=new Map;e.forEachActivity((s,o)=>{let c=s.proplannerId;typeof c=="number"&&n.set(c,o)});let i=new Map;for(let s of t){let o=s.activityId;if(typeof o!="number")continue;let c=n.get(o);if(c===void 0)continue;let l=i.get(c);l?l.push(s):i.set(c,[s])}let a=[];for(let[s,o]of i)e.setActivityField(s,"baselinePoints",o.map(c=>mn(c,r)).filter(c=>c!==null)),a.push(s);return e.forEachActivity((s,o)=>{if(i.has(o))return;let c=s.baselinePoints;Array.isArray(c)&&c.length>0&&(e.setActivityField(o,"baselinePoints",[]),a.push(o))}),a}function em(e){let t=ut(e);return t?{startDate:t.startDate,endDate:t.endDate,durationDays:t.durationDays,cost:t.cost,workHours:t.workHours}:null}function Yc(e){let t=[];return e.forEachActivity((r,n)=>{let i=em(r);if(!i){r.baselineSnapshot!==null&&(e.setActivityField(n,"baselineSnapshot",null),t.push(n));return}e.setActivityField(n,"baselineSnapshot",i),t.push(n)}),t}function gn(e,t,r,n,i=null){let a=new Set;for(let s of Vc(e,t,n))a.add(s);if(r)for(let s of Oe(e,r,i))a.add(s);for(let s of Yc(e))a.add(s);for(let s of Fe(e))a.add(s);return[...a]}function Kc(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=rm(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,P.PONDERATOR,s*u)}else(!Array.isArray(l)||l.length===0)&&r.setActivityField(o,P.PONDERATOR,0)}}function rm(e,t,r){let n=r.getActivity(e);if(!n)return 0;let i=ut(n);if(!i)return 0;if(t==="COST")return vn(i.cost);if(t==="HH")return vn(i.workHours);let a=n.type;return a==="project"?Gc(e,r):a==="milestone"?0:vn(i.durationDays)}function Gc(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+=Gc(String(n),t):s!=="milestone"&&(r+=vn(a.durationDays))}return r}function vn(e){let t=typeof e=="string"?parseFloat(e):e;return typeof t=="number"&&Number.isFinite(t)?t:0}function $c(e,t){t.forEachActivity((r,n)=>{t.setActivityField(n,P.PONDERATOR,0)}),t.forEachActivity((r,n)=>{t.getChildren(n).length>0&&Kc(String(n),e,t)})}function An(e,t){$c(t,e.adapter),Xe(e.adapter),e.now&&(Oe(e.adapter,e.now,e.defaultBaseCalendarId??null),ae(e.adapter,e.now)),Fe(e.adapter),e.now&&Wt(e.adapter,e.sector.statusCriteria)}function zc(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 qc(e,t){let r=await z(t.adapter,new Set(t.adapter.getAllIds())),n=zc(t),i=gn(t.adapter,e.points,t.now,t.reporter,t.defaultBaseCalendarId??null);return zc(t)!==n&&An(t,t.sector.activityCreter??"DURATION"),{ok:!0,changes:await B(t.adapter,{source:e,beforeSnap:r,touchedIds:i,scheduledIds:[],hoursPerDay:t.sector.hoursPerDay})}}function nm(e){if(!(e==="DURATION"||e==="COST"||e==="HH"))throw new Error(`ponderator-criterion-set: invalid criterion "${String(e)}"`)}async function Jc(e,t){nm(e.criterion);let r=new Set(t.adapter.getAllIds()),n=await z(t.adapter,r);return An(t,e.criterion),t.sector.activityCreter=e.criterion,{ok:!0,changes:await B(t.adapter,{source:e,beforeSnap:n,touchedIds:r,scheduledIds:[],hoursPerDay:t.sector.hoursPerDay})}}async function Xc(e,t){let r=zr(e.criteria),n=new Set(t.adapter.getAllIds()),i=await z(t.adapter,n),a=Wt(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 Zc=["name","description","type","startDate","durationHours","constraintType","constraintDate","calendarId","cost","hasCustomPonderator","subcontractId","responsableIds","tagIds"];function im(e){let t={};for(let r of Zc)Object.assign(t,{[r]:R(e[r])});return t}function am(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 Qc(e,t){let r=new Set(t.adapter.checkedIds().map(String));if(r.size===0)return{ok:!1,reason:C.NO_ACTIVITY_SELECTION};let n=am(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:im(s)}}),links:t.adapter.getAllLinks().filter(a=>r.has(String(a.source))&&r.has(String(a.target))).map(a=>R(a))};let i=hr({kind:"selection-replace",activityIds:[]},{adapter:t.adapter});return i.ok?{...i,changes:{...i.changes,source:e}}:i}function tl(e,t){return t.value=null,{ok:!0,changes:{source:e,activities:[],links:[],calendars:[],trackingEvents:[]}}}function sm(e,t){let r=t.getActivity(e);return r?r.parentId==null?t.getRootIds().length===1?{ok:!0,parentId:r.id}:{ok:!0,parentId:"0",afterSiblingId:e}:{ok:!0,parentId:String(r.parentId),afterSiblingId:e}:{ok:!1,reason:C.ANCHOR_SIBLING_NOT_FOUND}}var el=()=>({ok:!1,reason:C.ACTIVITY_PASTE_INVARIANT_FAILED});async function rl(e,t,r){let n=r.activityClipboard.value;if(n===null)return{ok:!1,reason:C.CLIPBOARD_EMPTY};let i=sm(e.destination.afterSiblingId,r.adapter);if(!i.ok)return i;let a=await z(r.adapter,new Set),s=new Set,o=new Map,c=[],l;for(let g of n.activities){let I=o.get(g.originalParentId),_=I===void 0?l??i.afterSiblingId:void 0,v=await or({kind:"activity-create",parentId:I??i.parentId,..._===void 0?{}:{afterSiblingId:_},overrides:R(g.overrides),eventSource:e.eventSource},r,{skipCorrelativeRecompute:!0,skipBeforeSnap:!0,customIdReferenceId:e.destination.afterSiblingId});if(!v.ok)return v;o.set(g.originalId,v.newId),c.push(v.newId),I===void 0&&(l=v.newId)}let d=st(r.adapter),u=new Set(c.map(String));$r(r.adapter,d,u,a,s);for(let g of c)s.add(String(g));let f=[];for(let g of n.links){let I=o.get(g.source),_=o.get(g.target);if(I===void 0||_===void 0)return el();let v={kind:"create",source:I,target:_,type:g.type,lag:g.lag},k=Ht(v,{port:r.adapter,newLinkId:r.linkIdGen.next});if(!k.applied)return el();f.push({op:v,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 nl(e,t,r){return e.kind==="activity-copy"?Qc(e,{adapter:r.adapter,clipboard:r.activityClipboard}):e.kind==="activity-clipboard-clear"?tl(e,r.activityClipboard):e.kind==="activity-paste-copied"?rl(e,t,r):e.kind==="activity-batch"?_c(e,t,r):e.kind==="persistence-acknowledge"?Oc(e,r):e.kind==="baseline-apply"?qc(e,r):e.kind==="ponderator-criterion-set"?Jc(e,r):e.kind==="status-criteria-set"?Xc(e,r):e.kind==="link-create"||e.kind==="link-update"||e.kind==="link-delete"?ec(e,t,r):e.kind==="links-batch"?rc(e,t,r):e.kind==="activity-create"?vc(e,t,r):e.kind==="activity-delete"?Sc(e,t,r):e.kind==="activity-move"?Nc(e,t,r):e.kind==="activity-indent"?Mc(e,t,r):e.kind==="activity-outdent"?Wc(e,t,r):e.kind==="activity-set-progress"?Bc(e,t,r):e.kind==="dates-batch"?jc(e,t,r):e.kind==="bulk-edit"?Uc(e,t,r):e.kind==="selection-toggle"?Na(e,Qi(r)):e.kind==="selection-replace"?hr(e,Qi(r)):e.kind==="visibility-set"?Ma(e,Qi(r)):e.kind==="filter-set"?Ka(e,{adapter:r.adapter,hoursPerDay:r.sector.hoursPerDay}):e.kind==="sort-set"?Ja(e,{adapter:r.adapter}):e.kind==="sir-sync"?bc(e,r):e.kind==="activity-lookahead-sync"?Fc(e,t,r):e.kind==="inline-edit"&&(e.column===P.CUSTOM_PREDECESSORS||e.column===P.CUSTOM_SUCESSORS)?nc(e,t,r):e.kind!=="inline-edit"?Xa(e,`[ScheduleCore] dispatch kind "${e.kind}" not supported yet`):tc(e,t,r)}function Qi(e){return{adapter:e.adapter}}var om=new Set(["startDate","endDate","constraintDate"]);function il(e,t){return om.has(e)&&typeof t=="string"?new Date(t):t}function al(e,t={}){let r=t.defaultUnit??"hour";return{getCalendar(n){let i=e.getCalendar(String(n));return i?cm(i,r):null}}}function cm(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 lm(e){return Array.isArray?Array.isArray(e):e&&e.length!==void 0&&e.pop&&e.push}function de(e){return e&&typeof e=="object"?!!(e.getFullYear&&e.getMonth&&e.getDate):!1}function ue(e){return de(e)&&!isNaN(e.getTime())}var dm={}.constructor.toString();function um(e){var t=e.constructor.toString();return t!==dm}function fm(e){return e.$$typeof&&e.$$typeof.toString().includes("react.")}function _t(e){var t,r;if(e&&typeof e=="object")switch(!0){case de(e):r=new Date(e);break;case lm(e):for(r=new Array(e.length),t=0;t<e.length;t++)r[t]=_t(e[t]);break;default:if(um(e))r=Object.create(e);else{if(fm(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 je(e,t,r){for(var n in t)(e[n]===void 0||r)&&(e[n]=t[n]);return e}function sl(e){return typeof e<"u"}var In;function ta(){return In||(In=new Date().valueOf()),In++,In}function mt(e,t){return e.bind?e.bind(t):function(){return e.apply(t,arguments)}}var hm=(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)},ym=(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)},ol={date_to_str:hm,str_to_date:ym},mm=(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}}),gm=(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])},cl={date_to_str:mm,str_to_date:gm};function ll(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=ol;return a()&&(l=cl),l.date_to_str(o,c,e)},str_to_date:function(o,c){var l=ol;return a()&&(l=cl),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 ea(e,t,r,n,i){return this.date=e,this.unit=t,this.task=r,this.id=n,this.calendar=i,this}function ra(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 na(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 vm(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 dl=function(e){return{getWorkHoursArguments:function(){var t=arguments[0];if(de(t)?t={date:t}:t=je({},t),!ue(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 ea)return t;var r;if(t.date?r=new ea(t.date,t.unit,t.task,null,t.calendar):r=new ea(arguments[0],arguments[1],arguments[2],null,arguments[3]),r.unit=r.unit||e.config.duration_unit,!ue(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 ra)return r;var n;if(de(r)?n=new ra(r):n=new ra(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,!ue(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=vm,n;if(t instanceof r)return t;if(de(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,!ue(n.start_date))throw e.assert(!1,"Invalid start_date argument for getDuration method"),new Error("Invalid start_date argument for getDuration method");if(!ue(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 na)return a;var s;if(de(a)?s=new na(arguments[0],arguments[1],arguments[2],void 0,arguments[3],void 0,arguments[4]):s=new na(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,!ue(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 ul(){}ul.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 g=Array.isArray(h)?h:d.hours;s.dates[u]=this._toHoursArray(this._mergeHoursConfig(f,g))}}}};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 ia=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}},aa=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={}}},sa=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 Am(){return typeof Map<"u"?new ia:new aa}var oa=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 ca(e,t){this.argumentsHelper=t,this.$gantt=e,this._workingUnitsCache=Am(),this._largeUnitsCache=new sa(this),this._dateDurationCache=new oa,this._worktime=null,this._cached_timestamps={},this._cached_timestamps_count=0}ca.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),g=this.units[h-1];g&&!this._isWorkTime(a,g)&&(c=this._getClosestWorkTimeFuture(a,g))}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 ca))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 g=!1,I=null,_=null,v=c.length-1;v>=0;v--)if(c[v].start<h-1&&c[v].end>=h-1){g=!0,I=c[v],_=c[v-1];break}if(g)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,_?n=new Date(Date.UTC(n.getUTCFullYear(),n.getUTCMonth(),n.getUTCDate(),0,0,_.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"),b=this._getWorkHours(m);if(b.length){var w=b[b.length-1];m.setUTCSeconds(w.durationSeconds)}}n=m}else n=this._getClosestWorkTimePast(new Date(n-1),"hour")}if(i<t){var S=t-i;s=this._subtractMinutesUntilHourStart(n,S),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,g=0;g<o.length;g++)if(o[g].start<=f&&o[g].end>f){p=!0,h=o[g];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-i;a=this._addMinutesUntilHourEnd(n,_),i+=a.added,n=a.end}return n},getClosestWorkTime:function(){var e=this.argumentsHelper.getClosestWorkTimeArguments.apply(this.argumentsHelper,arguments);return this._getClosestWorkTime(e.date,e.unit,e.dir)},_getClosestWorkTime:function(e,t,r){var n=new Date(e);if(this._isWorkTime(n,t))return n;if(n=this.$gantt.date[t+"_start"](n),r=="any"||!r){var i=this._getClosestWorkTimeFuture(n,t),a=this._getClosestWorkTimePast(n,t);Math.abs(i-e)<=Math.abs(e-a)?n=i:n=a}else r=="past"?n=this._getClosestWorkTimePast(n,t):n=this._getClosestWorkTimeFuture(n,t);return n},_getClosestWorkTimeFuture:function(e,t){return this._getClosestWorkTimeGeneric(e,t,1)},_getClosestWorkTimePast:function(e,t){var r=this._getClosestWorkTimeGeneric(e,t,-1);return this.$gantt.date.add(r,1,t)},_findClosestTimeInDay:function(e,t,r){var n=new Date(e),i=null,a=!1;this._getWorkHours(n).length||(n=this._getClosestWorkTime(n,"day",t<0?"past":"future"),t<0&&(n=new Date(n.valueOf()-1),a=!0),r=this._getWorkHours(n));var s=this._getTimeOfDayStamp(n);if(a&&(s=this._getTimeOfDayStamp(new Date(n.valueOf()+1),a)),t>0){for(var o=0;o<r.length;o++)if(r[o].start>=s){i=new Date(Date.UTC(n.getUTCFullYear(),n.getUTCMonth(),n.getUTCDate(),0,0,r[o].start));break}}else for(var o=r.length-1;o>=0;o--)if(r[o].end<=s){i=new Date(Date.UTC(n.getUTCFullYear(),n.getUTCMonth(),n.getUTCDate(),0,0,r[o].end));break}else if(r[o].end>s&&r[o].start<=s){i=new Date(Date.UTC(n.getUTCFullYear(),n.getUTCMonth(),n.getUTCDate(),0,0,s));break}return i},_getClosestWorkMinute:function(e,t,r){var n=new Date(e),i=this._getWorkHours(n),a=this._findClosestTimeInDay(n,r,i);return a||(r>0?(n=this.calculateEndDate(n,r,t),n=this.$gantt.date.day_start(n)):(n=this.calculateEndDate(n,r,"day"),n=this.$gantt.date.day_start(n),n=this.$gantt.date.add(n,1,"day"),n=new Date(n.valueOf()-1)),i=this._getWorkHours(n),a=this._findClosestTimeInDay(n,r,i)),r<0&&(a=this.$gantt.date.add(a,-1,t)),a},_getClosestWorkTimeGeneric:function(e,t,r){if(t==="hour"||t==="minute")return this._getClosestWorkMinute(e,t,r);for(var n=this._getUnitOrder(t),i=this.units[n-1],a=e,s=3e3,o=0;!this._isWorkTime(a,t)&&!(i&&!this._isWorkTime(a,i)&&(r>0?a=this._getClosestWorkTimeFuture(a,i):a=this._getClosestWorkTimePast(a,i),this._isWorkTime(a,t)));){if(o++,o>s)return this.$gantt.assert(!1,"Invalid working time check"),!1;a=this.$gantt.date.add(a,r,t),this.$gantt.date[t+"_start"]&&(a=this.$gantt.date[t+"_start"](a))}return a},hasWorkTime:function(){var e=this.getConfig(),t=e.dates,r=[0,1,2,3,4,5,6];for(var n in e.dates);var i=this._checkWorkHours(e.hours),a=!1;return r.forEach((function(s){if(!a){var o=t[s];o===!0?a=i:Array.isArray(o)&&(a=this._checkWorkHours(o))}}).bind(this)),a},_checkWorkHours:function(e){if(e.length===0)return!1;for(var t=!1,r=0;r<e.length;r+=2)e[r]!==e[r+1]&&(t=!0);return t},_isMinutePrecision:function(e){let t=!1;return this._getWorkHours(e).forEach(function(r){(r.startMinute%60||r.endMinute%60)&&(t=!0)}),t}};var cr={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 Cm=Im();function fl(e){this.$gantt=e,this._calendars={},this._legacyConfig=void 0,this.$gantt.attachEvent("onGanttReady",(function(){this.$gantt.config.resource_calendars&&(this._isLegacyConfig=cr.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))}fl.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 ul,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 ca(this.$gantt,dl(this.$gantt));t.id=String(ta());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 je(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=cr.getResourceProperty(t),Array.isArray(e[i])&&e[i].length)t.dynamic_resource_calendars?n=Cm.getCalendarIdFromMultipleResources(e[i],this):r=this.getResourceCalendar(e[i]);else if(this._legacyConfig===void 0&&(this._legacyConfig=cr.isLegacyResourceCalendarFormat(t.resource_calendars)),this._legacyConfig)var n=cr.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=cr.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||ta(),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 la(e,t){this.argumentsHelper=t,this.$gantt=e}la.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 la},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 pl(e){this.$gantt=e.$gantt,this.argumentsHelper=dl(this.$gantt),this.calendarManager=e,this.$disabledCalendar=new la(this.$gantt,this.argumentsHelper)}pl.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: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)}},Sm={create:km};function hl(e){var t=new fl(e),r=new pl(t),n=Sm.create(t,r);je(e,n)}var yl={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 ml(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||yl,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:sl,mixin:je,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=ll(r),r.date.init(),hl(r),r}function Dm(e={}){let t=ml(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 gl={createCalendar:Dm};var wO=3600*1e3;function Cl(e){return{getActivity(t){return e.getActivity(t)}}}var{createCalendar:Tm}=gl,lr="__replay_default__";function _m(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 vl={hours:["8:00-16:00"],days:[!1,!0,!0,!0,!0,!0,!1]},Al="__main_global__",Pm={hours:["8:00-12:00","13:00-17:00"],days:[!1,!0,!0,!0,!0,!0,!1]};function Il(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 bm(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:_m(e.hours),dates:t};return e.customWeeks&&(r.customWeeks=e.customWeeks),r}function kl(e){let t=Tm({config:{work_time:!0}});t.addCalendar({id:lr,worktime:vl}),t.addCalendar({id:Al,worktime:Pm});let r=new Set(e.filter(d=>!Il(d.worktime)).map(d=>String(d.id))),n=e.filter(d=>Il(d.worktime));for(let d of n)t.addCalendar({id:d.id,worktime:d.worktime?bm(d.worktime):vl});let i=al(t),a=i.getCalendar(lr),s=i.getCalendar(Al);if(!a||!s)throw new Error("[replay-calendar] fallback calendars failed to register in work-calendar instance");let o=new Set([lr]);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 Sl(e){return{hasChildren(t){return e.hasChildren(t)},getParentStartDateIfHasPredecessors(t){let r=e.getActivity(t);if(!r)return null;let n=e.getParent(r.id);return!n||e.getIncomingLinkIds(n.id).length===0?null:n.startDate},getDescendantIds(t){return Rm(e,t).map(r=>String(r))},getAncestorIds(t){let r=[],n=e.getActivity(t);for(;n;){let i=n.parentId;if(i===null)break;let a=e.getActivity(i);if(!a)break;r.push(String(i)),n=a}return r},getChildProgressInfo(t){return e.getChildren(t).map(n=>{let i=e.getActivity(n);return{id:n,progress:Number(i?.progress??0),ponderator:Number(i?.ponderator??0)}})},getChildHhInfo(t){return e.getChildren(t).map(n=>{let i=e.getActivity(n);return{id:n,workHours:Number(i?.workHours??0),progress:Number(i?.progress??0),realWorkHours:Number(i?.realWorkHours??0)}})},getChildUsedCostInfo(t){return e.getChildren(t).map(n=>{let i=e.getActivity(n);return{id:n,usedCost:Number(i?.usedCost??0)}})},getChildCostInfo(t){return e.getChildren(t).map(n=>{let i=e.getActivity(n);return{id:n,cost:Number(i?.cost??0)}})}}}function Rm(e,t){let r=[],n=new 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 Cn=class{_journal=null;begin(){this._journal={dirty:new Set,before:new Map,ops:[],linkFieldCaptured:new Set,correlativeBefore:new Map,scheduledBefore:new Map,progressFallbackBefore:new Map}}peek(){return this._journal}end(){this._journal=null}note(t,r){let n=this._journal;n&&(n.before.has(t)||n.before.set(t,Nt(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:Nt(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:Dl(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=Nt(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:Dl(r)}))}noteProgressFallback(t,r){let n=this._journal;!n||n.progressFallbackBefore.has(t)||n.progressFallbackBefore.set(t,r)}};function Dl(e){return{...e}}var kn=class{_cache={closestWorkTime:new Map,endDate:new Map,duration:new Map};reader;constructor(t){this.reader=t.reader}resolveCalendar(t){let r=Tl(t);return this.reader.getCalendar(r??lr)}getClosestWorkTime(t){let r=`${ua(t.task)}|${t.dir}|${t.date.getTime()}`;return da(this._cache.closestWorkTime,r,()=>this.resolveCalendar(t.task).getClosestWorkTime({direction:t.dir,date:t.date,unit:ct.HOUR}))}calculateEndDate(t){let r=`${ua(t.task)}|${t.startDate.getTime()}|${t.durationHours}`;return da(this._cache.endDate,r,()=>this.resolveCalendar(t.task).calculateEndDate(t.startDate,t.durationHours))}calculateDuration(t){let r=`${ua(t.task)}|${t.startDate.getTime()}|${t.endDate.getTime()}`;return da(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 da(e,t,r){let n=e.get(t);if(n!==void 0)return n;let i=r();return e.set(t,i),i}var Em="__default__";function Tl(e){if(!e)return null;let t=e.calendarId;return t==null?null:String(t)}function ua(e){return Tl(e)??Em}var Sn=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?mr(i,a):String(r).localeCompare(String(n))};this._roots.sort(t);for(let r of this._childrenByParent.values())r.sort(t)}};var Dn=class{checkedSet=new Set;hiddenSet=new Set;activeFilter=null;activeOrder=null;isChecked(t){return this.checkedSet.has(t)}isVisible(t){return!this.hiddenSet.has(t)}hiddenIds(){return[...this.hiddenSet]}getActiveFilter(){return this.activeFilter}setActiveFilter(t){this.activeFilter=t}getActiveOrder(){return this.activeOrder}setActiveOrder(t){this.activeOrder=t}checkedIds(){return[...this.checkedSet]}checkedCount(){return this.checkedSet.size}setChecked(t,r){return r===this.checkedSet.has(t)?!1:(r?this.checkedSet.add(t):this.checkedSet.delete(t),!0)}setVisible(t,r){return r===!this.hiddenSet.has(t)?!1:(r?this.hiddenSet.delete(t):this.hiddenSet.add(t),!0)}forget(t){this.checkedSet.delete(t),this.hiddenSet.delete(t)}hydrate(t){this.checkedSet=new Set(t.checkedIds??[]),this.hiddenSet=new Set(t.hiddenIds??[]),this.activeFilter=null,this.activeOrder=null}snapshot(){return{checked:new Set(this.checkedSet),hidden:new Set(this.hiddenSet),activeFilter:this.activeFilter,activeOrder:this.activeOrder}}restore(t){this.checkedSet=new Set(t.checked),this.hiddenSet=new Set(t.hidden),this.activeFilter=t.activeFilter,this.activeOrder=t.activeOrder}};var Ue=class e{_activities=new Map;_lastStartDate=new Map;_promotionSnapshot=new Map;_progressFallback=new Map;_links=new Map;_outgoing=new Map;_incoming=new Map;_hierarchy;_buildOrderComparator;_cache={ids:null,visualOrderIds:null,orderComparator:null};_writeCapture=new Cn;_viewState=new Dn;_filterProjection=null;_viewStateBefore=null;_lastStartDateBefore=null;_promotionSnapshotBefore=null;_calendar;_flags;_calendarSnapshot;constructor(t,r=()=>null){this._buildOrderComparator=r,this._calendarSnapshot=R(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 kn(kl(this._calendarSnapshot)),this._flags=wm(t),this._hierarchy=new Sn(this._activities),this._hierarchy.rebuild()}fork(){let t=new e({activities:this.getAllActivities().map(Nt),links:this.getAllLinks().map(r=>({...r})),calendars:R(this._calendarSnapshot)},this._buildOrderComparator);return t._viewState.restore(R(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,R(n)])),t._progressFallback=new Map(this._progressFallback),t._flags=R(this._flags),t._filterProjection=R(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=$a(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)}getProgressFallback(t){return this._progressFallback.get(String(t))??null}setProgressFallback(t,r){let n=String(t),i=this._progressFallback.get(n)??null;Object.is(i,r)||(this._writeCapture.noteProgressFallback(n,i),r===null?this._progressFallback.delete(n):this._progressFallback.set(n,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))??_l}getIncomingLinkIds(t){return this._incoming.get(String(t))??_l}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,pa(i,r),r===E.PARENT&&this._hierarchy.markDirty(),fa(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,il(r,n)),pa(i,r),r===E.PARENT&&this._hierarchy.markDirty(),fa(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)),pa(n,a),a===E.PARENT&&(i=!0),fa(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){bl(this._outgoing,String(t.source),t.id),bl(this._incoming,String(t.target),t.id)}_deindexLink(t){let r=this._outgoing.get(String(t.source));r&&this._outgoing.set(String(t.source),Pl(r,t.id));let n=this._incoming.get(String(t.target));n&&this._incoming.set(String(t.target),Pl(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(!Lm(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.setProgressFallback(n,null),(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,progressFallbackBefore:s}=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._restoreProgressFallbacks(s),this._viewStateBefore!==null&&(this._viewState.restore(this._viewStateBefore),this._filterProjection=null,this.invalidateDerivedOrder()),this._promotionSnapshotBefore!==null&&(this._promotionSnapshot=this._promotionSnapshotBefore),this._lastStartDateBefore!==null&&(this._lastStartDate=this._lastStartDateBefore),this._cache.ids=null,this._cache.visualOrderIds=null,this._hierarchy.markDirty()}_restoreProgressFallbacks(t){for(let[r,n]of t)n===null?this._progressFallback.delete(r):this._progressFallback.set(r,n)}_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))}},_l=[];function Lm(e){return e===tr.LAG||e===tr.TYPE||e===tr.FREE_SLACK_HOURS||e===tr.IS_CRITICAL}function fa(e){return e===E.PARENT||e===E.CORRELATIVE_ID}function pa(e,t){t!==E.START_DATE&&t!==E.END_DATE&&t!==E.TYPE||(e.calendarDuration=Rt(e))}function Pl(e,t){return e.filter(r=>String(r)!==String(t))}function bl(e,t,r){let n=e.get(t);n?n.push(r):e.set(t,[r])}function wm(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 Rl(e,t){let r=e.getActivity(t);return r?R(r):null}function El(e){return e.getAllActivities().map(R)}function Ll(e){return e.getAllIds().map(String)}function wl(e,t){e.forEachActivity((r,n)=>t(n))}function Ol(e,t){let r=t==="0"?ha(e,"0"):e.getChildren(t),n=[];for(let i of r){let a=e.getActivity(i);a&&n.push(R(a))}return n.sort((i,a)=>(i.correlativeId??0)-(a.correlativeId??0)),n}function ha(e,t){return gt(t,e)}function Fl(e){return e.checkedIds().map(String)}function xl(e,t){if(t==="0"){let r=!1;return e.forEachActivity(n=>{r||=L(n.parentId)}),r}return e.getChildren(t).length>0}function ya(e,t){let r=e.getLink(t);return r?ft(r):null}function Nl(e){return e.getAllLinks().map(t=>ft(t))}function Tn(e){let[t,r]=e.split(":");return Number(t)*60+Number(r??0)}function Om(e){return e.reduce((t,r)=>Tn(r)<Tn(t)?r:t)}function Fm(e){return e.reduce((t,r)=>Tn(r)>Tn(t)?r:t)}function xm(e){return e.worktime.days.flatMap(t=>Array.isArray(t)?t:t===!0?e.worktime.hours:[])}function Ml(e){let t=[...e].find(a=>a.is_default);if(!t)return null;let r=xm(t);if(r.length===0)return null;let n=r.map(a=>a.split("-")[0]),i=r.map(a=>a.split("-")[1]);return{startHour:Om(n),endHour:Fm(i)}}function Wl(e,t){return{calendars:e.calendarReader,hierarchy:Sl(e),activityReader:Cl(e),dateFormat:t.dateFormat??"YYYY-MM-DD",customHours:t.customHours??{},hoursPerDay:t.hoursPerDay}}function Bl(e){return ce(e)}var Nm=new Set(["freeSlackHours","isCritical"]);function Mm(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 Vl(e){let t=e.activities.map(i=>({...i,after:null})),r=e.links.map(i=>Mm(i,Nm)).filter(i=>i!==null),n=e.source.kind==="activity-batch"?{...e.source,items:[],links:[]}:e.source;return R({...e,source:n,activities:t,links:r})}function ma(e,t,r,n,i,a,s){return{changeSet:e,beforeSnap:t,beforeLinks:jl(r),afterSnap:n,afterLinks:jl(i),progressFallbackBefore:a,progressFallbackAfter:s}}function jl(e){if(e)return new Map(Array.from(e,([t,r])=>[t,{...r,freeSlackHours:null,isCritical:!1}]))}function Yl(e,t){let r=new Map,n=new Map;for(let i of t.activities){if(i.kind!=="created")continue;let a=e.getActivity(String(i.id));a&&r.set(String(i.id),X(a))}for(let i of t.links){if(i.kind==="deleted")continue;let a=e.getLink(String(i.id));a&&n.set(String(i.id),{...a})}return{afterSnap:r,afterLinks:n}}function Kl(e){return e.kind!=="inline-edit"||!ar.has(e.column)?null:`inline-edit:${String(e.activityId)}:${e.column}`}function Ul(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 Gl(e,t){if(!Ul(e)||!Ul(t))return!1;let r=e.changeSet.activities[0],n=t.changeSet.activities[0];return!!r&&!!n&&String(r.id)===String(n.id)}function $l(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 ma(o)}function zl(e){return e.kind==="persistence-acknowledge"?"checkpoint-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 ga(e){for(let t of e.changeSet.activities)if(t.kind==="created"||t.kind==="deleted"||t.kind==="updated"&&t.fields&&P.CUSTOM_ID in t.fields)return!0;return!1}function va(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:Hl(s.fields,r),after:c?X(c):null})}else if(s.kind==="deleted")if(r==="before"){let c=e.getActivity(o);n.push({id:o,kind:"created",after:c?X(c):null})}else n.push({id:o,kind:"deleted",after:null});else if(r==="before")n.push({id:o,kind:"deleted",after:null});else{let c=e.getActivity(o);n.push({id:o,kind:"created",after:c?X(c):null})}}for(let s of t.changeSet.links){let o=String(s.id);if(s.kind==="updated"){let c=e.getLink(o);i.push({id:o,kind:"updated",fields:Hl(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"?Wm(s):s);return{source:{kind:r==="before"?"undo":"redo"},activities:n,links:i,calendars:[],trackingEvents:[],effects:[],viewState:a}}function Hl(e,t){if(e!=null)return Object.fromEntries(Object.entries(e).map(([r,n])=>[r,t==="before"?{before:R(n.after),after:R(n.before)}:{before:R(n.before),after:R(n.after)}]))}function Wm(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 Aa(e){return e.activities.length>0||e.links.length>0||(e.viewState?.length??0)>0||(e.effects?.length??0)>0}function ql(e,t){Xl(e,t,"before")}function Jl(e,t){Xl(e,t,"after")}function Xl(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(X(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(X(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))po(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.progressFallbackBefore:t.progressFallbackAfter;for(let[a,s]of i??[])e.setProgressFallback(a,s)}var Bm=100,jm=600,_n=class e{constructor(t=Bm){this.maxDepth=t}maxDepth;undoStack=[];redoStack=[];sequence=0;_lastKey=null;_lastTime=0;fork(){let t=new e(this.maxDepth);return t.undoStack.push(...R(this.undoStack)),t.redoStack.push(...R(this.redoStack)),t.sequence=this.sequence,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<=jm&&i!==void 0&&Gl(i.entry,t)?(i.entry=$l(i.entry,t),i.touchedAt=this.touch()):(this.undoStack.push({entry:t,touchedAt:this.touch()}),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()?.entry??null}takeRedo(){return this.redoStack.pop()?.entry??null}pushRedo(t){this.redoStack.push({entry:t,touchedAt:this.touch()})}pushUndo(t){this.undoStack.push({entry:t,touchedAt:this.touch()})}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}undoDepth(){return this.undoStack.length}capturePersistenceBoundary(){return this.resetCoalesce(),this.sequence}discardThrough(t){this.removeEntriesThrough(this.undoStack,t),this.removeEntriesThrough(this.redoStack,t),this.resetCoalesce()}applyPersistedIdentities(t,r){let n=new Map(t.map(({id:a,proplannerId:s})=>[String(a),s])),i=new Map(r.map(({id:a,proplannerId:s})=>[String(a),s]));for(let a of[...this.undoStack,...this.redoStack])a.entry=this.withPersistedIdentities(a.entry,n,i)}clear(){this.undoStack.length=0,this.redoStack.length=0,this.resetCoalesce()}touch(){return this.sequence+=1,this.sequence}removeEntriesThrough(t,r){let n=t.filter(({touchedAt:i})=>i>r);t.splice(0,t.length,...n)}withPersistedIdentities(t,r,n){let i=s=>s===void 0?void 0:new Map(Array.from(s,([o,c])=>[o,r.has(o)?{...c,proplannerId:r.get(o)}:c])),a=s=>s===void 0?void 0:new Map(Array.from(s,([o,c])=>[o,n.has(o)?{...c,proplannerId:n.get(o)}:c]));return{...t,beforeSnap:i(t.beforeSnap),afterSnap:i(t.afterSnap),beforeLinks:a(t.beforeLinks),afterLinks:a(t.afterLinks)}}};var Um=["parentId","correlativeId"];function Ql(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(Zl(c.parentId?.before));continue}let s=i.fields;!s||!Um.some(c=>c in s)||(n(a),"parentId"in s&&r.add(Zl(s.parentId?.before)))}return r}function Zl(e){return e==null?"0":String(e)}function Hm(e){return{...e,id:String(e.id),source:String(e.source),target:String(e.target),type:e.type,lag:Number(e.lag)}}function Vm(e){return{days:e.days,hours:e.hours,...e.dates?{dates:e.dates}:{},...e.customWeeks?{customWeeks:e.customWeeks}:{}}}function td(e){return{id:String(e.id),worktime:Vm(e.worktime)}}function Pn(e,t,r,n=[]){let i=t.map(Hm),a=[...r.map(td),...n.map(td)];return{activities:[...e],links:i,calendars:a}}var ed={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"},rd=Object.keys(ed).filter(e=>ed[e]==="tracked"),nd=new Set(["startDate","endDate","constraintDate","dateOrigin"]),id=new Set(["newActivityIds","responsableIds","tagIds"]);function ad(e){let t=rd.map(r=>[r,Ym(r,e[r])]);return Object.fromEntries(t)}function Ym(e,t){return nd.has(e)?t instanceof Date?new Date(t):null:id.has(e)?Array.isArray(t)?[...t]:[]:t}function dr(e,t){return Ia(e,t).length>0}function Ia(e,t){return rd.filter(r=>!Km(r,e[r],t[r]))}function Km(e,t,r){return nd.has(e)?Gm(t,r):id.has(e)?$m(t,r):(t??null)===(r??null)}function Gm(e,t){let r=e instanceof Date?e.getTime():null,n=t instanceof Date?t.getTime():null;return r===n}function $m(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 sd={id:"ignored",source:"tracked",target:"tracked",type:"tracked",lag:"tracked",freeSlackHours:"ignored",isCritical:"ignored",ganttId:"ignored",sectorId:"ignored",proplannerId:"ignored"},zm=Object.keys(sd).filter(e=>sd[e]==="tracked");function bn(e,t){return zm.some(r=>e[r]!==t[r])}function od(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?bn(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 cd(e,t){for(let r of e)Pt(r.proplannerId);for(let r of t)Pt(r.proplannerId)}var Rn=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,R(n));for(let[r,n]of this.activitiesAtLastSave)t.activitiesAtLastSave.set(r,R(n));return t}init(t,r){if(this.trackingEnabled){cd(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,n=[],i=[],a,s){if(!this.trackingEnabled)return;let o=new Map(n.map(({id:p,proplannerId:h})=>[String(p),h])),c=new Map(i.map(({id:p,proplannerId:h})=>[String(p),h])),l=t.map(p=>({...p,proplannerId:o.get(String(p.id))??p.proplannerId})),d=r.map(p=>{let h=c.get(String(p.id));return h===void 0?{...p}:{...p,proplannerId:h}});if(cd(l,d),this.snapshotActivities(l),this.snapshotLinks(d),!a||!s)return;let u=new Map(a.map(p=>[String(p.id),p])),f=new Map(s.map(p=>[String(p.id),p]));for(let p of l){let h=String(p.id);this.activityIsDirty(h,u.get(h)??null)&&this.dirtyActivityIds.add(h)}for(let p of a){let h=String(p.id);this.activityIsDirty(h,p)&&this.dirtyActivityIds.add(h)}for(let p of d){let h=String(p.id);this.linkIsDirty(h,f.get(h)??null)&&this.dirtyLinkIds.add(h)}for(let p of s){let h=String(p.id);this.linkIsDirty(h,p)&&this.dirtyLinkIds.add(h)}}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=ad(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}}),dr(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||dr(r,n.persistable)}linkIsDirty(t,r){let n=this.linksAtLastSave.get(t);return r===null?n!==void 0:!Pt(r.proplannerId)||n===void 0||bn(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,autoScheduling:o.autoScheduling}:{}};this.activitiesAtLastSave.set(i,{...c,persistable:l}),this.initialCalendarRepairIds.has(i)||!Pt(o.proplannerId)||dr(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)||dr(i,a.persistable))&&r.push(i)}return r}modifiedActivityFields(t){let r=new Map;if(!this.trackingEnabled||!this.initialized)return r;for(let n of this.dirtyActivityIds){let i=t(n),a=this.activitiesAtLastSave.get(n);if(!i||!a)continue;let s=Ia(i,a.persistable);s.length>0&&r.set(n,s)}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||bn(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 ld=/^(\d{4})[/-](\d{1,2})[/-](\d{1,2})/;var Ca=[!1,!0,!0,!0,!0,!0,!1],dd=new Set(["1","true"]),ka="DURATION",ud="asap",fd={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 pd(e,t){let r=[],n=e.map(a=>{let s=ig(a,t);return a.should_be_showed===!1&&r.push(s.id),s});sg(n);let i=new Set(n.map(a=>a.id));return og(n,i,t.reporter),{activities:n,activityIds:i,hiddenIds:r}}function qm(e,t){if(!e)return null;let r=fd[e.toUpperCase()];return r===void 0?(t.warn(`[parseFromBackend] unknown constraint label "${e}" \u2014 defaulting to "asap"`),ud):r}function Jm(e,t){let r=qm(e.constraint,t),i=r!=="asap"&&r!=="alap"&&e.constraint_date?Mt(e.constraint_date):null;return{constraintType:r,constraintDate:i}}function Xm(e,t,r){if(e==null)return r;let n=String(e);return t.has(n)?n:r}function Zm(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 Qm(e){if(typeof e!="object"||e===null||!("id"in e))return!1;let t=e.id;return typeof t=="string"||typeof t=="number"}function Sa(e){if(!Array.isArray(e))return[];let t=[];for(let r of e)Qm(r)&&t.push(String(r.id));return t}function tg(e){return e==="0"?null:String(e)}function eg(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 rg(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 ng(e,t){return Array.isArray(e)?e.map(r=>mn(r,t)).filter(r=>r!==null):[]}function ig(e,t){let r=Xm(e.calendarId,t.knownCalendarIds,t.defaultCalendarId),n=e.calendarId==null||!t.knownCalendarIds.has(String(e.calendarId)),i=Number(e.progress),{constraintType:a,constraintDate:s}=Jm(e,t.reporter),o=e.type==="milestone",c=Mt(e.start_date),l=o?c:Mt(e.end_date),d=o?0:Number(e.duration),u=rg(e,t.reporter);return{id:String(e.unique_id),proplannerId:eg(e.id),parentId:tg(e.parent_id),name:e.name,description:e.description??"",type:e.type,startDate:c,endDate:l,durationHours:re(d,t.hoursPerDay),constraintType:a,constraintDate:s,autoScheduling:te(i),calendarId:r,assignedDefaultCalendar:r!=null&&n,dateOrigin:e.date_origin==null?null:Mt(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:ag(e),subcontractId:e.subcontractId,isLookahead:e.isOnLookahead,hasLookaheadTasks:Array.isArray(e.tasks)&&e.tasks.length>0,newActivityIds:Zm(e.newActivitiesArray),hasNewActivities:e.hasNewActivities??!1,...e.isNewActivity===!0?{isNewActivity:!0}:{},pendingRequestIds:Sa(e.pendingRequests),responsableIds:Sa(e.responsables),tagIds:Sa(e.tags),baselinePoints:ng(e.baseline_points,t.reporter),baselineSnapshot:null,recursiveDurationHours:re(Number(e.sumOfDurationRecursively??0),t.hoursPerDay),calendarDuration:Rt({type:e.type,startDate:c,endDate:l}),isCritical:u,freeSlackHours:null,expectedProgress:null,expectedProgressBaseline:null,status:null,criticalPath:null}}function ag(e){return e.has_childs?null:e.custom_id}function sg(e){let t=e.find(r=>r.correlativeId===0&&r.type==="project");t&&(t.parentId=null)}function og(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 gd(e,t,r,n=null){let s=(e!==void 0&&e.length>0?e:t??[]).map(c=>dg(c,n)),o=(r??[]).map(c=>ug(c,n));return{calendars:s,baseCalendars:o,knownCalendarIds:new Set(s.map(c=>c.id)),defaultCalendarId:lg(s)}}function lg(e){let t=e.find(n=>n.is_default);if(t)return t.id;let r=e[0];return r?r.id:null}function vd(e,t){let r=gg(e.working_days),{days:n,hours:i}=mg(e,r),a=fg(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 dg(e,t){let r=e.baseDefault,n=typeof r=="boolean"?r:void 0;return vd(e,{idSuffix:"",isDefault:!!e.is_default,baseDefault:n,exceptionsSource:e.exceptiondays,exceptionRange:t})}function ug(e,t){return vd(e,{idSuffix:"-base",isDefault:!1,baseDefault:!!e.is_default,exceptionsSource:e.baseexceptiondays??e.exceptiondays,exceptionRange:t})}function fg(e,t){if(!Array.isArray(e)||e.length===0)return null;let r={};for(let n of e){if(!n)continue;let i=pg(n.from_date,n.to_date,t);if(i.length===0)continue;let a=hg(n);if(a!==void 0)for(let s of i)r[s]=a}return Object.keys(r).length>0?r:null}function pg(e,t,r){let n=hd(e),i=hd(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 hd(e){if(typeof e!="string")return null;let t=ld.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 hg(e){if(e.workable===!1)return!1;let t=e.shifts;if(Array.isArray(t)&&t.length>0){let r=yg(t);if(r.length>0)return r}}var yd=/^\d{1,2}:\d{2}$/;function yg(e){let t=[];for(let r of e){let n=Cd(r?.shift_string);if(!n)continue;if(!n.startsCsv.includes(",")&&!n.endsCsv.includes(",")){let o=n.startsCsv.trim(),c=n.endsCsv.trim();!En(o)&&!En(c)&&yd.test(o)&&yd.test(c)&&t.push(`${o}-${c}`);continue}let s=Id(n.startsCsv,n.endsCsv).find(o=>o!==null);s&&t.push(s)}return t.sort(Ad),t}function md(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 Ad(e,t){return md(e)-md(t)}function mg(e,t){let r=Array.from({length:7},()=>[]),n=(l,d)=>{let u=Id(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=Cd(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(Ad);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 Id(e,t){let r=Array.from({length:7},()=>null);if(typeof e!="string"||typeof t!="string")return r;let n=e.split(",").map(o=>o.trim()),i=t.split(",").map(o=>o.trim());if(!(n.length===i.length&&n.length>0&&n.length<=7))return r;let s=[...r];for(let o=0;o<n.length;o+=1){let c=n[o],l=i[o];En(c)||En(l)||(s[o]=`${c}-${l}`)}return s}function Cd(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 gg(e){if(typeof e!="string")return[...Ca];let t=e.split(",").map(r=>r.trim());return t.length!==7?[...Ca]:t.map(r=>dd.has(r))}var vg=new Set(["false","null"]);function En(e){return!e||vg.has(e)}function Ag(e){return e==="0"||e==="1"||e==="2"||e==="3"}function Ig(e){if(typeof e!="string")return null;let t=_s(e);return t||(Ag(e)?e:null)}function Cg(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 Sd(e,t){let r=[];for(let n of e)try{r.push(kg(n,t.knownActivityIds,t.hoursPerDay))}catch(i){t.reporter.warn("[parseFromBackend] dropping invalid link",i)}return Sg(r)}function kg(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=Ig(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=Cg(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 Sg(e){let t=new Map;for(let r of e){let n=`${r.source}-${r.target}-${r.type}`,i=t.get(n);(!i||kd(r)>kd(i))&&t.set(n,r)}return[...t.values()]}function kd(e){let t=Number(e.id);return Number.isFinite(t)?t:-1/0}function Dg(e){if(typeof e!="string")return ka;switch(e.toUpperCase()){case"DURATION":return"DURATION";case"COST":return"COST";case"HH":return"HH";default:return ka}}function Tg(e){let t=e.custom_id_prefix;return typeof t=="string"&&t.length>0?t:void 0}function _g(e){let t=e.custom_id_increment;return typeof t=="string"?t:typeof t=="number"&&Number.isFinite(t)?String(t):void 0}function Dd(e){let t=Tg(e),r=_g(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:Dg(e.activity_creter),statusCriteria:yi,ganttId:null}}function Ln(e,t=ke){let r=Dd(e.sector),{calendars:n,baseCalendars:i,knownCalendarIds:a,defaultCalendarId:s}=gd(e.calendars,e.sector.calendars,e.baseCalendars,Pg(e.activities)),{activities:o,activityIds:c,hiddenIds:l}=pd(e.activities,{knownCalendarIds:a,defaultCalendarId:s,hoursPerDay:r.hoursPerDay,reporter:t}),d=Sd(e.links,{knownActivityIds:c,hoursPerDay:r.hoursPerDay,reporter:t});return{sector:r,activities:o,links:d,calendars:n,baseCalendars:i,viewStateSeed:{hiddenIds:l}}}function Pg(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 Ta(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 Ta({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 _a(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 _a({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 Pa(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 Pa({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 Td(e){return!!e&&typeof e=="string"&&e.trim().length>0}function wn(e){if(!e||typeof e!="string"||e.trim().length===0)return"";let t=e.match(/^(.*?)(\d+)$/);return t?t[1]??"":e}function On(e){if(!e||typeof e!="string"||e.trim().length===0)return"";let t=e.match(/(\d+)$/);return t?t[1]??"":""}function _d(e){if(!e||typeof e!="object")return"";let t=e.customId;return typeof t=="string"?t:""}function Pd(e,t){return!t&&Td(e)}function bd(e,t){return t&&Td(e)}function ur(e){return typeof e=="string"&&e.length>0&&/^\d+$/.test(e)}function Fn(e){if(!ur(e))return 0n;try{return BigInt(e)}catch{return 0n}}function bg(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=Fn(e),n=Fn(t),i=r+n;return bg(i,e)}function xn(e,t){let r=Fn(e),n=Fn(t);return r<n?-1:r>n?1:0}function Nn(e,t){return xn(e,t)<=0?e:t}function Mn(e,t){return xn(e,t)>=0?e:t}function Rd(e){if(!e||e.length===0)throw new Error("minSuffixFromArray requires non-empty array");return e.reduce((t,r)=>Nn(t,r))}function Ed(e){if(!e||e.length===0)throw new Error("maxSuffixFromArray requires non-empty array");return e.reduce((t,r)=>Mn(t,r))}function Ld(e){return{prefix:e,baseSuffix:null}}function wd(e,t){let r=On(e);return{prefix:wn(e),baseSuffix:Ct(r,t)}}function Od(e){return{prefix:e,baseSuffix:null}}function Fd(e,t){return Pd(e,t)?"parentConversion":bd(e,t)?"pasteReference":"noContext"}function xd(e){return{...e,usedSuffixes:new Set(e.usedSuffixes)}}var Wn=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?xd(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=Rd(n),r.max=Ed(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,xd(n));for(let r of this.processedIds)t.processedIds.add(r);return t}extractPrefix(t){return wn(t)}extractSuffix(t){return On(t)}analyzeCustomId(t){return{prefix:this.extractPrefix(t),suffix:this.extractSuffix(t)}}_updatePrefixStats(t,r){if(this._ensureFreshBounds(t),!this.prefixMap.has(t)){this.prefixMap.set(t,{min:r,max:r,next:r,quantity:1,usedSuffixes:new Set([r])}),this._recalculateNext(t);return}let n=this.prefixMap.get(t);n.usedSuffixes.has(r)||(n.usedSuffixes.add(r),n.min=Nn(r,n.min),n.max=Mn(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=Nn(n,i.min),i.max=Mn(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(;xn(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=_d(r),a=Fd(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 Ld(this.defaultPrefix);case"pasteReference":return wd(r,this.suffixIncrement);default:return Od(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 Rg=1,Eg=-1;function Lg(e,t){return!e&&!t?null:e&&t?0:e?Rg:Eg}function Nd(e){return e==null}function Md(e,t){let r=t.indexOf(String(e));return r===-1?t.length:r}function wg(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 Og(e,t){let r=Bt(e.field);return r===null?null:(n,i)=>{let a=r.extract(n,t),s=r.extract(i,t),o=Lg(Nd(a),Nd(s));if(o!==null)return o;let c=r.valueKind==="enum"?Md(a,r.order)-Md(s,r.order):wg(a,s,t.locale);return e.direction==="desc"?-c:c}}function Wd(e,t){let r=e.rules.map(n=>Og(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 Bd(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,Ce),Fg(e,r)}function Fg(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:Z.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 jd(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 Ud(e){let{state:t,sector:r,scheduler:n,skipAutoSchedule:i,now:a}=e;if(st(t),r.updateDurationForPrimaveraEndDate&&Ng(t),Mg(t),jd(t),i){Xe(t),a&&(ae(t,a),Wt(t,r.statusCriteria));return}let s=await n.schedule({});Ge(t,s),Wg(t),xg(t),await De(t,void 0,!1),Xe(t),a&&(ae(t,a),Wt(t,r.statusCriteria))}function xg(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 Ng(e){e.forEachActivity(t=>{!t.startDate||!t.endDate||(t.durationHours=e.calculateDuration({startDate:t.startDate,endDate:t.endDate,task:t}))})}function Mg(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 Wg(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 kt={READY:"ready",DESTROYED:"destroyed",POISONED:"poisoned"};function Hd(e){let t=e.clock??null,r=t?.()??null,n=r?Br(r):null,i=e.reporter??ke,a=Ln({sector:e.sector,activities:e.activities,links:e.links,calendars:e.calendars,baseCalendars:e.baseCalendars},i),s=a.sector;s.statusCriteria=zr(e.statusCriteria),s.ganttId=e.ganttId??null;let o=a.calendars,c=a.baseCalendars??[],l=Pn(a.activities,a.links,a.calendars,c),d=v=>Wd(v,Qt(s.hoursPerDay)),u=new Ue(l,d);u.hydrateViewState({hiddenIds:a.viewStateSeed.hiddenIds});let f=new Se(u,i);Bd(u);let p=Ta({knownIds:a.activities.map(v=>v.id)}),h=_a({seed:r?.getTime()??0,knownIds:a.links.map(v=>v.id)}),g=Pa({knownIds:a.activities.map(v=>v.uniqueCorrelativeId)}),I=new Wn({defaultPrefix:s.customIdPrefix,suffixIncrement:s.customIdIncrement});if(I.populateFromActivities(a.activities),e.baselinePoints&&e.baselinePoints.length>0){let v=c.find(k=>k.baseDefault)?.id??null;gn(u,e.baselinePoints,n,i,v)}let _=Ud({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:g,customIdTracker:I,calendars:o,baseCalendars:c,clock:t,reporter:i,initPromise:_}}function He(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(He)];if(e instanceof Map)return["map",Array.from(e,([t,r])=>[He(t),He(r)]).sort((t,r)=>JSON.stringify(t).localeCompare(JSON.stringify(r)))];if(e instanceof Set)return["set",Array.from(e,He).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,He(r)])];throw new TypeError(`Unsupported canonical value: ${typeof e}`)}function fe(e){return JSON.stringify(He(e))}function ba(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:R(c)});continue}let l=Bg(o,c);Object.keys(l).length>0&&a.push({id:s,kind:"updated",fields:l,after:R(c)})}return a}function Bg(e,t){let r={},n=[...new Set([...Object.keys(e),...Object.keys(t)])].sort();for(let i of n)fe(e[i])!==fe(t[i])&&(r[i]={before:R(e[i]),after:R(t[i])});return r}function jg(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 Vd(e,t){let r=fe(e.order)!==fe(t.order);return{source:{kind:"init"},activities:ba(e.activities,t.activities),links:ba(e.links,t.links),calendars:ba(e.calendars,t.calendars),trackingEvents:[],effects:[],viewState:jg(e,t),...r?{order:R(e.order)}:{}}}var Ug=()=>({constantStart:null,variableStartOffset:null,constantEnd:null,variableEndOffset:null}),Ra=(e,t)=>e===null?t:Math.min(e,t),Ea=(e,t)=>e===null?t:Math.max(e,t);function Kd(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=Hg(e,t,n);return Vg(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=Kg(o,s),l=Gg(o,s);if(c===null||l===null)throw new Error(`[ScheduleCore] incomplete date gesture bounds for ${String(a)}`);return{startTimeMs:c,endTimeMs:l}}}}function Hg(e,t,r){let n=new Map,i=t.kind==="move"?String(t.anchorActivityId):null,a=i===null?null:Yd(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=Yd(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 Vg(e,t,r){let n=Ze(e,new Set(t));for(let i of n){let a=Ug();for(let s of e.getChildren(i)){let o=r.get(s);if(o){Yg(a,o);continue}let c=e.getActivity(s);if(!c)throw new Error(`[ScheduleCore] missing child ${s} while previewing parent ${i}`);a.constantStart=Ra(a.constantStart,c.startDate.getTime()),a.constantEnd=Ea(a.constantEnd,c.endDate.getTime())}r.set(i,a)}}function Yd(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 Yg(e,t){t.constantStart!==null&&(e.constantStart=Ra(e.constantStart,t.constantStart)),t.variableStartOffset!==null&&(e.variableStartOffset=Ra(e.variableStartOffset,t.variableStartOffset)),t.constantEnd!==null&&(e.constantEnd=Ea(e.constantEnd,t.constantEnd)),t.variableEndOffset!==null&&(e.variableEndOffset=Ea(e.variableEndOffset,t.variableEndOffset))}function Kg(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 Gg(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 La=Symbol("ScheduleCore.fork.source");function $g(e){return e.kind==="persistence-acknowledge"||e.kind==="activity-lookahead-sync"&&e.acknowledgePersistedLookahead===!0}function zg(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 qg(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 Jg(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 Bn=class e{_activityClipboard={value:null};_status=kt.READY;coreRuntime;_isFork;_undo=new _n;_opQueue=Promise.resolve();_scheduleRevision=0;_pendingScheduleRevision=0;_criticalPathRevision=-1;_activeCriticalPath=null;constructor(t){if(La in t){this._isFork=!0;let i=t[La],a=i.coreRuntime.state.fork();this.coreRuntime={state:a,scheduler:new Se(a,i.coreRuntime.reporter),sector:R(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,R(o)])),baseCalendars:R(i.coreRuntime.baseCalendars),clock:i.coreRuntime.clock,reporter:i.coreRuntime.reporter},this._activityClipboard.value=R(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=Hd(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}fork(){return this._enqueue(async()=>(await this._ready,this.assertReady(),new e({[La]:this})))}get criticalPathReady(){return this._criticalPathReady}get status(){return this._status}getSector(){return R(this.coreRuntime.sector)}getActivityView(t){return this.assertReady(),Rl(this.coreRuntime.state,t)}createDateGesturePreview(t){this.assertReady();let r=this._scheduleRevision;return Kd(this.coreRuntime.state,t,()=>{if(this.assertReady(),this._scheduleRevision!==r)throw new Error("[ScheduleCore] date gesture preview is stale")})}getAllActivitiesView(){return this.assertReady(),El(this.coreRuntime.state)}getIndentTargetParentIds(t){this.assertReady();let r=yn(t.map(n=>String(n)),this.coreRuntime.state);return[...new Set(r.allowedMoves.map(n=>String(n.newParentId)))]}getChildrenView(t){return this.assertReady(),Ol(this.coreRuntime.state,t)}getLinkView(t){return this.assertReady(),ya(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=ya(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(),Nl(this.coreRuntime.state)}auditEffectiveGraph(){this.assertReady();let t=this.coreRuntime.state,r=t.getAllLinks(),n=ze(t,r),i=Pr(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?R(n[r]):null}getAllIds(){return this.assertReady(),Ll(this.coreRuntime.state)}forEachActivityId(t){this.assertReady(),wl(this.coreRuntime.state,t)}getChildrenIds(t){return this.assertReady(),ha(this.coreRuntime.state,t)}getSelectedActivityIds(){return this.assertReady(),Fl(this.coreRuntime.state)}getHiddenActivityIds(){return this.assertReady(),this.coreRuntime.state.hiddenIds().map(String)}getVisibleActivityIds(){this.assertReady();let t=new Set(this.coreRuntime.state.hiddenIds().map(String));return this.coreRuntime.state.getAllIds().map(String).filter(r=>!t.has(r))}getActiveFilter(){return this.assertReady(),R(this.coreRuntime.state.getActiveFilter())}getActiveOrder(){return this.assertReady(),R(this.coreRuntime.state.getActiveOrder())}getVisualOrderIds(){return this.assertReady(),[...this.coreRuntime.state.getVisualOrderIds()]}hasChild(t){return this.assertReady(),xl(this.coreRuntime.state,t)}getCalendar(t){this.assertReady();let r=this.coreRuntime.calendars.get(t);return r?R(r):null}getAllCalendars(){return this.assertReady(),Array.from(this.coreRuntime.calendars.values(),t=>R(t))}getBaseCalendars(){return this.assertReady(),this.coreRuntime.baseCalendars.map(t=>R(t))}isCustomIdInUse(t,r=null){return this.assertReady(),this.coreRuntime.customIdTracker.isCustomIdInUse(t,r)}getProjectWorkHours(){return this.assertReady(),Ml(this.coreRuntime.calendars.values())}getModifiedLinks(){return this.assertReady(),this._saveTracker.modifiedLinks(t=>this.coreRuntime.state.getLink(t)).map(R)}getNewLinks(){return this.assertReady(),this._saveTracker.newLinks(t=>this.coreRuntime.state.getLink(t)).map(R)}getModifiedActivities(){return this.assertReady(),this._saveTracker.modifiedActivities(t=>this.coreRuntime.state.getActivity(t)).map(R)}getModifiedActivityFields(){return this.assertReady(),R(this._saveTracker.modifiedActivityFields(t=>this.coreRuntime.state.getActivity(t)))}getNewActivities(){return this.assertReady(),this._saveTracker.newActivities(t=>this.coreRuntime.state.getActivity(t)).map(R)}hasUnsavedChanges(){return this.assertReady(),this._saveTracker.hasUnsavedChanges()}getScheduleRevision(){return this._scheduleRevision}capturePersistenceHistoryBoundary(){return this.assertReady(),this._undo.capturePersistenceBoundary()}getCanonicalDigest(){this.assertReady();let t=(r,n)=>String(r.id).localeCompare(String(n.id));return fe({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:ve(n.coreRuntime.state)});return Vd(r(this),r(t))}getDeletedActivitiesSinceLastSave(){return this.assertReady(),this._saveTracker.deletedActivities(t=>this.coreRuntime.state.getActivity(t)).map(R)}getDeletedLinksSinceLastSave(){return this.assertReady(),this._saveTracker.deletedLinks(t=>this.coreRuntime.state.getLink(t)).map(R)}_enqueue(t){let r=this._opQueue.then(t,t);return this._opQueue=r.then(()=>{},()=>{}),r}_beginScheduleMutation(t){return ji(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&&$g(t))return{result:{ok:!1,reason:C.SANDBOX_PERSISTENCE_FORBIDDEN},changedState:!1};let n=Wl(this.coreRuntime.state,{hoursPerDay:this.coreRuntime.sector.hoursPerDay,dateFormat:this.coreRuntime.sector.dateFormat}),i=zl(t),a=[this.coreRuntime.activityIdGenerator.snapshot(),this.coreRuntime.linkIdGenerator.snapshot(),this.coreRuntime.uniqueCorrelativeIdGenerator.snapshot()];this.coreRuntime.state.beginWriteCapture(),this.coreRuntime.customIdTracker.beginCustomIdTransaction();let s,o;try{s=await nl(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?Br(this.coreRuntime.clock()):null});let c=this.coreRuntime.state.peekWriteCapture()?.progressFallbackBefore;c&&c.size>0&&(o=new Map(c)),s.ok||this._rollback(a)}catch(c){throw this._rollback(a),c}finally{this.coreRuntime.state.endWriteCapture(),this.coreRuntime.customIdTracker.commitCustomIdTransaction()}if(s.ok&&i==="record"&&Aa(s.changes)){let c=Yl(this.coreRuntime.state,s.changes),l=o?new Map(Array.from(o.keys(),d=>[d,this.coreRuntime.state.getProgressFallback(d)])):void 0;this._undo.record(ma(Vl(s.changes),s.__beforeSnap,s.__beforeLinks,c.afterSnap,c.afterLinks,o,l),Kl(t),Date.now())}if(s.ok)if(i==="checkpoint-on-success"){if(t.kind!=="persistence-acknowledge")throw new Error("checkpoint-on-success requires persistence acknowledge");let c=this.coreRuntime.state.getAllActivities(),l=this.coreRuntime.state.getAllLinks(),d=t.checkpoint,u=d?.historyBoundary??this._undo.capturePersistenceBoundary();this._saveTracker.acknowledge(d?.activities??c,d?.links??l,t.activities,t.links,c,l),this._undo.discardThrough(u),this._undo.applyPersistedIdentities(t.activities??[],t.links??[])}else t.kind==="activity-lookahead-sync"&&t.acknowledgePersistedLookahead===!0?(this._saveTracker.acknowledgePersistedLookahead(s.changes.activities,c=>this.coreRuntime.state.getActivity(c)),t.persistedProgress!==void 0&&this._undo.clear()):this._saveTracker.recordChanges(s.changes.activities,s.changes.links,c=>this.coreRuntime.state.getActivity(c),c=>this.coreRuntime.state.getLink(c));return s=this._withReappliedViewState(t,s),s.ok?ji(t)&&Aa(s.changes)?(this._recordScheduleMutation(r.skipAutoSchedule!==!0&&r.skipCriticalPath!==!0&&ce(t)),{result:Gd(s),changedState:!0}):{result:Gd(s),changedState:!1}:{result:s,changedState:!1}}recomputeCriticalPath(){let t=this._enqueue(async()=>({job:this._startCriticalPathForCurrentRevision()})).then(({job:r})=>r);return this._criticalPathReady=t,t}isCriticalPathSettled(){return this._criticalPathRevision===this._scheduleRevision&&this._pendingScheduleRevision===this._scheduleRevision&&this._activeCriticalPath===null}async whenCriticalPathSettled(){for(;!this.isCriticalPathSettled();)await this.recomputeCriticalPath()}_withReappliedViewState(t,r){if(!r.ok||(t.kind==="visibility-set"&&this.coreRuntime.state.setFilterProjection(null),!Jo(t)))return r;let n=this._reapplyViewState(r.changes);return n===null?r:{...r,changes:n}}_reapplyViewState(t){let r=this._reapplyActiveFilter(t),n=this._emitTouchedBranchOrder(r??t);return this._reapplyActiveOrder(n.changes??r??t,n.touchedParents)??n.changes??r}_emitTouchedBranchOrder(t){let r=this.coreRuntime.state,n=Ql(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=zn(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:ve(n)};let a=new Set(r);for(let o of t.activities){if(o.kind==="deleted")return{...t,order:ve(n)};let c=n.getParentId(o.id);a.add(c===null?"0":String(c))}let s=zn(n,a);return s.length===0?null:{...t,order:s}}_reapplyActiveFilter(t){let r=this.coreRuntime.state,n=r.getActiveFilter();if(n===null)return null;let i=Qt(this.coreRuntime.sector.hoursPerDay),a=r.getFilterProjection(),s=Jg(a,n,i),o=zg(t)?null:qg(t,r),c,l;if(o===null||!s){let f=yr({activities:r.getAllActivities(),parentOf:p=>r.getParentId(p),filter:n,context:i});r.setFilterProjection(f),l=f.visibleIds,c=r.getAllIds()}else c=Ua(a,o,f=>r.getParentId(f)),l=a.visibleIds;let u=ge(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 Ue(Pn(this.coreRuntime.state.getAllActivities().map(o=>X(o)),this.coreRuntime.state.getAllLinks().map(o=>({...o})),Array.from(this.coreRuntime.calendars.values()),this.coreRuntime.baseCalendars)),i=()=>!r.cancelled&&this._status!==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.activities)Ni(this.coreRuntime.state,l,d);for(let[l,d]of o.links)Mi(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===kt.DESTROYED)return{changes:{source:{kind:"init"},activities:[],links:[],calendars:[],trackingEvents:[]}};this.coreRuntime.state.beginWriteCapture(),this.coreRuntime.customIdTracker.beginCustomIdTransaction();let t;try{await tn(this.coreRuntime.state,this.coreRuntime.sector.hoursPerDay),t=await B(this.coreRuntime.state,{source:{kind:"init"},beforeSnap:new Map,touchedIds:[],scheduledIds:[],hoursPerDay:this.coreRuntime.sector.hoursPerDay})}finally{this.coreRuntime.state.endWriteCapture(),this.coreRuntime.customIdTracker.commitCustomIdTransaction()}return{changes:t}}undo(t={}){let r=this._admitScheduleMutation(),n=!1,i=this._enqueue(async()=>{try{return await this._runUndo(t,a=>{n=a})}finally{this._settleScheduleMutation(r,n)}});return i.then(a=>{a&&t.skipCriticalPath!==!0&&this.recomputeCriticalPath().catch(s=>{this.coreRuntime.reporter.error("[ScheduleCore] Critical Path recompute after undo failed",s)})},()=>{}),i}async _runUndo(t,r){{if(this.assertReady(),t.expectedUndoDepth!==void 0&&this._undo.undoDepth()!==t.expectedUndoDepth)return null;let n=this._undo.takeUndo();if(!n)return null;ql(this.coreRuntime.state,n),this._recordScheduleMutation(!1),r(!0),ga(n)&&this._resyncCustomIdTrackerFromModel(),this._undo.pushRedo(n),this._undo.resetCoalesce();let i=va(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;Jl(this.coreRuntime.state,r),this._recordScheduleMutation(!1),t(!0),ga(r)&&this._resyncCustomIdTrackerFromModel(),this._undo.pushUndo(r),this._undo.resetCoalesce();let n=va(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 Rn;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 Gd(e){let{__beforeSnap:t,__beforeLinks:r,...n}=e;return n}var $d=(e=[])=>(e??[]).filter(t=>!t.proplannerId);var zd={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 qd=8;var $={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"},Xg={[$.ACTIVITY_CLIPBOARD_CLEAR]:!0,[$.ACTIVITY_COPY]:!0,[$.ACTIVITY_PASTE_COPIED]:!0,[$.PERSISTENCE_ACKNOWLEDGE]:!0,[$.BASELINE_APPLY]:!0,[$.PONDERATOR_CRITERION_SET]:!0,[$.STATUS_CRITERIA_SET]:!0,[$.INLINE_EDIT]:!0,[$.DATES_BATCH]:!0,[$.BULK_EDIT]:!0,[$.LINK_CREATE]:!0,[$.LINK_UPDATE]:!0,[$.LINK_DELETE]:!0,[$.LINKS_BATCH]:!0,[$.ACTIVITY_CREATE]:!0,[$.ACTIVITY_DELETE]:!0,[$.ACTIVITY_MOVE]:!0,[$.ACTIVITY_INDENT]:!0,[$.ACTIVITY_OUTDENT]:!0,[$.ACTIVITY_SET_PROGRESS]:!0,[$.SELECTION_TOGGLE]:!0,[$.SELECTION_REPLACE]:!0,[$.VISIBILITY_SET]:!0,[$.FILTER_SET]:!0,[$.SORT_SET]:!0,[$.SIR_SYNC]:!0,[$.ACTIVITY_LOOKAHEAD_SYNC]:!0},Jd=Object.keys(Xg);var Xd={CHILD:"child",CHILD_CONFIRMED:"child-confirmed",LINE:"line",ROOT:"root"};return iu(Zg);})();
2
2
  //# sourceMappingURL=schedule-core.global.js.map