@trakit/sync 0.0.60 → 0.0.61
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/API/Functions.d.ts
CHANGED
|
@@ -83,4 +83,12 @@ export declare function requestRelayCors(request: Request): Promise<Response>;
|
|
|
83
83
|
* @returns
|
|
84
84
|
*/
|
|
85
85
|
export declare function requestRelayCorsJson(request: Request): Promise<JsonObject>;
|
|
86
|
+
/**
|
|
87
|
+
* Utility function to get a value from a Map by key, or create and set it using a factory function if it doesn't exist.
|
|
88
|
+
* @param map The Map to get/set the value from/in.
|
|
89
|
+
* @param key The key to look up in the Map.
|
|
90
|
+
* @param factory A function that takes the key and returns a value to set if the key is not already in the Map.
|
|
91
|
+
* @returns The existing or newly created value associated with the key in the Map.
|
|
92
|
+
*/
|
|
93
|
+
export declare function MAP_GET_OR_SET<TKey>(map: Map<TKey, any>, key: TKey, factory: (key: TKey) => any): any;
|
|
86
94
|
//# sourceMappingURL=Functions.d.ts.map
|
|
@@ -29,7 +29,7 @@ export declare class TrakitSyncCommander extends TrakitObjectCommander<any> {
|
|
|
29
29
|
*/
|
|
30
30
|
get socketOnline(): boolean;
|
|
31
31
|
/**
|
|
32
|
-
*
|
|
32
|
+
* Details of the underlying Trak-iT WebSocket service.
|
|
33
33
|
*/
|
|
34
34
|
get socketDetails(): {
|
|
35
35
|
state: TrakitSocketStatus;
|
package/WebSocket/Events.d.ts
CHANGED
|
@@ -19,12 +19,16 @@ export declare class TrakitEventSocketMessage extends TrakitEvent {
|
|
|
19
19
|
/**
|
|
20
20
|
* Used when the Trak-iT WebSocket is closed, or an error occurs that causes the connection to close.
|
|
21
21
|
*/
|
|
22
|
-
export declare class
|
|
22
|
+
export declare class TrakitEventSocketState extends TrakitEvent {
|
|
23
|
+
/**
|
|
24
|
+
* Indicates whether the WebSocket connection is currently online (open) or offline (closed).
|
|
25
|
+
*/
|
|
26
|
+
readonly online: boolean;
|
|
23
27
|
/**
|
|
24
28
|
* The reply contains the details and reason provided by the Trak-iT service when the WebSocket is closed.
|
|
25
29
|
*/
|
|
26
30
|
readonly reply: Reply;
|
|
27
|
-
constructor(type: string, reply: Reply);
|
|
31
|
+
constructor(type: string, online: boolean, reply: Reply);
|
|
28
32
|
}
|
|
29
33
|
/**
|
|
30
34
|
* Event raised when a broadcast message is received from the Trak-iT WebSocket.
|
|
@@ -77,7 +77,7 @@ export declare class TrakitSocketCommander extends TrakitObjectCommander<[string
|
|
|
77
77
|
/**
|
|
78
78
|
* Gets invoked any time the WebSocket connection is established and the `connectionResponse` message is received.
|
|
79
79
|
*/
|
|
80
|
-
_handleOpen(this: TrakitSocketCommander,
|
|
80
|
+
_handleOpen(this: TrakitSocketCommander, reply: RepSelfGet): any;
|
|
81
81
|
/**
|
|
82
82
|
* Gets invoked any time the WebSocket connection is closed.
|
|
83
83
|
*/
|
package/index.d.ts
CHANGED
|
@@ -11,14 +11,14 @@ import { TrakitObjectCommander } from "./API/TrakitObjectCommander";
|
|
|
11
11
|
import { HttpVerb } from "./RESTful/Constants";
|
|
12
12
|
import { TrakitRestfulCommander } from "./RESTful/TrakitRestfulCommander";
|
|
13
13
|
import { TrakitSyncCommander } from "./Synchronization/TrakitSyncCommander";
|
|
14
|
-
import {
|
|
14
|
+
import { TrakitEventSocketBroadcast, TrakitEventSocketMessage, TrakitEventSocketState } from "./WebSocket/Events";
|
|
15
15
|
import { makeCommandName } from "./WebSocket/Functions";
|
|
16
16
|
import { SubscribedRegions } from "./WebSocket/SubscribedRegions";
|
|
17
17
|
import { TrakitSocketCommander, TrakitSocketStatus } from "./WebSocket/TrakitSocketCommander";
|
|
18
18
|
/**
|
|
19
19
|
* Version number for this release.
|
|
20
20
|
*/
|
|
21
|
-
export declare const version = "0.0.
|
|
21
|
+
export declare const version = "0.0.61";
|
|
22
22
|
/**
|
|
23
23
|
* API exports
|
|
24
24
|
*/
|
|
@@ -34,5 +34,5 @@ export { makeCommandName, SubscribedRegions, TrakitSocketCommander, TrakitSocket
|
|
|
34
34
|
/**
|
|
35
35
|
* Synchronization exports
|
|
36
36
|
*/
|
|
37
|
-
export {
|
|
37
|
+
export { TrakitEventSocketBroadcast, TrakitEventSocketMessage, TrakitEventSocketState, TrakitSyncCommander };
|
|
38
38
|
//# sourceMappingURL=index.d.ts.map
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@trakit/sync",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "0.0.
|
|
4
|
+
"version": "0.0.61",
|
|
5
5
|
"main": "./trakit-sync.min.js",
|
|
6
6
|
"types": "./index.d.ts",
|
|
7
7
|
"scripts": {
|
|
@@ -28,14 +28,14 @@
|
|
|
28
28
|
"homepage": "https://github.com/trakitwireless/trakit-ts-sync#readme",
|
|
29
29
|
"description": "Trak-iT uses these object definitions to interact with all our APIs.",
|
|
30
30
|
"devDependencies": {
|
|
31
|
-
"@rollup/plugin-terser": "^0.
|
|
31
|
+
"@rollup/plugin-terser": "^1.0.0",
|
|
32
32
|
"rollup": "^4.35.0",
|
|
33
33
|
"rollup-plugin-typescript2": "^0.37.0",
|
|
34
34
|
"tsx": "^4.21.0",
|
|
35
35
|
"vitest": "^4.0.7"
|
|
36
36
|
},
|
|
37
37
|
"dependencies": {
|
|
38
|
-
"@trakit/commands": "^0.0.
|
|
39
|
-
"@trakit/objects": "^0.0.
|
|
38
|
+
"@trakit/commands": "^0.0.36",
|
|
39
|
+
"@trakit/objects": "^0.0.36"
|
|
40
40
|
}
|
|
41
41
|
}
|
package/trakit-sync.min.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
function e(e,t){return{errorCode:u.unknown,message:"Client exception",errorDetails:{kind:"stack",message:e?.message??"Unknonwn error",stack:e?.stack??null,value:t??null}}}function t(e){if("CompanyLabels"===(e=ir.capitalize(e)))e="CompanyStyle";else e=ir.singularize(e);return e}function s(e){const t=e.getAction();let s="GET",r=new URLSearchParams,n=[...t.object.match(yr)].map((e=>ir.pluralize(e.toLowerCase()))).join("/");switch(t.object){case"Self":"Get"==t.kind?(s="GET",n="self"):(s="POST",n="self/"+t.filter.toLowerCase());break;case"Subscription":throw new Error(t.object+" only supported by TrakitSocketCommander",{cause:t});case"DispatchJob":switch(t.filter){case"Cancel":s=t.batch?"PATCH":"POST",n+="/cancel";break;case"Change":s=t.batch?"PATCH":"PUT"}default:if(!t.batch){switch(e.getKey&&(n=ir.isCompounded(t.object)?n.replace("/","/"+e.getKey()+"/"):n+"/"+e.getKey()),t.kind){case"Get":break;case"List":switch(t.filter){case"Asset":n=t.object in wr?wr[t.object].replace("{assetId}",e.asset.id):`assets/${e.asset.id}/${n}`;break;case"BillingProfile":n=t.object in gr?gr[t.object].replace("{profileId}",e.billingProfile.id):`billing/profiles/${e.billingProfile.id}/${n}`;break;case"Company":n=t.object in mr?mr[t.object].replace("{companyId}",e.company.id):`companies/${e.company.id}/${n}`;break;case"User":n=`users/${encodeURIComponent(e.user.login)}/${n}`}if(ir.isntNaN(e?.after?.valueOf())&&r.set("after",e.after.toISOString()),ir.isntNaN(e?.before?.valueOf())&&r.set("before",e.before.toISOString()),ir.isntNaN(e?.lowest)&&r.set("lowest",e.lowest),ir.isntNaN(e?.highest)&&r.set("highest",e.highest),e?.first&&r.set("first",e.first),e?.last&&r.set("last",e.last),e?.labels?.length&&r.set("labels",e.labels.join(",")),e?.references?.size)for(const[t,s]of e.references.entries())r.set(t,s);break;case"Merge":s="POST";break;case"Delete":s="DELETE";break;case"Restore":s="PATCH",n+="/restore";break;case"Suspend":s="PATCH",n+="/suspend";break;case"Reactivate":s="PATCH",n+="/revive"}break}switch(s="PATCH",t.kind){case"Get":case"List":s="GET";break;case"Merge":break;case"Delete":s="DELETE";break;case"Restore":n+="/restore";break;case"Suspend":n+="/suspend";break;case"Reactivate":n+="/revive"}}return[s,r.size?n+"?"+r.toString():n]}async function r(e,t){const[r,i]=s(t);return n(e.account,e.createBaseUrl(i),r,"GET"===r?null:JSON.stringify(t.toJSON()),e.headers)}async function n(e,t,s="GET",r=null,n=null){const i=new Map(n),o={method:s,cache:"no-store",mode:"cors",credentials:"omit"};return r&&"GET"!==s&&(o.body=r),e.machine?i.set("Authorization",e.machine.secret?.length?"HMAC256 "+btoa(e.machine.key+":"+await e.machine.createHmacSignature(t,s,o.body?.length??0,new Date)):"Machine "+btoa(e.machine.key)):e.ghostId&&i.set("Authorization","Bearer "+e.ghostId),i.size>0&&(o.headers=new Headers([...i.entries()])),new Request(t,o)}async function i(t){try{const s=await async function(t){try{return fetch(t)}catch(t){throw e(t)}}(t);return await s.json()}catch(t){throw e(t)}}function o(e){const t=e.getAction(),s=new Error("no command supported for "+e.constructor.name,{cause:t});switch(t.object){case"Subscription":switch(t.kind){case"Merge":return"subscribe";case"Delete":return"unsubscribe";case"List":return"getSubscriptionsList";default:throw s}case"Self":switch(t.filter){case"Get":return"getSessionDetails";case"Login":case"Logout":return t.filter.toLowerCase();case"Contact":case"Password":case"Preferences":case"State":return"updateOwn"+t.filter;default:throw s}case"Session":switch(t.kind){case"Get":case"List":break;case"Delete":return"killSession";default:throw s}break;case"DispatchJob":switch(t.filter){case"Cancel":case"Change":return t.kind.toLocaleLowerCase()+t.object}}switch(t.kind){case"Get":case"Merge":case"Restore":case"Suspend":return t.kind.toLocaleLowerCase()+t.object;case"Delete":return"remove"+t.object;case"Reactivate":return"revive"+t.object;case"List":return"get"+ir.pluralize(t.object)+"List"+("Company"!=(t.filter||"Company")?"By"+t.filter:"");default:throw s}}function a(e){return e.reduce(((e,t)=>e.concat(Pr[t]||[])),[]).filter(((e,t,s)=>s.indexOf(e)===t))}function c(e){const t=[];for(const[s,r]of Object.entries(Er)){const n=r.map((e=>Pr[e])).flat();n.filter((t=>e.includes(t))).length/n.length>=.5&&t.push(s)}const s=t.reduce(((e,t)=>e.concat([t],Er[t])),[]);for(const[r,n]of Object.entries(Pr))!s.includes(r)&&n.some((t=>e.includes(t)))&&t.push(r);return t}import*as h from"@trakit/commands";import{ErrorCode as u,RepSelfGet as d,ReplySync as p,ReplySyncList as l,ReplySyncGet as m,ReplySyncDelete as w,ReplySyncBatchDelete as g,PaySelfGet as y,PaySelfLogin as v,PaySelfLogout as f,PaySelfContact as b,PaySelfPassword as C,PaySelfPreferences as P,PaySelfState as S,PayCompanyGet as R,PayCompanyMerge as k,PayCompanyDelete as A,PayCompanyRestore as M,PayCompanyGeneralListByCompany as D,PayCompanyGeneralGet as I,PayCompanyPolicyListByCompany as T,PayCompanyPolicyGet as G,PayCompanyStyleListByCompany as U,PayCompanyStyleGet as B,PayCompanyDirectoryListByCompany as J,PayCompanyDirectoryGet as E,PayCompanyResellerGet as L,PayCompanyResellerMerge as x,PayCompanyResellerDelete as N,PayCompanyResellerRestore as O,PayContactListByCompany as _,PayContactGet as F,PayContactMerge as H,PayContactDelete as q,PayContactRestore as $,PayContactBatchMerge as W,PayContactBatchDelete as j,PayUserListByCompany as z,PayUserGet as K,PayUserMerge as Z,PayUserDelete as Q,PayUserRestore as V,PayUserGeneralListByCompany as X,PayUserGeneralGet as Y,PayUserAdvancedListByCompany as ee,PayUserAdvancedGet as te,PayUserGroupListByCompany as se,PayUserGroupGet as re,PayUserGroupMerge as ne,PayUserGroupDelete as ie,PayUserGroupRestore as oe,PayMachineListByCompany as ae,PayMachineGet as ce,PayMachineMerge as he,PayMachineDelete as ue,PayMachineRestore as de,PaySessionListByCompany as pe,PaySessionListByUser as le,PaySessionDelete as me,PayIconListByCompany as we,PayIconGet as ge,PayIconMerge as ye,PayIconDelete as ve,PayIconRestore as fe,PayPictureListByCompany as be,PayPictureGet as Ce,PayPictureMerge as Pe,PayPictureDelete as Se,PayPictureRestore as Re,PayDocumentListByCompany as ke,PayDocumentGet as Ae,PayDocumentMerge as Me,PayDocumentDelete as De,PayDocumentRestore as Ie,PayFormTemplateListByCompany as Te,PayFormTemplateGet as Ge,PayFormTemplateMerge as Ue,PayFormTemplateDelete as Be,PayFormTemplateRestore as Je,PayFormResultListByCompany as Ee,PayFormResultGet as Le,PayFormResultMerge as xe,PayFormResultBatchMerge as Ne,PayFormResultDelete as Oe,PayFormResultRestore as _e,PayDashcamListByCompany as Fe,PayDashcamGet as He,PayDashcamLiveListByCompany as qe,PayAssetListByCompany as $e,PayAssetGet as We,PayAssetMerge as je,PayAssetBatchMerge as ze,PayAssetDelete as Ke,PayAssetRestore as Ze,PayAssetSuspend as Qe,PayAssetReactivate as Ve,PayAssetGeneralListByCompany as Xe,PayAssetGeneralGet as Ye,PayAssetAdvancedListByCompany as et,PayAssetAdvancedGet as tt,PayAssetDispatchMerge as st,PayDispatchTaskListByCompany as rt,PayDispatchTaskListByAsset as nt,PayDispatchTaskGet as it,PayDispatchTaskMerge as ot,PayDispatchTaskBatchMerge as at,PayDispatchTaskDelete as ct,PayDispatchTaskRestore as ht,PayDispatchJobListByCompany as ut,PayDispatchJobListByAsset as dt,PayDispatchJobGet as pt,PayDispatchJobMerge as lt,PayDispatchJobBatchMerge as mt,PayDispatchJobDelete as wt,PayDispatchJobRestore as gt,PayDispatchJobChange as yt,PayDispatchJobCancel as vt,PayAssetMessageListByCompany as ft,PayAssetMessageListByAsset as bt,PayAssetMessageGet as Ct,PayAssetMessageMerge as Pt,PayAssetMessageBatchMerge as St,PayAssetMessageDelete as Rt,PayAssetMessageRestore as kt,PayPlaceListByCompany as At,PayPlaceGet as Mt,PayPlaceMerge as Dt,PayPlaceDelete as It,PayPlaceRestore as Tt,PayProviderListByCompany as Gt,PayProviderGet as Ut,PayProviderMerge as Bt,PayProviderBatchMerge as Jt,PayProviderBatchDelete as Et,PayProviderDelete as Lt,PayProviderRestore as xt,PayProviderGeneralListByCompany as Nt,PayProviderGeneralGet as Ot,PayProviderAdvancedListByCompany as _t,PayProviderAdvancedGet as Ft,PayProviderControlListByCompany as Ht,PayProviderControlGet as qt,PayProviderScriptListByCompany as $t,PayProviderScriptGet as Wt,PayProviderScriptMerge as jt,PayProviderScriptDelete as zt,PayProviderScriptRestore as Kt,PayProviderConfigListByCompany as Zt,PayProviderConfigGet as Qt,PayProviderConfigMerge as Vt,PayProviderConfigBatchMerge as Xt,PayProviderConfigDelete as Yt,PayProviderConfigRestore as es,PayProviderConfigurationListByCompany as ts,PayProviderConfigurationGet as ss,PayProviderConfigurationMerge as rs,PayProviderConfigurationBatchMerge as ns,PayProviderConfigurationDelete as is,PayProviderConfigurationRestore as os,PayProviderRegistrationListByCompany as as,PayProviderRegistrationGet as cs,PayProviderRegistrationMerge as hs,PayProviderRegistrationDelete as us,PayBehaviourListByCompany as ds,PayBehaviourGet as ps,PayBehaviourMerge as ls,PayBehaviourBatchMerge as ms,PayBehaviourDelete as ws,PayBehaviourRestore as gs,PayBehaviourScriptListByCompany as ys,PayBehaviourScriptGet as vs,PayBehaviourScriptMerge as fs,PayBehaviourScriptDelete as bs,PayBehaviourScriptRestore as Cs,PayBehaviourLogListByAsset as Ps,PayBehaviourLogBatchDeleteByAsset as Ss,PayBehaviourLogListByBehaviour as Rs,PayBehaviourLogBatchDeleteByBehaviour as ks,PayBehaviourLogListByScript as As,PayBehaviourLogBatchDeleteByScript as Ms,PayReportTemplateListByCompany as Ds,PayReportTemplateGet as Is,PayReportTemplateMerge as Ts,PayReportTemplateDelete as Gs,PayReportTemplateRestore as Us,PayReportScheduleListByCompany as Bs,PayReportScheduleGet as Js,PayReportScheduleMerge as Es,PayReportScheduleDelete as Ls,PayReportScheduleRestore as xs,PayReportResultListByCompany as Ns,PayReportResultGet as Os,PayReportResultMerge as _s,PayReportResultDelete as Fs,PayReportResultRestore as Hs,PayMaintenanceScheduleListByCompany as qs,PayMaintenanceScheduleGet as $s,PayMaintenanceScheduleMerge as Ws,PayMaintenanceScheduleDelete as js,PayMaintenanceScheduleRestore as zs,PayMaintenanceJobListByCompany as Ks,PayMaintenanceJobGet as Zs,PayMaintenanceJobMerge as Qs,PayMaintenanceJobDelete as Vs,PayMaintenanceJobRestore as Xs,SubscriptionType as Ys,Reply as er,PaySubscriptionMerge as tr,RepSubscription as sr,PaySubscriptionDelete as rr,PaySubscriptionList as nr}from"@trakit/commands";import{utility as ir,Machine as or,serialization as ar}from"@trakit/objects";class cr{type;constructor(e){this.type=e}}class hr extends cr{kind;companyId;constructor(e,t,s){super(e),this.kind=t,this.companyId=s}}class ur extends cr{account;constructor(e,t){super(e),this.account=t}}class dr extends hr{objects;constructor(e,t,s,r){super(e,t,s),this.objects=r}}class pr extends hr{object;constructor(e,t,s,r){super(e,t,s),this.object=r}}class lr extends hr{key;constructor(e,t,s,r){super(e,t,s),this.key=r}}const mr={Company:"/companies/generals?parent={companyId}",CompanyGeneral:"/companies/generals?parent={companyId}",CompanyDirectory:"/companies/directory?parent={companyId}",CompanyStyle:"/companies/styles?parent={companyId}",CompanyPolicy:"/companies/policies?parent={companyId}",CompanyReseller:"/companies/resellers?parent={companyId}",Contact:"/companies/{companyId}/contacts",Machine:"/companies/{companyId}/machines",User:"/companies/{companyId}/users",UserGeneral:"/companies/{companyId}/users/generals",UserAdvanced:"/companies/{companyId}/users/advanceds",UserAuthentication:"/companies/{companyId}/users/authentications",UserState:"/companies/{companyId}/users/states",UserGroup:"/companies/{companyId}/users/groups",Session:"/companies/{companyId}/users/sessions",Dashcam:"/companies/{companyId}/dashcams",DashcamLive:"/companies/{companyId}/dashcams/live",Icon:"/companies/{companyId}/icons",Picture:"/companies/{companyId}/pictures",Document:"/companies/{companyId}/documents",FormTemplate:"/companies/{companyId}/forms/templates",FormResult:"/companies/{companyId}/forms",Asset:"/companies/{companyId}/assets",AssetGeneral:"/companies/{companyId}/assets/generals",AssetAdvanced:"/companies/{companyId}/assets/advanceds",AssetDispatch:"/companies/{companyId}/assets/dispatches",AssetMessage:"/companies/{companyId}/assets/messages",AssetAlert:"/companies/{companyId}/assets/alerts",DispatchTask:"/companies/{companyId}/assets/dispatch/tasks",DispatchJob:"/companies/{companyId}/assets/dispatch/jobs",MaintenanceSchedule:"/companies/{companyId}/maintenance/schedules",MaintenanceJob:"/companies/{companyId}/maintenance/jobs",Place:"/companies/{companyId}/places",Behaviour:"/companies/{companyId}/behaviours",BehaviourScript:"/companies/{companyId}/behaviours/scripts",BehaviourLog:"",Provider:"/companies/{companyId}/providers",ProviderGeneral:"/companies/{companyId}/providers/generals",ProviderAdvanced:"/companies/{companyId}/providers/advanceds",ProviderControl:"/companies/{companyId}/providers/controls",ProviderConfiguration:"/companies/{companyId}/providers/configurations",ProviderConfigurationType:"",ProviderScript:"/companies/{companyId}/providers/scripts",ProviderConfig:"/companies/{companyId}/providers/configs",ProviderRegistration:"/companies/{companyId}/providers/registrations",ReportTemplate:"/companies/{companyId}/reports/templates",ReportSchedule:"/companies/{companyId}/reports/schedules",ReportResult:"/companies/{companyId}/reports/results",BillingProfile:"/companies/{companyId}/billing/profiles",BillingReport:"/companies/{companyId}/billing/profiles/reports",BillableHostingRule:"",BillableHostingLicense:""},wr={AssetMessage:"/assets/{assetId}/messages",DispatchTask:"/assets/{assetId}/dispatch/tasks",DispatchJob:"/assets/{assetId}/dispatch/jobs",FormResult:"/assets/{assetId}/forms",MaintenanceJob:"/assets/{assetId}/maintenance/jobs"},gr={BillingHosting:"/billing/profiles/{profileId}/rules",BillingLicense:"/billing/profiles/{profileId}/licenses",BillingReport:"/billing/profiles/{profileId}/reports"},yr=/[A-Z][a-z]+/;class vr{account;baseAddress;query=new Map;headers=new Map;createBaseUrl(e){const t=this.baseAddress?new URL(e??"",this.baseAddress):new URL(e),s=new Map(this.query);for(const[e,r]of s)t.searchParams.append(e,r);return t}constructor(e,t){this.baseAddress=t?new URL(t):null,this.setAuth(e)}setAuth(e){e instanceof d?this.account=e:"string"==typeof e?this.setAuth({ghostId:e}):e instanceof or||e?.key?this.setAuth({machine:e.toJSON?.()??e}):e?.machine?.key||e?.ghostId?this.setAuth(new d({errorCode:u.success,message:"Authenticated via "+(e?.machine?.key?"Machine":"Session"),...e.toJSON?.()??e})):this.setAuth(new d)}t=0;i=new Map;command(t){const s=t.constructor.name+JSON.stringify(t.toJSON());let r=this.i.get(s);return r||this.i.set(s,r=new Promise((async(r,n)=>{let i=null,o=null,a=null;try{t.reqId=++this.t,i=await this.requestCreate(t)}catch(t){o=e(t)}try{o=o??await this.requestRelay(i)}catch(s){a=t.createReply(s instanceof Error?e(s):s)}try{a=a??t.createReply(o)}catch(s){a=t.createReply(e(s,o))}(a.errorCode===u.success?r:n)(a),this.i.delete(s)}))),r}}class fr extends vr{o=new Map;h(e){this.setAuth(e??new d(this.account.toJSON())),this.fire("account",(()=>new ur("account",this.account)))}u(e,t,s){this.fire("list",(()=>new dr("list",e,t,s)))}p(e,t,s){this.fire("update",(()=>new pr("update",e,t,s)))}l(e,t,s){this.fire("delete",(()=>new lr("delete",e,t,s)))}on(e,t){let s=this.o.get(e);s||this.o.set(e,s=[]);const r=s.includes(t);return r||s.push(t),!r}off(e,t){const s=this.o.get(e);if(s?.length){if(t){const e=s.indexOf(t);return!!(e>-1&&s.splice(e,1))}return!(s.length=0)}return!1}fire(e,t){const s=this.o.get(e)?.slice();if(s?.length){const e=t();s.forEach((t=>t.call(this,e)),this)}}handles(e,t){return this.o.get(e)?.includes(t)??!1}dispose(){for(const e of[...this.o.keys()])this.off(e)}async command(e){const t=await super.command(e);if(t instanceof p&&t.store()){const s=e.getAction(),r=t.getCompanyId();t instanceof l?s.filter?t.getList().forEach((e=>this.p(s.object,r,e))):this.u(s.object,r,t.getList()):t instanceof m?this.p(s.object,r,t.getObject()):t instanceof w?this.l(s.object,r,t.getKey()):t instanceof g&&t.getResults().forEach((e=>this.l(s.object,e.getCompanyId(),e.getKey())))}return t}async selfDetails(){const e=await this.command(new y);return this.h(e),e}async login(e,t,s){const r=await this.command(new v({username:e,password:t,userAgent:s??null}));return this.h(r),r}logout(){const e=this.command(new f);return this.h(new d),e}updateContact(e,t,s,r,n,i,o,a,c,h,u){return this.command(new b({contact:{name:e??null,notes:t??null,otherNames:s??null,emails:r??null,phones:n??null,addresses:i??null,urls:o??null,dates:a??null,options:c??null,roles:h??null,pictures:u??null}}))}updatePassword(e,t){return this.command(new C({current:e,password:t}))}updatePreferences(e,t,s,r,n){return this.command(new P({language:e??null,timezone:t?.code??t??null,notify:s?.map((e=>e.toJSON?.()??e))??null,formats:r instanceof Map?ar.fromMap(r):r??null,measurements:n instanceof Map?ar.fromMap(n):n??null}))}updateState(e){return this.command(new S({options:e instanceof Map?ar.fromMap(e):e??null}))}getCompany(e){return this.command(new R({company:{id:e}}))}mergeCompany(e){return this.command(new k({company:e}))}removeCompany(e){return this.command(new A({company:{id:e}}))}restoreCompany(e){return this.command(new M({company:{id:e}}))}listCompanyGenerals(e,t){return this.command(new D({...t,company:{id:e}}))}getCompanyGeneral(e){return this.command(new I({company:{id:e}}))}listCompanyPolicies(e,t){return this.command(new T({...t,company:{id:e}}))}getCompanyPolicy(e){return this.command(new G({company:{id:e}}))}listCompanyStyles(e,t){return this.command(new U({...t,company:{id:e}}))}getCompanyStyle(e){return this.command(new B({company:{id:e}}))}listCompanyDirectories(e,t){return this.command(new J({...t,company:{id:e}}))}getCompanyDirectory(e){return this.command(new E({company:{id:e}}))}getReseller(e){return this.command(new L({company:{id:e}}))}mergeReseller(e){return this.command(new x({company:e}))}removeReseller(e){return this.command(new N({company:{id:e}}))}restoreReseller(e){return this.command(new O({company:{id:e}}))}listContacts(e,t){return this.command(new _({...t,company:{id:e}}))}getContact(e){return this.command(new F({contact:{id:e}}))}mergeContact(e){return this.command(new H({contact:e}))}removeContact(e){return this.command(new q({contact:{id:e}}))}restoreContact(e){return this.command(new $({contact:{id:e}}))}multiMergeContact(e){return this.command(new W({contacts:e}))}multiRemoveContact(e){return this.command(new j({contacts:e.map((e=>({id:e})))}))}listUsers(e,t){return this.command(new z({...t,company:{id:e}}))}getUser(e){return this.command(new K({user:{login:e}}))}mergeUser(e){return this.command(new Z({user:e}))}removeUser(e){return this.command(new Q({user:{login:e}}))}restoreUser(e){return this.command(new V({user:{login:e}}))}listUserGenerals(e,t){return this.command(new X({...t,company:{id:e}}))}getUserGeneral(e){return this.command(new Y({user:{login:e}}))}listUserAdvanceds(e,t){return this.command(new ee({...t,company:{id:e}}))}getUserAdvanced(e){return this.command(new te({user:{login:e}}))}listUserGroups(e,t){return this.command(new se({...t,company:{id:e}}))}getUserGroup(e){return this.command(new re({userGroup:{id:e}}))}mergeUserGroup(e){return this.command(new ne({userGroup:e}))}removeUserGroup(e){return this.command(new ie({userGroup:{id:e}}))}restoreUserGroup(e){return this.command(new oe({userGroup:{id:e}}))}listMachines(e,t){return this.command(new ae({...t,company:{id:e}}))}getMachine(e){return this.command(new ce({machine:{id:e}}))}mergeMachine(e){return this.command(new he({machine:e}))}removeMachine(e){return this.command(new ue({machine:{id:e}}))}restoreMachine(e){return this.command(new de({machine:{id:e}}))}listSessions(e,t){return this.command(new pe({...t,company:{id:e}}))}listSessionsByUser(e,t){return this.command(new le({...t,user:{login:e}}))}killSession(e){return this.command(new me({session:{handle:e}}))}listIcons(e,t){return this.command(new we({...t,company:{id:e}}))}getIcon(e){return this.command(new ge({icon:{id:e}}))}mergeIcon(e){return this.command(new ye({icon:e}))}removeIcon(e){return this.command(new ve({icon:{id:e}}))}restoreIcon(e){return this.command(new fe({icon:{id:e}}))}listPictures(e,t){return this.command(new be({...t,company:{id:e}}))}getPicture(e){return this.command(new Ce({picture:{id:e}}))}mergePicture(e){return this.command(new Pe({picture:e}))}removePicture(e){return this.command(new Se({picture:{id:e}}))}restorePicture(e){return this.command(new Re({picture:{id:e}}))}listDocuments(e,t){return this.command(new ke({...t,company:{id:e}}))}getDocument(e){return this.command(new Ae({document:{id:e}}))}mergeDocument(e){return this.command(new Me({document:e}))}removeDocument(e){return this.command(new De({document:{id:e}}))}restoreDocument(e){return this.command(new Ie({document:{id:e}}))}listFormTemplates(e,t){return this.command(new Te({...t,company:{id:e}}))}getFormTemplate(e){return this.command(new Ge({formTemplate:{id:e}}))}mergeFormTemplate(e){return this.command(new Ue({formTemplate:e}))}removeFormTemplate(e){return this.command(new Be({formTemplate:{id:e}}))}restoreFormTemplate(e){return this.command(new Je({formTemplate:{id:e}}))}listFormResults(e,t){return this.command(new Ee({...t,company:{id:e}}))}getFormResult(e){return this.command(new Le({formResult:{id:e}}))}mergeFormResult(e){return this.command(new xe({formResult:e}))}multiMergeFormResult(e){return this.command(new Ne({formResult:{id:e}}))}removeFormResult(e){return this.command(new Oe({formResult:{id:e}}))}restoreFormResult(e){return this.command(new _e({formResult:{id:e}}))}listDashcamDatas(e,t){return this.command(new Fe({...t,company:{id:e}}))}getDashcamData(e){return this.command(new He({dashcam:{guid:e}}))}listDashcamLives(e,t){return this.command(new qe({...t,company:{id:e}}))}listAssets(e,t){return this.command(new $e({...t,company:{id:e}}))}getAsset(e){return this.command(new We({asset:{id:e}}))}mergeAsset(e){return this.command(new je({asset:e}))}multiMergeAsset(e){return this.command(new ze({assets:e}))}removeAsset(e){return this.command(new Ke({asset:{id:e}}))}restoreAsset(e){return this.command(new Ze({asset:{id:e}}))}suspendAsset(e){return this.command(new Qe({asset:{id:e}}))}reviveAsset(e){return this.command(new Ve({asset:{id:e}}))}searchAssets(e,t){}listAssetGenerals(e,t){return this.command(new Xe({...t,company:{id:e}}))}getAssetGeneral(e){return this.command(new Ye({asset:{id:e}}))}searchAssetGenerals(e,t){}listAssetAdvanceds(e,t){return this.command(new et({...t,company:{id:e}}))}getAssetAdvanced(e){return this.command(new tt({asset:{id:e}}))}searchAssetAdvanceds(e,t){}mergeAssetDispatch(e){return this.command(new st({assetDispatch:e}))}listDispatchTasks(e,t){return this.command(new rt({...t,company:{id:e}}))}getDispatchTasksByAsset(e,t){return this.command(new nt({...t,asset:{id:e}}))}getDispatchTask(e){return this.command(new it({dispatchTask:{id:e}}))}mergeDispatchTask(e){return this.command(new ot({dispatchTask:e}))}multiMergeDispatchTask(e){return this.command(new at({dispatchTask:{id:e}}))}removeDispatchTask(e){return this.command(new ct({dispatchTask:{id:e}}))}restoreDispatchTask(e){return this.command(new ht({dispatchTask:{id:e}}))}listDispatchJobs(e,t){return this.command(new ut({...t,company:{id:e}}))}getDispatchJobsByAsset(e,t){return this.command(new dt({...t,asset:{id:e}}))}getDispatchJob(e){return this.command(new pt({dispatchJob:{id:e}}))}mergeDispatchJob(e){return this.command(new lt({dispatchJob:e}))}multiMergeDispatchJob(e){return this.command(new mt({dispatchJob:{id:e}}))}removeDispatchJob(e){return this.command(new wt({dispatchJob:{id:e}}))}restoreDispatchJob(e){return this.command(new gt({dispatchJob:{id:e}}))}changeDispatchJob(e){return this.command(new yt({dispatchJob:e}))}cancelDispatchJob(e){return this.command(new vt({dispatchJob:e}))}listAssetMessages(e,t){return this.command(new ft({...t,company:{id:e}}))}getAssetMessagesByAsset(e,t){return this.command(new bt({...t,asset:{id:e}}))}getAssetMessage(e){return this.command(new Ct({message:{id:e}}))}mergeAssetMessage(e){return this.command(new Pt({assetMessage:e}))}multiMergeAssetMessage(e){return this.command(new St({assetMessage:{id:e}}))}removeAssetMessage(e){return this.command(new Rt({assetMessage:{id:e}}))}restoreAssetMessage(e){return this.command(new kt({assetMessage:{id:e}}))}listPlaces(e,t){return this.command(new At({...t,company:{id:e}}))}getPlace(e){return this.command(new Mt({place:{id:e}}))}mergePlace(e){return this.command(new Dt({place:e}))}removePlace(e){return this.command(new It({place:{id:e}}))}restorePlace(e){return this.command(new Tt({place:{id:e}}))}listProviders(e,t){return this.command(new Gt({...t,company:{id:e}}))}getProvider(e){return this.command(new Ut({provider:{id:e}}))}mergeProvider(e){return this.command(new Bt({provider:e}))}multiMergeProvider(e){return this.command(new Jt({providers:e}))}multiRemoveProvider(e){return this.command(new Et({providers:e.map((e=>({id:e})))}))}removeProvider(e){return this.command(new Lt({provider:{id:e}}))}restoreProvider(e){return this.command(new xt({provider:{id:e}}))}searchProviders(e,t){}listProviderGenerals(e,t){return this.command(new Nt({...t,company:{id:e}}))}getProviderGeneral(e){return this.command(new Ot({provider:{id:e}}))}searchProviderGenerals(e,t){}listProviderAdvanceds(e,t){return this.command(new _t({...t,company:{id:e}}))}getProviderAdvanced(e){return this.command(new Ft({provider:{id:e}}))}searchProviderAdvanceds(e,t){}listProviderControls(e,t){return this.command(new Ht({...t,company:{id:e}}))}getProviderControl(e){return this.command(new qt({provider:{id:e}}))}searchProviderControls(e,t){}listProviderScripts(e,t){return this.command(new $t({...t,company:{id:e}}))}getProviderScript(e){return this.command(new Wt({providerScript:{id:e}}))}mergeProviderScript(e){return this.command(new jt({providerScript:e}))}removeProviderScript(e){return this.command(new zt({providerScript:{id:e}}))}restoreProviderScript(e){return this.command(new Kt({providerScript:{id:e}}))}listProviderConfigs(e,t){return this.command(new Zt({...t,company:{id:e}}))}getProviderConfig(e){return this.command(new Qt({providerConfig:{id:e}}))}mergeProviderConfig(e){return this.command(new Vt({providerConfig:e}))}multiMergeProviderConfig(e){return this.command(new Xt({providerConfig:{id:e}}))}removeProviderConfig(e){return this.command(new Yt({providerConfig:{id:e}}))}restoreProviderConfig(e){return this.command(new es({providerConfig:{id:e}}))}listProviderConfigurations(e,t){return this.command(new ts({...t,company:{id:e}}))}getProviderConfiguration(e){return this.command(new ss({providerConfiguration:{id:e}}))}mergeProviderConfiguration(e){return this.command(new rs({providerConfiguration:e}))}multiMergeProviderConfiguration(e){return this.command(new ns({providerConfiguration:{id:e}}))}removeProviderConfiguration(e){return this.command(new is({providerConfiguration:{id:e}}))}restoreProviderConfiguration(e){return this.command(new os({providerConfiguration:{id:e}}))}listProviderRegistration(e,t){return this.command(new as({...t,company:{id:e}}))}getProviderRegistration(e){return this.command(new cs({providerRegistration:{id:e}}))}mergeProviderRegistration(e){return this.command(new hs({providerRegistration:e}))}removeProviderRegistration(e){return this.command(new us({providerRegistration:{id:e}}))}listBehaviours(e,t){return this.command(new ds({...t,company:{id:e}}))}getBehaviour(e){return this.command(new ps({behaviour:{id:e}}))}mergeBehaviour(e){return this.command(new ls({behaviour:e}))}multiMergeBehaviour(e){return this.command(new ms({behaviour:{id:e}}))}removeBehaviour(e){return this.command(new ws({behaviour:{id:e}}))}restoreBehaviour(e){return this.command(new gs({behaviour:{id:e}}))}listBehaviourScripts(e,t){return this.command(new ys({...t,company:{id:e}}))}getBehaviourScript(e){return this.command(new vs({behaviourScript:{id:e}}))}mergeBehaviourScript(e){return this.command(new fs({behaviourScript:e}))}removeBehaviourScript(e){return this.command(new bs({behaviourScript:{id:e}}))}restoreBehaviourScript(e){return this.command(new Cs({behaviourScript:{id:e}}))}listBehaviourAssetLogs(e,t){return this.command(new Ps({...t,behaviour:{id:e}}))}clearBehaviourAssetLogs(e){return this.command(new Ss({behaviour:{id:e}}))}listBehaviourLogs(e,t){return this.command(new Rs({...t,behaviour:{id:e}}))}clearBehaviourLogs(e){return this.command(new ks({behaviour:{id:e}}))}listBehaviourScriptLogs(e,t){return this.command(new As({...t,behaviourScript:{id:e}}))}clearBehaviourScriptLogs(e,t){return this.command(new Ms({...t,behaviourScript:{id:e}}))}listReportTemplates(e,t){return this.command(new Ds({...t,company:{id:e}}))}getReportTemplate(e){return this.command(new Is({reportTemplate:{id:e}}))}mergeReportTemplate(e){return this.command(new Ts({reportTemplate:e}))}removeReportTemplate(e){return this.command(new Gs({reportTemplate:{id:e}}))}restoreReportTemplate(e){return this.command(new Us({reportTemplate:{id:e}}))}listReportSchedules(e,t){return this.command(new Bs({...t,company:{id:e}}))}getReportSchedule(e){return this.command(new Js({reportSchedule:{id:e}}))}mergeReportSchedule(e){return this.command(new Es({reportSchedule:e}))}removeReportSchedule(e){return this.command(new Ls({reportSchedule:{id:e}}))}restoreReportSchedule(e){return this.command(new xs({reportSchedule:{id:e}}))}listReportResults(e,t){return this.command(new Ns({...t,company:{id:e}}))}getReportResult(e){return this.command(new Os({reportResult:{id:e}}))}mergeReportResult(e){return this.command(new _s({reportResult:e}))}removeReportResult(e){return this.command(new Fs({reportResult:{id:e}}))}restoreReportResult(e){return this.command(new Hs({reportResult:{id:e}}))}listMaintenanceSchedules(e,t){return this.command(new qs({...t,company:{id:e}}))}getMaintenanceSchedule(e){return this.command(new $s({maintenanceSchedule:{id:e}}))}mergeMaintenanceSchedule(e){return this.command(new Ws({maintenanceSchedule:e}))}removeMaintenanceSchedule(e){return this.command(new js({maintenanceSchedule:{id:e}}))}restoreMaintenanceSchedule(e){return this.command(new zs({maintenanceSchedule:{id:e}}))}listMaintenanceJobs(e,t){return this.command(new Ks({...t,company:{id:e}}))}getMaintenanceJob(e){return this.command(new Zs({maintenanceJob:{id:e}}))}mergeMaintenanceJob(e){return this.command(new Qs({maintenanceJob:e}))}removeMaintenanceJob(e){return this.command(new Vs({maintenanceJob:{id:e}}))}restoreMaintenanceJob(e){return this.command(new Xs({maintenanceJob:{id:e}}))}}class br extends fr{static URI_PROD="https://rest.trakit.ca/";static URI_BETA="https://mindflayer.trakit.ca/";constructor(e,t){super(e,t??br.URI_PROD)}requestCreate(e){return r(this,e)}requestRelay(e){return i(e)}}const Cr=/^(.+?)(Merged|Deleted|Suspended)$/,Pr={Company:[Ys.companyGeneral,Ys.companyLabels,Ys.companyPolicies],CompanyGeneral:[Ys.companyGeneral],CompanyDirectory:[],CompanyStyle:[Ys.companyLabels],CompanyPolicy:[Ys.companyPolicies],CompanyReseller:[Ys.companyReseller],Contact:[Ys.contact],Machine:[Ys.machine],User:[Ys.userGeneral,Ys.userAdvanced,Ys.userAuthentication],UserGeneral:[Ys.userGeneral],UserAdvanced:[Ys.userAdvanced],UserAuthentication:[Ys.userAuthentication],UserState:[Ys.userState],UserGroup:[Ys.userGroup],Session:[],Dashcam:[],Icon:[Ys.icon],Picture:[Ys.picture],Document:[Ys.document],FormTemplate:[Ys.formTemplate],FormResult:[Ys.formResult],Asset:[Ys.assetGeneral,Ys.assetAdvanced,Ys.assetDispatch],AssetGeneral:[Ys.assetGeneral],AssetAdvanced:[Ys.assetAdvanced],AssetDispatch:[Ys.assetDispatch],AssetMessage:[Ys.assetMessage],AssetAlert:[],DispatchTask:[Ys.dispatchTask],DispatchJob:[Ys.dispatchJob],MaintenanceSchedule:[Ys.maintenanceSchedule],MaintenanceJob:[Ys.maintenanceJob],Place:[Ys.placeGeneral],BehaviourScript:[Ys.behaviourScript],Behaviour:[Ys.behaviour],BehaviourLog:[Ys.behaviourLog],Provider:[Ys.providerGeneral,Ys.providerAdvanced,Ys.providerControl],ProviderGeneral:[Ys.providerGeneral],ProviderAdvanced:[Ys.providerAdvanced],ProviderControl:[Ys.providerControl],ProviderConfiguration:[Ys.providerConfiguration],ProviderConfigurationType:[],ProviderScript:[Ys.providerScript],ProviderConfig:[Ys.providerConfig],ProviderRegistration:[Ys.providerRegistration],ReportTemplate:[Ys.reportTemplate],ReportSchedule:[Ys.reportSchedule],ReportResult:[Ys.reportResult],BillingProfile:[Ys.billingProfile],BillingReport:[Ys.billingReport],BillableHostingRule:[Ys.billingHosting],BillableHostingLicense:[Ys.billingLicense]};class Sr{#e=new Map;get regions(){return[...this.#e.keys()]}getExpired(){const e=new Date,t=[];for(let[s,r]of this.#e)r&&r<e&&t.push(s);return t}purgeExpired(){const e=this.getExpired();return e.forEach((e=>this.#e.delete(e))),e}getExpiring(){const e=[];for(let[t,s]of this.#e)s&&e.push(t);return e}#t(e,t){return t=t||null,this.#e.set(e,t),t}expireRegion(e,t=!1){const s=t?0:(new Date).valueOf();return this.#t(e,new Date(s+3e5))}expireRegions(e,t=!1){return e.map((e=>this.expireRegion(e,t)))}preserveRegion(e){const t=this.#e.get(e);return this.#t(e),t||null}preserveRegions(e){return e.map((e=>this.preserveRegion(e)))}reset(){const e=[];for(let[t,s]of this.#e)s||e.push(t);return this.#e.clear(),e}}var Rr;!function(e){e.maintenance="maintenance",e.upgrade="upgrade"}(Rr||(Rr={}));class kr{static fromJson(e){switch(e?.kind){case Rr.maintenance:return new Ar(e);case Rr.upgrade:return new Mr(e);default:throw new Error(`Unknown broadcast type: ${e?.kind}`)}}kind;serverTime;message;constructor(e){this.kind=e?.kind,this.serverTime=ir.date(e?.serverTime),this.message=e?.message??""}}class Ar extends kr{starting;ending;constructor(e){super(e),this.starting=ir.date(e?.starting),this.ending=ir.date(e?.ending)}}class Mr extends kr{eta;reload;constructor(e){super(e),this.eta=ir.date(e?.eta),this.reload=!!e?.reload}}class Dr extends cr{name;body;constructor(e,t,s){super(e),this.name=t,this.body=s}}class Ir extends cr{reply;constructor(e,t){super(e),this.reply=t}}class Tr extends cr{broadcast;constructor(e,t){super(e),this.broadcast=kr.fromJson(t)}}const Gr="connection",Ur="dis"+Gr;var Br;!function(e){e[e.opening=WebSocket.CONNECTING]="opening",e[e.open=WebSocket.OPEN]="open",e[e.closing=WebSocket.CLOSING]="closing",e[e.closed=WebSocket.CLOSED]="closed"}(Br||(Br={}));class Jr extends fr{static URI_PROD="wss://socket.trakit.ca/";static URI_BETA="wss://kraken.trakit.ca/";static msgNameToSyncName(e){const s=Cr.exec(e);return 3===s?.length?t(s[1])||null:void 0}#s=new Date(NaN);#r=new Date(NaN);#n="";#i=new Date(NaN);get lastConnected(){return this.#s}get lastReceived(){return this.#r}get lastMessage(){return this.#n}get lastSent(){return this.#i}get state(){switch(this.#o?.readyState){case WebSocket.CONNECTING:return Br.opening;case WebSocket.OPEN:return this.#a?Br.open:Br.opening;case WebSocket.CLOSING:return Br.closing;default:return Br.closed}}get ready(){return this.#a&&this.#c}m(e){const t=this.o.get("open");if(t?.length){const s=new ur("open",e);t.forEach((e=>e.call(this,s)))}}v(e){const t=this.o.get("close");if(t?.length){const s=new Ir("close",e);t.forEach((e=>e.call(this,s)))}}C(e,t){const s=this.o.get("message");if(s?.length){const r=new Dr("message",e,t);s.forEach((e=>e.call(this,r)))}}P(e){const t=this.o.get("error");if(t?.length){const s=new Ir("error",e);t.forEach((e=>e.call(this,s)))}}S(e){const t=this.o.get("broadcast");if(t?.length){const s=new Tr("broadcast",e);t.forEach((e=>e.call(this,s)))}}#h=new Map;#u(e,t){return this.#h.get(e)?.(t),this.#h.delete(e)}#o;#a=!1;#c=!0;#d(e){this.#o.onopen=null,this.#o.onmessage=e=>this.#p(e),this.#l=0}#m(e){this.P(new er({errorCode:u.service,message:"WebSocket error",errorDetails:{kind:"connection",state:this.state,reconnect:this.reconnectEnabled}}))}#w(e){clearTimeout(this.#g),clearTimeout(this.#y),this.#a=!1,this.#l=this.#l?2*this.#l:this.lastReceived?(new Date).valueOf()-this.lastReceived.valueOf():5e3;const t=Math.min(this.#l,3e5),s={kind:"connection",state:Br.closed,code:e.code,reason:e.reason,wasClean:e.wasClean,reconnect:this.reconnectEnabled,retry:(new Date).valueOf()+t},r={errorCode:u.success,message:"Disconnected",errorDetails:s};for(const e of[...this.#h.keys()].sort())this.#u(e,e===Ur?r:{...r,reqId:e,errorCode:u.service,errorDetails:{...s}});this.v?.(new er(r)),this.#y=this.reconnectEnabled&&this.#c?setTimeout((()=>this.open()),t,this):0,this.#o=this.#o.onopen=this.#o.onerror=this.#o.onclose=this.#o.onmessage=null}#p(e){this.#r=new Date;const t=e.data.substring(0,e.data.indexOf(" ")),s=JSON.parse(e.data.substring(t.length+1));switch(this.#n=t,"connectionResponse"!==t&&"noopResponse"!==t&&this.C(t,s),t){case"connectionResponse":this.#v(s),this.#s=new Date(this.#r),this.#a=!0,this.#u(Gr,s),this.h(),this.m(this.account);break;case"loginResponse":case"getSessionDetailsResponse":this.#v(s),this.h();break;case"updateOwnPasswordResponse":this.#c||(this.#c=0===s.errorCode);break;case"logoutResponse":this.close();case"sessionEnded":this.#c=!1,this.#v(s),this.h();break;case"sessionGeneralMerged":case"sessionAdvancedMerged":case"sessionAuthenticationMerged":case"sessionStateMerged":this.#f({user:s}),this.h();break;case"sessionMachineMerged":this.#f({machine:s}),this.h();break;case"sessionPoliciesMerged":this.#f(s),this.h();break;case"broadcast":this.S(s)}if(t.endsWith("Response"))this.#u(s.reqId,s);else if(!t.startsWith("session")){const e=Cr.exec(t);e?.length&&this.#b(e,s)}this.resetKeepAlive()}#v(e){this.setAuth(new d(e)),this.#c=0===this.account.errorCode&&!this.account.user?.passwordExpired,this.account.store()}#f(e){const t=this.account.toJSON();this.setAuth(new d({...t,user:e?.user?{...t.user,...e.user}:null,machine:e?.machine??t.machine,sessionPolicy:e?.sessionPolicy??t.sessionPolicy,passwordPolicy:e?.passwordPolicy??t.passwordPolicy,multiFactorPolicy:e?.multiFactorPolicy??t.multiFactorPolicy,ssoPolicy:e?.ssoPolicy??t.ssoPolicy})),this.account.store()}#b(e,s){const r=t(e[1]),n=s[r.startsWith("Company")?"parent":"company"],i=function(e,t){return h["Rep"+e+(t??"Get")]}(r,"Merged"===e[2]?"Get":e[2].slice(0,-1).slice(0,7));if(!i)throw new Error("No Reply class found for "+r+" and action "+e[2]);const o=new i({errorCode:u.success,message:e[2]+" event",[e[1]]:s});if(o.store())switch(e[2]){case"Merged":case"Suspended":this.p(r,n,o.getObject());break;case"Deleted":this.l(r,n,function(e,t){return e[function(e){switch(e){case"User":case"UserGeneral":case"UserAdvanced":return"login";case"ProviderRegistration":return"code";case"Session":return"handle";case"Machine":return"key";case"Dashcam":return"guid";default:return"id"}}(t)]}(s,r))}return o}reconnectEnabled=!0;#l=0;#y=0;keepAliveEnabled=!1;#g=0;constructor(e,t){super(e,t??Jr.URI_PROD)}dispose(){this.close().finally((()=>{super.dispose(),this.#o=this.#h=null}))}open(){let e=this.i.get(Gr);return e||(clearTimeout(this.#y),this.i.set(Gr,e=new Promise((async(e,t)=>{const s=this.state;if(s===Br.closed){const s=this.createBaseUrl();this.#o=new WebSocket(s,this.account.machine?(this.account.machine.secret?.length?"HMAC256#"+btoa(this.account.machine.key+":"+await this.account.machine.createHmacSignature(s)):"MACHINE#"+btoa(this.account.machine.key)).replaceAll("/","|").replace(/=*$/,""):this.account.ghostId||void 0),this.#o.onopen=e=>this.#d(e),this.#o.onerror=e=>this.#m(e),this.#o.onclose=e=>this.#w(e),this.#h.set(Gr,(s=>{(0===s.errorCode?e:t)(this.account)}))}else t(new d({errorCode:u.unknown,message:"WebSocket not closed",errorDetails:{kind:"connection",connection:s}}))})))),e}close(){let e=this.i.get(Gr);return e||(clearTimeout(this.#y),this.i.set(Gr,e=new Promise(((e,t)=>{const s=this.state;switch(s){case Br.opening:case Br.open:this.#c=!1,this.reconnectEnabled=!1,this.#h.set(Ur,(s=>{(0===s.errorCode?e:t)(new er(s))})),this.#o.close(1e3,"Bye!");break;default:t(new er({errorCode:u.unknown,message:"WebSocket not open",errorDetails:{kind:"connection",connection:s}}))}})))),e}requestCreate(e){return Promise.resolve([o(e),e.toJSON()])}requestRelay(t){const s=t[0],r=t[1]||{};return new Promise(((n,i)=>{if(this.state===Br.open){const t=++this.t,i=setTimeout((()=>this.#u(t,{reqId:t,errorCode:u.unknown,message:"Command timeout"})),12e4);r.reqId=t,this.#h.set(t,(e=>{clearTimeout(i),n(e)}));try{this.#o.send(s+" "+JSON.stringify(r)),this.#i=new Date}catch(s){this.#u(t,e(s))}this.resetKeepAlive()}else this.open().then((()=>this.requestRelay(t).then(n))).catch(i)}))}resetKeepAlive(){return clearTimeout(this.#g),this.#g=this.keepAliveEnabled&&this.#c?setTimeout((()=>this.requestRelay(["noop",{}])),3e5):0,Promise.resolve(0!==this.#g)}subscribe(e,t){return t?.length?this.command(new tr({company:{id:e},subscriptionTypes:t})):Promise.resolve(new sr({errorCode:u.success,message:"No subscriptions specified"}))}unsubscribe(e,t){return t?.length?this.command(new rr({company:{id:e},subscriptionTypes:t})):Promise.resolve(new sr({errorCode:u.success,message:"No subscriptions specified"}))}listSubscriptions(){return this.command(new nr)}}const Er={Company:["CompanyGeneral","CompanyDirectory","CompanyStyle","CompanyPolicy"],Asset:["AssetGeneral","AssetAdvanced","AssetDispatch"],Provider:["ProviderGeneral","ProviderAdvanced","ProviderControl"],User:["UserGeneral","UserAdvanced"]};class Lr extends fr{R;k;get autoConnect(){return this.R.reconnectEnabled}set autoConnect(e){this.R.reconnectEnabled=!!e,e&&this.R.state===Br.closed&&this.R.open()}get socketOnline(){return this.R.state===Br.open}get socketDetails(){return{state:this.R.state,ready:this.R.ready,lastConnected:this.R.lastConnected,lastSent:this.R.lastSent,lastReceived:this.R.lastReceived,lastMessage:this.R.lastMessage}}get socketAddress(){return this.R.baseAddress}set socketAddress(e){this.R.baseAddress=e}get restAddress(){return this.k.baseAddress}set restAddress(e){this.k.baseAddress=e}constructor(e,t,s){super(e);const r=e=>this.setAuth(e.account),n=e=>this.fire(e.type,(()=>e));this.k=new br(this.account,t??br.URI_PROD),this.k.on("account",r),this.R=new Jr(this.account,s??Jr.URI_PROD),this.R.on("account",r),this.R.on("open",(e=>this.#C(e.account))),this.R.on("close",(e=>this.#P(e.reply)));for(const e of["account","list","update","delete"])this.k.on(e,n),this.R.on(e,n);for(const e of["open","close","broadcast"])this.R.on(e,n);this.autoConnect=!(!this.account.ghostId&&!this.account.machine?.key)}dispose(){super.dispose(),this.k.dispose(),this.R.dispose(),this.k=this.R=null}setAuth(e){super.setAuth(e),this.k?.setAuth(this.account),this.R?.setAuth(this.account)}command(e){const t=e.getAction().object;return"Subscription"===t||"Self"===t&&this.socketOnline?this.socket(e):this.rest(e)}requestCreate(e){throw new Error("Method not implemented.")}requestRelay(e){throw new Error("Method not implemented.")}rest(e){return this.k.command(e)}socket(e){return this.R.command(e)}#C(e){this.#S.forEach(((e,t)=>{this.sync(t,c(e.reset()))})),this.#R()}#P(e){clearTimeout(this.#k)}isSynced(e,t){let s=this.R.state===Br.open;if(s){const r=this.#A(e);s=a(t).every((e=>r.regions.includes(e)))}return s}getSyncs(e,t=!1){const s=this.#A(e),r=t?[]:s.getExpiring();return c(s.regions.filter((e=>!r.includes(e))))}async sync(t,s){const r=[],n=this.#A(t),i=a(s).filter((e=>!n.regions.includes(e)));if(i.length>0){n.preserveRegions(i);const s=await this.R.subscribe(t,i);n.expireRegions((s.denied??[]).concat(s.invalid??[]),!0),c(s.merged??[]).forEach((s=>{const n=function(e,t){return h["Pay"+e+(t??"Get")]}(s,s.startsWith("Company")?"Get":"ListByCompany");r.push(n?this.command(new n({company:{id:t}})):Promise.reject(e(new Error(`No payload class could be made for sync type ${s}`))))}))}return Promise.all(r)}desync(e,t){const s=this.#A(e),r=t.reduce(((e,t)=>e.concat(Pr[t]||[])),[]).filter((e=>s.regions.includes(e))).filter(((e,t,s)=>s.indexOf(e)===t));return s.expireRegions(r),r}#S=new Map;#R(){const e=[];this.R.state===Br.open&&this.#S.forEach(((t,s)=>{const r=t.purgeExpired();r.length&&e.push(this.unsubscribe(s,r))})),Promise.allSettled(e).finally((()=>{this.#k=setTimeout((()=>this.#R()),1e4)}))}#k;#A(e){let t=this.#S.get(e);return t||this.#S.set(e,t=new Sr),t}subscribe(e,t){return this.R.subscribe(e,t)}unsubscribe(e,t){return this.R.unsubscribe(e,t)}listSubscriptions(){return this.R.listSubscriptions()}}
|
|
1
|
+
function e(e,t){return{errorCode:d.unknown,message:"Client exception",errorDetails:{kind:"stack",message:e?.message??"Unknonwn error",stack:e?.stack??null,value:t??null}}}function t(e){if("CompanyLabels"===(e=or.capitalize(e)))e="CompanyStyle";else e=or.singularize(e);return e}function s(e){const t=e.getAction();let s="GET",r=new URLSearchParams,n=[...t.object.match(vr)].map((e=>or.pluralize(e.toLowerCase()))).join("/");switch(t.object){case"Self":"Get"==t.kind?(s="GET",n="self"):(s="POST",n="self/"+t.filter.toLowerCase());break;case"Subscription":throw new Error(t.object+" only supported by TrakitSocketCommander",{cause:t});case"DispatchJob":switch(t.filter){case"Cancel":s=t.batch?"PATCH":"POST",n+="/cancel";break;case"Change":s=t.batch?"PATCH":"PUT"}default:if(!t.batch){switch(e.getKey&&(n=or.isCompounded(t.object)?n.replace("/","/"+e.getKey()+"/"):n+"/"+e.getKey()),t.kind){case"Get":break;case"List":switch(t.filter){case"Asset":n=t.object in gr?gr[t.object].replace("{assetId}",e.asset.id):`assets/${e.asset.id}/${n}`;break;case"BillingProfile":n=t.object in yr?yr[t.object].replace("{profileId}",e.billingProfile.id):`billing/profiles/${e.billingProfile.id}/${n}`;break;case"Company":n=t.object in wr?wr[t.object].replace("{companyId}",e.company.id):`companies/${e.company.id}/${n}`;break;case"User":n=`users/${encodeURIComponent(e.user.login)}/${n}`}if(or.isntNaN(e?.after?.valueOf())&&r.set("after",e.after.toISOString()),or.isntNaN(e?.before?.valueOf())&&r.set("before",e.before.toISOString()),or.isntNaN(e?.lowest)&&r.set("lowest",e.lowest),or.isntNaN(e?.highest)&&r.set("highest",e.highest),e?.first&&r.set("first",e.first),e?.last&&r.set("last",e.last),e?.labels?.length&&r.set("labels",e.labels.join(",")),e?.references?.size)for(const[t,s]of e.references.entries())r.set(t,s);break;case"Merge":s="POST";break;case"Delete":s="DELETE";break;case"Restore":s="PATCH",n+="/restore";break;case"Suspend":s="PATCH",n+="/suspend";break;case"Reactivate":s="PATCH",n+="/revive"}break}switch(s="PATCH",t.kind){case"Get":case"List":s="GET";break;case"Merge":break;case"Delete":s="DELETE";break;case"Restore":n+="/restore";break;case"Suspend":n+="/suspend";break;case"Reactivate":n+="/revive"}}return[s,r.size?n+"?"+r.toString():n]}async function r(e,t){const[r,i]=s(t);return n(e.account,e.createBaseUrl(i),r,"GET"===r?null:JSON.stringify(t.toJSON()),e.headers)}async function n(e,t,s="GET",r=null,n=null){const i=new Map(n),o={method:s,cache:"no-store",mode:"cors",credentials:"omit"};return r&&"GET"!==s&&(o.body=r),e.machine?i.set("Authorization",e.machine.secret?.length?"HMAC256 "+btoa(e.machine.key+":"+await e.machine.createHmacSignature(t,s,o.body?.length??0,new Date)):"Machine "+btoa(e.machine.key)):e.ghostId&&i.set("Authorization","Bearer "+e.ghostId),i.size>0&&(o.headers=new Headers([...i.entries()])),new Request(t,o)}async function i(t){try{const s=await async function(t){try{return fetch(t)}catch(t){throw e(t)}}(t);return await s.json()}catch(t){throw e(t)}}function o(e,t,s){if(!e.has(t)){const r=s(t);return e.set(t,r),r}return e.get(t)}function a(e){const t=e.getAction(),s=new Error("no command supported for "+e.constructor.name,{cause:t});switch(t.object){case"Subscription":switch(t.kind){case"Merge":return"subscribe";case"Delete":return"unsubscribe";case"List":return"getSubscriptionsList";default:throw s}case"Self":switch(t.filter){case"Get":return"getSessionDetails";case"Login":case"Logout":return t.filter.toLowerCase();case"Contact":case"Password":case"Preferences":case"State":return"updateOwn"+t.filter;default:throw s}case"Session":switch(t.kind){case"Get":case"List":break;case"Delete":return"killSession";default:throw s}break;case"DispatchJob":switch(t.filter){case"Cancel":case"Change":return t.kind.toLocaleLowerCase()+t.object}}switch(t.kind){case"Get":case"Merge":case"Restore":case"Suspend":return t.kind.toLocaleLowerCase()+t.object;case"Delete":return"remove"+t.object;case"Reactivate":return"revive"+t.object;case"List":return"get"+or.pluralize(t.object)+"List"+("Company"!=(t.filter||"Company")?"By"+t.filter:"");default:throw s}}function c(e){return e.reduce(((e,t)=>e.concat(Sr[t]||[])),[]).filter(((e,t,s)=>s.indexOf(e)===t))}function h(e){const t=[];for(const[s,r]of Object.entries(Lr)){const n=r.map((e=>Sr[e])).flat();n.filter((t=>e.includes(t))).length/n.length>=.5&&t.push(s)}const s=t.reduce(((e,t)=>e.concat([t],Lr[t])),[]);for(const[r,n]of Object.entries(Sr))!s.includes(r)&&n.some((t=>e.includes(t)))&&t.push(r);return t}import*as u from"@trakit/commands";import{ErrorCode as d,RepSelfGet as p,ReplySync as l,ReplySyncList as m,ReplySyncGet as w,ReplySyncDelete as g,ReplySyncBatchDelete as y,PaySelfGet as v,PaySelfLogin as f,PaySelfLogout as b,PaySelfContact as C,PaySelfPassword as P,PaySelfPreferences as S,PaySelfState as R,PayCompanyGet as k,PayCompanyMerge as A,PayCompanyDelete as M,PayCompanyRestore as D,PayCompanyGeneralListByCompany as I,PayCompanyGeneralGet as T,PayCompanyPolicyListByCompany as G,PayCompanyPolicyGet as U,PayCompanyStyleListByCompany as B,PayCompanyStyleGet as J,PayCompanyDirectoryListByCompany as E,PayCompanyDirectoryGet as L,PayCompanyResellerGet as x,PayCompanyResellerMerge as N,PayCompanyResellerDelete as O,PayCompanyResellerRestore as _,PayContactListByCompany as F,PayContactGet as H,PayContactMerge as q,PayContactDelete as $,PayContactRestore as W,PayContactBatchMerge as j,PayContactBatchDelete as z,PayUserListByCompany as K,PayUserGet as Z,PayUserMerge as Q,PayUserDelete as V,PayUserRestore as X,PayUserGeneralListByCompany as Y,PayUserGeneralGet as ee,PayUserAdvancedListByCompany as te,PayUserAdvancedGet as se,PayUserGroupListByCompany as re,PayUserGroupGet as ne,PayUserGroupMerge as ie,PayUserGroupDelete as oe,PayUserGroupRestore as ae,PayMachineListByCompany as ce,PayMachineGet as he,PayMachineMerge as ue,PayMachineDelete as de,PayMachineRestore as pe,PaySessionListByCompany as le,PaySessionListByUser as me,PaySessionDelete as we,PayIconListByCompany as ge,PayIconGet as ye,PayIconMerge as ve,PayIconDelete as fe,PayIconRestore as be,PayPictureListByCompany as Ce,PayPictureGet as Pe,PayPictureMerge as Se,PayPictureDelete as Re,PayPictureRestore as ke,PayDocumentListByCompany as Ae,PayDocumentGet as Me,PayDocumentMerge as De,PayDocumentDelete as Ie,PayDocumentRestore as Te,PayFormTemplateListByCompany as Ge,PayFormTemplateGet as Ue,PayFormTemplateMerge as Be,PayFormTemplateDelete as Je,PayFormTemplateRestore as Ee,PayFormResultListByCompany as Le,PayFormResultGet as xe,PayFormResultMerge as Ne,PayFormResultBatchMerge as Oe,PayFormResultDelete as _e,PayFormResultRestore as Fe,PayDashcamListByCompany as He,PayDashcamGet as qe,PayDashcamLiveListByCompany as $e,PayAssetListByCompany as We,PayAssetGet as je,PayAssetMerge as ze,PayAssetBatchMerge as Ke,PayAssetDelete as Ze,PayAssetRestore as Qe,PayAssetSuspend as Ve,PayAssetReactivate as Xe,PayAssetGeneralListByCompany as Ye,PayAssetGeneralGet as et,PayAssetAdvancedListByCompany as tt,PayAssetAdvancedGet as st,PayAssetDispatchMerge as rt,PayDispatchTaskListByCompany as nt,PayDispatchTaskListByAsset as it,PayDispatchTaskGet as ot,PayDispatchTaskMerge as at,PayDispatchTaskBatchMerge as ct,PayDispatchTaskDelete as ht,PayDispatchTaskRestore as ut,PayDispatchJobListByCompany as dt,PayDispatchJobListByAsset as pt,PayDispatchJobGet as lt,PayDispatchJobMerge as mt,PayDispatchJobBatchMerge as wt,PayDispatchJobDelete as gt,PayDispatchJobRestore as yt,PayDispatchJobChange as vt,PayDispatchJobCancel as ft,PayAssetMessageListByCompany as bt,PayAssetMessageListByAsset as Ct,PayAssetMessageGet as Pt,PayAssetMessageMerge as St,PayAssetMessageBatchMerge as Rt,PayAssetMessageDelete as kt,PayAssetMessageRestore as At,PayPlaceListByCompany as Mt,PayPlaceGet as Dt,PayPlaceMerge as It,PayPlaceDelete as Tt,PayPlaceRestore as Gt,PayProviderListByCompany as Ut,PayProviderGet as Bt,PayProviderMerge as Jt,PayProviderBatchMerge as Et,PayProviderBatchDelete as Lt,PayProviderDelete as xt,PayProviderRestore as Nt,PayProviderGeneralListByCompany as Ot,PayProviderGeneralGet as _t,PayProviderAdvancedListByCompany as Ft,PayProviderAdvancedGet as Ht,PayProviderControlListByCompany as qt,PayProviderControlGet as $t,PayProviderScriptListByCompany as Wt,PayProviderScriptGet as jt,PayProviderScriptMerge as zt,PayProviderScriptDelete as Kt,PayProviderScriptRestore as Zt,PayProviderConfigListByCompany as Qt,PayProviderConfigGet as Vt,PayProviderConfigMerge as Xt,PayProviderConfigBatchMerge as Yt,PayProviderConfigDelete as es,PayProviderConfigRestore as ts,PayProviderConfigurationListByCompany as ss,PayProviderConfigurationGet as rs,PayProviderConfigurationMerge as ns,PayProviderConfigurationBatchMerge as is,PayProviderConfigurationDelete as os,PayProviderConfigurationRestore as as,PayProviderRegistrationListByCompany as cs,PayProviderRegistrationGet as hs,PayProviderRegistrationMerge as us,PayProviderRegistrationDelete as ds,PayBehaviourListByCompany as ps,PayBehaviourGet as ls,PayBehaviourMerge as ms,PayBehaviourBatchMerge as ws,PayBehaviourDelete as gs,PayBehaviourRestore as ys,PayBehaviourScriptListByCompany as vs,PayBehaviourScriptGet as fs,PayBehaviourScriptMerge as bs,PayBehaviourScriptDelete as Cs,PayBehaviourScriptRestore as Ps,PayBehaviourLogListByAsset as Ss,PayBehaviourLogBatchDeleteByAsset as Rs,PayBehaviourLogListByBehaviour as ks,PayBehaviourLogBatchDeleteByBehaviour as As,PayBehaviourLogListByScript as Ms,PayBehaviourLogBatchDeleteByScript as Ds,PayReportTemplateListByCompany as Is,PayReportTemplateGet as Ts,PayReportTemplateMerge as Gs,PayReportTemplateDelete as Us,PayReportTemplateRestore as Bs,PayReportScheduleListByCompany as Js,PayReportScheduleGet as Es,PayReportScheduleMerge as Ls,PayReportScheduleDelete as xs,PayReportScheduleRestore as Ns,PayReportResultListByCompany as Os,PayReportResultGet as _s,PayReportResultMerge as Fs,PayReportResultDelete as Hs,PayReportResultRestore as qs,PayMaintenanceScheduleListByCompany as $s,PayMaintenanceScheduleGet as Ws,PayMaintenanceScheduleMerge as js,PayMaintenanceScheduleDelete as zs,PayMaintenanceScheduleRestore as Ks,PayMaintenanceJobListByCompany as Zs,PayMaintenanceJobGet as Qs,PayMaintenanceJobMerge as Vs,PayMaintenanceJobDelete as Xs,PayMaintenanceJobRestore as Ys,SubscriptionType as er,Reply as tr,PaySubscriptionMerge as sr,RepSubscription as rr,PaySubscriptionDelete as nr,PaySubscriptionList as ir}from"@trakit/commands";import{utility as or,Machine as ar,serialization as cr}from"@trakit/objects";class hr{type;constructor(e){this.type=e}}class ur extends hr{kind;companyId;constructor(e,t,s){super(e),this.kind=t,this.companyId=s}}class dr extends hr{account;constructor(e,t){super(e),this.account=t}}class pr extends ur{objects;constructor(e,t,s,r){super(e,t,s),this.objects=r}}class lr extends ur{object;constructor(e,t,s,r){super(e,t,s),this.object=r}}class mr extends ur{key;constructor(e,t,s,r){super(e,t,s),this.key=r}}const wr={Company:"/companies/generals?parent={companyId}",CompanyGeneral:"/companies/generals?parent={companyId}",CompanyDirectory:"/companies/directory?parent={companyId}",CompanyStyle:"/companies/styles?parent={companyId}",CompanyPolicy:"/companies/policies?parent={companyId}",CompanyReseller:"/companies/resellers?parent={companyId}",Contact:"/companies/{companyId}/contacts",Machine:"/companies/{companyId}/machines",User:"/companies/{companyId}/users",UserGeneral:"/companies/{companyId}/users/generals",UserAdvanced:"/companies/{companyId}/users/advanceds",UserAuthentication:"/companies/{companyId}/users/authentications",UserState:"/companies/{companyId}/users/states",UserGroup:"/companies/{companyId}/users/groups",Session:"/companies/{companyId}/users/sessions",Dashcam:"/companies/{companyId}/dashcams",DashcamLive:"/companies/{companyId}/dashcams/live",Icon:"/companies/{companyId}/icons",Picture:"/companies/{companyId}/pictures",Document:"/companies/{companyId}/documents",FormTemplate:"/companies/{companyId}/forms/templates",FormResult:"/companies/{companyId}/forms",Asset:"/companies/{companyId}/assets",AssetGeneral:"/companies/{companyId}/assets/generals",AssetAdvanced:"/companies/{companyId}/assets/advanceds",AssetDispatch:"/companies/{companyId}/assets/dispatches",AssetMessage:"/companies/{companyId}/assets/messages",AssetAlert:"/companies/{companyId}/assets/alerts",DispatchTask:"/companies/{companyId}/assets/dispatch/tasks",DispatchJob:"/companies/{companyId}/assets/dispatch/jobs",MaintenanceSchedule:"/companies/{companyId}/maintenance/schedules",MaintenanceJob:"/companies/{companyId}/maintenance/jobs",Place:"/companies/{companyId}/places",Behaviour:"/companies/{companyId}/behaviours",BehaviourScript:"/companies/{companyId}/behaviours/scripts",BehaviourLog:"",Provider:"/companies/{companyId}/providers",ProviderGeneral:"/companies/{companyId}/providers/generals",ProviderAdvanced:"/companies/{companyId}/providers/advanceds",ProviderControl:"/companies/{companyId}/providers/controls",ProviderConfiguration:"/companies/{companyId}/providers/configurations",ProviderConfigurationType:"",ProviderScript:"/companies/{companyId}/providers/scripts",ProviderConfig:"/companies/{companyId}/providers/configs",ProviderRegistration:"/companies/{companyId}/providers/registrations",ReportTemplate:"/companies/{companyId}/reports/templates",ReportSchedule:"/companies/{companyId}/reports/schedules",ReportResult:"/companies/{companyId}/reports/results",BillingProfile:"/companies/{companyId}/billing/profiles",BillingReport:"/companies/{companyId}/billing/profiles/reports",BillableHostingRule:"",BillableHostingLicense:""},gr={AssetMessage:"/assets/{assetId}/messages",DispatchTask:"/assets/{assetId}/dispatch/tasks",DispatchJob:"/assets/{assetId}/dispatch/jobs",FormResult:"/assets/{assetId}/forms",MaintenanceJob:"/assets/{assetId}/maintenance/jobs"},yr={BillingHosting:"/billing/profiles/{profileId}/rules",BillingLicense:"/billing/profiles/{profileId}/licenses",BillingReport:"/billing/profiles/{profileId}/reports"},vr=/[A-Z][a-z]+/;class fr{account;baseAddress;query=new Map;headers=new Map;createBaseUrl(e){const t=this.baseAddress?new URL(e??"",this.baseAddress):new URL(e),s=new Map(this.query);for(const[e,r]of s)t.searchParams.append(e,r);return t}constructor(e,t){this.baseAddress=t?new URL(t):null,this.setAuth(e)}setAuth(e){e instanceof p?this.account=e:"string"==typeof e?this.setAuth({ghostId:e}):e instanceof ar||e?.key?this.setAuth({machine:e.toJSON?.()??e}):e?.machine?.key||e?.ghostId?this.setAuth(new p({errorCode:d.success,message:"Authenticated via "+(e?.machine?.key?"Machine":"Session"),...e.toJSON?.()??e})):this.setAuth(new p)}t=0;i=new Map;command(t){return o(this.i,t.constructor.name+JSON.stringify(t.toJSON()),(s=>new Promise((async(r,n)=>{let i=null,o=null,a=null;try{t.reqId=++this.t,i=await this.requestCreate(t)}catch(t){o=e(t)}try{o=o??await this.requestRelay(i)}catch(s){a=t.createReply(s instanceof Error?e(s):s)}try{a=a??t.createReply(o)}catch(s){a=t.createReply(e(s,o))}(a.errorCode===d.success?r:n)(a),this.i.delete(s)}))))}}class br extends fr{o=new Map;h(e){this.setAuth(e??new p(this.account.toJSON())),this.fire("account",(()=>new dr("account",this.account)))}u(e,t,s){this.fire("list",(()=>new pr("list",e,t,s)))}p(e,t,s){this.fire("update",(()=>new lr("update",e,t,s)))}l(e,t,s){this.fire("delete",(()=>new mr("delete",e,t,s)))}on(e,t){let s=this.o.get(e);s||this.o.set(e,s=[]);const r=s.includes(t);return r||s.push(t),!r}off(e,t){const s=this.o.get(e);if(s?.length){if(t){const e=s.indexOf(t);return!!(e>-1&&s.splice(e,1))}return!(s.length=0)}return!1}fire(e,t){const s=this.o.get(e)?.slice();if(s?.length){const e=t();s.forEach((t=>t.call(this,e)),this)}}handles(e,t){return this.o.get(e)?.includes(t)??!1}dispose(){for(const e of[...this.o.keys()])this.off(e)}async command(e){const t=await super.command(e);if(t instanceof l&&t.store()){const s=e.getAction(),r=t.getCompanyId();t instanceof m?s.filter?t.getList().forEach((e=>this.p(s.object,r,e))):this.u(s.object,r,t.getList()):t instanceof w?this.p(s.object,r,t.getObject()):t instanceof g?this.l(s.object,r,t.getKey()):t instanceof y&&t.getResults().forEach((e=>this.l(s.object,e.getCompanyId(),e.getKey())))}return t}async selfDetails(){const e=await this.command(new v);return this.h(e),e}async login(e,t,s){const r=await this.command(new f({username:e,password:t,userAgent:s??null}));return this.h(r),r}logout(){const e=this.command(new b);return this.h(new p),e}updateContact(e,t,s,r,n,i,o,a,c,h,u){return this.command(new C({contact:{name:e??null,notes:t??null,otherNames:s??null,emails:r??null,phones:n??null,addresses:i??null,urls:o??null,dates:a??null,options:c??null,roles:h??null,pictures:u??null}}))}updatePassword(e,t){return this.command(new P({current:e,password:t}))}updatePreferences(e,t,s,r,n){return this.command(new S({language:e??null,timezone:t?.code??t??null,notify:s?.map((e=>e.toJSON?.()??e))??null,formats:r instanceof Map?cr.fromMap(r):r??null,measurements:n instanceof Map?cr.fromMap(n):n??null}))}updateState(e){return this.command(new R({options:e instanceof Map?cr.fromMap(e):e??null}))}getCompany(e){return this.command(new k({company:{id:e}}))}mergeCompany(e){return this.command(new A({company:e}))}removeCompany(e){return this.command(new M({company:{id:e}}))}restoreCompany(e){return this.command(new D({company:{id:e}}))}listCompanyGenerals(e,t){return this.command(new I({...t,company:{id:e}}))}getCompanyGeneral(e){return this.command(new T({company:{id:e}}))}listCompanyPolicies(e,t){return this.command(new G({...t,company:{id:e}}))}getCompanyPolicy(e){return this.command(new U({company:{id:e}}))}listCompanyStyles(e,t){return this.command(new B({...t,company:{id:e}}))}getCompanyStyle(e){return this.command(new J({company:{id:e}}))}listCompanyDirectories(e,t){return this.command(new E({...t,company:{id:e}}))}getCompanyDirectory(e){return this.command(new L({company:{id:e}}))}getReseller(e){return this.command(new x({company:{id:e}}))}mergeReseller(e){return this.command(new N({company:e}))}removeReseller(e){return this.command(new O({company:{id:e}}))}restoreReseller(e){return this.command(new _({company:{id:e}}))}listContacts(e,t){return this.command(new F({...t,company:{id:e}}))}getContact(e){return this.command(new H({contact:{id:e}}))}mergeContact(e){return this.command(new q({contact:e}))}removeContact(e){return this.command(new $({contact:{id:e}}))}restoreContact(e){return this.command(new W({contact:{id:e}}))}multiMergeContact(e){return this.command(new j({contacts:e}))}multiRemoveContact(e){return this.command(new z({contacts:e.map((e=>({id:e})))}))}listUsers(e,t){return this.command(new K({...t,company:{id:e}}))}getUser(e){return this.command(new Z({user:{login:e}}))}mergeUser(e){return this.command(new Q({user:e}))}removeUser(e){return this.command(new V({user:{login:e}}))}restoreUser(e){return this.command(new X({user:{login:e}}))}listUserGenerals(e,t){return this.command(new Y({...t,company:{id:e}}))}getUserGeneral(e){return this.command(new ee({user:{login:e}}))}listUserAdvanceds(e,t){return this.command(new te({...t,company:{id:e}}))}getUserAdvanced(e){return this.command(new se({user:{login:e}}))}listUserGroups(e,t){return this.command(new re({...t,company:{id:e}}))}getUserGroup(e){return this.command(new ne({userGroup:{id:e}}))}mergeUserGroup(e){return this.command(new ie({userGroup:e}))}removeUserGroup(e){return this.command(new oe({userGroup:{id:e}}))}restoreUserGroup(e){return this.command(new ae({userGroup:{id:e}}))}listMachines(e,t){return this.command(new ce({...t,company:{id:e}}))}getMachine(e){return this.command(new he({machine:{id:e}}))}mergeMachine(e){return this.command(new ue({machine:e}))}removeMachine(e){return this.command(new de({machine:{id:e}}))}restoreMachine(e){return this.command(new pe({machine:{id:e}}))}listSessions(e,t){return this.command(new le({...t,company:{id:e}}))}listSessionsByUser(e,t){return this.command(new me({...t,user:{login:e}}))}killSession(e){return this.command(new we({session:{handle:e}}))}listIcons(e,t){return this.command(new ge({...t,company:{id:e}}))}getIcon(e){return this.command(new ye({icon:{id:e}}))}mergeIcon(e){return this.command(new ve({icon:e}))}removeIcon(e){return this.command(new fe({icon:{id:e}}))}restoreIcon(e){return this.command(new be({icon:{id:e}}))}listPictures(e,t){return this.command(new Ce({...t,company:{id:e}}))}getPicture(e){return this.command(new Pe({picture:{id:e}}))}mergePicture(e){return this.command(new Se({picture:e}))}removePicture(e){return this.command(new Re({picture:{id:e}}))}restorePicture(e){return this.command(new ke({picture:{id:e}}))}listDocuments(e,t){return this.command(new Ae({...t,company:{id:e}}))}getDocument(e){return this.command(new Me({document:{id:e}}))}mergeDocument(e){return this.command(new De({document:e}))}removeDocument(e){return this.command(new Ie({document:{id:e}}))}restoreDocument(e){return this.command(new Te({document:{id:e}}))}listFormTemplates(e,t){return this.command(new Ge({...t,company:{id:e}}))}getFormTemplate(e){return this.command(new Ue({formTemplate:{id:e}}))}mergeFormTemplate(e){return this.command(new Be({formTemplate:e}))}removeFormTemplate(e){return this.command(new Je({formTemplate:{id:e}}))}restoreFormTemplate(e){return this.command(new Ee({formTemplate:{id:e}}))}listFormResults(e,t){return this.command(new Le({...t,company:{id:e}}))}getFormResult(e){return this.command(new xe({formResult:{id:e}}))}mergeFormResult(e){return this.command(new Ne({formResult:e}))}multiMergeFormResult(e){return this.command(new Oe({formResult:{id:e}}))}removeFormResult(e){return this.command(new _e({formResult:{id:e}}))}restoreFormResult(e){return this.command(new Fe({formResult:{id:e}}))}listDashcamDatas(e,t){return this.command(new He({...t,company:{id:e}}))}getDashcamData(e){return this.command(new qe({dashcam:{guid:e}}))}listDashcamLives(e,t){return this.command(new $e({...t,company:{id:e}}))}listAssets(e,t){return this.command(new We({...t,company:{id:e}}))}getAsset(e){return this.command(new je({asset:{id:e}}))}mergeAsset(e){return this.command(new ze({asset:e}))}multiMergeAsset(e){return this.command(new Ke({assets:e}))}removeAsset(e){return this.command(new Ze({asset:{id:e}}))}restoreAsset(e){return this.command(new Qe({asset:{id:e}}))}suspendAsset(e){return this.command(new Ve({asset:{id:e}}))}reviveAsset(e){return this.command(new Xe({asset:{id:e}}))}searchAssets(e,t){}listAssetGenerals(e,t){return this.command(new Ye({...t,company:{id:e}}))}getAssetGeneral(e){return this.command(new et({asset:{id:e}}))}searchAssetGenerals(e,t){}listAssetAdvanceds(e,t){return this.command(new tt({...t,company:{id:e}}))}getAssetAdvanced(e){return this.command(new st({asset:{id:e}}))}searchAssetAdvanceds(e,t){}mergeAssetDispatch(e){return this.command(new rt({assetDispatch:e}))}listDispatchTasks(e,t){return this.command(new nt({...t,company:{id:e}}))}getDispatchTasksByAsset(e,t){return this.command(new it({...t,asset:{id:e}}))}getDispatchTask(e){return this.command(new ot({dispatchTask:{id:e}}))}mergeDispatchTask(e){return this.command(new at({dispatchTask:e}))}multiMergeDispatchTask(e){return this.command(new ct({dispatchTask:{id:e}}))}removeDispatchTask(e){return this.command(new ht({dispatchTask:{id:e}}))}restoreDispatchTask(e){return this.command(new ut({dispatchTask:{id:e}}))}listDispatchJobs(e,t){return this.command(new dt({...t,company:{id:e}}))}getDispatchJobsByAsset(e,t){return this.command(new pt({...t,asset:{id:e}}))}getDispatchJob(e){return this.command(new lt({dispatchJob:{id:e}}))}mergeDispatchJob(e){return this.command(new mt({dispatchJob:e}))}multiMergeDispatchJob(e){return this.command(new wt({dispatchJob:{id:e}}))}removeDispatchJob(e){return this.command(new gt({dispatchJob:{id:e}}))}restoreDispatchJob(e){return this.command(new yt({dispatchJob:{id:e}}))}changeDispatchJob(e){return this.command(new vt({dispatchJob:e}))}cancelDispatchJob(e){return this.command(new ft({dispatchJob:e}))}listAssetMessages(e,t){return this.command(new bt({...t,company:{id:e}}))}getAssetMessagesByAsset(e,t){return this.command(new Ct({...t,asset:{id:e}}))}getAssetMessage(e){return this.command(new Pt({message:{id:e}}))}mergeAssetMessage(e){return this.command(new St({assetMessage:e}))}multiMergeAssetMessage(e){return this.command(new Rt({assetMessage:{id:e}}))}removeAssetMessage(e){return this.command(new kt({assetMessage:{id:e}}))}restoreAssetMessage(e){return this.command(new At({assetMessage:{id:e}}))}listPlaces(e,t){return this.command(new Mt({...t,company:{id:e}}))}getPlace(e){return this.command(new Dt({place:{id:e}}))}mergePlace(e){return this.command(new It({place:e}))}removePlace(e){return this.command(new Tt({place:{id:e}}))}restorePlace(e){return this.command(new Gt({place:{id:e}}))}listProviders(e,t){return this.command(new Ut({...t,company:{id:e}}))}getProvider(e){return this.command(new Bt({provider:{id:e}}))}mergeProvider(e){return this.command(new Jt({provider:e}))}multiMergeProvider(e){return this.command(new Et({providers:e}))}multiRemoveProvider(e){return this.command(new Lt({providers:e.map((e=>({id:e})))}))}removeProvider(e){return this.command(new xt({provider:{id:e}}))}restoreProvider(e){return this.command(new Nt({provider:{id:e}}))}searchProviders(e,t){}listProviderGenerals(e,t){return this.command(new Ot({...t,company:{id:e}}))}getProviderGeneral(e){return this.command(new _t({provider:{id:e}}))}searchProviderGenerals(e,t){}listProviderAdvanceds(e,t){return this.command(new Ft({...t,company:{id:e}}))}getProviderAdvanced(e){return this.command(new Ht({provider:{id:e}}))}searchProviderAdvanceds(e,t){}listProviderControls(e,t){return this.command(new qt({...t,company:{id:e}}))}getProviderControl(e){return this.command(new $t({provider:{id:e}}))}searchProviderControls(e,t){}listProviderScripts(e,t){return this.command(new Wt({...t,company:{id:e}}))}getProviderScript(e){return this.command(new jt({providerScript:{id:e}}))}mergeProviderScript(e){return this.command(new zt({providerScript:e}))}removeProviderScript(e){return this.command(new Kt({providerScript:{id:e}}))}restoreProviderScript(e){return this.command(new Zt({providerScript:{id:e}}))}listProviderConfigs(e,t){return this.command(new Qt({...t,company:{id:e}}))}getProviderConfig(e){return this.command(new Vt({providerConfig:{id:e}}))}mergeProviderConfig(e){return this.command(new Xt({providerConfig:e}))}multiMergeProviderConfig(e){return this.command(new Yt({providerConfig:{id:e}}))}removeProviderConfig(e){return this.command(new es({providerConfig:{id:e}}))}restoreProviderConfig(e){return this.command(new ts({providerConfig:{id:e}}))}listProviderConfigurations(e,t){return this.command(new ss({...t,company:{id:e}}))}getProviderConfiguration(e){return this.command(new rs({providerConfiguration:{id:e}}))}mergeProviderConfiguration(e){return this.command(new ns({providerConfiguration:e}))}multiMergeProviderConfiguration(e){return this.command(new is({providerConfiguration:{id:e}}))}removeProviderConfiguration(e){return this.command(new os({providerConfiguration:{id:e}}))}restoreProviderConfiguration(e){return this.command(new as({providerConfiguration:{id:e}}))}listProviderRegistration(e,t){return this.command(new cs({...t,company:{id:e}}))}getProviderRegistration(e){return this.command(new hs({providerRegistration:{id:e}}))}mergeProviderRegistration(e){return this.command(new us({providerRegistration:e}))}removeProviderRegistration(e){return this.command(new ds({providerRegistration:{id:e}}))}listBehaviours(e,t){return this.command(new ps({...t,company:{id:e}}))}getBehaviour(e){return this.command(new ls({behaviour:{id:e}}))}mergeBehaviour(e){return this.command(new ms({behaviour:e}))}multiMergeBehaviour(e){return this.command(new ws({behaviour:{id:e}}))}removeBehaviour(e){return this.command(new gs({behaviour:{id:e}}))}restoreBehaviour(e){return this.command(new ys({behaviour:{id:e}}))}listBehaviourScripts(e,t){return this.command(new vs({...t,company:{id:e}}))}getBehaviourScript(e){return this.command(new fs({behaviourScript:{id:e}}))}mergeBehaviourScript(e){return this.command(new bs({behaviourScript:e}))}removeBehaviourScript(e){return this.command(new Cs({behaviourScript:{id:e}}))}restoreBehaviourScript(e){return this.command(new Ps({behaviourScript:{id:e}}))}listBehaviourAssetLogs(e,t){return this.command(new Ss({...t,behaviour:{id:e}}))}clearBehaviourAssetLogs(e){return this.command(new Rs({behaviour:{id:e}}))}listBehaviourLogs(e,t){return this.command(new ks({...t,behaviour:{id:e}}))}clearBehaviourLogs(e){return this.command(new As({behaviour:{id:e}}))}listBehaviourScriptLogs(e,t){return this.command(new Ms({...t,behaviourScript:{id:e}}))}clearBehaviourScriptLogs(e,t){return this.command(new Ds({...t,behaviourScript:{id:e}}))}listReportTemplates(e,t){return this.command(new Is({...t,company:{id:e}}))}getReportTemplate(e){return this.command(new Ts({reportTemplate:{id:e}}))}mergeReportTemplate(e){return this.command(new Gs({reportTemplate:e}))}removeReportTemplate(e){return this.command(new Us({reportTemplate:{id:e}}))}restoreReportTemplate(e){return this.command(new Bs({reportTemplate:{id:e}}))}listReportSchedules(e,t){return this.command(new Js({...t,company:{id:e}}))}getReportSchedule(e){return this.command(new Es({reportSchedule:{id:e}}))}mergeReportSchedule(e){return this.command(new Ls({reportSchedule:e}))}removeReportSchedule(e){return this.command(new xs({reportSchedule:{id:e}}))}restoreReportSchedule(e){return this.command(new Ns({reportSchedule:{id:e}}))}listReportResults(e,t){return this.command(new Os({...t,company:{id:e}}))}getReportResult(e){return this.command(new _s({reportResult:{id:e}}))}mergeReportResult(e){return this.command(new Fs({reportResult:e}))}removeReportResult(e){return this.command(new Hs({reportResult:{id:e}}))}restoreReportResult(e){return this.command(new qs({reportResult:{id:e}}))}listMaintenanceSchedules(e,t){return this.command(new $s({...t,company:{id:e}}))}getMaintenanceSchedule(e){return this.command(new Ws({maintenanceSchedule:{id:e}}))}mergeMaintenanceSchedule(e){return this.command(new js({maintenanceSchedule:e}))}removeMaintenanceSchedule(e){return this.command(new zs({maintenanceSchedule:{id:e}}))}restoreMaintenanceSchedule(e){return this.command(new Ks({maintenanceSchedule:{id:e}}))}listMaintenanceJobs(e,t){return this.command(new Zs({...t,company:{id:e}}))}getMaintenanceJob(e){return this.command(new Qs({maintenanceJob:{id:e}}))}mergeMaintenanceJob(e){return this.command(new Vs({maintenanceJob:e}))}removeMaintenanceJob(e){return this.command(new Xs({maintenanceJob:{id:e}}))}restoreMaintenanceJob(e){return this.command(new Ys({maintenanceJob:{id:e}}))}}class Cr extends br{static URI_PROD="https://rest.trakit.ca/";static URI_BETA="https://mindflayer.trakit.ca/";constructor(e,t){super(e,t??Cr.URI_PROD)}requestCreate(e){return r(this,e)}requestRelay(e){return i(e)}}const Pr=/^(.+?)(Merged|Deleted|Suspended)$/,Sr={Company:[er.companyGeneral,er.companyLabels,er.companyPolicies],CompanyGeneral:[er.companyGeneral],CompanyDirectory:[],CompanyStyle:[er.companyLabels],CompanyPolicy:[er.companyPolicies],CompanyReseller:[er.companyReseller],Contact:[er.contact],Machine:[er.machine],User:[er.userGeneral,er.userAdvanced,er.userAuthentication],UserGeneral:[er.userGeneral],UserAdvanced:[er.userAdvanced],UserAuthentication:[er.userAuthentication],UserState:[er.userState],UserGroup:[er.userGroup],Session:[],Dashcam:[],Icon:[er.icon],Picture:[er.picture],Document:[er.document],FormTemplate:[er.formTemplate],FormResult:[er.formResult],Asset:[er.assetGeneral,er.assetAdvanced,er.assetDispatch],AssetGeneral:[er.assetGeneral],AssetAdvanced:[er.assetAdvanced],AssetDispatch:[er.assetDispatch],AssetMessage:[er.assetMessage],AssetAlert:[],DispatchTask:[er.dispatchTask],DispatchJob:[er.dispatchJob],MaintenanceSchedule:[er.maintenanceSchedule],MaintenanceJob:[er.maintenanceJob],Place:[er.placeGeneral],BehaviourScript:[er.behaviourScript],Behaviour:[er.behaviour],BehaviourLog:[er.behaviourLog],Provider:[er.providerGeneral,er.providerAdvanced,er.providerControl],ProviderGeneral:[er.providerGeneral],ProviderAdvanced:[er.providerAdvanced],ProviderControl:[er.providerControl],ProviderConfiguration:[er.providerConfiguration],ProviderConfigurationType:[],ProviderScript:[er.providerScript],ProviderConfig:[er.providerConfig],ProviderRegistration:[er.providerRegistration],ReportTemplate:[er.reportTemplate],ReportSchedule:[er.reportSchedule],ReportResult:[er.reportResult],BillingProfile:[er.billingProfile],BillingReport:[er.billingReport],BillableHostingRule:[er.billingHosting],BillableHostingLicense:[er.billingLicense]};class Rr{#e=new Map;get regions(){return[...this.#e.keys()]}getExpired(){const e=new Date,t=[];for(let[s,r]of this.#e)r&&r<e&&t.push(s);return t}purgeExpired(){const e=this.getExpired();return e.forEach((e=>this.#e.delete(e))),e}getExpiring(){const e=[];for(let[t,s]of this.#e)s&&e.push(t);return e}#t(e,t){return t=t||null,this.#e.set(e,t),t}expireRegion(e,t=!1){const s=t?0:(new Date).valueOf();return this.#t(e,new Date(s+3e5))}expireRegions(e,t=!1){return e.map((e=>this.expireRegion(e,t)))}preserveRegion(e){const t=this.#e.get(e);return this.#t(e),t||null}preserveRegions(e){return e.map((e=>this.preserveRegion(e)))}reset(){const e=[];for(let[t,s]of this.#e)s||e.push(t);return this.#e.clear(),e}}var kr;!function(e){e.maintenance="maintenance",e.upgrade="upgrade"}(kr||(kr={}));class Ar{static fromJson(e){switch(e?.kind){case kr.maintenance:return new Mr(e);case kr.upgrade:return new Dr(e);default:throw new Error(`Unknown broadcast type: ${e?.kind}`)}}kind;serverTime;message;constructor(e){this.kind=e?.kind,this.serverTime=or.date(e?.serverTime),this.message=e?.message??""}}class Mr extends Ar{starting;ending;constructor(e){super(e),this.starting=or.date(e?.starting),this.ending=or.date(e?.ending)}}class Dr extends Ar{eta;reload;constructor(e){super(e),this.eta=or.date(e?.eta),this.reload=!!e?.reload}}class Ir extends hr{name;body;constructor(e,t,s){super(e),this.name=t,this.body=s}}class Tr extends hr{online;reply;constructor(e,t,s){super(e),this.online=t,this.reply=s}}class Gr extends hr{broadcast;constructor(e,t){super(e),this.broadcast=Ar.fromJson(t)}}const Ur="connection",Br="dis"+Ur;var Jr;!function(e){e[e.opening=WebSocket.CONNECTING]="opening",e[e.open=WebSocket.OPEN]="open",e[e.closing=WebSocket.CLOSING]="closing",e[e.closed=WebSocket.CLOSED]="closed"}(Jr||(Jr={}));class Er extends br{static URI_PROD="wss://socket.trakit.ca/";static URI_BETA="wss://kraken.trakit.ca/";static msgNameToSyncName(e){const s=Pr.exec(e);return 3===s?.length?t(s[1])||null:void 0}#s=new Date(NaN);#r=new Date(NaN);#n="";#i=new Date(NaN);get lastConnected(){return this.#s}get lastReceived(){return this.#r}get lastMessage(){return this.#n}get lastSent(){return this.#i}get state(){switch(this.#o?.readyState){case WebSocket.CONNECTING:return Jr.opening;case WebSocket.OPEN:return this.#a?Jr.open:Jr.opening;case WebSocket.CLOSING:return Jr.closing;default:return Jr.closed}}get ready(){return this.#a&&this.#c}m(e){const t=this.o.get("open");if(t?.length){const s=new Tr("open",this.#a,e);t.forEach((e=>e.call(this,s)))}}v(e){const t=this.o.get("close");if(t?.length){const s=new Tr("close",this.#a,e);t.forEach((e=>e.call(this,s)))}}C(e,t){const s=this.o.get("message");if(s?.length){const r=new Ir("message",e,t);s.forEach((e=>e.call(this,r)))}}P(e){const t=this.o.get("error");if(t?.length){const s=new Tr("error",!1,e);t.forEach((e=>e.call(this,s)))}}S(e){const t=this.o.get("broadcast");if(t?.length){const s=new Gr("broadcast",e);t.forEach((e=>e.call(this,s)))}}#h=new Map;#u(e,t){return this.#h.get(e)?.(t),this.#h.delete(e)}#o;#a=!1;#c=!0;#d(e){this.#o.onopen=null,this.#o.onmessage=e=>this.#p(e),this.#l=0}#m(e){this.P(new tr({errorCode:d.service,message:"WebSocket error",errorDetails:{kind:"connection",state:this.state,reconnect:this.reconnectEnabled}}))}#w(e){clearTimeout(this.#g),clearTimeout(this.#y),this.#a=!1,this.#l=this.#l?2*this.#l:this.lastReceived?(new Date).valueOf()-this.lastReceived.valueOf():5e3;const t=Math.min(this.#l,3e5),s={kind:"connection",state:Jr.closed,code:e.code,reason:e.reason,wasClean:e.wasClean,reconnect:this.reconnectEnabled,retry:(new Date).valueOf()+t},r={errorCode:d.success,message:"Disconnected",errorDetails:s};for(const e of[...this.#h.keys()].sort())this.#u(e,e===Br?r:{...r,reqId:e,errorCode:d.service,errorDetails:{...s}});this.v?.(new tr(r)),this.#y=this.reconnectEnabled&&this.#c?setTimeout((()=>this.open()),t,this):0,this.#o=this.#o.onopen=this.#o.onerror=this.#o.onclose=this.#o.onmessage=null}#p(e){this.#r=new Date;const t=e.data.substring(0,e.data.indexOf(" ")),s=JSON.parse(e.data.substring(t.length+1));switch(this.#n=t,"connectionResponse"!==t&&"noopResponse"!==t&&this.C(t,s),t){case"connectionResponse":this.#v(s),this.#s=new Date(this.#r),this.#a=!0,this.#u(Ur,s),this.h(),this.m(this.account);break;case"loginResponse":case"getSessionDetailsResponse":this.#v(s),this.h();break;case"updateOwnPasswordResponse":this.#c||(this.#c=0===s.errorCode);break;case"logoutResponse":this.close();case"sessionEnded":this.#c=!1,this.#v(s),this.h();break;case"sessionGeneralMerged":case"sessionAdvancedMerged":case"sessionAuthenticationMerged":case"sessionStateMerged":this.#f({user:s}),this.h();break;case"sessionMachineMerged":this.#f({machine:s}),this.h();break;case"sessionPoliciesMerged":this.#f(s),this.h();break;case"broadcast":this.S(s)}if(t.endsWith("Response"))this.#u(s.reqId,s);else if(!t.startsWith("session")){const e=Pr.exec(t);e?.length&&this.#b(e,s)}this.resetKeepAlive()}#v(e){this.setAuth(new p(e)),this.#c=0===this.account.errorCode&&!this.account.user?.passwordExpired,this.account.store()}#f(e){const t=this.account.toJSON();this.setAuth(new p({...t,user:e?.user?{...t.user,...e.user}:null,machine:e?.machine??t.machine,sessionPolicy:e?.sessionPolicy??t.sessionPolicy,passwordPolicy:e?.passwordPolicy??t.passwordPolicy,multiFactorPolicy:e?.multiFactorPolicy??t.multiFactorPolicy,ssoPolicy:e?.ssoPolicy??t.ssoPolicy})),this.account.store()}#b(e,s){const r=t(e[1]),n=s[r.startsWith("Company")?"parent":"company"],i=function(e,t){return u["Rep"+e+(t??"Get")]}(r,"Merged"===e[2]?"Get":e[2].slice(0,-1).slice(0,7));if(!i)throw new Error("No Reply class found for "+r+" and action "+e[2]);const o=new i({errorCode:d.success,message:e[2]+" event",[e[1]]:s});if(o.store())switch(e[2]){case"Merged":case"Suspended":this.p(r,n,o.getObject());break;case"Deleted":this.l(r,n,function(e,t){return e[function(e){switch(e){case"User":case"UserGeneral":case"UserAdvanced":return"login";case"ProviderRegistration":return"code";case"Session":return"handle";case"Machine":return"key";case"Dashcam":return"guid";default:return"id"}}(t)]}(s,r))}return o}reconnectEnabled=!0;#l=0;#y=0;keepAliveEnabled=!1;#g=0;constructor(e,t){super(e,t??Er.URI_PROD)}dispose(){this.close().finally((()=>{super.dispose(),this.#o=this.#h=null}))}open(){return o(this.i,Ur,(e=>(clearTimeout(this.#y),new Promise((async(t,s)=>{const r=this.state;if(r===Jr.closed){const r=this.createBaseUrl();this.#o=new WebSocket(r,this.account.machine?(this.account.machine.secret?.length?"HMAC256#"+btoa(this.account.machine.key+":"+await this.account.machine.createHmacSignature(r)):"MACHINE#"+btoa(this.account.machine.key)).replaceAll("/","|").replace(/=*$/,""):this.account.ghostId||void 0),this.#o.onopen=e=>this.#d(e),this.#o.onerror=e=>this.#m(e),this.#o.onclose=e=>this.#w(e),this.#h.set(Ur,(r=>{(0===r.errorCode?t:s)(this.account),this.i.delete(e)}))}else s(new p({errorCode:d.unknown,message:"WebSocket not closed",errorDetails:{kind:"connection",connection:r}}))})))))}close(){return o(this.i,Br,(e=>(clearTimeout(this.#y),new Promise(((t,s)=>{const r=this.state;switch(r){case Jr.opening:case Jr.open:this.#c=!1,this.reconnectEnabled=!1,this.#h.set(Br,(r=>{(0===r.errorCode?t:s)(new tr(r)),this.i.delete(e)})),this.#o.close(1e3,"Bye!");break;default:s(new tr({errorCode:d.unknown,message:"WebSocket not open",errorDetails:{kind:"connection",connection:r}}))}})))))}requestCreate(e){return Promise.resolve([a(e),e.toJSON()])}requestRelay(t){const s=t[0],r=t[1]||{};return new Promise(((n,i)=>{if(this.state===Jr.open){const t=++this.t,i=setTimeout((()=>this.#u(t,{reqId:t,errorCode:d.unknown,message:"Command timeout"})),12e4);r.reqId=t,this.#h.set(t,(e=>{clearTimeout(i),n(e)}));try{this.#o.send(s+" "+JSON.stringify(r)),this.#i=new Date}catch(s){this.#u(t,e(s))}this.resetKeepAlive()}else this.open().then((()=>this.requestRelay(t).then(n))).catch(i)}))}resetKeepAlive(){return clearTimeout(this.#g),this.#g=this.keepAliveEnabled&&this.#c?setTimeout((()=>this.requestRelay(["noop",{}])),3e5):0,Promise.resolve(0!==this.#g)}subscribe(e,t){return t?.length?this.command(new sr({company:{id:e},subscriptionTypes:t})):Promise.resolve(new rr({errorCode:d.success,message:"No subscriptions specified"}))}unsubscribe(e,t){return t?.length?this.command(new nr({company:{id:e},subscriptionTypes:t})):Promise.resolve(new rr({errorCode:d.success,message:"No subscriptions specified"}))}listSubscriptions(){return this.command(new ir)}}const Lr={Company:["CompanyGeneral","CompanyDirectory","CompanyStyle","CompanyPolicy"],Asset:["AssetGeneral","AssetAdvanced","AssetDispatch"],Provider:["ProviderGeneral","ProviderAdvanced","ProviderControl"],User:["UserGeneral","UserAdvanced"]};class xr extends br{R;k;get autoConnect(){return this.R.reconnectEnabled}set autoConnect(e){this.R.reconnectEnabled=!!e,e&&this.R.state===Jr.closed&&this.R.open()}get socketOnline(){return this.R.state===Jr.open}get socketDetails(){return{state:this.R.state,ready:this.R.ready,lastConnected:this.R.lastConnected,lastSent:this.R.lastSent,lastReceived:this.R.lastReceived,lastMessage:this.R.lastMessage}}get socketAddress(){return this.R.baseAddress}set socketAddress(e){this.R.baseAddress=e}get restAddress(){return this.k.baseAddress}set restAddress(e){this.k.baseAddress=e}constructor(e,t,s){super(e);const r=e=>this.#C(e.account),n=e=>this.fire(e.type,(()=>e));this.k=new Cr(this.account,t??Cr.URI_PROD),this.k.on("account",r),this.R=new Er(this.account,s??Er.URI_PROD),this.R.on("account",r),this.R.on("open",(e=>this.#P(e))),this.R.on("close",(e=>this.#S(e)));for(const e of["account","list","update","delete"])this.k.on(e,n),this.R.on(e,n);for(const e of["open","close","broadcast"])this.R.on(e,n);this.autoConnect=!(!this.account.ghostId&&!this.account.machine?.key)}dispose(){super.dispose(),this.k.dispose(),this.R.dispose(),this.k=this.R=null}setAuth(e){super.setAuth(e),this.k?.setAuth(this.account),this.R?.setAuth(this.account)}command(e){const t=e.getAction().object;return"Subscription"===t||"Self"===t&&this.socketOnline?this.socket(e):this.rest(e)}requestCreate(e){throw new Error("Method not implemented.")}requestRelay(e){throw new Error("Method not implemented.")}rest(e){return this.k.command(e)}socket(e){return this.R.command(e)}#P(e){this.#R.forEach(((e,t)=>{this.sync(t,h(e.reset()))})),this.#k()}#S(e){clearTimeout(this.#A)}#C(e){this.setAuth(e),this.autoConnect=!(!this.account.user?.login&&!this.account.machine?.key)}isSynced(e,t){let s=this.R.state===Jr.open;if(s){const r=this.#M(e);s=c(t).every((e=>r.regions.includes(e)))}return s}getSyncs(e,t=!1){const s=this.#M(e),r=t?[]:s.getExpiring();return h(s.regions.filter((e=>!r.includes(e))))}async sync(t,s){const r=[],n=this.#M(t),i=c(s).filter((e=>!n.regions.includes(e)));if(i.length>0){n.preserveRegions(i);const s=await this.R.subscribe(t,i);n.expireRegions((s.denied??[]).concat(s.invalid??[]),!0),h(s.merged??[]).forEach((s=>{const n=function(e,t){return u["Pay"+e+(t??"Get")]}(s,s.startsWith("Company")?"Get":"ListByCompany");r.push(n?this.command(new n({company:{id:t}})):Promise.reject(e(new Error(`No payload class could be made for sync type ${s}`))))}))}return Promise.all(r)}desync(e,t){const s=this.#M(e),r=t.reduce(((e,t)=>e.concat(Sr[t]||[])),[]).filter((e=>s.regions.includes(e))).filter(((e,t,s)=>s.indexOf(e)===t));return s.expireRegions(r),r}#R=new Map;#k(){const e=[];this.R.state===Jr.open&&this.#R.forEach(((t,s)=>{const r=t.purgeExpired();r.length&&e.push(this.unsubscribe(s,r))})),Promise.allSettled(e).finally((()=>{this.#A=setTimeout((()=>this.#k()),1e4)}))}#A;#M(e){let t=this.#R.get(e);return t||this.#R.set(e,t=new Rr),t}subscribe(e,t){return this.R.subscribe(e,t)}unsubscribe(e,t){return this.R.unsubscribe(e,t)}listSubscriptions(){return this.R.listSubscriptions()}}
|
|
2
2
|
/**
|
|
3
3
|
* Synchronization library main process.
|
|
4
4
|
* {@link https://github.com/trakitwireless/trakit-ts-sync|Client synchronization library.}
|
|
5
5
|
* Last updated on Thu Feb 27 2025 11:59:01
|
|
6
6
|
* @copyright Trak-iT Wireless Inc. 2025
|
|
7
|
-
*/const
|
|
7
|
+
*/const Nr="0.0.61";export{Rr as SubscribedRegions,fr as TrakitBaseCommander,hr as TrakitEvent,dr as TrakitEventAccount,mr as TrakitEventDelete,pr as TrakitEventList,Gr as TrakitEventSocketBroadcast,Ir as TrakitEventSocketMessage,Tr as TrakitEventSocketState,ur as TrakitEventSync,lr as TrakitEventUpdate,br as TrakitObjectCommander,Cr as TrakitRestfulCommander,Er as TrakitSocketCommander,Jr as TrakitSocketStatus,xr as TrakitSyncCommander,e as createClientErrorResponse,a as makeCommandName,s as makeVerbRoute,r as requestCreateCommander,n as requestCreateCors,i as requestRelayCorsJson,Nr as version};
|