UNPKG

@geoapify/route-planner-sdk

Version:

TypeScript SDK for the Geoapify Route Planner API. Supports route optimization, delivery planning, and timeline visualization in browser and Node.js

1 lines 598 kB
function t(t,e,i,n){return new(i||(i=Promise))((function(s,o){function a(t){try{l(n.next(t))}catch(t){o(t)}}function r(t){try{l(n.throw(t))}catch(t){o(t)}}function l(t){var e;t.done?s(t.value):(e=t.value,e instanceof i?e:new i((function(t){t(e)}))).then(a,r)}l((n=n.apply(t,e||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;const e="reoptimize",i="preserveOrder";class n{constructor(t){this.raw=t||{capabilities:[],time_windows:[],breaks:[]}}getRaw(){return this.raw}setRaw(t){return this.raw=t,this}setStartLocation(t,e){return this.raw.start_location=[t,e],this}setStartLocationIndex(t){return this.raw.start_location_index=t,this}setEndLocation(t,e){return this.raw.end_location=[t,e],this}setEndLocationIndex(t){return this.raw.end_location_index=t,this}setPickupCapacity(t){return this.raw.pickup_capacity=t,this}setDeliveryCapacity(t){return this.raw.delivery_capacity=t,this}addCapability(t){return this.raw.capabilities.push(t),this}addTimeWindow(t,e){return this.raw.time_windows.push([t,e]),this}addBreak(t){return this.raw.breaks.push(t.getRaw()),this}setId(t){return this.raw.id=t,this}setDescription(t){return this.raw.description=t,this}}class s{constructor(t){this.raw=t||{}}getRaw(){return this.raw}setRaw(t){return this.raw=t,this}setLat(t){return this.raw.lat=t,this}setLon(t){return this.raw.lon=t,this}}class o{constructor(t){this.raw=t||{values:[]}}getRaw(){return this.raw}setRaw(t){return this.raw=t,this}setType(t){return this.raw.type=t,this}addValue(t,e){let i=(new s).setLat(e).setLon(t);return this.raw.values.push(i.getRaw()),this}}class a{constructor(t){this.raw=t||{time_windows:[]}}getRaw(){return this.raw}setRaw(t){return this.raw=t,this}addTimeWindow(t,e){return this.raw.time_windows.push([t,e]),this}setDuration(t){return this.raw.duration=t,this}}class r{constructor(t){this.raw=t||{requirements:[],time_windows:[]}}getRaw(){return this.raw}setRaw(t){return this.raw=t,this}setLocation(t,e){return this.raw.location=[t,e],this}setLocationIndex(t){return this.raw.location_index=t,this}setPriority(t){return this.raw.priority=t,this}setDuration(t){return this.raw.duration=t,this}setPickupAmount(t){return this.raw.pickup_amount=t,this}setDeliveryAmount(t){return this.raw.delivery_amount=t,this}addRequirement(t){return this.raw.requirements.push(t),this}addTimeWindow(t,e){return this.raw.time_windows.push([t,e]),this}setId(t){return this.raw.id=t,this}setDescription(t){return this.raw.description=t,this}}class l{constructor(t){this.raw=t||{}}getRaw(){return this.raw}setRaw(t){return this.raw=t,this}setId(t){return this.raw.id=t,this}setLocation(t,e){return this.raw.location=[t,e],this}}class d{constructor(t){this.raw=t||{requirements:[]}}getRaw(){return this.raw}setRaw(t){return this.raw=t,this}setId(t){return this.raw.id=t,this}setPickup(t){return this.raw.pickup=t.getRaw(),this}setDelivery(t){return this.raw.delivery=t.getRaw(),this}addRequirement(t){return this.raw.requirements.push(t),this}setPriority(t){return this.raw.priority=t,this}setDescription(t){return this.raw.description=t,this}setAmount(t){return this.raw.amount=t,this}}class c{constructor(t){this.raw=t||{time_windows:[]}}getRaw(){return this.raw}setRaw(t){return this.raw=t,this}setLocation(t,e){return this.raw.location=[t,e],this}setLocationIndex(t){return this.raw.location_index=t,this}setDuration(t){return this.raw.duration=t,this}addTimeWindow(t,e){return this.raw.time_windows.push([t,e]),this}}class p{constructor(t){if(!t)throw new Error("RouteLegStepData is undefined");this.raw=t}getRaw(){return this.raw}getDistance(){return this.raw.distance}getTime(){return this.raw.time}getFromIndex(){return this.raw.from_index}getToIndex(){return this.raw.to_index}}class u{constructor(t){if(!t)throw new Error("RouteLegData is undefined");this.raw=t}getRaw(){return this.raw}getTime(){return this.raw.time}getDistance(){return this.raw.distance}getSteps(){return this.raw.steps.map((t=>new p(t)))}getFromWaypointIndex(){return this.raw.from_waypoint_index}getToWaypointIndex(){return this.raw.to_waypoint_index}}class h{constructor(t){if(!t)throw new Error("ActionResponseData is undefined");this.raw=t}getRaw(){return this.raw}getType(){return this.raw.type}getStartTime(){return this.raw.start_time}getDuration(){return this.raw.duration}getShipmentIndex(){return this.raw.shipment_index}getShipmentId(){return this.raw.shipment_id}getLocationIndex(){return this.raw.location_index}getLocationId(){return this.raw.location_id}getJobIndex(){return this.raw.job_index}getJobId(){return this.raw.job_id}getActionIndex(){return this.raw.index}getWaypointIndex(){return this.raw.waypoint_index}}class g{constructor(t){if(!t)throw new Error("WaypointData is undefined");this.raw=t}getRaw(){return this.raw}getOriginalLocation(){return this.raw.original_location}getOriginalLocationIndex(){return this.raw.original_location_index}getOriginalLocationId(){return this.raw.original_location_id}getLocation(){return this.raw.location||this.raw.original_location}getStartTime(){return this.raw.start_time}getDuration(){return this.raw.duration}getActions(){return this.raw.actions.map((t=>new h(t)))}getPrevLegIndex(){return this.raw.prev_leg_index}getNextLegIndex(){return this.raw.next_leg_index}}class m{constructor(t,e,i,n,s){if(this.raw=t,this.agentInputData=e,this.routingOptions=i,this.callOptions=n,this.violations=s,!t)throw new Error("AgentSolutionData is undefined")}getRaw(){return this.raw}getAgentIndex(){return this.raw.agent_index}getAgentId(){return this.raw.agent_id}getTime(){return this.raw.time}getStartTime(){return this.raw.start_time}getEndTime(){return this.raw.end_time}getDistance(){return this.raw.distance}getMode(){return this.raw.mode}getLegs(){return this.raw.legs.map((t=>new u(t)))}getActions(){return this.raw.actions.map((t=>new h(t)))}getDelays(){return this.getActions().filter((t=>"delay"===t.getType()))}getWaypoints(){return this.raw.waypoints.map((t=>new g(t)))}getPlannedShipments(){return[...new Set(this.raw.actions.filter((t=>void 0!==t.shipment_index)).map((t=>t.shipment_index)))]}getPlannedJobs(){return[...new Set(this.raw.actions.filter((t=>void 0!==t.job_index)).map((t=>t.job_index)))]}getAgentInputData(){return this.agentInputData}containsShipment(t){return this.getActions().some((e=>e.getShipmentIndex()===t||e.getShipmentId()===t))}containsJob(t){return this.getActions().some((e=>e.getJobIndex()===t||e.getJobId()===t))}getViolations(){return this.violations}getRoute(e){var i;return t(this,void 0,void 0,(function*(){const t=this.getWaypoints().map((t=>t.getLocation())),n=t.map((t=>"lonlat:"+t)).join("|");if(0===n.length)return;const s=yield fetch(this.constructRoutingRequest(n,e||this.routingOptions,this.callOptions)),o=yield s.json(),a=null===(i=null==o?void 0:o.features)||void 0===i?void 0:i[0];return a?(a.properties=Object.assign(Object.assign({},a.properties||{}),{agent_index:this.getAgentIndex(),agent_id:this.getAgentId()}),a):{type:"Feature",geometry:{type:"LineString",coordinates:t},properties:{agent_index:this.getAgentIndex(),agent_id:this.getAgentId()}}}))}constructRoutingRequest(t,e,i){let n=`${i.baseUrl}/v1/routing?waypoints=${t}&apiKey=${i.apiKey}`;return e.mode&&(n+=`&mode=${e.mode}`),e.type&&(n+=`&type=${e.type}`),e.units&&(n+=`&units=${e.units}`),e.lang&&(n+=`&lang=${e.lang}`),e.avoid&&e.avoid.length>0&&(n+=`&avoid=${e.avoid.map((t=>t.type)).join("|")}`),e.details&&e.details.length>0&&(n+=`&details=${e.details.join(",")}`),e.traffic&&(n+=`&traffic=${e.traffic}`),e.max_speed&&(n+=`&max_speed=${e.max_speed}`),n}}class y extends Error{constructor(t,e,i){super(e),this.errorName=t,this.message=e,this.rawResponse=i,this.name=t,this.rawResponse=i}}class v{static cleanObject(t){if(Array.isArray(t))return t.length>0?t.map(v.cleanObject):void 0;if(null!==t&&"object"==typeof t){const e=Object.entries(t).reduce(((t,[e,i])=>{const n=v.cleanObject(i);return void 0!==n&&(t[e]=n),t}),{});return Object.keys(e).length>0?e:void 0}return t}static cloneObject(t){return JSON.parse(JSON.stringify(t))}}class f{static generateRoutePlannerResultData(t){var e,i,n;let s=v.cloneObject(t);return{agents:this.generateAgents(s),inputData:s.properties.params,unassignedAgents:null===(e=s.properties.issues)||void 0===e?void 0:e.unassigned_agents,unassignedJobs:null===(i=s.properties.issues)||void 0===i?void 0:i.unassigned_jobs,unassignedShipments:null===(n=s.properties.issues)||void 0===n?void 0:n.unassigned_shipments}}static generateAgents(t){let e=[];return t.features.forEach((t=>{e.push(t.properties)})),e}}class w{constructor(t,e,i){if(this.jobIndex=t,this.jobInputData=e,this.agentPlan=i,!e)throw new Error("jobInputData is undefined")}getAgentId(){return this.agentPlan?this.agentPlan.getAgentId():void 0}getAgentIndex(){return this.agentPlan?this.agentPlan.getAgentIndex():void 0}getRouteActions(){return this.agentPlan?this.agentPlan.getActions().filter((t=>t.getJobIndex()===this.jobIndex)):[]}getAgentPlan(){return this.agentPlan}getJobInputData(){return this.jobInputData}getJobIndex(){return this.jobIndex}}class x{constructor(t,e,i){if(this.shipmentIndex=t,this.shipmentInputData=e,this.agentPlan=i,!e)throw new Error("shipmentInputData is undefined")}getAgentId(){return this.agentPlan?this.agentPlan.getAgentId():void 0}getAgentIndex(){return this.agentPlan?this.agentPlan.getAgentIndex():void 0}getShipmentId(){return this.shipmentInputData.id}getShipmentIndex(){return this.shipmentIndex}getRouteActions(){return this.agentPlan?this.agentPlan.getActions().filter((t=>t.getShipmentIndex()===this.shipmentIndex)):[]}getAgentPlan(){return this.agentPlan}getShipmentInputData(){return this.shipmentInputData}}class _{constructor(t,e){this.agentIndex=e,this.message=t,this.name="Violation"}toString(){return this.message}}class A extends _{constructor(t,e,i,n){super(t,e),this.totalAmount=i,this.capacity=n,this.name="AgentPickupCapacityExceeded"}}class b extends _{constructor(t,e,i,n){super(t,e),this.totalAmount=i,this.capacity=n,this.name="AgentDeliveryCapacityExceeded"}}class I extends _{constructor(t,e,i){super(t,e),this.missingCapabilities=i,this.name="AgentMissingCapability"}}class T extends _{constructor(t,e){super(t,e),this.name="TimeWindowViolation"}}class S extends _{constructor(t,e){super(t,e),this.name="BreakViolation"}}class L extends Error{constructor(t,e){super(t),this.parameterName=e,this.name="InvalidParameter"}}class D extends Error{constructor(t,e){super(t),this.agentIdOrIndex=e,this.name="AgentNotFound"}}class P extends Error{constructor(t,e){super(t),this.jobIdOrIndex=e,this.name="JobNotFound"}}class E extends Error{constructor(t,e){super(t),this.shipmentIdOrIndex=e,this.name="ShipmentNotFound"}}class R extends Error{constructor(t,e){super(t),this.agentIndex=e,this.name="AgentHasNoPlan"}}class k extends Error{constructor(t,e){super(t),this.itemType=e,this.name="ItemsNotUnique"}}class $ extends Error{constructor(t,e){super(t),this.itemType=e,this.name="NoItemsProvided"}}class O extends Error{constructor(t,e,i,n){super(t),this.itemType=e,this.itemIndex=i,this.agentIndex=n,this.name="ItemAlreadyAssigned"}}class W extends Error{constructor(t,e,i,n){super(t),this.agentIndex=e,this.waypointIndex=i,this.actionId=n,this.name="InvalidInsertionPosition"}}class j extends Error{constructor(t,e,i){super(t),this.strategy=e,this.operationType=i,this.name="UnknownStrategy"}}class C extends Error{constructor(t,e,i){super(t),this.statusCode=e,this.statusText=i,this.name="RouteMatrixApiError"}}class M extends Error{constructor(t,e,i){super(t),this.statusCode=e,this.statusText=i,this.name="RoutingApiError"}}class J{static convertAgentToIndex(t,e,i=!1){if("number"==typeof e)return e;let n=t.properties.params.agents.findIndex((t=>t.id===e));if(-1===n){if(i)throw new D(`Agent with id ${e} not found`,e);return-1}return n}static convertJobToIndex(t,e){if("number"==typeof e)return e;let i=t.properties.params.jobs.findIndex((t=>t.id===e));return i<0?-1:i}static convertShipmentToIndex(t,e){if("number"==typeof e)return e;let i=t.properties.params.shipments.findIndex((t=>t.id===e));return i<0?-1:i}static convertJobsToIndexes(t,e){if("number"==typeof e[0])return e;let i=[];return e.forEach((e=>{let n=t.properties.params.jobs.findIndex((t=>t.id===e));if(n<0)throw new P(`Job with id ${e} not found`,e);i.push(n)})),i}static convertShipmentsToIndexes(t,e){if("number"==typeof e[0])return e;let i=[];return e.forEach((e=>{let n=t.properties.params.shipments.findIndex((t=>t.id===e));if(n<0)throw new E(`Shipment with id ${e} not found`,e);i.push(n)})),i}}class N{constructor(t,e){this.callOptions=t,this.rawData=e,this.data=f.generateRoutePlannerResultData(this.rawData),this.agentPlans=new Array(this.data.inputData.agents.length).fill(void 0),this.data.agents.forEach((t=>{this.agentPlans[t.agent_index]=new m(t,this.data.inputData.agents[t.agent_index],this.getData().inputData,this.callOptions,this.getAgentViolations(t.agent_index))})),this.shipmentPlans=(this.data.inputData.shipments||[]).map(((t,e)=>{const i=this.agentPlans.find((t=>!!t&&t.containsShipment(e)));return new x(e,t,i)})),this.jobPlans=(this.data.inputData.jobs||[]).map(((t,e)=>{const i=this.agentPlans.find((t=>!!t&&t.containsJob(e)));return new w(e,t,i)}))}getData(){return this.data}getRaw(){return this.rawData}getAgentPlans(){return this.agentPlans}getAgentPlan(t){const e=J.convertAgentToIndex(this.getRaw(),t);if(e>=0)return this.agentPlans[e]}getUnassignedAgents(){let t=this.getData();return t.unassignedAgents&&0!=t.unassignedAgents.length?t.unassignedAgents.map((e=>t.inputData.agents[e])):[]}getUnassignedJobs(){let t=this.getData();return t.unassignedJobs&&0!=t.unassignedJobs.length?t.unassignedJobs.map((e=>t.inputData.jobs[e])):[]}getUnassignedShipments(){let t=this.getData();return t.unassignedShipments&&0!=t.unassignedShipments.length?t.unassignedShipments.map((e=>t.inputData.shipments[e])):[]}getJobPlans(){return this.jobPlans}getJobPlan(t){const e=J.convertJobToIndex(this.getRaw(),t);if(e>=0)return this.jobPlans[e]}getShipmentPlans(){return this.shipmentPlans}getShipmentPlan(t){const e=J.convertShipmentToIndex(this.getRaw(),t);if(e>=0)return this.shipmentPlans[e]}getCallOptions(){return this.callOptions}getRoutingOptions(){return this.data.inputData}getAgentViolations(t){var e,i;return null!==(i=null===(e=this.rawData.properties.violations)||void 0===e?void 0:e.filter((e=>e.agentIndex===t)))&&void 0!==i?i:[]}}var F={__proto__:null,Agent:n,AgentDeliveryCapacityExceeded:b,AgentHasNoPlan:R,AgentMissingCapability:I,AgentNotFound:D,AgentPickupCapacityExceeded:A,AgentPlan:m,Avoid:o,Break:a,BreakViolation:S,Coordinates:s,InvalidInsertionPosition:W,InvalidParameter:L,ItemAlreadyAssigned:O,ItemsNotUnique:k,Job:r,JobNotFound:P,Location:l,NoItemsProvided:$,PRESERVE_ORDER:i,REOPTIMIZE:e,RouteAction:h,RouteLeg:u,RouteLegStep:p,RouteMatrixApiError:C,RoutePlannerError:y,RoutePlannerResult:N,RoutingApiError:M,Shipment:d,ShipmentNotFound:E,ShipmentStep:c,TimeWindowViolation:T,UnknownStrategy:j,Violation:_,Waypoint:g};class U{constructor(t,e){this.baseUrl=t.baseUrl||"https://api.geoapify.com",this.options=Object.assign(Object.assign({},t),{baseUrl:this.baseUrl}),this.raw=e||{agents:[],jobs:[],shipments:[],locations:[],avoid:[]}}getRaw(){return this.raw}setRaw(t){return this.raw=t,this}setMode(t){return this.raw.mode=t,this}addAgent(t){return this.raw.agents.push(t.getRaw()),this}addJob(t){return this.raw.jobs.push(t.getRaw()),this}addLocation(t){return this.raw.locations.push(t.getRaw()),this}addShipment(t){return this.raw.shipments.push(t.getRaw()),this}addAvoid(t){return this.raw.avoid=this.raw.avoid||[],this.raw.avoid.push(t.getRaw()),this}setTraffic(t){return this.raw.traffic=t,this}setType(t){return this.raw.type=t,this}setMaxSpeed(t){return this.raw.max_speed=t,this}setUnits(t){return this.raw.units=t,this}plan(){return t(this,void 0,void 0,(function*(){try{return yield this.callPlan()}catch(t){if(t instanceof y)throw t;throw new y((null==t?void 0:t.name)||"UnknownError",(null==t?void 0:t.message)||"An unknown error occurred",t)}}))}callPlan(){return t(this,void 0,void 0,(function*(){const e=v.cleanObject(this.raw),i=yield function(e,i){return t(this,void 0,void 0,(function*(){if("undefined"!=typeof fetch)return fetch(e,i);try{const t=Function("return import('node-fetch')")();return(0,(yield t).default)(e,i)}catch(t){throw new Error("Fetch is not available in this environment. If you are using Node.js <18, install 'node-fetch' manually: npm install node-fetch")}}))}(`${this.baseUrl}/v1/routeplanner?apiKey=${this.options.apiKey}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!i.ok){let t=yield i.json();throw new y(t.error,t.message,t)}let n=yield i.json();return new N(this.options,n)}))}}class B{static createAssignAgentRequirement(t){return`${this.ASSIGN_AGENT_PREFIX}${t}`}static ensureRequirementsArray(t){t.requirements||(t.requirements=[])}static addRequirement(t,e){t.includes(e)||t.push(e)}static removeRequirement(t,e){const i=t.indexOf(e);-1!==i&&t.splice(i,1)}static markAsUnassigned(t){this.ensureRequirementsArray(t),this.addRequirement(t.requirements,this.UNASSIGNED_REQ)}static assignToAgent(t,e){const i=this.createAssignAgentRequirement(e);this.ensureRequirementsArray(t),this.removeRequirement(t.requirements,this.UNASSIGNED_REQ),this.addRequirement(t.requirements,i)}static markItemsAsUnassigned(t,e){for(const i of e)t[i]&&this.markAsUnassigned(t[i])}static assignItemsToAgent(t,e,i){for(const n of e)t[n]&&this.assignToAgent(t[n],i)}static markExistingUnassignedJobs(t,e){var i;const n=null===(i=t.getRawData().properties.issues)||void 0===i?void 0:i.unassigned_jobs;n&&this.markItemsAsUnassigned(e,n)}static markExistingUnassignedShipments(t,e){var i;const n=null===(i=t.getRawData().properties.issues)||void 0===i?void 0:i.unassigned_shipments;n&&this.markItemsAsUnassigned(e,n)}static markRemainingJobsWithAgentRequirement(t,e,i){for(let n=0;n<e.length;n++){if(i.includes(n))continue;const s=t.getAgentIndexForJob(n);void 0!==s&&this.assignToAgent(e[n],s)}}static markRemainingShipmentsWithAgentRequirement(t,e,i){for(let n=0;n<e.length;n++){if(i.includes(n))continue;const s=t.getAgentIndexForShipment(n);void 0!==s&&this.assignToAgent(e[n],s)}}static extendAgentTimeWindows(t){var e,i,n;const s=null!==(n=null===(i=null===(e=null==t?void 0:t.time_windows)||void 0===e?void 0:e[0])||void 0===i?void 0:i[0])&&void 0!==n?n:0;t.time_windows=[[s,4102444800]]}static restrictAssignmentsToTargetSet(t,e){for(let i=0;i<t.length;i++){const n=t[i];n&&(e.has(i)?delete n.requirements:(this.ensureRequirementsArray(n),this.addRequirement(n.requirements,this.NON_ASSIGNABLE_REQUIREMENT)))}}}B.UNASSIGNED_REQ="unassigned",B.ASSIGN_AGENT_PREFIX="assign-agent-",B.NON_ASSIGNABLE_REQUIREMENT="NON_ASSIGNABLE";class q{static validate(t,e){const i=t.getRawData(),n=[];let s=this.validateTimeWindows(t,e);n.push(...s);let o=this.validateBreaks(t,e);n.push(...o);let a=this.validateCapacity(t,e);n.push(...a);let r=this.validateCapabilities(t,e);n.push(...r),this.addViolationsToResult(i,e,n)}static validateTimeWindows(t,e){var i;const n=[],s=t.getRawData(),o=s.properties.params.agents[e],a=t.getAgentActions(e);for(const t of a){if(t.type===this.ACTION_TYPE_START||t.type===this.ACTION_TYPE_END||t.type===this.ACTION_TYPE_BREAK||t.type===this.ACTION_TYPE_DELAY)continue;const a=this.getActionTimeWindow(t),r=this.getItemTimeWindows(s,t);r.length>0&&!this.isWithinAnyTimeWindow(a,r)&&n.push(new T(`Action at time ${t.start_time} is outside ${t.type} time windows`,e)),(null===(i=o.time_windows)||void 0===i?void 0:i.length)>0&&!this.isWithinAnyTimeWindow(a,o.time_windows)&&n.push(new T(`Action at time ${t.start_time} is outside agent time windows`,e))}return n}static validateBreaks(t,e){var i;const n=[],s=t.getRawData().properties.params.agents[e],o=t.getAgentActions(e);if(!(null===(i=s.breaks)||void 0===i?void 0:i.length))return n;for(const t of o){if(t.type===this.ACTION_TYPE_START||t.type===this.ACTION_TYPE_END||t.type===this.ACTION_TYPE_BREAK||t.type===this.ACTION_TYPE_DELAY)continue;const i=this.getActionTimeWindow(t);for(const o of s.breaks)if(this.intersectsAnyTimeWindow(i,o.time_windows)){n.push(new S(`Action at time ${t.start_time} conflicts with agent break`,e));break}}return n}static validateCapacity(t,e){const i=[],n=t.getRawData(),s=n.properties.params.agents[e],o=t.getAgentActions(e);let a=0,r=0;for(const t of o)t.type===this.ACTION_TYPE_PICKUP?a+=this.getActionAmount(n,t):t.type===this.ACTION_TYPE_DELIVERY?r+=this.getActionAmount(n,t):t.type===this.ACTION_TYPE_JOB&&(a+=this.getJobPickupAmount(n,t),r+=this.getJobDeliveryAmount(n,t));const l=this.normalizeCapacity(s.pickup_capacity);void 0!==s.pickup_capacity&&void 0===l?i.push(new A(`Agent pickup capacity is invalid (${String(s.pickup_capacity)})`,e,a,0)):void 0!==l&&a>l&&i.push(new A(`Total pickup amount (${a}) exceeds agent pickup capacity (${l})`,e,a,l));const d=this.normalizeCapacity(s.delivery_capacity);return void 0!==s.delivery_capacity&&void 0===d?i.push(new b(`Agent delivery capacity is invalid (${String(s.delivery_capacity)})`,e,r,0)):void 0!==d&&r>d&&i.push(new b(`Total delivery amount (${r}) exceeds agent delivery capacity (${d})`,e,r,d)),i}static validateCapabilities(t,e){var i,n;const s=[],o=t.getRawData(),a=o.properties.params.agents[e],r=t.getAgentActions(e),l=new Set;for(const t of r){if(void 0!==t.job_index){const e=null===(i=o.properties.params.jobs)||void 0===i?void 0:i[t.job_index];this.collectMissingRequirements(a,null==e?void 0:e.requirements,l)}if(void 0!==t.shipment_index){const e=null===(n=o.properties.params.shipments)||void 0===n?void 0:n[t.shipment_index];this.collectMissingRequirements(a,null==e?void 0:e.requirements,l)}}if(0===l.size)return s;const d=Array.from(l),c=1===d.length?`Agent is missing required capability: '${d[0]}'`:`Agent is missing required capabilities: ${d.join(", ")}`;return s.push(new I(c,e,d)),s}static collectMissingRequirements(t,e,i){var n;if(null==e?void 0:e.length)for(const s of e)(null===(n=t.capabilities)||void 0===n?void 0:n.includes(s))||i.add(s)}static getActionTimeWindow(t){return[t.start_time,t.start_time+(t.duration||0)]}static getItemTimeWindows(t,e){var i,n;if(void 0!==e.job_index){const i=t.properties.params.jobs[e.job_index];return(null==i?void 0:i.time_windows)||[]}if(void 0!==e.shipment_index){const s=t.properties.params.shipments[e.shipment_index];if(e.type===this.ACTION_TYPE_PICKUP)return(null===(i=null==s?void 0:s.pickup)||void 0===i?void 0:i.time_windows)||[];if(e.type===this.ACTION_TYPE_DELIVERY)return(null===(n=null==s?void 0:s.delivery)||void 0===n?void 0:n.time_windows)||[]}return[]}static getActionAmount(t,e){if(void 0!==e.shipment_index){const i=t.properties.params.shipments[e.shipment_index];return this.normalizeAmount(null==i?void 0:i.amount)}return 0}static getJobPickupAmount(t,e){if(void 0!==e.job_index){const i=t.properties.params.jobs[e.job_index];return this.normalizeAmount(null==i?void 0:i.pickup_amount)}return 0}static getJobDeliveryAmount(t,e){if(void 0!==e.job_index){const i=t.properties.params.jobs[e.job_index];return this.normalizeAmount(null==i?void 0:i.delivery_amount)}return 0}static normalizeAmount(t){return"number"!=typeof t||!Number.isFinite(t)||t<0?0:t}static normalizeCapacity(t){if(void 0!==t&&"number"==typeof t&&Number.isFinite(t)&&!(t<0))return t}static isWithinAnyTimeWindow(t,e){const[i,n]=t;return e.some((([t,e])=>i>=t&&n<=e))}static intersectsAnyTimeWindow(t,e){const[i,n]=t;return e.some((([t,e])=>i<e&&n>t))}static addViolationsToResult(t,e,i){t.properties.violations=(t.properties.violations||[]).filter((t=>t.agentIndex!==e)),0!==i.length?t.properties.violations.push(...i):t.properties.violations.length||delete t.properties.violations}}q.ACTION_TYPE_PICKUP="pickup",q.ACTION_TYPE_DELIVERY="delivery",q.ACTION_TYPE_START="start",q.ACTION_TYPE_END="end",q.ACTION_TYPE_BREAK="break",q.ACTION_TYPE_DELAY="delay",q.ACTION_TYPE_JOB="job";class z{static hasExplicitInsertPosition(t){return(void 0!==t.afterId&&""!==t.afterId||void 0!==t.afterWaypointIndex)&&!0===t.append}static shouldAppend(t){return!0===t.append&&!t.afterId&&void 0===t.afterWaypointIndex}static resolveInsertPosition(t){return void 0!==t.afterWaypointIndex?t.afterWaypointIndex+1:0}static validateAfterWaypointIndex(t,e,i){const n=t.getAgentWaypoints(e),s=n.length-1;if(0===n.length)throw new W(`Agent ${e} has no route.`,e);if(i<0||i>=n.length)throw new W(`Waypoint index ${i} out of range (0-${n.length-1})`,e,i);if(i===s&&n[s].actions.some((t=>"end"===t.type)))throw new W(`Cannot change the route after waypoint ${i} (end location).`,e,i)}static extractRouteLocations(t){return t.properties.waypoints.map((t=>t.location||t.original_location))}}class Y{static createJobAction(t,e,i){const n=this.getJobByIndex(t,e);return{index:0,type:"job",start_time:0,duration:n.duration||0,job_index:e,job_id:n.id,waypoint_index:i}}static createShipmentAction(t,e,i,n){var s,o;const a=this.getShipmentByIndex(t,e);return{index:0,type:i,start_time:0,duration:"pickup"===i?(null===(s=a.pickup)||void 0===s?void 0:s.duration)||0:(null===(o=a.delivery)||void 0===o?void 0:o.duration)||0,shipment_index:e,shipment_id:a.id,waypoint_index:n}}static getJobByIndex(t,e){return t.getRawData().properties.params.jobs[e]}static getShipmentByIndex(t,e){return t.getRawData().properties.params.shipments[e]}static resolveShipmentStepLocation(t,e){return this.resolveShipmentStepWaypointLocationData(t,e).location}static resolveShipmentStepWaypointLocationData(t,e){if(e.location)return{location:e.location};if(void 0!==e.location_index){const i=t.getRawData().properties.params.locations[e.location_index];if(!(null==i?void 0:i.location))throw new Error(`Shipment step has invalid location_index ${e.location_index}`);return{location:i.location,locationIndex:e.location_index,locationId:i.id}}throw new Error("Shipment step must have either location or location_index")}static resolveJobLocation(t,e){return this.resolveJobWaypointLocationData(t,e).location}static resolveJobWaypointLocationData(t,e){if(e.location)return{location:e.location};if(void 0!==e.location_index){const i=t.getRawData().properties.params.locations[e.location_index];if(!(null==i?void 0:i.location))throw new Error(`Job has invalid location_index ${e.location_index}`);return{location:i.location,locationIndex:e.location_index,locationId:i.id}}throw new Error("Job must have either location or location_index")}}const K=-1;class V{static replaceLegsForInsertedWaypoint(t,e,i){const n=t.getAgentFeature(e).properties;n.legs||(n.legs=[]);const s=n.legs,o=n.waypoints,a={from_waypoint_index:i-1,to_waypoint_index:i,time:K,distance:K,steps:[]},r={from_waypoint_index:i,to_waypoint_index:i+1,time:K,distance:K,steps:[]};o.length<=1||(0===i?s.splice(i,0,r):i===o.length-1?s.splice(i,0,a):s.splice(i-1,1,a,r),s.forEach(((t,e)=>{t.from_waypoint_index=e,t.to_waypoint_index=e+1})))}static fillMissingLegData(e,i){return t(this,void 0,void 0,(function*(){const t=i.properties.waypoints||[],n=i.properties.legs||[],s=this.findMissingLegIndices(n);s.length>0&&(yield this.fillMissingOrderedLegs(e,t,n,s)),this.recreateGeometry(i,t,n)}))}static fillMissingOrderedLegs(e,i,n,s){var o,a,r,l,d,c;return t(this,void 0,void 0,(function*(){const p=e.getRoutingHelper(),u=yield Promise.all(s.map((e=>t(this,void 0,void 0,(function*(){const t=i[e+1],n=this.getWaypointLocation(i[e]),s=this.getWaypointLocation(t);if(!n||!s)return{legIndex:e,routeData:null};try{const t=yield p.calculateRouteData([n,s]);return{legIndex:e,routeData:t}}catch(t){return{legIndex:e,routeData:null}}})))));for(const t of u){const e=n[t.legIndex];if(!e)continue;const s=null===(a=null===(o=t.routeData)||void 0===o?void 0:o.legs)||void 0===a?void 0:a[0];s?(e.time=null!==(r=s.time)&&void 0!==r?r:0,e.distance=null!==(l=s.distance)&&void 0!==l?l:0,e.steps=[{distance:e.distance,time:s.time,from_index:0,to_index:1}]):(e.time=0,e.distance=0,e.steps=[]);const p=this.getMappedRouteWaypointLocation(null===(d=t.routeData)||void 0===d?void 0:d.waypoints,0),u=this.getMappedRouteWaypointLocation(null===(c=t.routeData)||void 0===c?void 0:c.waypoints,1);p&&(i[t.legIndex].location=p),u&&(i[t.legIndex+1].location=u)}}))}static recreateGeometry(t,e,i){const n=[];for(let t=0;t<i.length;t++){const s=this.getWaypointLocation(e[t]),o=this.getWaypointLocation(e[t+1]);s&&o&&(i[t].from_waypoint_index=t,i[t].to_waypoint_index=t+1,n.push([s,o]))}t.geometry=Object.assign(Object.assign({},t.geometry),{type:"MultiLineString",coordinates:n})}static getMappedRouteWaypointLocation(t,e){var i;if(!t||0===t.length)return;const n=t.find((t=>(null==t?void 0:t.original_index)===e));return(null==n?void 0:n.location)||(null===(i=t[e])||void 0===i?void 0:i.location)}static getWaypointLocation(t){if(t)return t.location||t.original_location}static findMissingLegIndices(t){const e=[];for(let i=0;i<t.length;i++){const n=t[i];n&&(void 0===n.time||n.time===K||n.time<0||void 0===n.distance||n.distance===K||n.distance<0)&&e.push(i)}return e}}class H{static insertJobWaypoint(t,e,i,n){const s=t.getAgentFeature(e).properties.waypoints,o=Y.getJobByIndex(t,i),a=Y.resolveJobWaypointLocationData(t,o),r=Y.createJobAction(t,i,n.position);n.createWaypoint?(s.splice(n.position,0,{original_location:a.location,original_location_index:a.locationIndex,original_location_id:a.locationId,start_time:r.start_time||0,duration:r.duration||0,actions:[r],prev_leg_index:void 0,next_leg_index:void 0}),V.replaceLegsForInsertedWaypoint(t,e,n.position)):this.addActionToWaypoint(s[n.position],r)}static insertShipmentWaypoints(t,e,i,n){const s=t.getAgentFeature(e).properties.waypoints,o=Y.getShipmentByIndex(t,i),a=Y.createShipmentAction(t,i,"pickup",n.pickup),r=Y.createShipmentAction(t,i,"delivery",n.delivery);if(n.createPickupWaypoint){const i=Y.resolveShipmentStepWaypointLocationData(t,o.pickup),r={original_location:i.location,original_location_index:i.locationIndex,original_location_id:i.locationId,start_time:a.start_time||0,duration:a.duration||0,actions:[Object.assign(Object.assign({},a),{waypoint_index:n.pickup})],prev_leg_index:void 0,next_leg_index:void 0};s.splice(n.pickup,0,r),V.replaceLegsForInsertedWaypoint(t,e,n.pickup)}else{const t=s[n.pickup];t&&this.addActionToWaypoint(t,a)}if(n.createDeliveryWaypoint){const i=Y.resolveShipmentStepWaypointLocationData(t,o.delivery),a={original_location:i.location,original_location_index:i.locationIndex,original_location_id:i.locationId,start_time:r.start_time||0,duration:r.duration||0,actions:[Object.assign(Object.assign({},r),{waypoint_index:n.delivery})],prev_leg_index:void 0,next_leg_index:void 0};s.splice(n.delivery,0,a),V.replaceLegsForInsertedWaypoint(t,e,n.delivery)}else{const t=s[n.delivery];t&&this.addActionToWaypoint(t,r)}}static addActionToWaypoint(t,e){const i=t.actions.findIndex((t=>"end"===t.type));i>=0?t.actions.splice(i,0,Object.assign({},e)):t.actions.push(Object.assign({},e))}static actionsMatch(t,e){return t.type===e.type&&("job"===t.type?t.job_index===e.job_index:"pickup"===t.type||"delivery"===t.type?t.shipment_index===e.shipment_index:"start"===t.type||"end"===t.type)}static removeJobsFromWaypoints(t,e){for(const i of t)i.actions=i.actions.filter((t=>t.job_index!==e))}static removeShipmentsFromWaypoints(t,e){for(const i of t)i.actions=i.actions.filter((t=>t.shipment_index!==e))}static removeEmptyWaypoints(t,e){const i=[],n=[];for(let e=0;e<t.length;e++)t[e].actions.length>0?i.push(t[e]):n.push(e);return e&&0!==n.length?{waypoints:i,legs:this.rebuildLegs(i,e),removedWaypointIndices:n}:{waypoints:i,removedWaypointIndices:n}}static buildLegDataMap(t,e){const i=new Map;for(const n of e){const e=t[n.from_waypoint_index],s=t[n.to_waypoint_index];if(!e||!s)continue;const o=this.getLocationPairKey(this.getWaypointLocation(e),this.getWaypointLocation(s));i.set(o,n)}return i}static rebuildLegs(t,e){const i=[];for(let n=0;n<t.length-1;n++){const s=t[n+1],o=this.getLocationPairKey(this.getWaypointLocation(t[n]),this.getWaypointLocation(s)),a=e.get(o);i.push(a?{from_waypoint_index:n,to_waypoint_index:n+1,time:a.time,distance:a.distance,steps:a.steps||[]}:{from_waypoint_index:n,to_waypoint_index:n+1,time:K,distance:K,steps:[]})}return i}static getLocationPairKey(t,e){return`${t[0]},${t[1]}->${e[0]},${e[1]}`}static getWaypointLocation(t){return t.location||t.original_location}}class G{static recalculate(e,i){return t(this,void 0,void 0,(function*(){const t=e.getAgentFeature(i),n=t.properties.waypoints,s=t.properties.legs||[];yield V.fillMissingLegData(e,t);let o=t.properties.start_time;const a=[];for(let e=0;e<n.length;e++)if(o+=e>0?s[e-1].time:0,n[e].start_time=o,0===e?delete n[e].prev_leg_index:n[e].prev_leg_index=e-1,e===n.length-1?delete n[e].next_leg_index:n[e].next_leg_index=e,n[e].actions.forEach((t=>{t.waypoint_index=e,t.index=a.length,t.start_time=o,o+=t.duration||0,a.push(t)})),n[e].duration=o-n[e].start_time,e<n.length-1)n[e].location=t.geometry.coordinates[e][0];else{const i=t.geometry.coordinates[e-1];n[e].location=i[i.length-1]}t.properties.end_time=o,t.properties.time=t.properties.end_time-t.properties.start_time,t.properties.actions=a,t.properties.distance=s.reduce(((t,e)=>t+e.distance),0)}))}}class X{constructor(t,e){this.baseUrl=t.baseUrl||"https://api.geoapify.com",this.apiKey=t.apiKey,this.routingOptions=e}calculateMatrix(e,i){return t(this,void 0,void 0,(function*(){const t=`${this.baseUrl}/v1/routematrix?apiKey=${this.apiKey}`,n=yield fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mode:this.routingOptions.mode||"drive",type:this.routingOptions.type,avoid:this.routingOptions.avoid,traffic:this.routingOptions.traffic,max_speed:this.routingOptions.max_speed,units:this.routingOptions.units,sources:e,targets:i})});if(!n.ok)throw new C(`Route Matrix API failed: ${n.statusText}`,n.status,n.statusText);return yield n.json()}))}calculateTravelTime(e,i){return t(this,void 0,void 0,(function*(){return(yield this.calculateMatrix([{location:e}],[{location:i}])).sources_to_targets[0][0].time}))}calculateTimesToLocation(e,i){return t(this,void 0,void 0,(function*(){return(yield this.calculateMatrix(this.toMatrixLocations(e),this.toMatrixLocations([i]))).sources_to_targets.map((t=>t[0].time))}))}calculateTimesFromLocation(e,i){return t(this,void 0,void 0,(function*(){return(yield this.calculateMatrix(this.toMatrixLocations([e]),this.toMatrixLocations(i))).sources_to_targets[0].map((t=>t.time))}))}toMatrixLocations(t){return t.map((t=>({location:t})))}}class Q{constructor(t,e){this.baseUrl=t.baseUrl||"https://api.geoapify.com",this.apiKey=t.apiKey,this.routingOptions=e}calculateConsecutiveTravelTimes(e){var i,n;return t(this,void 0,void 0,(function*(){if(e.length<2)return[];const t=e.map((t=>`lonlat:${t[0]},${t[1]}`)).join("|"),s=this.constructRoutingUrl(t),o=yield fetch(s);if(!o.ok)throw new M(`Routing API failed: ${o.statusText}`,o.status,o.statusText);const a=yield o.json(),r=null===(i=null==a?void 0:a.features)||void 0===i?void 0:i[0];return r&&(null===(n=r.properties)||void 0===n?void 0:n.legs)?r.properties.legs.map((t=>t.time)):new Array(e.length-1).fill(0)}))}calculateLegData(e){return t(this,void 0,void 0,(function*(){return(yield this.calculateRouteData(e)).legs}))}calculateRouteData(e){var i,n;return t(this,void 0,void 0,(function*(){if(e.length<2)return{legs:[],waypoints:[]};const t=e.map((t=>`lonlat:${t[0]},${t[1]}`)).join("|"),s=this.constructRoutingUrl(t),o=yield fetch(s);if(!o.ok)throw new M(`Routing API failed: ${o.statusText}`,o.status,o.statusText);const a=yield o.json(),r=null===(i=null==a?void 0:a.features)||void 0===i?void 0:i[0];return r&&(null===(n=r.properties)||void 0===n?void 0:n.legs)?{legs:r.properties.legs||[],waypoints:r.properties.waypoints||[]}:{legs:[],waypoints:[]}}))}constructRoutingUrl(t){let e=`${this.baseUrl}/v1/routing?waypoints=${t}&apiKey=${this.apiKey}`;return this.routingOptions.mode&&(e+=`&mode=${this.routingOptions.mode}`),this.routingOptions.type&&(e+=`&type=${this.routingOptions.type}`),this.routingOptions.units&&(e+=`&units=${this.routingOptions.units}`),this.routingOptions.avoid&&this.routingOptions.avoid.length>0&&(e+=`&avoid=${this.routingOptions.avoid.map((t=>t.type)).join("|")}`),this.routingOptions.traffic&&(e+=`&traffic=${this.routingOptions.traffic}`),this.routingOptions.max_speed&&(e+=`&max_speed=${this.routingOptions.max_speed}`),e}}const Z=1e-6;class tt{static findOptimalInsertionPoint(e,i,n,s,o){return t(this,void 0,void 0,(function*(){if(0===n.length)return 0;const t=this.getInsertionPositions(n.length,(null==o?void 0:o.canInsertBeforeFirst)||!1,(null==o?void 0:o.canInsertAfterLast)||!1);if(1===t.length)return t[0];const a=this.buildTravelTimeMap((null==o?void 0:o.travelTimes)||[]),r=yield this.getConsecutiveTimes(e,i,n,a);let l=t[0],d=Number.POSITIVE_INFINITY;for(const e of t){const t=this.calculateInsertionCost(e,n,s,a,r);t<d&&(d=t,l=e)}return l}))}static getConsecutiveTimes(e,i,n,s){return t(this,void 0,void 0,(function*(){if(n.length<2)return[];const t=e.getAgentFeature(i),o=t.properties.legs||[],a=(t.properties.waypoints||[]).map((t=>t.location||t.original_location)),r=this.findSubRouteStartIndex(a,n),l=[];for(let t=0;t<n.length-1;t++){const i=n[t],a=n[t+1];if(this.sameLocation(i,a)){l.push(0);continue}if(-1!==r){const e=r+t,i=e+1,n=o.find((t=>t.from_waypoint_index===e&&t.to_waypoint_index===i));if(n&&"number"==typeof n.time&&n.time>=0){l.push(n.time);continue}}const d=this.getTravelTimeKey(i,a),c=s.get(d);if(void 0!==c){l.push(c);continue}const p=(yield e.getRoutingHelper().calculateConsecutiveTravelTimes([i,a]))[0];if("number"!=typeof p)throw new Error(`Unable to calculate travel time between ${i[0]},${i[1]} and ${a[0]},${a[1]}.`);l.push(p)}return l}))}static findSubRouteStartIndex(t,e){if(0===e.length||t.length<e.length)return-1;const i=t.length-e.length;for(let n=0;n<=i;n++){let i=!0;for(let s=0;s<e.length;s++)if(!this.sameLocation(t[n+s],e[s])){i=!1;break}if(i)return n}return-1}static sameLocation(t,e){return Math.abs(t[0]-e[0])<=Z&&Math.abs(t[1]-e[1])<=Z}static calculateInsertionCost(t,e,i,n,s){if(t<=0)return this.getTravelTime(n,i,e[0]);if(t>=e.length)return this.getTravelTime(n,e[e.length-1],i);const o=t-1;return this.getTravelTime(n,e[o],i)+this.getTravelTime(n,i,e[t])-s[o]}static buildTravelTimeMap(t){const e=new Map;for(const i of t)e.set(this.getTravelTimeKey(i.locationFrom,i.locationTo),i.time);return e}static getTravelTime(t,e,i){const n=this.getTravelTimeKey(e,i),s=t.get(n);if(void 0===s)throw new Error(`Missing travel time for pair ${n}.`);return s}static getTravelTimeKey(t,e){return`${t[0]},${t[1]}->${e[0]},${e[1]}`}static getInsertionPositions(t,e,i){const n=i?t:t-1,s=[];for(let t=e?0:1;t<=n;t++)s.push(t);return s}}class et{execute(e,i,n){return t(this,void 0,void 0,(function*(){const t=new Set;for(const n of i){const i=this.removeJobFromResult(e,n);-1!==i&&t.add(i)}for(const i of t)yield G.recalculate(e,i),q.validate(e,i);return!0}))}removeJobFromResult(t,e){const i=t.getAgentIndexForJob(e);if(void 0===i)return-1;const n=t.getAgentFeature(i),s=n.properties.waypoints,o=H.buildLegDataMap(s,n.properties.legs||[]);H.removeJobsFromWaypoints(s,e);const a=H.removeEmptyWaypoints(s,o);return n.properties.waypoints=a.waypoints,a.legs&&(n.properties.legs=a.legs),this.addToUnassignedJobs(t,e),i}addToUnassignedJobs(t,e){const i=t.getRawData();i.properties.issues||(i.properties.issues={});const n=i.properties.issues;n.unassigned_jobs||(n.unassigned_jobs=[]),n.unassigned_jobs.includes(e)||n.unassigned_jobs.push(e)}}class it{execute(e,i,n){return t(this,void 0,void 0,(function*(){const t=new Map;for(const n of i){const i=e.getAgentIndexForJob(n);void 0!==i&&(t.has(i)||t.set(i,[]),t.get(i).push(n))}for(const[i,n]of t.entries()){const t=new Set(n),s=e.getAgentJobs(i).filter((e=>!t.has(e))),o=new Set(s),a=e.cloneInputData(),r=new Set(e.getAgentShipments(i)),l=a.agents[i];l&&(a.agents=[l],B.restrictAssignmentsToTargetSet(a.jobs||[],o),B.restrictAssignmentsToTargetSet(a.shipments||[],r),yield e.executeAgentPlan(i,a),q.validate(e,i))}return!0}))}}class nt{static getEndPosition(e,i){return t(this,void 0,void 0,(function*(){const t=(yield e.getOrCreateAgentFeature(i)).properties.waypoints||[];if(0===t.length)return 0;const n=t.length-1;return(t[n].actions||[]).some((t=>"end"===t.type))?n:n+1}))}static hasAgentStartLocation(t,e){const i=t.getRawData().properties.params.agents[e];return void 0!==i.start_location_index||void 0!==i.start_location}static hasAgentEndLocation(t,e){const i=t.getRawData().properties.params.agents[e];return void 0!==i.end_location_index||void 0!==i.end_location}}const st=1e-6;class ot extends nt{static determineInsertPosition(e,i,n,s){var o;return t(this,void 0,void 0,(function*(){const t=Y.getJobByIndex(e,n),a=Y.resolveJobLocation(e,t),r=e.getAgentFeature(i).properties.waypoints||[];if(z.shouldAppend(s))return{position:yield this.getEndPosition(e,i),createWaypoint:!0};if(z.hasExplicitInsertPosition(s))return{position:z.resolveInsertPosition(s),createWaypoint:!0};if(void 0!==s.afterWaypointIndex&&!s.append){const t=null!==(o=s.afterWaypointIndex)&&void 0!==o?o:0,l=this.findExistingWaypointByLocation(r,a,t+1);return-1!==l?{position:l,createWaypoint:!1}:{position:yield this.findOptimalInsertPositionAfter(e,i,n,t),createWaypoint:!0}}const l=this.findExistingWaypointByLocation(r,a,0);return-1!==l?{position:l,createWaypoint:!1}:{position:yield this.findOptimalInsertPosition(e,i,n),createWaypoint:!0}}))}static findOptimalInsertPosition(e,i,n){return t(this,void 0,void 0,(function*(){const t=Y.getJobByIndex(e,n),s=Y.resolveJobLocation(e,t),o=e.getAgentFeature(i);if(!o)return 1;const a=z.extractRouteLocations(o);if(0===a.length)return 1;const r=yield this.calculateTravelTimes(e,a,s);return yield tt.findOptimalInsertionPoint(e,i,a,s,{canInsertBeforeFirst:!this.hasAgentStartLocation(e,i),canInsertAfterLast:!this.hasAgentEndLocation(e,i),travelTimes:r})}))}static findOptimalInsertPositionAfter(e,i,n,s){return t(this,void 0,void 0,(function*(){const t=Y.getJobByIndex(e,n),o=Y.resolveJobLocation(e,t),a=e.getAgentFeature(i),r=z.extractRouteLocations(a),l=Math.max(0,s),d=r.slice(l);if(0===d.length)return l;const c=yield this.calculateTravelTimes(e,d,o);return l+(yield tt.findOptimalInsertionPoint(e,i,d,o,{canInsertBeforeFirst:!1,canInsertAfterLast:!this.hasAgentEndLocation(e,i),travelTimes:c}))}))}static calculateTravelTimes(e,i,n){return t(this,void 0,void 0,(function*(){const t=e.getMatrixHelper(),[s,o]=yield Promise.all([t.calculateTimesToLocation(i,n),t.calculateTimesFromLocation(n,i)]),a=[];for(let t=0;t<i.length;t++)a.push({locationFrom:i[t],locationTo:n,time:s[t]}),a.push({locationFrom:n,locationTo:i[t],time:o[t]});return a}))}static findExistingWaypointByLocation(t,e,i){for(let n=Math.max(0,i);n<t.length;n++)if(this.sameLocation(t[n].original_location||t[n].location,e))return n;return-1}static sameLocation(t,e){return Math.abs(t[0]-e[0])<=st&&Math.abs(t[1]-e[1])<=st}}class at{static createAssignStrategy(t){const e=this.assignStrategies.get(t);if(!e)throw new j(`Unknown assign strategy: ${t}`,t,"assign");return e}static createRemoveStrategy(t){const e=this.removeStrategies.get(t);if(!e)throw new j(`Unknown remove strategy: ${t}`,t,"remove");return e}}at.assignStrategies=new Map([[e,new class{execute(e,i,n,s){return t(this,void 0,void 0,(function*(){yield this.removeJobsFromCurrentAgents(e,n,s);const t=new Set(e.getAgentJobs(i));n.forEach((e=>t.add(e)));const o=new Set(e.getAgentShipments(i)),a=e.cloneInputData(),r=a.agents[i];if(!r)return!1;B.extendAgentTimeWindows(r),this.clearTimeWindowsForAssignedJobs(a.jobs||[],n),a.agents=[r],B.restrictAssignmentsToTargetSet(a.jobs||[],t),B.restrictAssignmentsToTargetSet(a.shipments||[],o);const l=yield e.executeAgentPlan(i,a);return q.validate(e,i),l}))}removeJobsFromCurrentAgents(n,s,o){var a;return t(this,void 0,void 0,(function*(){const t=null!==(a=o.removeStrategy)&&void 0!==a?a:i,r=t===e?new it:new et,l={strategy:t};yield r.execute(n,s,l)}))}clearTimeWindowsForAssignedJobs(t,e){for(const i of e){const e=t[i];e&&delete e.time_windows}}}],[i,new class{execute(e,i,n,s){return t(this,void 0,void 0,(function*(){yield this.removeJobsFromCurrentAgents(e,n,s);for(let t=0;t<n.length;t++){const o=yield ot.determineInsertPosition(e,i,n[t],s);H.insertJobWaypoint(e,i,n[t],o),yield G.recalculate(e,i)}return q.validate(e,i),!0}))}removeJobsFromCurrentAgents(n,s,o){var a;return t(this,void 0,void 0,(function*(){const t=null!==(a=o.removeStrategy)&&void 0!==a?a:i,r=t===e?new it:new et,l={strategy:t};yield r.execute(n,s,l)}))}}]]),at.removeStrategies=new Map([[e,new it],[i,new et]]);class rt{execute(e,i,n){return t(this,void 0,void 0,(function*(){const t=new Set;for(const n of i){const i=this.removeShipmentFromResult(e,n);-1!==i&&t.add(i)}for(const i of t)yield G.recalculate(e,i),q.validate(e,i);return!0}))}removeShipmentFromResult(t,e){const i=t.getAgentIndexForShipment(e);if(void 0===i)return-1;const n=t.getAgentFeature(i),s=n.properties.waypoints,o=n.properties.legs||[];H.removeShipmentsFromWaypoints(s,e);const a=H.buildLegDataMap(s,o),r=H.removeEmptyWaypoints(s,a);return n.properties.waypoints=r.waypoints,r.legs&&(n.properties.legs=r.legs),i}}class lt{execute(e,i,n){return t(this,void 0,void 0,(function*(){const t=new Map;for(const n of i){const i=e.getAgentIndexForShipment(n);void 0!==i&&(t.has(i)||t.set(i,[]),t.get(i).push(n))}for(const[i,n]of t.entries()){const t=new Set(n),s=e.getAgentShipments(i).filter((e=>!t.has(e))),o=new Set(s),a=e.cloneInputData(),r=new Set(e.getAgentJobs(i)),l=a.agents[i];l&&(a.agents=[l],B.restrictAssignmentsToTargetSet(a.jobs||[],r),B.restrictAssignmentsToTargetSet(a.shipments||[],o),yield e.executeAgentPlan(i,a),q.validate(e,i))}return!0}))}}const dt=1e-6;class ct extends nt{static determineShipmentInsertPositions(e,i,n,s){return t(this,void 0,void 0,(function*(){if(z.shouldAppend(s)){const t=yield this.getAppendToEndPositions(e,i);return Object.assign(Object.assign({},t),{createPickupWaypoint:!0,createDeliveryWaypoint:!0})}if(z.hasExplicitInsertPosition(s)){const t=z.resolveInsertPosition(s);return{pickup:t,delivery:t+1,createPickupWaypoint:!0,createDeliveryWaypoint:!0}}if(void 0!==s.afterWaypointIndex&&!s.append){const t=s.afterWaypointIndex;return yield this.findOptimalShipmentPositionsAfter(e,i,n,t)}return yield this.findOptimalShipmentPositions(e,i,n)}))}static getAppendToEndPositions(e,i){return t(this,void 0,void 0,(function*(){const t=(yield e.getOrCreateAgentFeature(i)).properties.waypoints||[];return 0===t.length?{pickup:0,delivery:1}:t[t.length-1].actions.some((t=>"end"===t.type))?{pickup:t.length-1,delivery:t.length}:{pickup:t.length,delivery:t.length+1}}))}static findOptimalShipmentPositions(e,i,n){return t(this,void 0,void 0,(function*(){const t=Y.getShipmentByIndex(e,n),s=Y.resolveShipmentStepLocation(e,t.pickup),o=Y.resolveShipmentStepLocation(e,t.delivery),a=e.getAgentFeature(i),r=z.extractRouteLocations(a),l=a.properties.waypoints||[],d=this.findExistingWaypointByOriginalLocation(l,s,0),c=this.findExistingWaypointByOriginalLocation(l,o,0);let p,u=!0,h=!0,g=0,m=0;if(-1!==d)u=!1,g=d;else if(-1!==c){const t=r.slice(0,c+1);p=yield this.calculateTravelTimes(e,t,s),g=yield tt.findOptimalInsertionPoint(e,i,t,s,{canInsertBeforeFirst:!this.hasAgentStartLocation(e,i),canInsertAfterLast:!1,travelTimes:p})}else 0===r.length?g=0:1===r.length?g=this.hasAgentStartLocation(e,i)?1:0:(p=yield this.calculateTravelTimes(e,r,s),g=yield tt.findOptimalInsertionPoint(e,i,r,s,{canInsertBeforeFirst:!this.hasAgentStartLocation(e,i),canInsertAfterLast:!this.hasAgentEndLocation(e,i),travelTimes:p}));if(-1!==c&&c>=g)h=!1,m=c;else{const t=[...r];u&&t.splice(g,0,s);const n=yield this.calculateTravelTimes(e,t.slice(g),o,p);m=g+(yield tt.findOptimalInsertionPoint(e,i,t.slice(g),o,{canInsertBeforeFirst:!1,travelTimes:n}))}return{pickup:g,delivery:m,createPickupWaypoint:u,createDeliveryWaypoint:h}}))}static findOptimalShipmentPositionsAfter(e,i,n,s){return t(this,void 0,void 0,(function*(){const t=Y.getShipmentByIndex(e,n),o=Y.resolveShipmentStepLocation(e,t.pickup),a=Y.resolveShipmentStepLocation(e,t.delivery),r=e.getAgentFeature(i),l=z.extractRouteLocations(r),d=r.properties.waypoints||[],c=this.findExistingWaypointByOriginalLocation(d,o,0),p=this.findExistingWaypointByOriginalLocation(d,a,0);let u,h=!0,g=!0,m=0,y=0,v=-1;if(-1!==c&&c>=s&&(h=!1,m=c,v=c),-1===v){const t=Math.max(0,s),n=-1!==p&&p>=t;let a;const r=n?l.slice(t,p+1):l.slice(t);if(0===r.length)m=t,v=t;else{const s=n?{canInsertBeforeFirst:!1,canInsertAfterLast:!1}:{canInsertBeforeFirst:!1,canInsertAfterLast:!this.hasAgentEndLocation(e,i)};u=yield this.calculateTravelTimes(e,r,o),a=yield tt.findOptimalInsertionPoint(e,i,r,o,Object.assign(Object.assign({},s),{travelTimes:u})),v=t+a,m=v}}if(-1!==p&&p>=v)g=!1,y=h?p+1:p;else{const t=[...l];h&&t.splice(v,0,o);const n=yield this.calculateTravelTimes(e,t.slice(v),a,u),s=yield tt.findOptimalInsertionPoint(e,i,t.slice(v),a,{canInsertBeforeFirst:!1,travelTimes:n});y=h?m+s+1:m+s}return{pickup:m,delivery:y,createPickupWaypoint:h,createDeliveryWaypoint:g}}))}static findExistingWaypointByOriginalLocation(t,e,i){for(let n=Math.max(0,i);n<t.length;n++)if(this.sameLocation(t[n].original_location,e))return n;return-1}static sameLocation(t,e){return Math.abs(t[0]-e[0])<=dt&&Math.abs(t[1]-e[1])<=dt}static calculateTravelTimes(e,i,n,s){return t(this,void 0,void 0,(function*(){const t=e.getMatrixHelper(),[o,a]=yield Promise.all([t.calculateTimesToLocation(i,n),t.calculateTimesFromLocation(n,i)]),r=s||[];for(let t=0;t<i.length;t++)r.push({locationFrom:i[t],locationTo:n,time:o[t]}),r.push({locationFrom:n,locationTo:i[t],time:a[t]});return r}))}}class pt{static createAssignStrategy(t){const e=this.assignStrategies.get(t);if(!e)throw new j(`Unknown assign strategy: ${t}`,t,"assign");return e}static createRemoveStrategy(t){const e=this.removeStrategies.get(t);if(!e)throw new j(`Unknown remove strategy: ${t}`,t,"remove");return e}}pt.assignStrategies=new Map([[e,new class{execu