@trakit/sync 0.1.9 → 0.1.10
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/Audit/AuditConstraints.d.ts +37 -0
- package/Audit/TrakitAuditCommander.d.ts +59 -0
- package/index.d.ts +7 -1
- package/package.json +1 -1
- package/trakit-sync.min.js +2 -2
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { datetime, nothing, uint, ulong } from "@trakit/objects";
|
|
2
|
+
/**
|
|
3
|
+
* Defines constraints for querying audit data, including time range, version range, and result limit.
|
|
4
|
+
*/
|
|
5
|
+
export type AuditConstraints = {
|
|
6
|
+
/**
|
|
7
|
+
* The earliest timestamp for the audit data to be retrieved.
|
|
8
|
+
* If specified, only audit entries after this date will be included.
|
|
9
|
+
*/
|
|
10
|
+
after?: Date | datetime;
|
|
11
|
+
/**
|
|
12
|
+
* The latest timestamp for the audit data to be retrieved.
|
|
13
|
+
* If specified, only audit entries before this date will be included.
|
|
14
|
+
*/
|
|
15
|
+
before?: Date | datetime;
|
|
16
|
+
/**
|
|
17
|
+
* The lowest {@link BaseComponent.v|version key} for the audit data to be retrieved.
|
|
18
|
+
* In rare cases, multiple events can happen at the same moment,
|
|
19
|
+
* and to avoid missing or duplicating data, you should also specify
|
|
20
|
+
* the {@link BaseComponent.v|version key} which is incremented for each event.
|
|
21
|
+
*/
|
|
22
|
+
lowest?: uint | nothing;
|
|
23
|
+
/**
|
|
24
|
+
* The highest {@link BaseComponent.v|version key} for the audit data to be retrieved.
|
|
25
|
+
* In rare cases, multiple events can happen at the same moment,
|
|
26
|
+
* and to avoid missing or duplicating data, you should also specify
|
|
27
|
+
* the {@link BaseComponent.v|version key} which is incremented for each event.
|
|
28
|
+
*/
|
|
29
|
+
highest?: uint | nothing;
|
|
30
|
+
/**
|
|
31
|
+
* The maximum number of audit entries to retrieve.
|
|
32
|
+
* Each object type has its own default value for this limit,
|
|
33
|
+
* which can be overridden by specifying a different value here.
|
|
34
|
+
*/
|
|
35
|
+
limit?: ulong | nothing;
|
|
36
|
+
};
|
|
37
|
+
//# sourceMappingURL=AuditConstraints.d.ts.map
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { Payload, RepAssetAdvancedAudit, RepSelfGet } from "@trakit/commands";
|
|
2
|
+
import { AssetAdvanced, guid, JsonObject, Machine, nothing, ulong, url } from "@trakit/objects";
|
|
3
|
+
import { TrakitBaseCommander } from "../API/TrakitBaseCommander";
|
|
4
|
+
import { AuditConstraints } from "./AuditConstraints";
|
|
5
|
+
/**
|
|
6
|
+
* Uses Trak-iT's RESTful service to access and manipulate Trak-iT API objects.
|
|
7
|
+
*/
|
|
8
|
+
export declare class TrakitAuditCommander extends TrakitBaseCommander<Request> {
|
|
9
|
+
/**
|
|
10
|
+
* Production RESTful service URL.
|
|
11
|
+
* This service is covered by the SLA and should be used for serices and code running in your own production environment.
|
|
12
|
+
* Both services access the same data-set, so be careful making changes as they will be reflected in production as well.
|
|
13
|
+
*/
|
|
14
|
+
static readonly URI_PROD: url;
|
|
15
|
+
/**
|
|
16
|
+
* Testing or beta RESTful service URL.
|
|
17
|
+
* This service is not covered by the SLA and should be used to test your own code before deployment.
|
|
18
|
+
* Throttling of connections and commands is tighter to help you diagnose issues before switching to production.
|
|
19
|
+
* Both services access the same data-set, so be careful making changes as they will be reflected in production as well.
|
|
20
|
+
*/
|
|
21
|
+
static readonly URI_BETA: url;
|
|
22
|
+
constructor(account?: RepSelfGet | {
|
|
23
|
+
machine: {
|
|
24
|
+
key: string;
|
|
25
|
+
};
|
|
26
|
+
} | Machine | {
|
|
27
|
+
key: string;
|
|
28
|
+
} | {
|
|
29
|
+
ghostId: guid;
|
|
30
|
+
} | guid | nothing, baseAddress?: URL | url | nothing);
|
|
31
|
+
/**
|
|
32
|
+
* Creates a request object for the specified HTTP method and body.
|
|
33
|
+
* @param payload
|
|
34
|
+
* @returns A {@link Request} object configured with the specified parameters.
|
|
35
|
+
*/
|
|
36
|
+
requestCreate(payload: Payload): Promise<Request>;
|
|
37
|
+
/**
|
|
38
|
+
* Sends the given request to Trak-iT's RESTful API and awaits a result.
|
|
39
|
+
* @param request.path Relative path to the resource being accessed.
|
|
40
|
+
* @param request.verb HTTP method to use for the request.
|
|
41
|
+
* @param request.body Optional JSON body to send with the request.
|
|
42
|
+
* @returns A promise that resolves with the JSON response from the server.
|
|
43
|
+
*/
|
|
44
|
+
requestRelay(request: Request): Promise<JsonObject>;
|
|
45
|
+
/**
|
|
46
|
+
*
|
|
47
|
+
* @param asset
|
|
48
|
+
* @returns
|
|
49
|
+
*/
|
|
50
|
+
beginAssetAdvanced(asset: AssetAdvanced, limit?: ulong | nothing): Promise<RepAssetAdvancedAudit>;
|
|
51
|
+
/**
|
|
52
|
+
*
|
|
53
|
+
* @param assetId
|
|
54
|
+
* @param constraints
|
|
55
|
+
* @returns
|
|
56
|
+
*/
|
|
57
|
+
auditAssetAdvanced(assetId: ulong, constraints?: AuditConstraints): Promise<RepAssetAdvancedAudit>;
|
|
58
|
+
}
|
|
59
|
+
//# sourceMappingURL=TrakitAuditCommander.d.ts.map
|
package/index.d.ts
CHANGED
|
@@ -8,6 +8,8 @@ import { TrakitEvent, TrakitEventAccount, TrakitEventDelete, TrakitEventList, Tr
|
|
|
8
8
|
import { createClientErrorResponse, makeVerbRoute, requestCreateCommander, requestCreateCors, requestRelayCorsJson } from "./API/Functions";
|
|
9
9
|
import { TrakitBaseCommander } from "./API/TrakitBaseCommander";
|
|
10
10
|
import { TrakitObjectCommander } from "./API/TrakitObjectCommander";
|
|
11
|
+
import { AuditConstraints } from "./Audit/AuditConstraints";
|
|
12
|
+
import { TrakitAuditCommander } from "./Audit/TrakitAuditCommander";
|
|
11
13
|
import { HttpVerb } from "./RESTful/Constants";
|
|
12
14
|
import { TrakitRestfulCommander } from "./RESTful/TrakitRestfulCommander";
|
|
13
15
|
import { TrakitSyncCommander } from "./Synchronization/TrakitSyncCommander";
|
|
@@ -18,7 +20,7 @@ import { TrakitSocketCommander, TrakitSocketStatus } from "./WebSocket/TrakitSoc
|
|
|
18
20
|
/**
|
|
19
21
|
* Version number for this release.
|
|
20
22
|
*/
|
|
21
|
-
export declare const version = "0.1.
|
|
23
|
+
export declare const version = "0.1.10";
|
|
22
24
|
/**
|
|
23
25
|
* API exports
|
|
24
26
|
*/
|
|
@@ -35,4 +37,8 @@ export { makeCommandName, SubscribedRegions, TrakitSocketCommander, TrakitSocket
|
|
|
35
37
|
* Synchronization exports
|
|
36
38
|
*/
|
|
37
39
|
export { TrakitEventSocketBroadcast, TrakitEventSocketMessage, TrakitEventSocketState, TrakitSyncCommander };
|
|
40
|
+
/**
|
|
41
|
+
* Audit service exports
|
|
42
|
+
*/
|
|
43
|
+
export { TrakitAuditCommander, type AuditConstraints };
|
|
38
44
|
//# sourceMappingURL=index.d.ts.map
|
package/package.json
CHANGED
package/trakit-sync.min.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
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){switch(e=cr.capitalize(e)){case"CompanyLabels":e="CompanyStyle";break;case"PlaceGeneral":e="Place";break;default:e=cr.singularize(e)}return e}function s(e){const t=e.getAction();let s="GET",r=new URLSearchParams,n=[...t.object.match(br)].map((e=>cr.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=cr.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 vr?vr[t.object].replace("{assetId}",e.asset.id):`assets/${e.asset.id}/${n}`;break;case"BillingProfile":n=t.object in fr?fr[t.object].replace("{profileId}",e.billingProfile.id):`billing/profiles/${e.billingProfile.id}/${n}`;break;case"Company":n=t.object in yr?yr[t.object].replace("{companyId}",e.company.id):`companies/${e.company.id}/${n}`;break;case"User":n=`users/${encodeURIComponent(e.user.login)}/${n}`}if(cr.isntNaN(e?.limit)&&r.set("limit",e.limit),cr.isntNaN(e?.after?.valueOf())&&r.set("after",e.after.toISOString()),cr.isntNaN(e?.before?.valueOf())&&r.set("before",e.before.toISOString()),cr.isntNaN(e?.lowest)&&r.set("lowest",e.lowest),cr.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"+cr.pluralize(t.object)+"List"+("Company"!=(t.filter||"Company")?"By"+t.filter:"");default:throw s}}function c(e){return e.reduce(((e,t)=>e.concat(kr[t]||[])),[]).filter(((e,t,s)=>s.indexOf(e)===t))}function h(e){const t=[];for(const[s,r]of Object.entries(Nr)){const n=r.map((e=>kr[e])).flat();n.filter((t=>e.includes(t))).length/n.length>=.5&&t.push(s)}const s=t.reduce(((e,t)=>e.concat([t],Nr[t])),[]);for(const[r,n]of Object.entries(kr))!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,PaySelfRecoverStart as k,PaySelfRecoverComplete as A,PayCompanyGet as M,PayCompanyMerge as D,PayCompanyDelete as I,PayCompanyRestore as T,PayCompanyGeneralListByCompany as G,PayCompanyGeneralGet as U,PayCompanyPolicyListByCompany as B,PayCompanyPolicyGet as J,PayCompanyStyleListByCompany as E,PayCompanyStyleGet as L,PayCompanyDirectoryListByCompany as x,PayCompanyDirectoryGet as N,PayCompanyResellerGet as O,PayCompanyResellerMerge as _,PayCompanyResellerDelete as F,PayCompanyResellerRestore as H,PayContactListByCompany as q,PayContactGet as $,PayContactMerge as W,PayContactDelete as j,PayContactRestore as z,PayContactBatchMerge as K,PayContactBatchDelete as Z,PayUserListByCompany as Q,PayUserGet as V,PayUserMerge as X,PayUserDelete as Y,PayUserRestore as ee,PayUserGeneralListByCompany as te,PayUserGeneralGet as se,PayUserAdvancedListByCompany as re,PayUserAdvancedGet as ne,PayUserGroupListByCompany as ie,PayUserGroupGet as oe,PayUserGroupMerge as ae,PayUserGroupDelete as ce,PayUserGroupRestore as he,PayMachineListByCompany as ue,PayMachineGet as de,PayMachineMerge as pe,PayMachineDelete as le,PayMachineRestore as me,PaySessionListByCompany as we,PaySessionListByUser as ge,PaySessionDelete as ye,PayIconListByCompany as ve,PayIconGet as fe,PayIconMerge as be,PayIconDelete as Ce,PayIconRestore as Pe,PayPictureListByCompany as Se,PayPictureGet as Re,PayPictureMerge as ke,PayPictureDelete as Ae,PayPictureRestore as Me,PayDocumentListByCompany as De,PayDocumentGet as Ie,PayDocumentMerge as Te,PayDocumentDelete as Ge,PayDocumentRestore as Ue,PayFormTemplateListByCompany as Be,PayFormTemplateGet as Je,PayFormTemplateMerge as Ee,PayFormTemplateDelete as Le,PayFormTemplateRestore as xe,PayFormResultListByCompany as Ne,PayFormResultGet as Oe,PayFormResultMerge as _e,PayFormResultBatchMerge as Fe,PayFormResultDelete as He,PayFormResultRestore as qe,PayDashcamListByCompany as $e,PayDashcamGet as We,PayDashcamLiveListByCompany as je,PayAssetListByCompany as ze,PayAssetGet as Ke,PayAssetMerge as Ze,PayAssetBatchMerge as Qe,PayAssetDelete as Ve,PayAssetRestore as Xe,PayAssetSuspend as Ye,PayAssetReactivate as et,PayAssetGeneralListByCompany as tt,PayAssetGeneralGet as st,PayAssetAdvancedListByCompany as rt,PayAssetAdvancedGet as nt,PayAssetDispatchMerge as it,PayDispatchTaskListByCompany as ot,PayDispatchTaskListByAsset as at,PayDispatchTaskGet as ct,PayDispatchTaskMerge as ht,PayDispatchTaskBatchMerge as ut,PayDispatchTaskDelete as dt,PayDispatchTaskRestore as pt,PayDispatchJobListByCompany as lt,PayDispatchJobListByAsset as mt,PayDispatchJobGet as wt,PayDispatchJobMerge as gt,PayDispatchJobBatchMerge as yt,PayDispatchJobDelete as vt,PayDispatchJobRestore as ft,PayDispatchJobChange as bt,PayDispatchJobCancel as Ct,PayAssetMessageListByCompany as Pt,PayAssetMessageListByAsset as St,PayAssetMessageGet as Rt,PayAssetMessageMerge as kt,PayAssetMessageBatchMerge as At,PayAssetMessageDelete as Mt,PayAssetMessageRestore as Dt,PayPlaceListByCompany as It,PayPlaceGet as Tt,PayPlaceMerge as Gt,PayPlaceDelete as Ut,PayPlaceRestore as Bt,PayProviderListByCompany as Jt,PayProviderGet as Et,PayProviderMerge as Lt,PayProviderBatchMerge as xt,PayProviderBatchDelete as Nt,PayProviderDelete as Ot,PayProviderRestore as _t,PayProviderGeneralListByCompany as Ft,PayProviderGeneralGet as Ht,PayProviderAdvancedListByCompany as qt,PayProviderAdvancedGet as $t,PayProviderControlListByCompany as Wt,PayProviderControlGet as jt,PayProviderScriptListByCompany as zt,PayProviderScriptGet as Kt,PayProviderScriptMerge as Zt,PayProviderScriptDelete as Qt,PayProviderScriptRestore as Vt,PayProviderConfigListByCompany as Xt,PayProviderConfigGet as Yt,PayProviderConfigMerge as es,PayProviderConfigBatchMerge as ts,PayProviderConfigDelete as ss,PayProviderConfigRestore as rs,PayProviderConfigurationListByCompany as ns,PayProviderConfigurationGet as is,PayProviderConfigurationMerge as os,PayProviderConfigurationBatchMerge as as,PayProviderConfigurationDelete as cs,PayProviderConfigurationRestore as hs,PayProviderRegistrationListByCompany as us,PayProviderRegistrationGet as ds,PayProviderRegistrationMerge as ps,PayProviderRegistrationDelete as ls,PayBehaviourListByCompany as ms,PayBehaviourGet as ws,PayBehaviourMerge as gs,PayBehaviourBatchMerge as ys,PayBehaviourDelete as vs,PayBehaviourRestore as fs,PayBehaviourScriptListByCompany as bs,PayBehaviourScriptGet as Cs,PayBehaviourScriptMerge as Ps,PayBehaviourScriptDelete as Ss,PayBehaviourScriptRestore as Rs,PayBehaviourLogListByAsset as ks,PayBehaviourLogBatchDeleteByAsset as As,PayBehaviourLogListByBehaviour as Ms,PayBehaviourLogBatchDeleteByBehaviour as Ds,PayBehaviourLogListByScript as Is,PayBehaviourLogBatchDeleteByScript as Ts,PayReportTemplateListByCompany as Gs,PayReportTemplateGet as Us,PayReportTemplateMerge as Bs,PayReportTemplateDelete as Js,PayReportTemplateRestore as Es,PayReportScheduleListByCompany as Ls,PayReportScheduleGet as xs,PayReportScheduleMerge as Ns,PayReportScheduleDelete as Os,PayReportScheduleRestore as _s,PayReportResultListByCompany as Fs,PayReportResultGet as Hs,PayReportResultMerge as qs,PayReportResultDelete as $s,PayReportResultRestore as Ws,PayMaintenanceScheduleListByCompany as js,PayMaintenanceScheduleGet as zs,PayMaintenanceScheduleMerge as Ks,PayMaintenanceScheduleDelete as Zs,PayMaintenanceScheduleRestore as Qs,PayMaintenanceJobListByCompany as Vs,PayMaintenanceJobGet as Xs,PayMaintenanceJobMerge as Ys,PayMaintenanceJobDelete as er,PayMaintenanceJobRestore as tr,SubscriptionType as sr,Reply as rr,PaySubscriptionMerge as nr,RepSubscription as ir,PaySubscriptionDelete as or,PaySubscriptionList as ar}from"@trakit/commands";import{utility as cr,Machine as hr,serialization as ur}from"@trakit/objects";class dr{type;constructor(e){this.type=e}}class pr extends dr{kind;companyId;constructor(e,t,s){super(e),this.kind=t,this.companyId=s}}class lr extends dr{account;constructor(e,t){super(e),this.account=t}}class mr extends pr{objects;constructor(e,t,s,r){super(e,t,s),this.objects=r}}class wr extends pr{object;constructor(e,t,s,r){super(e,t,s),this.object=r}}class gr extends pr{key;constructor(e,t,s,r){super(e,t,s),this.key=r}}const yr={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:""},vr={AssetMessage:"/assets/{assetId}/messages",DispatchTask:"/assets/{assetId}/dispatch/tasks",DispatchJob:"/assets/{assetId}/dispatch/jobs",FormResult:"/assets/{assetId}/forms",MaintenanceJob:"/assets/{assetId}/maintenance/jobs"},fr={BillingHosting:"/billing/profiles/{profileId}/rules",BillingLicense:"/billing/profiles/{profileId}/licenses",BillingReport:"/billing/profiles/{profileId}/reports"},br=/[A-Z][a-z]+/;class Cr{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 hr||e?.key?this.setAuth({machine:e.toJSON?.()??e}):e?.machine?.key||e?.ghostId?this.setAuth(new p({...e.toJSON?.()??e,errorCode:d.success,message:"Authenticated via "+(e?.machine?.key?"Machine":"Session")})):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 Pr extends Cr{o=new Map;h(e){this.setAuth(e??new p(this.account.toJSON())),this.fire("account",(()=>new lr("account",this.account)))}u(e,t,s){this.fire("list",(()=>new mr("list",e,t,s)))}p(e,t,s){this.fire("update",(()=>new wr("update",e,t,s)))}l(e,t,s){this.fire("delete",(()=>new gr("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?ur.fromMap(r):r??null,measurements:n instanceof Map?ur.fromMap(n):n??null}))}updateState(e){return this.command(new R({options:e instanceof Map?ur.fromMap(e):e??null}))}recoverStart(e,t,s){return this.command(new k({username:e,key:t??null,query:s??null}))}recoverComplete(e,t){return this.command(new A({guid:e,length:t??null}))}getCompany(e){return this.command(new M({company:{id:e}}))}mergeCompany(e){return this.command(new D({company:e}))}removeCompany(e){return this.command(new I({company:{id:e}}))}restoreCompany(e){return this.command(new T({company:{id:e}}))}listCompanyGenerals(e,t){return this.command(new G({...t,company:{id:e}}))}getCompanyGeneral(e){return this.command(new U({company:{id:e}}))}listCompanyPolicies(e,t){return this.command(new B({...t,company:{id:e}}))}getCompanyPolicy(e){return this.command(new J({company:{id:e}}))}listCompanyStyles(e,t){return this.command(new E({...t,company:{id:e}}))}getCompanyStyle(e){return this.command(new L({company:{id:e}}))}listCompanyDirectories(e,t){return this.command(new x({...t,company:{id:e}}))}getCompanyDirectory(e){return this.command(new N({company:{id:e}}))}getReseller(e){return this.command(new O({company:{id:e}}))}mergeReseller(e){return this.command(new _({company:e}))}removeReseller(e){return this.command(new F({company:{id:e}}))}restoreReseller(e){return this.command(new H({company:{id:e}}))}listContacts(e,t){return this.command(new q({...t,company:{id:e}}))}getContact(e){return this.command(new $({contact:{id:e}}))}mergeContact(e){return this.command(new W({contact:e}))}removeContact(e){return this.command(new j({contact:{id:e}}))}restoreContact(e){return this.command(new z({contact:{id:e}}))}multiMergeContact(e){return this.command(new K({contacts:e}))}multiRemoveContact(e){return this.command(new Z({contacts:e.map((e=>({id:e})))}))}listUsers(e,t){return this.command(new Q({...t,company:{id:e}}))}getUser(e){return this.command(new V({user:{login:e}}))}mergeUser(e){return this.command(new X({user:e}))}removeUser(e){return this.command(new Y({user:{login:e}}))}restoreUser(e){return this.command(new ee({user:{login:e}}))}listUserGenerals(e,t){return this.command(new te({...t,company:{id:e}}))}getUserGeneral(e){return this.command(new se({user:{login:e}}))}listUserAdvanceds(e,t){return this.command(new re({...t,company:{id:e}}))}getUserAdvanced(e){return this.command(new ne({user:{login:e}}))}listUserGroups(e,t){return this.command(new ie({...t,company:{id:e}}))}getUserGroup(e){return this.command(new oe({userGroup:{id:e}}))}mergeUserGroup(e){return this.command(new ae({userGroup:e}))}removeUserGroup(e){return this.command(new ce({userGroup:{id:e}}))}restoreUserGroup(e){return this.command(new he({userGroup:{id:e}}))}listMachines(e,t){return this.command(new ue({...t,company:{id:e}}))}getMachine(e){return this.command(new de({machine:{id:e}}))}mergeMachine(e){return this.command(new pe({machine:e}))}removeMachine(e){return this.command(new le({machine:{id:e}}))}restoreMachine(e){return this.command(new me({machine:{id:e}}))}listSessions(e,t){return this.command(new we({...t,company:{id:e}}))}listSessionsByUser(e,t){return this.command(new ge({...t,user:{login:e}}))}killSession(e){return this.command(new ye({session:{handle:e}}))}listIcons(e,t){return this.command(new ve({...t,company:{id:e}}))}getIcon(e){return this.command(new fe({icon:{id:e}}))}mergeIcon(e){return this.command(new be({icon:e}))}removeIcon(e){return this.command(new Ce({icon:{id:e}}))}restoreIcon(e){return this.command(new Pe({icon:{id:e}}))}listPictures(e,t){return this.command(new Se({...t,company:{id:e}}))}getPicture(e){return this.command(new Re({picture:{id:e}}))}mergePicture(e){return this.command(new ke({picture:e}))}removePicture(e){return this.command(new Ae({picture:{id:e}}))}restorePicture(e){return this.command(new Me({picture:{id:e}}))}listDocuments(e,t){return this.command(new De({...t,company:{id:e}}))}getDocument(e){return this.command(new Ie({document:{id:e}}))}mergeDocument(e){return this.command(new Te({document:e}))}removeDocument(e){return this.command(new Ge({document:{id:e}}))}restoreDocument(e){return this.command(new Ue({document:{id:e}}))}listFormTemplates(e,t){return this.command(new Be({...t,company:{id:e}}))}getFormTemplate(e){return this.command(new Je({formTemplate:{id:e}}))}mergeFormTemplate(e){return this.command(new Ee({formTemplate:e}))}removeFormTemplate(e){return this.command(new Le({formTemplate:{id:e}}))}restoreFormTemplate(e){return this.command(new xe({formTemplate:{id:e}}))}listFormResults(e,t){return this.command(new Ne({...t,company:{id:e}}))}getFormResult(e){return this.command(new Oe({formResult:{id:e}}))}mergeFormResult(e){return this.command(new _e({formResult:e}))}multiMergeFormResult(e){return this.command(new Fe({formResult:{id:e}}))}removeFormResult(e){return this.command(new He({formResult:{id:e}}))}restoreFormResult(e){return this.command(new qe({formResult:{id:e}}))}listDashcamDatas(e,t){return this.command(new $e({...t,company:{id:e}}))}getDashcamData(e){return this.command(new We({dashcam:{guid:e}}))}listDashcamLives(e,t){return this.command(new je({...t,company:{id:e}}))}listAssets(e,t){return this.command(new ze({...t,company:{id:e}}))}getAsset(e){return this.command(new Ke({asset:{id:e}}))}mergeAsset(e){return this.command(new Ze({asset:e}))}multiMergeAsset(e){return this.command(new Qe({assets:e}))}removeAsset(e){return this.command(new Ve({asset:{id:e}}))}restoreAsset(e){return this.command(new Xe({asset:{id:e}}))}suspendAsset(e){return this.command(new Ye({asset:{id:e}}))}reviveAsset(e){return this.command(new et({asset:{id:e}}))}searchAssets(e,t){}listAssetGenerals(e,t){return this.command(new tt({...t,company:{id:e}}))}getAssetGeneral(e){return this.command(new st({asset:{id:e}}))}searchAssetGenerals(e,t){}listAssetAdvanceds(e,t){return this.command(new rt({...t,company:{id:e}}))}getAssetAdvanced(e){return this.command(new nt({asset:{id:e}}))}searchAssetAdvanceds(e,t){}mergeAssetDispatch(e){return this.command(new it({assetDispatch:e}))}listDispatchTasks(e,t){return this.command(new ot({...t,company:{id:e}}))}getDispatchTasksByAsset(e,t){return this.command(new at({...t,asset:{id:e}}))}getDispatchTask(e){return this.command(new ct({dispatchTask:{id:e}}))}mergeDispatchTask(e){return this.command(new ht({dispatchTask:e}))}multiMergeDispatchTask(e){return this.command(new ut({dispatchTask:{id:e}}))}removeDispatchTask(e){return this.command(new dt({dispatchTask:{id:e}}))}restoreDispatchTask(e){return this.command(new pt({dispatchTask:{id:e}}))}listDispatchJobs(e,t){return this.command(new lt({...t,company:{id:e}}))}getDispatchJobsByAsset(e,t){return this.command(new mt({...t,asset:{id:e}}))}getDispatchJob(e){return this.command(new wt({dispatchJob:{id:e}}))}mergeDispatchJob(e){return this.command(new gt({dispatchJob:e}))}multiMergeDispatchJob(e){return this.command(new yt({dispatchJob:{id:e}}))}removeDispatchJob(e){return this.command(new vt({dispatchJob:{id:e}}))}restoreDispatchJob(e){return this.command(new ft({dispatchJob:{id:e}}))}changeDispatchJob(e){return this.command(new bt({dispatchJob:e}))}cancelDispatchJob(e){return this.command(new Ct({dispatchJob:e}))}listAssetMessages(e,t){return this.command(new Pt({...t,company:{id:e}}))}getAssetMessagesByAsset(e,t){return this.command(new St({...t,asset:{id:e}}))}getAssetMessage(e){return this.command(new Rt({message:{id:e}}))}mergeAssetMessage(e){return this.command(new kt({assetMessage:e}))}multiMergeAssetMessage(e){return this.command(new At({assetMessage:{id:e}}))}removeAssetMessage(e){return this.command(new Mt({assetMessage:{id:e}}))}restoreAssetMessage(e){return this.command(new Dt({assetMessage:{id:e}}))}listPlaces(e,t){return this.command(new It({...t,company:{id:e}}))}getPlace(e){return this.command(new Tt({place:{id:e}}))}mergePlace(e){return this.command(new Gt({place:e}))}removePlace(e){return this.command(new Ut({place:{id:e}}))}restorePlace(e){return this.command(new Bt({place:{id:e}}))}listProviders(e,t){return this.command(new Jt({...t,company:{id:e}}))}getProvider(e){return this.command(new Et({provider:{id:e}}))}mergeProvider(e){return this.command(new Lt({provider:e}))}multiMergeProvider(e){return this.command(new xt({providers:e}))}multiRemoveProvider(e){return this.command(new Nt({providers:e.map((e=>({id:e})))}))}removeProvider(e){return this.command(new Ot({provider:{id:e}}))}restoreProvider(e){return this.command(new _t({provider:{id:e}}))}searchProviders(e,t){}listProviderGenerals(e,t){return this.command(new Ft({...t,company:{id:e}}))}getProviderGeneral(e){return this.command(new Ht({provider:{id:e}}))}searchProviderGenerals(e,t){}listProviderAdvanceds(e,t){return this.command(new qt({...t,company:{id:e}}))}getProviderAdvanced(e){return this.command(new $t({provider:{id:e}}))}searchProviderAdvanceds(e,t){}listProviderControls(e,t){return this.command(new Wt({...t,company:{id:e}}))}getProviderControl(e){return this.command(new jt({provider:{id:e}}))}searchProviderControls(e,t){}listProviderScripts(e,t){return this.command(new zt({...t,company:{id:e}}))}getProviderScript(e){return this.command(new Kt({providerScript:{id:e}}))}mergeProviderScript(e){return this.command(new Zt({providerScript:e}))}removeProviderScript(e){return this.command(new Qt({providerScript:{id:e}}))}restoreProviderScript(e){return this.command(new Vt({providerScript:{id:e}}))}listProviderConfigs(e,t){return this.command(new Xt({...t,company:{id:e}}))}getProviderConfig(e){return this.command(new Yt({providerConfig:{id:e}}))}mergeProviderConfig(e){return this.command(new es({providerConfig:e}))}multiMergeProviderConfig(e){return this.command(new ts({providerConfig:{id:e}}))}removeProviderConfig(e){return this.command(new ss({providerConfig:{id:e}}))}restoreProviderConfig(e){return this.command(new rs({providerConfig:{id:e}}))}listProviderConfigurations(e,t){return this.command(new ns({...t,company:{id:e}}))}getProviderConfiguration(e){return this.command(new is({providerConfiguration:{id:e}}))}mergeProviderConfiguration(e){return this.command(new os({providerConfiguration:e}))}multiMergeProviderConfiguration(e){return this.command(new as({providerConfiguration:{id:e}}))}removeProviderConfiguration(e){return this.command(new cs({providerConfiguration:{id:e}}))}restoreProviderConfiguration(e){return this.command(new hs({providerConfiguration:{id:e}}))}listProviderRegistration(e,t){return this.command(new us({...t,company:{id:e}}))}getProviderRegistration(e){return this.command(new ds({providerRegistration:{id:e}}))}mergeProviderRegistration(e){return this.command(new ps({providerRegistration:e}))}removeProviderRegistration(e){return this.command(new ls({providerRegistration:{id:e}}))}listBehaviours(e,t){return this.command(new ms({...t,company:{id:e}}))}getBehaviour(e){return this.command(new ws({behaviour:{id:e}}))}mergeBehaviour(e){return this.command(new gs({behaviour:e}))}multiMergeBehaviour(e){return this.command(new ys({behaviour:{id:e}}))}removeBehaviour(e){return this.command(new vs({behaviour:{id:e}}))}restoreBehaviour(e){return this.command(new fs({behaviour:{id:e}}))}listBehaviourScripts(e,t){return this.command(new bs({...t,company:{id:e}}))}getBehaviourScript(e){return this.command(new Cs({behaviourScript:{id:e}}))}mergeBehaviourScript(e){return this.command(new Ps({behaviourScript:e}))}removeBehaviourScript(e){return this.command(new Ss({behaviourScript:{id:e}}))}restoreBehaviourScript(e){return this.command(new Rs({behaviourScript:{id:e}}))}listBehaviourAssetLogs(e,t){return this.command(new ks({...t,behaviour:{id:e}}))}clearBehaviourAssetLogs(e){return this.command(new As({behaviour:{id:e}}))}listBehaviourLogs(e,t){return this.command(new Ms({...t,behaviour:{id:e}}))}clearBehaviourLogs(e){return this.command(new Ds({behaviour:{id:e}}))}listBehaviourScriptLogs(e,t){return this.command(new Is({...t,behaviourScript:{id:e}}))}clearBehaviourScriptLogs(e,t){return this.command(new Ts({...t,behaviourScript:{id:e}}))}listReportTemplates(e,t){return this.command(new Gs({...t,company:{id:e}}))}getReportTemplate(e){return this.command(new Us({reportTemplate:{id:e}}))}mergeReportTemplate(e){return this.command(new Bs({reportTemplate:e}))}removeReportTemplate(e){return this.command(new Js({reportTemplate:{id:e}}))}restoreReportTemplate(e){return this.command(new Es({reportTemplate:{id:e}}))}listReportSchedules(e,t){return this.command(new Ls({...t,company:{id:e}}))}getReportSchedule(e){return this.command(new xs({reportSchedule:{id:e}}))}mergeReportSchedule(e){return this.command(new Ns({reportSchedule:e}))}removeReportSchedule(e){return this.command(new Os({reportSchedule:{id:e}}))}restoreReportSchedule(e){return this.command(new _s({reportSchedule:{id:e}}))}listReportResults(e,t){return this.command(new Fs({...t,company:{id:e}}))}getReportResult(e){return this.command(new Hs({reportResult:{id:e}}))}mergeReportResult(e){return this.command(new qs({reportResult:e}))}removeReportResult(e){return this.command(new $s({reportResult:{id:e}}))}restoreReportResult(e){return this.command(new Ws({reportResult:{id:e}}))}listMaintenanceSchedules(e,t){return this.command(new js({...t,company:{id:e}}))}getMaintenanceSchedule(e){return this.command(new zs({maintenanceSchedule:{id:e}}))}mergeMaintenanceSchedule(e){return this.command(new Ks({maintenanceSchedule:e}))}removeMaintenanceSchedule(e){return this.command(new Zs({maintenanceSchedule:{id:e}}))}restoreMaintenanceSchedule(e){return this.command(new Qs({maintenanceSchedule:{id:e}}))}listMaintenanceJobs(e,t){return this.command(new Vs({...t,company:{id:e}}))}getMaintenanceJob(e){return this.command(new Xs({maintenanceJob:{id:e}}))}mergeMaintenanceJob(e){return this.command(new Ys({maintenanceJob:e}))}removeMaintenanceJob(e){return this.command(new er({maintenanceJob:{id:e}}))}restoreMaintenanceJob(e){return this.command(new tr({maintenanceJob:{id:e}}))}}class Sr extends Pr{static URI_PROD="https://rest.trakit.ca/";static URI_BETA="https://mindflayer.trakit.ca/";constructor(e,t){super(e,t??Sr.URI_PROD)}requestCreate(e){return r(this,e)}requestRelay(e){return i(e)}}const Rr=/^(.+?)(Merged|Deleted|Suspended)$/,kr={Company:[sr.companyGeneral,sr.companyLabels,sr.companyPolicies],CompanyGeneral:[sr.companyGeneral],CompanyDirectory:[],CompanyStyle:[sr.companyLabels],CompanyPolicy:[sr.companyPolicies],CompanyReseller:[sr.companyReseller],Contact:[sr.contact],Machine:[sr.machine],User:[sr.userGeneral,sr.userAdvanced,sr.userAuthentication],UserGeneral:[sr.userGeneral],UserAdvanced:[sr.userAdvanced],UserAuthentication:[sr.userAuthentication],UserState:[sr.userState],UserGroup:[sr.userGroup],Session:[],Dashcam:[],Icon:[sr.icon],Picture:[sr.picture],Document:[sr.document],FormTemplate:[sr.formTemplate],FormResult:[sr.formResult],Asset:[sr.assetGeneral,sr.assetAdvanced,sr.assetDispatch],AssetGeneral:[sr.assetGeneral],AssetAdvanced:[sr.assetAdvanced],AssetDispatch:[sr.assetDispatch],AssetMessage:[sr.assetMessage],AssetAlert:[],DispatchTask:[sr.dispatchTask],DispatchJob:[sr.dispatchJob],MaintenanceSchedule:[sr.maintenanceSchedule],MaintenanceJob:[sr.maintenanceJob],Place:[sr.placeGeneral],BehaviourScript:[sr.behaviourScript],Behaviour:[sr.behaviour],BehaviourLog:[sr.behaviourLog],Provider:[sr.providerGeneral,sr.providerAdvanced,sr.providerControl],ProviderGeneral:[sr.providerGeneral],ProviderAdvanced:[sr.providerAdvanced],ProviderControl:[sr.providerControl],ProviderConfiguration:[sr.providerConfiguration],ProviderConfigurationType:[],ProviderScript:[sr.providerScript],ProviderConfig:[sr.providerConfig],ProviderRegistration:[sr.providerRegistration],ReportTemplate:[sr.reportTemplate],ReportSchedule:[sr.reportSchedule],ReportResult:[sr.reportResult],BillingProfile:[sr.billingProfile],BillingReport:[sr.billingReport],BillableHostingRule:[sr.billingHosting],BillableHostingLicense:[sr.billingLicense]};class Ar{#e=new Map;get regions(){return[...this.#e.keys()]}getExpired(){const e=new Date,t=[];for(const[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(const[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(const[t,s]of this.#e)s||e.push(t);return this.#e.clear(),e}}var Mr;!function(e){e.maintenance="maintenance",e.upgrade="upgrade"}(Mr||(Mr={}));class Dr{static fromJson(e){switch(e?.kind){case Mr.maintenance:return new Ir(e);case Mr.upgrade:return new Tr(e);default:throw new Error(`Unknown broadcast type: ${e?.kind}`)}}kind;serverTime;message;constructor(e){this.kind=e?.kind,this.serverTime=cr.date(e?.serverTime),this.message=e?.message??""}}class Ir extends Dr{starting;ending;constructor(e){super(e),this.starting=cr.date(e?.starting),this.ending=cr.date(e?.ending)}}class Tr extends Dr{eta;reload;constructor(e){super(e),this.eta=cr.date(e?.eta),this.reload=!!e?.reload}}class Gr extends dr{name;body;constructor(e,t,s){super(e),this.name=t,this.body=s}}class Ur extends dr{online;reply;constructor(e,t,s){super(e),this.online=t,this.reply=s}}class Br extends dr{broadcast;constructor(e,t){super(e),this.broadcast=Dr.fromJson(t)}}const Jr="connection",Er="dis"+Jr;var Lr;!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"}(Lr||(Lr={}));class xr extends Pr{static URI_PROD="wss://socket.trakit.ca/";static URI_BETA="wss://kraken.trakit.ca/";static msgNameToSyncName(e){const s=Rr.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 Lr.opening;case WebSocket.OPEN:return this.#a?Lr.open:Lr.opening;case WebSocket.CLOSING:return Lr.closing;default:return Lr.closed}}get ready(){return this.#a&&this.#c}m(e){const t=this.o.get("open");if(t?.length){const s=new Ur("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 Ur("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 Gr("message",e,t);s.forEach((e=>e.call(this,r)))}}P(e){const t=this.o.get("error");if(t?.length){const s=new Ur("error",!1,e);t.forEach((e=>e.call(this,s)))}}S(e){const t=this.o.get("broadcast");if(t?.length){const s=new Br("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 rr({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:Lr.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===Er?r:{...r,reqId:e,errorCode:d.service,errorDetails:{...s}});this.v?.(new rr(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(Jr,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({policy: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=Rr.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,policy:e?.policies??t.policies})),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??xr.URI_PROD)}dispose(){super.dispose(),this.close().finally((()=>{this.#o=this.#h=null}))}open(){return o(this.i,Jr,(e=>(clearTimeout(this.#y),new Promise((async(t,s)=>{if(this.state===Lr.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(Jr,(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:this.state}}))})))))}close(){return o(this.i,Er,(e=>(clearTimeout(this.#y),new Promise(((t,s)=>{switch(this.state){case Lr.opening:case Lr.open:this.#c=!1,this.reconnectEnabled=!1,this.#h.set(Er,(r=>{(0===r.errorCode?t:s)(new rr(r)),this.i.delete(e)})),this.#o.close(1e3,"Bye!");break;default:s(new rr({errorCode:d.unknown,message:"WebSocket not open",errorDetails:{kind:"connection",connection:this.state}}))}})))))}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===Lr.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 nr({company:{id:e},subscriptionTypes:t})):Promise.resolve(new ir({errorCode:d.success,message:"No subscriptions specified"}))}unsubscribe(e,t){return t?.length?this.command(new or({company:{id:e},subscriptionTypes:t})):Promise.resolve(new ir({errorCode:d.success,message:"No subscriptions specified"}))}listSubscriptions(){return this.command(new ar)}}const Nr={Company:["CompanyGeneral","CompanyDirectory","CompanyStyle","CompanyPolicy"],Asset:["AssetGeneral","AssetAdvanced","AssetDispatch"],Provider:["ProviderGeneral","ProviderAdvanced","ProviderControl"],User:["UserGeneral","UserAdvanced"]};class Or extends Pr{R;k;get socketOnline(){return this.R.state===Lr.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 Sr(this.account,t??Sr.URI_PROD),this.k.on("account",r),this.R=new xr(this.account,s??xr.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.account.ghostId||this.account.machine?.key)&&this.R.open()}dispose(){super.dispose(),this.k.dispose(),this.R.dispose(),this.k=this.R=null}setAuth(e){if(super.setAuth(e),this.k?.setAuth(this.account),this.R)switch(this.R.setAuth(this.account),this.R.state){case Lr.open:this.account.ghostId||this.account.machine?.key||this.R.close().catch((()=>this.setAuth()));break;case Lr.closed:(this.account.ghostId||this.account.machine?.key)&&this.R.open().catch((()=>this.setAuth()))}}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)}isSynced(e,t){let s=this.R.state===Lr.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.getExpiring().forEach((e=>i.includes(e)&&n.preserveRegion(e)));const s=await this.R.subscribe(t,i);n.preserveRegions(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(kr[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===Lr.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 Ar),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){switch(e=hr.capitalize(e)){case"CompanyLabels":e="CompanyStyle";break;case"PlaceGeneral":e="Place";break;default:e=hr.singularize(e)}return e}function s(e){const t=e.getAction();let s="GET",r=new URLSearchParams,n=[...t.object.match(Cr)].map((e=>hr.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=hr.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 fr?fr[t.object].replace("{assetId}",e.asset.id):`assets/${e.asset.id}/${n}`;break;case"BillingProfile":n=t.object in br?br[t.object].replace("{profileId}",e.billingProfile.id):`billing/profiles/${e.billingProfile.id}/${n}`;break;case"Company":n=t.object in vr?vr[t.object].replace("{companyId}",e.company.id):`companies/${e.company.id}/${n}`;break;case"User":n=`users/${encodeURIComponent(e.user.login)}/${n}`}if(hr.isntNaN(e?.limit)&&r.set("limit",e.limit),hr.isntNaN(e?.after?.valueOf())&&r.set("after",e.after.toISOString()),hr.isntNaN(e?.before?.valueOf())&&r.set("before",e.before.toISOString()),hr.isntNaN(e?.lowest)&&r.set("lowest",e.lowest),hr.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"+hr.pluralize(t.object)+"List"+("Company"!=(t.filter||"Company")?"By"+t.filter:"");default:throw s}}function c(e){return e.reduce(((e,t)=>e.concat(Dr[t]||[])),[]).filter(((e,t,s)=>s.indexOf(e)===t))}function h(e){const t=[];for(const[s,r]of Object.entries(Nr)){const n=r.map((e=>Dr[e])).flat();n.filter((t=>e.includes(t))).length/n.length>=.5&&t.push(s)}const s=t.reduce(((e,t)=>e.concat([t],Nr[t])),[]);for(const[r,n]of Object.entries(Dr))!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,PaySelfRecoverStart as k,PaySelfRecoverComplete as A,PayCompanyGet as D,PayCompanyMerge as M,PayCompanyDelete as I,PayCompanyRestore as T,PayCompanyGeneralListByCompany as G,PayCompanyGeneralGet as U,PayCompanyPolicyListByCompany as B,PayCompanyPolicyGet as J,PayCompanyStyleListByCompany as E,PayCompanyStyleGet as L,PayCompanyDirectoryListByCompany as x,PayCompanyDirectoryGet as _,PayCompanyResellerGet as O,PayCompanyResellerMerge as N,PayCompanyResellerDelete as F,PayCompanyResellerRestore as q,PayContactListByCompany as H,PayContactGet as $,PayContactMerge as W,PayContactDelete as j,PayContactRestore as z,PayContactBatchMerge as K,PayContactBatchDelete as Z,PayUserListByCompany as Q,PayUserGet as V,PayUserMerge as X,PayUserDelete as Y,PayUserRestore as ee,PayUserGeneralListByCompany as te,PayUserGeneralGet as se,PayUserAdvancedListByCompany as re,PayUserAdvancedGet as ne,PayUserGroupListByCompany as ie,PayUserGroupGet as oe,PayUserGroupMerge as ae,PayUserGroupDelete as ce,PayUserGroupRestore as he,PayMachineListByCompany as ue,PayMachineGet as de,PayMachineMerge as pe,PayMachineDelete as le,PayMachineRestore as me,PaySessionListByCompany as we,PaySessionListByUser as ge,PaySessionDelete as ye,PayIconListByCompany as ve,PayIconGet as fe,PayIconMerge as be,PayIconDelete as Ce,PayIconRestore as Pe,PayPictureListByCompany as Se,PayPictureGet as Re,PayPictureMerge as ke,PayPictureDelete as Ae,PayPictureRestore as De,PayDocumentListByCompany as Me,PayDocumentGet as Ie,PayDocumentMerge as Te,PayDocumentDelete as Ge,PayDocumentRestore as Ue,PayFormTemplateListByCompany as Be,PayFormTemplateGet as Je,PayFormTemplateMerge as Ee,PayFormTemplateDelete as Le,PayFormTemplateRestore as xe,PayFormResultListByCompany as _e,PayFormResultGet as Oe,PayFormResultMerge as Ne,PayFormResultBatchMerge as Fe,PayFormResultDelete as qe,PayFormResultRestore as He,PayDashcamListByCompany as $e,PayDashcamGet as We,PayDashcamLiveListByCompany as je,PayAssetListByCompany as ze,PayAssetGet as Ke,PayAssetMerge as Ze,PayAssetBatchMerge as Qe,PayAssetDelete as Ve,PayAssetRestore as Xe,PayAssetSuspend as Ye,PayAssetReactivate as et,PayAssetGeneralListByCompany as tt,PayAssetGeneralGet as st,PayAssetAdvancedListByCompany as rt,PayAssetAdvancedGet as nt,PayAssetDispatchMerge as it,PayDispatchTaskListByCompany as ot,PayDispatchTaskListByAsset as at,PayDispatchTaskGet as ct,PayDispatchTaskMerge as ht,PayDispatchTaskBatchMerge as ut,PayDispatchTaskDelete as dt,PayDispatchTaskRestore as pt,PayDispatchJobListByCompany as lt,PayDispatchJobListByAsset as mt,PayDispatchJobGet as wt,PayDispatchJobMerge as gt,PayDispatchJobBatchMerge as yt,PayDispatchJobDelete as vt,PayDispatchJobRestore as ft,PayDispatchJobChange as bt,PayDispatchJobCancel as Ct,PayAssetMessageListByCompany as Pt,PayAssetMessageListByAsset as St,PayAssetMessageGet as Rt,PayAssetMessageMerge as kt,PayAssetMessageBatchMerge as At,PayAssetMessageDelete as Dt,PayAssetMessageRestore as Mt,PayPlaceListByCompany as It,PayPlaceGet as Tt,PayPlaceMerge as Gt,PayPlaceDelete as Ut,PayPlaceRestore as Bt,PayProviderListByCompany as Jt,PayProviderGet as Et,PayProviderMerge as Lt,PayProviderBatchMerge as xt,PayProviderBatchDelete as _t,PayProviderDelete as Ot,PayProviderRestore as Nt,PayProviderGeneralListByCompany as Ft,PayProviderGeneralGet as qt,PayProviderAdvancedListByCompany as Ht,PayProviderAdvancedGet as $t,PayProviderControlListByCompany as Wt,PayProviderControlGet as jt,PayProviderScriptListByCompany as zt,PayProviderScriptGet as Kt,PayProviderScriptMerge as Zt,PayProviderScriptDelete as Qt,PayProviderScriptRestore as Vt,PayProviderConfigListByCompany as Xt,PayProviderConfigGet as Yt,PayProviderConfigMerge as es,PayProviderConfigBatchMerge as ts,PayProviderConfigDelete as ss,PayProviderConfigRestore as rs,PayProviderConfigurationListByCompany as ns,PayProviderConfigurationGet as is,PayProviderConfigurationMerge as os,PayProviderConfigurationBatchMerge as as,PayProviderConfigurationDelete as cs,PayProviderConfigurationRestore as hs,PayProviderRegistrationListByCompany as us,PayProviderRegistrationGet as ds,PayProviderRegistrationMerge as ps,PayProviderRegistrationDelete as ls,PayBehaviourListByCompany as ms,PayBehaviourGet as ws,PayBehaviourMerge as gs,PayBehaviourBatchMerge as ys,PayBehaviourDelete as vs,PayBehaviourRestore as fs,PayBehaviourScriptListByCompany as bs,PayBehaviourScriptGet as Cs,PayBehaviourScriptMerge as Ps,PayBehaviourScriptDelete as Ss,PayBehaviourScriptRestore as Rs,PayBehaviourLogListByAsset as ks,PayBehaviourLogBatchDeleteByAsset as As,PayBehaviourLogListByBehaviour as Ds,PayBehaviourLogBatchDeleteByBehaviour as Ms,PayBehaviourLogListByScript as Is,PayBehaviourLogBatchDeleteByScript as Ts,PayReportTemplateListByCompany as Gs,PayReportTemplateGet as Us,PayReportTemplateMerge as Bs,PayReportTemplateDelete as Js,PayReportTemplateRestore as Es,PayReportScheduleListByCompany as Ls,PayReportScheduleGet as xs,PayReportScheduleMerge as _s,PayReportScheduleDelete as Os,PayReportScheduleRestore as Ns,PayReportResultListByCompany as Fs,PayReportResultGet as qs,PayReportResultMerge as Hs,PayReportResultDelete as $s,PayReportResultRestore as Ws,PayMaintenanceScheduleListByCompany as js,PayMaintenanceScheduleGet as zs,PayMaintenanceScheduleMerge as Ks,PayMaintenanceScheduleDelete as Zs,PayMaintenanceScheduleRestore as Qs,PayMaintenanceJobListByCompany as Vs,PayMaintenanceJobGet as Xs,PayMaintenanceJobMerge as Ys,PayMaintenanceJobDelete as er,PayMaintenanceJobRestore as tr,PayAssetAdvancedAudit as sr,SubscriptionType as rr,Reply as nr,PaySubscriptionMerge as ir,RepSubscription as or,PaySubscriptionDelete as ar,PaySubscriptionList as cr}from"@trakit/commands";import{utility as hr,Machine as ur,serialization as dr}from"@trakit/objects";class pr{type;constructor(e){this.type=e}}class lr extends pr{kind;companyId;constructor(e,t,s){super(e),this.kind=t,this.companyId=s}}class mr extends pr{account;constructor(e,t){super(e),this.account=t}}class wr extends lr{objects;constructor(e,t,s,r){super(e,t,s),this.objects=r}}class gr extends lr{object;constructor(e,t,s,r){super(e,t,s),this.object=r}}class yr extends lr{key;constructor(e,t,s,r){super(e,t,s),this.key=r}}const vr={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:""},fr={AssetMessage:"/assets/{assetId}/messages",DispatchTask:"/assets/{assetId}/dispatch/tasks",DispatchJob:"/assets/{assetId}/dispatch/jobs",FormResult:"/assets/{assetId}/forms",MaintenanceJob:"/assets/{assetId}/maintenance/jobs"},br={BillingHosting:"/billing/profiles/{profileId}/rules",BillingLicense:"/billing/profiles/{profileId}/licenses",BillingReport:"/billing/profiles/{profileId}/reports"},Cr=/[A-Z][a-z]+/;class Pr{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 ur||e?.key?this.setAuth({machine:e.toJSON?.()??e}):e?.machine?.key||e?.ghostId?this.setAuth(new p({...e.toJSON?.()??e,errorCode:d.success,message:"Authenticated via "+(e?.machine?.key?"Machine":"Session")})):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 Sr extends Pr{o=new Map;h(e){this.setAuth(e??new p(this.account.toJSON())),this.fire("account",(()=>new mr("account",this.account)))}u(e,t,s){this.fire("list",(()=>new wr("list",e,t,s)))}p(e,t,s){this.fire("update",(()=>new gr("update",e,t,s)))}l(e,t,s){this.fire("delete",(()=>new yr("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?dr.fromMap(r):r??null,measurements:n instanceof Map?dr.fromMap(n):n??null}))}updateState(e){return this.command(new R({options:e instanceof Map?dr.fromMap(e):e??null}))}recoverStart(e,t,s){return this.command(new k({username:e,key:t??null,query:s??null}))}recoverComplete(e,t){return this.command(new A({guid:e,length:t??null}))}getCompany(e){return this.command(new D({company:{id:e}}))}mergeCompany(e){return this.command(new M({company:e}))}removeCompany(e){return this.command(new I({company:{id:e}}))}restoreCompany(e){return this.command(new T({company:{id:e}}))}listCompanyGenerals(e,t){return this.command(new G({...t,company:{id:e}}))}getCompanyGeneral(e){return this.command(new U({company:{id:e}}))}listCompanyPolicies(e,t){return this.command(new B({...t,company:{id:e}}))}getCompanyPolicy(e){return this.command(new J({company:{id:e}}))}listCompanyStyles(e,t){return this.command(new E({...t,company:{id:e}}))}getCompanyStyle(e){return this.command(new L({company:{id:e}}))}listCompanyDirectories(e,t){return this.command(new x({...t,company:{id:e}}))}getCompanyDirectory(e){return this.command(new _({company:{id:e}}))}getReseller(e){return this.command(new O({company:{id:e}}))}mergeReseller(e){return this.command(new N({company:e}))}removeReseller(e){return this.command(new F({company:{id:e}}))}restoreReseller(e){return this.command(new q({company:{id:e}}))}listContacts(e,t){return this.command(new H({...t,company:{id:e}}))}getContact(e){return this.command(new $({contact:{id:e}}))}mergeContact(e){return this.command(new W({contact:e}))}removeContact(e){return this.command(new j({contact:{id:e}}))}restoreContact(e){return this.command(new z({contact:{id:e}}))}multiMergeContact(e){return this.command(new K({contacts:e}))}multiRemoveContact(e){return this.command(new Z({contacts:e.map((e=>({id:e})))}))}listUsers(e,t){return this.command(new Q({...t,company:{id:e}}))}getUser(e){return this.command(new V({user:{login:e}}))}mergeUser(e){return this.command(new X({user:e}))}removeUser(e){return this.command(new Y({user:{login:e}}))}restoreUser(e){return this.command(new ee({user:{login:e}}))}listUserGenerals(e,t){return this.command(new te({...t,company:{id:e}}))}getUserGeneral(e){return this.command(new se({user:{login:e}}))}listUserAdvanceds(e,t){return this.command(new re({...t,company:{id:e}}))}getUserAdvanced(e){return this.command(new ne({user:{login:e}}))}listUserGroups(e,t){return this.command(new ie({...t,company:{id:e}}))}getUserGroup(e){return this.command(new oe({userGroup:{id:e}}))}mergeUserGroup(e){return this.command(new ae({userGroup:e}))}removeUserGroup(e){return this.command(new ce({userGroup:{id:e}}))}restoreUserGroup(e){return this.command(new he({userGroup:{id:e}}))}listMachines(e,t){return this.command(new ue({...t,company:{id:e}}))}getMachine(e){return this.command(new de({machine:{id:e}}))}mergeMachine(e){return this.command(new pe({machine:e}))}removeMachine(e){return this.command(new le({machine:{id:e}}))}restoreMachine(e){return this.command(new me({machine:{id:e}}))}listSessions(e,t){return this.command(new we({...t,company:{id:e}}))}listSessionsByUser(e,t){return this.command(new ge({...t,user:{login:e}}))}killSession(e){return this.command(new ye({session:{handle:e}}))}listIcons(e,t){return this.command(new ve({...t,company:{id:e}}))}getIcon(e){return this.command(new fe({icon:{id:e}}))}mergeIcon(e){return this.command(new be({icon:e}))}removeIcon(e){return this.command(new Ce({icon:{id:e}}))}restoreIcon(e){return this.command(new Pe({icon:{id:e}}))}listPictures(e,t){return this.command(new Se({...t,company:{id:e}}))}getPicture(e){return this.command(new Re({picture:{id:e}}))}mergePicture(e){return this.command(new ke({picture:e}))}removePicture(e){return this.command(new Ae({picture:{id:e}}))}restorePicture(e){return this.command(new De({picture:{id:e}}))}listDocuments(e,t){return this.command(new Me({...t,company:{id:e}}))}getDocument(e){return this.command(new Ie({document:{id:e}}))}mergeDocument(e){return this.command(new Te({document:e}))}removeDocument(e){return this.command(new Ge({document:{id:e}}))}restoreDocument(e){return this.command(new Ue({document:{id:e}}))}listFormTemplates(e,t){return this.command(new Be({...t,company:{id:e}}))}getFormTemplate(e){return this.command(new Je({formTemplate:{id:e}}))}mergeFormTemplate(e){return this.command(new Ee({formTemplate:e}))}removeFormTemplate(e){return this.command(new Le({formTemplate:{id:e}}))}restoreFormTemplate(e){return this.command(new xe({formTemplate:{id:e}}))}listFormResults(e,t){return this.command(new _e({...t,company:{id:e}}))}getFormResult(e){return this.command(new Oe({formResult:{id:e}}))}mergeFormResult(e){return this.command(new Ne({formResult:e}))}multiMergeFormResult(e){return this.command(new Fe({formResult:{id:e}}))}removeFormResult(e){return this.command(new qe({formResult:{id:e}}))}restoreFormResult(e){return this.command(new He({formResult:{id:e}}))}listDashcamDatas(e,t){return this.command(new $e({...t,company:{id:e}}))}getDashcamData(e){return this.command(new We({dashcam:{guid:e}}))}listDashcamLives(e,t){return this.command(new je({...t,company:{id:e}}))}listAssets(e,t){return this.command(new ze({...t,company:{id:e}}))}getAsset(e){return this.command(new Ke({asset:{id:e}}))}mergeAsset(e){return this.command(new Ze({asset:e}))}multiMergeAsset(e){return this.command(new Qe({assets:e}))}removeAsset(e){return this.command(new Ve({asset:{id:e}}))}restoreAsset(e){return this.command(new Xe({asset:{id:e}}))}suspendAsset(e){return this.command(new Ye({asset:{id:e}}))}reviveAsset(e){return this.command(new et({asset:{id:e}}))}searchAssets(e,t){}listAssetGenerals(e,t){return this.command(new tt({...t,company:{id:e}}))}getAssetGeneral(e){return this.command(new st({asset:{id:e}}))}searchAssetGenerals(e,t){}listAssetAdvanceds(e,t){return this.command(new rt({...t,company:{id:e}}))}getAssetAdvanced(e){return this.command(new nt({asset:{id:e}}))}searchAssetAdvanceds(e,t){}mergeAssetDispatch(e){return this.command(new it({assetDispatch:e}))}listDispatchTasks(e,t){return this.command(new ot({...t,company:{id:e}}))}getDispatchTasksByAsset(e,t){return this.command(new at({...t,asset:{id:e}}))}getDispatchTask(e){return this.command(new ct({dispatchTask:{id:e}}))}mergeDispatchTask(e){return this.command(new ht({dispatchTask:e}))}multiMergeDispatchTask(e){return this.command(new ut({dispatchTask:{id:e}}))}removeDispatchTask(e){return this.command(new dt({dispatchTask:{id:e}}))}restoreDispatchTask(e){return this.command(new pt({dispatchTask:{id:e}}))}listDispatchJobs(e,t){return this.command(new lt({...t,company:{id:e}}))}getDispatchJobsByAsset(e,t){return this.command(new mt({...t,asset:{id:e}}))}getDispatchJob(e){return this.command(new wt({dispatchJob:{id:e}}))}mergeDispatchJob(e){return this.command(new gt({dispatchJob:e}))}multiMergeDispatchJob(e){return this.command(new yt({dispatchJob:{id:e}}))}removeDispatchJob(e){return this.command(new vt({dispatchJob:{id:e}}))}restoreDispatchJob(e){return this.command(new ft({dispatchJob:{id:e}}))}changeDispatchJob(e){return this.command(new bt({dispatchJob:e}))}cancelDispatchJob(e){return this.command(new Ct({dispatchJob:e}))}listAssetMessages(e,t){return this.command(new Pt({...t,company:{id:e}}))}getAssetMessagesByAsset(e,t){return this.command(new St({...t,asset:{id:e}}))}getAssetMessage(e){return this.command(new Rt({message:{id:e}}))}mergeAssetMessage(e){return this.command(new kt({assetMessage:e}))}multiMergeAssetMessage(e){return this.command(new At({assetMessage:{id:e}}))}removeAssetMessage(e){return this.command(new Dt({assetMessage:{id:e}}))}restoreAssetMessage(e){return this.command(new Mt({assetMessage:{id:e}}))}listPlaces(e,t){return this.command(new It({...t,company:{id:e}}))}getPlace(e){return this.command(new Tt({place:{id:e}}))}mergePlace(e){return this.command(new Gt({place:e}))}removePlace(e){return this.command(new Ut({place:{id:e}}))}restorePlace(e){return this.command(new Bt({place:{id:e}}))}listProviders(e,t){return this.command(new Jt({...t,company:{id:e}}))}getProvider(e){return this.command(new Et({provider:{id:e}}))}mergeProvider(e){return this.command(new Lt({provider:e}))}multiMergeProvider(e){return this.command(new xt({providers:e}))}multiRemoveProvider(e){return this.command(new _t({providers:e.map((e=>({id:e})))}))}removeProvider(e){return this.command(new Ot({provider:{id:e}}))}restoreProvider(e){return this.command(new Nt({provider:{id:e}}))}searchProviders(e,t){}listProviderGenerals(e,t){return this.command(new Ft({...t,company:{id:e}}))}getProviderGeneral(e){return this.command(new qt({provider:{id:e}}))}searchProviderGenerals(e,t){}listProviderAdvanceds(e,t){return this.command(new Ht({...t,company:{id:e}}))}getProviderAdvanced(e){return this.command(new $t({provider:{id:e}}))}searchProviderAdvanceds(e,t){}listProviderControls(e,t){return this.command(new Wt({...t,company:{id:e}}))}getProviderControl(e){return this.command(new jt({provider:{id:e}}))}searchProviderControls(e,t){}listProviderScripts(e,t){return this.command(new zt({...t,company:{id:e}}))}getProviderScript(e){return this.command(new Kt({providerScript:{id:e}}))}mergeProviderScript(e){return this.command(new Zt({providerScript:e}))}removeProviderScript(e){return this.command(new Qt({providerScript:{id:e}}))}restoreProviderScript(e){return this.command(new Vt({providerScript:{id:e}}))}listProviderConfigs(e,t){return this.command(new Xt({...t,company:{id:e}}))}getProviderConfig(e){return this.command(new Yt({providerConfig:{id:e}}))}mergeProviderConfig(e){return this.command(new es({providerConfig:e}))}multiMergeProviderConfig(e){return this.command(new ts({providerConfig:{id:e}}))}removeProviderConfig(e){return this.command(new ss({providerConfig:{id:e}}))}restoreProviderConfig(e){return this.command(new rs({providerConfig:{id:e}}))}listProviderConfigurations(e,t){return this.command(new ns({...t,company:{id:e}}))}getProviderConfiguration(e){return this.command(new is({providerConfiguration:{id:e}}))}mergeProviderConfiguration(e){return this.command(new os({providerConfiguration:e}))}multiMergeProviderConfiguration(e){return this.command(new as({providerConfiguration:{id:e}}))}removeProviderConfiguration(e){return this.command(new cs({providerConfiguration:{id:e}}))}restoreProviderConfiguration(e){return this.command(new hs({providerConfiguration:{id:e}}))}listProviderRegistration(e,t){return this.command(new us({...t,company:{id:e}}))}getProviderRegistration(e){return this.command(new ds({providerRegistration:{id:e}}))}mergeProviderRegistration(e){return this.command(new ps({providerRegistration:e}))}removeProviderRegistration(e){return this.command(new ls({providerRegistration:{id:e}}))}listBehaviours(e,t){return this.command(new ms({...t,company:{id:e}}))}getBehaviour(e){return this.command(new ws({behaviour:{id:e}}))}mergeBehaviour(e){return this.command(new gs({behaviour:e}))}multiMergeBehaviour(e){return this.command(new ys({behaviour:{id:e}}))}removeBehaviour(e){return this.command(new vs({behaviour:{id:e}}))}restoreBehaviour(e){return this.command(new fs({behaviour:{id:e}}))}listBehaviourScripts(e,t){return this.command(new bs({...t,company:{id:e}}))}getBehaviourScript(e){return this.command(new Cs({behaviourScript:{id:e}}))}mergeBehaviourScript(e){return this.command(new Ps({behaviourScript:e}))}removeBehaviourScript(e){return this.command(new Ss({behaviourScript:{id:e}}))}restoreBehaviourScript(e){return this.command(new Rs({behaviourScript:{id:e}}))}listBehaviourAssetLogs(e,t){return this.command(new ks({...t,behaviour:{id:e}}))}clearBehaviourAssetLogs(e){return this.command(new As({behaviour:{id:e}}))}listBehaviourLogs(e,t){return this.command(new Ds({...t,behaviour:{id:e}}))}clearBehaviourLogs(e){return this.command(new Ms({behaviour:{id:e}}))}listBehaviourScriptLogs(e,t){return this.command(new Is({...t,behaviourScript:{id:e}}))}clearBehaviourScriptLogs(e,t){return this.command(new Ts({...t,behaviourScript:{id:e}}))}listReportTemplates(e,t){return this.command(new Gs({...t,company:{id:e}}))}getReportTemplate(e){return this.command(new Us({reportTemplate:{id:e}}))}mergeReportTemplate(e){return this.command(new Bs({reportTemplate:e}))}removeReportTemplate(e){return this.command(new Js({reportTemplate:{id:e}}))}restoreReportTemplate(e){return this.command(new Es({reportTemplate:{id:e}}))}listReportSchedules(e,t){return this.command(new Ls({...t,company:{id:e}}))}getReportSchedule(e){return this.command(new xs({reportSchedule:{id:e}}))}mergeReportSchedule(e){return this.command(new _s({reportSchedule:e}))}removeReportSchedule(e){return this.command(new Os({reportSchedule:{id:e}}))}restoreReportSchedule(e){return this.command(new Ns({reportSchedule:{id:e}}))}listReportResults(e,t){return this.command(new Fs({...t,company:{id:e}}))}getReportResult(e){return this.command(new qs({reportResult:{id:e}}))}mergeReportResult(e){return this.command(new Hs({reportResult:e}))}removeReportResult(e){return this.command(new $s({reportResult:{id:e}}))}restoreReportResult(e){return this.command(new Ws({reportResult:{id:e}}))}listMaintenanceSchedules(e,t){return this.command(new js({...t,company:{id:e}}))}getMaintenanceSchedule(e){return this.command(new zs({maintenanceSchedule:{id:e}}))}mergeMaintenanceSchedule(e){return this.command(new Ks({maintenanceSchedule:e}))}removeMaintenanceSchedule(e){return this.command(new Zs({maintenanceSchedule:{id:e}}))}restoreMaintenanceSchedule(e){return this.command(new Qs({maintenanceSchedule:{id:e}}))}listMaintenanceJobs(e,t){return this.command(new Vs({...t,company:{id:e}}))}getMaintenanceJob(e){return this.command(new Xs({maintenanceJob:{id:e}}))}mergeMaintenanceJob(e){return this.command(new Ys({maintenanceJob:e}))}removeMaintenanceJob(e){return this.command(new er({maintenanceJob:{id:e}}))}restoreMaintenanceJob(e){return this.command(new tr({maintenanceJob:{id:e}}))}}class Rr extends Pr{static URI_PROD="https://audit.trakit.ca/";static URI_BETA="https://gloomhands.trakit.ca/";constructor(e,t){super(e,t??Rr.URI_PROD)}requestCreate(e){return r(this,e)}requestRelay(e){return i(e)}beginAssetAdvanced(e,t){return this.auditAssetAdvanced(e.id,{before:e.position?.date??[...e.attributes.values()].reduce(((e,t)=>t.dts>e?t.dts:e),new Date),highest:e.v[0],limit:t})}auditAssetAdvanced(e,t){return this.command(new sr({...t,asset:{id:e}}))}}class kr extends Sr{static URI_PROD="https://rest.trakit.ca/";static URI_BETA="https://mindflayer.trakit.ca/";constructor(e,t){super(e,t??kr.URI_PROD)}requestCreate(e){return r(this,e)}requestRelay(e){return i(e)}}const Ar=/^(.+?)(Merged|Deleted|Suspended)$/,Dr={Company:[rr.companyGeneral,rr.companyLabels,rr.companyPolicies],CompanyGeneral:[rr.companyGeneral],CompanyDirectory:[],CompanyStyle:[rr.companyLabels],CompanyPolicy:[rr.companyPolicies],CompanyReseller:[rr.companyReseller],Contact:[rr.contact],Machine:[rr.machine],User:[rr.userGeneral,rr.userAdvanced,rr.userAuthentication],UserGeneral:[rr.userGeneral],UserAdvanced:[rr.userAdvanced],UserAuthentication:[rr.userAuthentication],UserState:[rr.userState],UserGroup:[rr.userGroup],Session:[],Dashcam:[],Icon:[rr.icon],Picture:[rr.picture],Document:[rr.document],FormTemplate:[rr.formTemplate],FormResult:[rr.formResult],Asset:[rr.assetGeneral,rr.assetAdvanced,rr.assetDispatch],AssetGeneral:[rr.assetGeneral],AssetAdvanced:[rr.assetAdvanced],AssetDispatch:[rr.assetDispatch],AssetMessage:[rr.assetMessage],AssetAlert:[],DispatchTask:[rr.dispatchTask],DispatchJob:[rr.dispatchJob],MaintenanceSchedule:[rr.maintenanceSchedule],MaintenanceJob:[rr.maintenanceJob],Place:[rr.placeGeneral],BehaviourScript:[rr.behaviourScript],Behaviour:[rr.behaviour],BehaviourLog:[rr.behaviourLog],Provider:[rr.providerGeneral,rr.providerAdvanced,rr.providerControl],ProviderGeneral:[rr.providerGeneral],ProviderAdvanced:[rr.providerAdvanced],ProviderControl:[rr.providerControl],ProviderConfiguration:[rr.providerConfiguration],ProviderConfigurationType:[],ProviderScript:[rr.providerScript],ProviderConfig:[rr.providerConfig],ProviderRegistration:[rr.providerRegistration],ReportTemplate:[rr.reportTemplate],ReportSchedule:[rr.reportSchedule],ReportResult:[rr.reportResult],BillingProfile:[rr.billingProfile],BillingReport:[rr.billingReport],BillableHostingRule:[rr.billingHosting],BillableHostingLicense:[rr.billingLicense]};class Mr{#e=new Map;get regions(){return[...this.#e.keys()]}getExpired(){const e=new Date,t=[];for(const[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(const[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(const[t,s]of this.#e)s||e.push(t);return this.#e.clear(),e}}var Ir;!function(e){e.maintenance="maintenance",e.upgrade="upgrade"}(Ir||(Ir={}));class Tr{static fromJson(e){switch(e?.kind){case Ir.maintenance:return new Gr(e);case Ir.upgrade:return new Ur(e);default:throw new Error(`Unknown broadcast type: ${e?.kind}`)}}kind;serverTime;message;constructor(e){this.kind=e?.kind,this.serverTime=hr.date(e?.serverTime),this.message=e?.message??""}}class Gr extends Tr{starting;ending;constructor(e){super(e),this.starting=hr.date(e?.starting),this.ending=hr.date(e?.ending)}}class Ur extends Tr{eta;reload;constructor(e){super(e),this.eta=hr.date(e?.eta),this.reload=!!e?.reload}}class Br extends pr{name;body;constructor(e,t,s){super(e),this.name=t,this.body=s}}class Jr extends pr{online;reply;constructor(e,t,s){super(e),this.online=t,this.reply=s}}class Er extends pr{broadcast;constructor(e,t){super(e),this.broadcast=Tr.fromJson(t)}}const Lr="connection",xr="dis"+Lr;var _r;!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"}(_r||(_r={}));class Or extends Sr{static URI_PROD="wss://socket.trakit.ca/";static URI_BETA="wss://kraken.trakit.ca/";static msgNameToSyncName(e){const s=Ar.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 _r.opening;case WebSocket.OPEN:return this.#a?_r.open:_r.opening;case WebSocket.CLOSING:return _r.closing;default:return _r.closed}}get ready(){return this.#a&&this.#c}m(e){const t=this.o.get("open");if(t?.length){const s=new Jr("open",this.#a,e);t.forEach((e=>e.call(this,s)))}}C(e){const t=this.o.get("close");if(t?.length){const s=new Jr("close",this.#a,e);t.forEach((e=>e.call(this,s)))}}P(e,t){const s=this.o.get("message");if(s?.length){const r=new Br("message",e,t);s.forEach((e=>e.call(this,r)))}}S(e){const t=this.o.get("error");if(t?.length){const s=new Jr("error",!1,e);t.forEach((e=>e.call(this,s)))}}R(e){const t=this.o.get("broadcast");if(t?.length){const s=new Er("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.S(new nr({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:_r.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===xr?r:{...r,reqId:e,errorCode:d.service,errorDetails:{...s}});this.C?.(new nr(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.P(t,s),t){case"connectionResponse":this.#v(s),this.#s=new Date(this.#r),this.#a=!0,this.#u(Lr,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({policy:s}),this.h();break;case"broadcast":this.R(s)}if(t.endsWith("Response"))this.#u(s.reqId,s);else if(!t.startsWith("session")){const e=Ar.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,policy:e?.policies??t.policies})),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??Or.URI_PROD)}dispose(){super.dispose(),this.close().finally((()=>{this.#o=this.#h=null}))}open(){return o(this.i,Lr,(e=>(clearTimeout(this.#y),new Promise((async(t,s)=>{if(this.state===_r.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(Lr,(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:this.state}}))})))))}close(){return o(this.i,xr,(e=>(clearTimeout(this.#y),new Promise(((t,s)=>{switch(this.state){case _r.opening:case _r.open:this.#c=!1,this.reconnectEnabled=!1,this.#h.set(xr,(r=>{(0===r.errorCode?t:s)(new nr(r)),this.i.delete(e)})),this.#o.close(1e3,"Bye!");break;default:s(new nr({errorCode:d.unknown,message:"WebSocket not open",errorDetails:{kind:"connection",connection:this.state}}))}})))))}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===_r.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 ir({company:{id:e},subscriptionTypes:t})):Promise.resolve(new or({errorCode:d.success,message:"No subscriptions specified"}))}unsubscribe(e,t){return t?.length?this.command(new ar({company:{id:e},subscriptionTypes:t})):Promise.resolve(new or({errorCode:d.success,message:"No subscriptions specified"}))}listSubscriptions(){return this.command(new cr)}}const Nr={Company:["CompanyGeneral","CompanyDirectory","CompanyStyle","CompanyPolicy"],Asset:["AssetGeneral","AssetAdvanced","AssetDispatch"],Provider:["ProviderGeneral","ProviderAdvanced","ProviderControl"],User:["UserGeneral","UserAdvanced"]};class Fr extends Sr{k;A;get socketOnline(){return this.k.state===_r.open}get socketDetails(){return{state:this.k.state,ready:this.k.ready,lastConnected:this.k.lastConnected,lastSent:this.k.lastSent,lastReceived:this.k.lastReceived,lastMessage:this.k.lastMessage}}get socketAddress(){return this.k.baseAddress}set socketAddress(e){this.k.baseAddress=e}get restAddress(){return this.A.baseAddress}set restAddress(e){this.A.baseAddress=e}constructor(e,t,s){super(e);const r=e=>this.#C(e.account),n=e=>this.fire(e.type,(()=>e));this.A=new kr(this.account,t??kr.URI_PROD),this.A.on("account",r),this.k=new Or(this.account,s??Or.URI_PROD),this.k.on("account",r),this.k.on("open",(e=>this.#P(e))),this.k.on("close",(e=>this.#S(e)));for(const e of["account","list","update","delete"])this.A.on(e,n),this.k.on(e,n);for(const e of["open","close","broadcast"])this.k.on(e,n);(this.account.ghostId||this.account.machine?.key)&&this.k.open()}dispose(){super.dispose(),this.A.dispose(),this.k.dispose(),this.A=this.k=null}setAuth(e){if(super.setAuth(e),this.A?.setAuth(this.account),this.k)switch(this.k.setAuth(this.account),this.k.state){case _r.open:this.account.ghostId||this.account.machine?.key||this.k.close().catch((()=>this.setAuth()));break;case _r.closed:(this.account.ghostId||this.account.machine?.key)&&this.k.open().catch((()=>this.setAuth()))}}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.A.command(e)}socket(e){return this.k.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)}isSynced(e,t){let s=this.k.state===_r.open;if(s){const r=this.#D(e);s=c(t).every((e=>r.regions.includes(e)))}return s}getSyncs(e,t=!1){const s=this.#D(e),r=t?[]:s.getExpiring();return h(s.regions.filter((e=>!r.includes(e))))}async sync(t,s){const r=[],n=this.#D(t),i=c(s).filter((e=>!n.regions.includes(e)));if(i.length>0){n.getExpiring().forEach((e=>i.includes(e)&&n.preserveRegion(e)));const s=await this.k.subscribe(t,i);n.preserveRegions(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.#D(e),r=t.reduce(((e,t)=>e.concat(Dr[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.k.state===_r.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;#D(e){let t=this.#R.get(e);return t||this.#R.set(e,t=new Mr),t}subscribe(e,t){return this.k.subscribe(e,t)}unsubscribe(e,t){return this.k.unsubscribe(e,t)}listSubscriptions(){return this.k.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 qr="0.1.10";export{Mr as SubscribedRegions,Rr as TrakitAuditCommander,Pr as TrakitBaseCommander,pr as TrakitEvent,mr as TrakitEventAccount,yr as TrakitEventDelete,wr as TrakitEventList,Er as TrakitEventSocketBroadcast,Br as TrakitEventSocketMessage,Jr as TrakitEventSocketState,lr as TrakitEventSync,gr as TrakitEventUpdate,Sr as TrakitObjectCommander,kr as TrakitRestfulCommander,Or as TrakitSocketCommander,_r as TrakitSocketStatus,Fr as TrakitSyncCommander,e as createClientErrorResponse,a as makeCommandName,s as makeVerbRoute,r as requestCreateCommander,n as requestCreateCors,i as requestRelayCorsJson,qr as version};
|