@dronedeploy/rocos-js-sdk 3.0.1-alpha.1 → 3.0.1-alpha.3
Sign up to get free protection for your applications and to get access to all the features.
- package/constants/api.d.ts +3 -4
- package/constants/api.js +3 -4
- package/helpers/websandbox/frame/frame.source.js +1 -1
- package/helpers/websandbox/frame/worker/manager.d.ts +1 -3
- package/helpers/websandbox/frame/worker/manager.js +26 -19
- package/helpers/websandbox/frame/worker/manager.spec.d.ts +4 -0
- package/helpers/websandbox/frame/worker/manager.spec.js +127 -0
- package/helpers/websandbox/sandbox.d.ts +3 -0
- package/helpers/websandbox/sandbox.js +39 -10
- package/models/index.d.ts +1 -0
- package/models/index.js +1 -0
- package/models/workflow/Workflow.d.ts +36 -0
- package/models/workflow/Workflow.js +1 -0
- package/package.json +1 -1
- package/services/WorkflowService.d.ts +25 -29
- package/services/WorkflowService.js +30 -62
package/constants/api.d.ts
CHANGED
@@ -98,10 +98,6 @@ export declare const API_PROJECT_ROBOT_DASHBOARD_URL = "https://{url}/projects/{
|
|
98
98
|
export declare const API_PROJECT_ROBOT_DASHBOARD_ID_URL = "https://{url}/projects/{projectId}/robots/{callsign}/dashboards/{dashboardId}";
|
99
99
|
export declare const API_PROJECT_ROBOT_DASHBOARD_CUSTOM_WIDGET_URL = "https://{url}/projects/{projectId}/robots/{callsign}/dashboards/{dashboardId}/custom-widgets";
|
100
100
|
export declare const API_PROJECT_CALLSIGN_STREAM_URL = "https://{url}/projects/{projectId}/callsigns/{callsign}/streams";
|
101
|
-
export declare const API_PROJECT_CALLSIGN_WORKFLOW_URL = "https://{url}/projects/{projectId}/callsigns/{callsign}/workflows";
|
102
|
-
export declare const API_PROJECT_WORKFLOW_URL = "https://{url}/projects/{projectId}/workflows";
|
103
|
-
export declare const API_PROJECT_ROBOT_DEPLOYED_WORKFLOW_URL = "https://{url}/projects/{projectId}/robots/{callsign}/automate/flows/deployments";
|
104
|
-
export declare const API_PROJECT_WORKFLOW_ID_URL = "https://{url}/projects/{projectId}/workflows/{workflowId}";
|
105
101
|
export declare const API_PROJECT_PROFILE_DASHBOARD_URL = "https://{url}/projects/{projectId}/profiles/{profileId}/dashboards";
|
106
102
|
export declare const API_PROJECT_PROFILE_DASHBOARD_ID_URL = "https://{url}/projects/{projectId}/profiles/{profileId}/dashboards/{dashboardId}";
|
107
103
|
export declare const API_PROJECT_PROFILE_DASHBOARD_CUSTOM_WIDGET_URL = "https://{url}/projects/{projectId}/profiles/{profileId}/dashboards/{dashboardId}/custom-widgets";
|
@@ -125,3 +121,6 @@ export declare const API_MAP_ID_URL = "https://{url}/projects/{projectId}/maps/{
|
|
125
121
|
export declare const API_MAPS_COPY_URL = "https://{url}/projects/{projectId}/maps/{mapId}/copy";
|
126
122
|
export declare const API_MAPS_DEPLOY_URL = "https://{url}/projects/{projectId}/maps/{mapId}/deploy";
|
127
123
|
export declare const API_MAPS_GEOJSON_URL = "https://{url}/projects/{projectId}/maps/{mapId}/geojson";
|
124
|
+
export declare const API_PROJECT_WORKFLOW_URL = "https://{url}/projects/{projectId}/automate/flows";
|
125
|
+
export declare const API_PROJECT_WORKFLOW_ID_URL = "https://{url}/projects/{projectId}/automate/flows/{workflowId}";
|
126
|
+
export declare const API_PROJECT_DEPLOYED_WORKFLOW_URL = "https://{url}/projects/{projectId}/robots/{callsign}/automate/flows/deployments";
|
package/constants/api.js
CHANGED
@@ -98,10 +98,6 @@ export const API_PROJECT_ROBOT_DASHBOARD_URL = 'https://{url}/projects/{projectI
|
|
98
98
|
export const API_PROJECT_ROBOT_DASHBOARD_ID_URL = 'https://{url}/projects/{projectId}/robots/{callsign}/dashboards/{dashboardId}';
|
99
99
|
export const API_PROJECT_ROBOT_DASHBOARD_CUSTOM_WIDGET_URL = 'https://{url}/projects/{projectId}/robots/{callsign}/dashboards/{dashboardId}/custom-widgets';
|
100
100
|
export const API_PROJECT_CALLSIGN_STREAM_URL = 'https://{url}/projects/{projectId}/callsigns/{callsign}/streams';
|
101
|
-
export const API_PROJECT_CALLSIGN_WORKFLOW_URL = 'https://{url}/projects/{projectId}/callsigns/{callsign}/workflows';
|
102
|
-
export const API_PROJECT_WORKFLOW_URL = 'https://{url}/projects/{projectId}/workflows';
|
103
|
-
export const API_PROJECT_ROBOT_DEPLOYED_WORKFLOW_URL = 'https://{url}/projects/{projectId}/robots/{callsign}/automate/flows/deployments';
|
104
|
-
export const API_PROJECT_WORKFLOW_ID_URL = 'https://{url}/projects/{projectId}/workflows/{workflowId}';
|
105
101
|
export const API_PROJECT_PROFILE_DASHBOARD_URL = 'https://{url}/projects/{projectId}/profiles/{profileId}/dashboards';
|
106
102
|
export const API_PROJECT_PROFILE_DASHBOARD_ID_URL = 'https://{url}/projects/{projectId}/profiles/{profileId}/dashboards/{dashboardId}';
|
107
103
|
export const API_PROJECT_PROFILE_DASHBOARD_CUSTOM_WIDGET_URL = 'https://{url}/projects/{projectId}/profiles/{profileId}/dashboards/{dashboardId}/custom-widgets';
|
@@ -125,3 +121,6 @@ export const API_MAP_ID_URL = 'https://{url}/projects/{projectId}/maps/{mapId}';
|
|
125
121
|
export const API_MAPS_COPY_URL = 'https://{url}/projects/{projectId}/maps/{mapId}/copy';
|
126
122
|
export const API_MAPS_DEPLOY_URL = 'https://{url}/projects/{projectId}/maps/{mapId}/deploy';
|
127
123
|
export const API_MAPS_GEOJSON_URL = 'https://{url}/projects/{projectId}/maps/{mapId}/geojson';
|
124
|
+
export const API_PROJECT_WORKFLOW_URL = 'https://{url}/projects/{projectId}/automate/flows';
|
125
|
+
export const API_PROJECT_WORKFLOW_ID_URL = 'https://{url}/projects/{projectId}/automate/flows/{workflowId}';
|
126
|
+
export const API_PROJECT_DEPLOYED_WORKFLOW_URL = 'https://{url}/projects/{projectId}/robots/{callsign}/automate/flows/deployments';
|
@@ -1,5 +1,5 @@
|
|
1
1
|
// Auto-generated file
|
2
2
|
/* eslint-disable */
|
3
3
|
import __WORKER_SOURCE__ from './worker/worker.source';
|
4
|
-
const source = `(()=>{"use strict";var e={880:(e,t)=>{var s;Object.defineProperty(t,"__esModule",{value:!0}),function(e){e.RESPONSE="response",e.MESSAGE="message"}(s||(s={}));const r={allowedSenderOrigin:void 0,debugMode:!1};t.default=class{constructor(e,t,s,i,o={}){this.callbacks=new Map,this.serviceMethods=new Map,this.name=e,this.options={...r,...o},this.log("Created connection w/ allowedOrigin:",this.options.allowedSenderOrigin),this.serviceMethods=new Map(Object.entries(s));const[n]=crypto.getRandomValues(new Uint32Array(1));this.incrementalID=n,this.postMessageInternal=t,i((e=>this.onMessageListener(e)))}callRemoteMethod(e,...t){return this.log("Calling Remote Method",{name:e,args:t}),new Promise(((r,i)=>{const o=this.registerCallback(r,i);this.postMessage({callId:o,type:s.MESSAGE,methodName:e,arguments:t})}))}onMessageListener(e){this.log("Received message",e);const{data:t}=e,{allowedSenderOrigin:r}=this.options;switch(r&&e.origin!==r&&console.warn(\`Received message from invalid origin: \${e.origin}\`),t.type){case s.RESPONSE:return void this.popCallback(t.callId,t.success,t.result);case s.MESSAGE:this.callLocalMethod(t.methodName,t.arguments).then((e=>this.responseOtherSide(t.callId,e))).catch((e=>this.responseOtherSide(t.callId,e,!1)))}}async callLocalMethod(e,t){this.log("calling local method",e,t);const s=this.serviceMethods.get(e);if(!s)throw new Error(\`service method \${e} not found\`);return s(...t)}responseOtherSide(e,t,r=!0){this.log("responding to remote call",{id:e,result:t,success:r});const i=t=>{this.postMessage({callId:e,type:s.RESPONSE,success:r,result:t})};try{i(t)}catch(e){e instanceof DOMException&&i(JSON.parse(JSON.stringify(t)))}}registerCallback(e,t){const s=(++this.incrementalID).toString();return this.log("registering callback for id",s),this.callbacks.set(s,{success:e,failure:t}),s}popCallback(e,t,s){this.log("calling callback for id",e,{success:t,result:s});const r=this.callbacks.get(e);t?r?.success(s):r?.failure(s),this.callbacks.delete(e)}postMessage(e,t="*"){this.log("sending message",{data:e,targetOrigin:t}),this.postMessageInternal(e,t)}log(...e){this.options.debugMode&&console.debug(\`[\${this.name}]\`,...e)}}},306:function(e,t,s){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const i=r(s(880)),o=r(s(54)),n=new class{constructor(){const e=!!window?.debugMode;this.connection=new i.default("FRAME",window.parent.postMessage.bind(window.parent),{startTask:this.runCode.bind(this)},(e=>{window.addEventListener("message",e)}),{debugMode:e}),this.connection.callRemoteMethod("iframeInitialised"),this.workerManager=new o.default}async runCode(e){return this.workerManager.execute(e)}};t.default=n},54:function(e,t,s){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const i=r(s(420));t.default=i.default},420:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default=class{constructor(){this.worker=this.createWorker()}async execute(e){const t={...e,contextVariable:e.contextVariable??"ctx"},s=this.runTask(t),r=
|
4
|
+
const source = `(()=>{"use strict";var e={880:(e,t)=>{var s;Object.defineProperty(t,"__esModule",{value:!0}),function(e){e.RESPONSE="response",e.MESSAGE="message"}(s||(s={}));const r={allowedSenderOrigin:void 0,debugMode:!1};t.default=class{constructor(e,t,s,i,o={}){this.callbacks=new Map,this.serviceMethods=new Map,this.name=e,this.options={...r,...o},this.log("Created connection w/ allowedOrigin:",this.options.allowedSenderOrigin),this.serviceMethods=new Map(Object.entries(s));const[n]=crypto.getRandomValues(new Uint32Array(1));this.incrementalID=n,this.postMessageInternal=t,i((e=>this.onMessageListener(e)))}callRemoteMethod(e,...t){return this.log("Calling Remote Method",{name:e,args:t}),new Promise(((r,i)=>{const o=this.registerCallback(r,i);this.postMessage({callId:o,type:s.MESSAGE,methodName:e,arguments:t})}))}onMessageListener(e){this.log("Received message",e);const{data:t}=e,{allowedSenderOrigin:r}=this.options;switch(r&&e.origin!==r&&console.warn(\`Received message from invalid origin: \${e.origin}\`),t.type){case s.RESPONSE:return void this.popCallback(t.callId,t.success,t.result);case s.MESSAGE:this.callLocalMethod(t.methodName,t.arguments).then((e=>this.responseOtherSide(t.callId,e))).catch((e=>this.responseOtherSide(t.callId,e,!1)))}}async callLocalMethod(e,t){this.log("calling local method",e,t);const s=this.serviceMethods.get(e);if(!s)throw new Error(\`service method \${e} not found\`);return s(...t)}responseOtherSide(e,t,r=!0){this.log("responding to remote call",{id:e,result:t,success:r});const i=t=>{this.postMessage({callId:e,type:s.RESPONSE,success:r,result:t})};try{i(t)}catch(e){e instanceof DOMException&&i(JSON.parse(JSON.stringify(t)))}}registerCallback(e,t){const s=(++this.incrementalID).toString();return this.log("registering callback for id",s),this.callbacks.set(s,{success:e,failure:t}),s}popCallback(e,t,s){this.log("calling callback for id",e,{success:t,result:s});const r=this.callbacks.get(e);t?r?.success(s):r?.failure(s),this.callbacks.delete(e)}postMessage(e,t="*"){this.log("sending message",{data:e,targetOrigin:t}),this.postMessageInternal(e,t)}log(...e){this.options.debugMode&&console.debug(\`[\${this.name}]\`,...e)}}},306:function(e,t,s){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const i=r(s(880)),o=r(s(54)),n=new class{constructor(){const e=!!window?.debugMode;this.connection=new i.default("FRAME",window.parent.postMessage.bind(window.parent),{startTask:this.runCode.bind(this)},(e=>{window.addEventListener("message",e)}),{debugMode:e}),this.connection.callRemoteMethod("iframeInitialised"),this.workerManager=new o.default}async runCode(e){return this.workerManager.execute(e)}};t.default=n},54:function(e,t,s){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const i=r(s(420));t.default=i.default},420:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default=class{constructor(){this.messageListeners=new Map,this.worker=this.createWorker()}async execute(e){const t={...e,contextVariable:e.contextVariable??"ctx"},s=this.runTask(t),r=new Promise(((t,s)=>{const r=AbortSignal.timeout(e.timeout);r.addEventListener("abort",(()=>{s(r.reason)}))}));return Promise.race([s,r]).catch((e=>{throw"TimeoutError"===e.name&&this.terminate(),e})).finally((()=>{this.removeMessageListener(e.id)}))}terminate(){for(const e of this.messageListeners.values())this.worker.removeEventListener("message",e);this.worker.terminate(),this.worker=this.createWorker()}runTask(e){return new Promise(((t,s)=>{const r=r=>{const{data:i}=r;i.id===e.id&&(i.success?t(i.result):s(i.result))};this.messageListeners.set(e.id,r),this.worker.addEventListener("message",r),this.worker.postMessage(e)}))}createWorker(){const e=URL.createObjectURL(new Blob(["${__WORKER_SOURCE__.replace(/(['`"$])/g, '\\$1')}"],{type:"application/javascript"}));return new Worker(e)}removeMessageListener(e){const t=this.messageListeners.get(e);t&&this.worker.removeEventListener("message",t)}}}},t={};!function s(r){var i=t[r];if(void 0!==i)return i.exports;var o=t[r]={exports:{}};return e[r].call(o.exports,o,o.exports,s),o.exports}(306)})();`;
|
5
5
|
export default source;
|
@@ -1,13 +1,11 @@
|
|
1
1
|
import { Task } from '../../types';
|
2
2
|
export default class Manager {
|
3
3
|
private worker;
|
4
|
-
private
|
4
|
+
private messageListeners;
|
5
5
|
constructor();
|
6
6
|
execute(task: Task): Promise<unknown>;
|
7
7
|
terminate(): void;
|
8
8
|
private runTask;
|
9
|
-
private timeout;
|
10
|
-
private stopTimer;
|
11
9
|
private createWorker;
|
12
10
|
private removeMessageListener;
|
13
11
|
}
|
@@ -2,6 +2,7 @@
|
|
2
2
|
const WORKER_SOURCE = '__WORKER_SOURCE__';
|
3
3
|
export default class Manager {
|
4
4
|
constructor() {
|
5
|
+
this.messageListeners = new Map();
|
5
6
|
this.worker = this.createWorker();
|
6
7
|
}
|
7
8
|
async execute(task) {
|
@@ -10,13 +11,27 @@ export default class Manager {
|
|
10
11
|
contextVariable: task.contextVariable ?? 'ctx',
|
11
12
|
};
|
12
13
|
const result = this.runTask(workerTask);
|
13
|
-
const timeout =
|
14
|
-
|
15
|
-
|
14
|
+
const timeout = new Promise((_, reject) => {
|
15
|
+
const signal = AbortSignal.timeout(task.timeout);
|
16
|
+
signal.addEventListener('abort', () => {
|
17
|
+
reject(signal.reason);
|
18
|
+
});
|
19
|
+
});
|
20
|
+
return Promise.race([result, timeout])
|
21
|
+
.catch((e) => {
|
22
|
+
if (e.name === 'TimeoutError') {
|
23
|
+
this.terminate();
|
24
|
+
}
|
25
|
+
throw e;
|
26
|
+
})
|
27
|
+
.finally(() => {
|
28
|
+
this.removeMessageListener(task.id);
|
16
29
|
});
|
17
30
|
}
|
18
31
|
terminate() {
|
19
|
-
this.
|
32
|
+
for (const listener of this.messageListeners.values()) {
|
33
|
+
this.worker.removeEventListener('message', listener);
|
34
|
+
}
|
20
35
|
this.worker.terminate();
|
21
36
|
this.worker = this.createWorker();
|
22
37
|
}
|
@@ -25,7 +40,6 @@ export default class Manager {
|
|
25
40
|
const listener = (event) => {
|
26
41
|
const { data } = event;
|
27
42
|
if (data.id === task.id) {
|
28
|
-
this.stopTimer();
|
29
43
|
if (data.success) {
|
30
44
|
resolve(data.result);
|
31
45
|
}
|
@@ -34,27 +48,20 @@ export default class Manager {
|
|
34
48
|
}
|
35
49
|
}
|
36
50
|
};
|
51
|
+
this.messageListeners.set(task.id, listener);
|
37
52
|
this.worker.addEventListener('message', listener);
|
38
|
-
this.removeMessageListener = () => this.worker.removeEventListener('message', listener);
|
39
53
|
this.worker.postMessage(task);
|
40
54
|
});
|
41
55
|
}
|
42
|
-
timeout(timeoutMs) {
|
43
|
-
return new Promise((_, reject) => {
|
44
|
-
this.timerId = window.setTimeout(() => {
|
45
|
-
this.terminate();
|
46
|
-
reject(new Error('maximum execution time exceeded'));
|
47
|
-
}, timeoutMs);
|
48
|
-
});
|
49
|
-
}
|
50
|
-
stopTimer() {
|
51
|
-
clearTimeout(this.timerId);
|
52
|
-
}
|
53
56
|
createWorker() {
|
54
57
|
const blob = URL.createObjectURL(new Blob([WORKER_SOURCE], { type: 'application/javascript' }));
|
55
58
|
return new Worker(blob);
|
56
59
|
}
|
57
|
-
removeMessageListener() {
|
58
|
-
|
60
|
+
removeMessageListener(id) {
|
61
|
+
const listener = this.messageListeners.get(id);
|
62
|
+
if (!listener) {
|
63
|
+
return;
|
64
|
+
}
|
65
|
+
this.worker.removeEventListener('message', listener);
|
59
66
|
}
|
60
67
|
}
|
@@ -0,0 +1,127 @@
|
|
1
|
+
/**
|
2
|
+
* @jest-environment jsdom
|
3
|
+
*/
|
4
|
+
import WorkerManager from './manager';
|
5
|
+
const WorkerMocks = {
|
6
|
+
postMessage: jest.fn(),
|
7
|
+
terminate: jest.fn(),
|
8
|
+
addEventListener: jest.fn(),
|
9
|
+
removeEventListener: jest.fn(),
|
10
|
+
onerror: jest.fn(),
|
11
|
+
onmessage: jest.fn(),
|
12
|
+
onmessageerror: jest.fn(),
|
13
|
+
dispatchEvent: jest.fn(),
|
14
|
+
clearAllMocks() {
|
15
|
+
this.postMessage.mockClear();
|
16
|
+
this.terminate.mockClear();
|
17
|
+
this.addEventListener.mockClear();
|
18
|
+
this.removeEventListener.mockClear();
|
19
|
+
this.onerror.mockClear();
|
20
|
+
this.onmessage.mockClear();
|
21
|
+
this.onmessageerror.mockClear();
|
22
|
+
this.dispatchEvent.mockClear();
|
23
|
+
},
|
24
|
+
};
|
25
|
+
class MockWorkerClass {
|
26
|
+
constructor() {
|
27
|
+
this.postMessage = WorkerMocks.postMessage;
|
28
|
+
this.terminate = WorkerMocks.terminate;
|
29
|
+
this.addEventListener = WorkerMocks.addEventListener;
|
30
|
+
this.removeEventListener = WorkerMocks.removeEventListener;
|
31
|
+
this.onerror = WorkerMocks.onerror;
|
32
|
+
this.onmessage = WorkerMocks.onmessage;
|
33
|
+
this.onmessageerror = WorkerMocks.onmessageerror;
|
34
|
+
this.dispatchEvent = WorkerMocks.dispatchEvent;
|
35
|
+
}
|
36
|
+
}
|
37
|
+
Object.defineProperty(window, 'Worker', {
|
38
|
+
value: MockWorkerClass,
|
39
|
+
writable: true,
|
40
|
+
});
|
41
|
+
Object.defineProperty(window, 'URL', {
|
42
|
+
value: {
|
43
|
+
createObjectURL: jest.fn(),
|
44
|
+
},
|
45
|
+
});
|
46
|
+
// add mock to AbortSignal.timeout
|
47
|
+
Object.defineProperty(AbortSignal, 'timeout', {
|
48
|
+
value: jest.fn().mockImplementation((timeout) => {
|
49
|
+
return new AbortController().signal;
|
50
|
+
}),
|
51
|
+
});
|
52
|
+
const task = {
|
53
|
+
id: 'test',
|
54
|
+
code: '1',
|
55
|
+
timeout: 1000,
|
56
|
+
};
|
57
|
+
const response = {
|
58
|
+
data: {
|
59
|
+
id: 'test',
|
60
|
+
success: true,
|
61
|
+
result: 'test',
|
62
|
+
},
|
63
|
+
};
|
64
|
+
describe('WorkerManager', () => {
|
65
|
+
beforeEach(() => {
|
66
|
+
WorkerMocks.clearAllMocks();
|
67
|
+
});
|
68
|
+
it('should send a task to the worker', async () => {
|
69
|
+
const listeners = [];
|
70
|
+
WorkerMocks.addEventListener.mockImplementation((_, listener) => {
|
71
|
+
listeners.push(listener);
|
72
|
+
});
|
73
|
+
WorkerMocks.postMessage.mockImplementation((msg) => {
|
74
|
+
listeners.forEach((listener) => {
|
75
|
+
listener(response);
|
76
|
+
});
|
77
|
+
});
|
78
|
+
const manager = new WorkerManager();
|
79
|
+
const result = await manager.execute(task);
|
80
|
+
expect(result).toEqual('test');
|
81
|
+
});
|
82
|
+
it('should handle listener for a single task', async () => {
|
83
|
+
const listeners = [];
|
84
|
+
WorkerMocks.addEventListener.mockImplementation((_, listener) => {
|
85
|
+
listeners.push(listener);
|
86
|
+
});
|
87
|
+
WorkerMocks.removeEventListener.mockImplementation((_, listener) => {
|
88
|
+
const index = listeners.indexOf(listener);
|
89
|
+
listeners.splice(index, 1);
|
90
|
+
});
|
91
|
+
const manager = new WorkerManager();
|
92
|
+
expect(listeners.length).toEqual(0);
|
93
|
+
const result = manager.execute(task);
|
94
|
+
expect(listeners.length).toEqual(1);
|
95
|
+
listeners[0](response);
|
96
|
+
await result;
|
97
|
+
expect(listeners.length).toEqual(0);
|
98
|
+
});
|
99
|
+
it('should handle listener for multiple simultaneous task', async () => {
|
100
|
+
const listeners = [];
|
101
|
+
WorkerMocks.addEventListener.mockImplementation((_, listener) => {
|
102
|
+
listeners.push(listener);
|
103
|
+
});
|
104
|
+
WorkerMocks.removeEventListener.mockImplementation((_, listener) => {
|
105
|
+
const index = listeners.indexOf(listener);
|
106
|
+
listeners.splice(index, 1);
|
107
|
+
});
|
108
|
+
const manager = new WorkerManager();
|
109
|
+
expect(listeners.length).toEqual(0);
|
110
|
+
const result1 = manager.execute(task);
|
111
|
+
const result2 = manager.execute(task);
|
112
|
+
expect(listeners.length).toEqual(2);
|
113
|
+
const result3 = manager.execute(task);
|
114
|
+
expect(listeners.length).toEqual(3);
|
115
|
+
const [listener1, listener2, listener3] = listeners;
|
116
|
+
listener1(response);
|
117
|
+
await result1;
|
118
|
+
expect(listeners.length).toEqual(2);
|
119
|
+
listener3(response);
|
120
|
+
await result3;
|
121
|
+
expect(listeners.length).toEqual(1);
|
122
|
+
listener2(response);
|
123
|
+
await result2;
|
124
|
+
expect(listeners.length).toEqual(0);
|
125
|
+
expect(WorkerMocks.removeEventListener).toHaveBeenCalledTimes(3);
|
126
|
+
});
|
127
|
+
});
|
@@ -19,6 +19,7 @@ export interface RunCodeOptions {
|
|
19
19
|
*/
|
20
20
|
maximumMs: number;
|
21
21
|
};
|
22
|
+
abortSignal?: AbortSignal | null;
|
22
23
|
}
|
23
24
|
export declare const BaseOptions: SandboxOptions;
|
24
25
|
export interface SandboxMethods {
|
@@ -34,6 +35,7 @@ export default class WebSandbox {
|
|
34
35
|
private frame;
|
35
36
|
private connection?;
|
36
37
|
private initialised;
|
38
|
+
private frameAbortController;
|
37
39
|
static new(options?: Partial<SandboxOptions>): Promise<WebSandbox>;
|
38
40
|
private constructor();
|
39
41
|
/** Runs code in the sandbox. Can be either a string or a function */
|
@@ -49,6 +51,7 @@ export default class WebSandbox {
|
|
49
51
|
private removeMessageListener;
|
50
52
|
private runFunction;
|
51
53
|
private runCode;
|
54
|
+
private promisifyAbortSignal;
|
52
55
|
private createFrame;
|
53
56
|
private prepareFrameContent;
|
54
57
|
}
|
@@ -9,6 +9,7 @@ export const BaseOptions = {
|
|
9
9
|
minimumMs: 1000,
|
10
10
|
maximumMs: 1500,
|
11
11
|
},
|
12
|
+
abortSignal: null,
|
12
13
|
};
|
13
14
|
/** A sandbox for running untrusted code in an iframe & embedded web worker.
|
14
15
|
*
|
@@ -26,6 +27,12 @@ export default class WebSandbox {
|
|
26
27
|
this.frame = this.createFrame();
|
27
28
|
this.validateOptions(this.options);
|
28
29
|
this.initialised = this.initialise();
|
30
|
+
this.frameAbortController = new AbortController();
|
31
|
+
if (options.abortSignal) {
|
32
|
+
this.promisifyAbortSignal(options.abortSignal).catch(() => {
|
33
|
+
void this.destroyAndRebuild(this.frame.id);
|
34
|
+
});
|
35
|
+
}
|
29
36
|
}
|
30
37
|
/** Runs code in the sandbox. Can be either a string or a function */
|
31
38
|
async run(code, context, options) {
|
@@ -39,6 +46,7 @@ export default class WebSandbox {
|
|
39
46
|
* This will remove the iframe from the DOM and remove the message listener.
|
40
47
|
*/
|
41
48
|
destroy() {
|
49
|
+
this.frameAbortController.abort();
|
42
50
|
this.frame.remove();
|
43
51
|
this.removeMessageListener();
|
44
52
|
}
|
@@ -71,9 +79,13 @@ export default class WebSandbox {
|
|
71
79
|
throw new Error('maximum timeout must be less than or equal to 5000ms');
|
72
80
|
}
|
73
81
|
}
|
74
|
-
async destroyAndRebuild() {
|
82
|
+
async destroyAndRebuild(frameId) {
|
83
|
+
if (this.frame.id !== frameId) {
|
84
|
+
return;
|
85
|
+
}
|
75
86
|
this.destroy();
|
76
87
|
this.frame = this.createFrame();
|
88
|
+
this.frameAbortController = new AbortController();
|
77
89
|
await this.initialise();
|
78
90
|
}
|
79
91
|
removeMessageListener() {
|
@@ -90,22 +102,38 @@ export default class WebSandbox {
|
|
90
102
|
...this.options,
|
91
103
|
...options,
|
92
104
|
});
|
93
|
-
|
94
|
-
const timeout =
|
95
|
-
|
96
|
-
|
97
|
-
}, options?.timeout?.maximumMs ?? this.options.timeout.maximumMs);
|
98
|
-
});
|
105
|
+
const frameId = this.frame.id;
|
106
|
+
const timeout = this.promisifyAbortSignal(AbortSignal.timeout(options?.timeout?.maximumMs ?? this.options.timeout.maximumMs));
|
107
|
+
const frameAbortedSignal = this.promisifyAbortSignal(this.frameAbortController.signal);
|
108
|
+
const userAbortedSignal = options?.abortSignal ? this.promisifyAbortSignal(options.abortSignal) : null;
|
99
109
|
const taskId = generateUUID();
|
100
|
-
const task =
|
110
|
+
const task = this.connection.callRemoteMethod('startTask', {
|
101
111
|
id: taskId,
|
102
112
|
code,
|
103
113
|
context,
|
104
114
|
timeout: this.options.timeout.minimumMs,
|
105
115
|
contextVariable: options?.contextVariable ?? this.options.contextVariable,
|
106
116
|
});
|
107
|
-
|
108
|
-
|
117
|
+
const signals = [task, timeout, frameAbortedSignal, userAbortedSignal].filter((i) => i !== null);
|
118
|
+
return Promise.race(signals).catch(async (e) => {
|
119
|
+
if (e.name === 'TimeoutError') {
|
120
|
+
await this.destroyAndRebuild(frameId);
|
121
|
+
}
|
122
|
+
throw e;
|
123
|
+
});
|
124
|
+
}
|
125
|
+
promisifyAbortSignal(signal) {
|
126
|
+
return new Promise((_, reject) => {
|
127
|
+
// If the signal is already aborted, immediately throw in order to reject the promise.
|
128
|
+
if (signal.aborted) {
|
129
|
+
reject(signal.reason);
|
130
|
+
}
|
131
|
+
// Watch for 'abort' signals
|
132
|
+
signal.addEventListener('abort', () => {
|
133
|
+
// Stop the main operation
|
134
|
+
// Reject the promise with the abort reason.
|
135
|
+
reject(signal.reason);
|
136
|
+
});
|
109
137
|
});
|
110
138
|
}
|
111
139
|
createFrame() {
|
@@ -123,6 +151,7 @@ export default class WebSandbox {
|
|
123
151
|
}
|
124
152
|
iframe.srcdoc = this.prepareFrameContent();
|
125
153
|
iframe.style.display = 'none';
|
154
|
+
iframe.id = generateUUID();
|
126
155
|
container.appendChild(iframe);
|
127
156
|
return iframe;
|
128
157
|
}
|
package/models/index.d.ts
CHANGED
package/models/index.js
CHANGED
@@ -0,0 +1,36 @@
|
|
1
|
+
export type ResourceType = 'Manifest' | 'AgentGraph' | 'Javascript' | 'NodeDefinition';
|
2
|
+
export interface Resource {
|
3
|
+
type: ResourceType;
|
4
|
+
data: string;
|
5
|
+
contentLink: string;
|
6
|
+
hash: string;
|
7
|
+
link: string;
|
8
|
+
path: string;
|
9
|
+
size: number;
|
10
|
+
}
|
11
|
+
export interface Resources {
|
12
|
+
[key: string]: Resource;
|
13
|
+
}
|
14
|
+
export interface Author {
|
15
|
+
id: string;
|
16
|
+
name: string;
|
17
|
+
email: string;
|
18
|
+
}
|
19
|
+
export interface WorkflowBase {
|
20
|
+
flowId: string;
|
21
|
+
name: string;
|
22
|
+
description: string;
|
23
|
+
resources?: Resources;
|
24
|
+
type?: string;
|
25
|
+
}
|
26
|
+
export interface Workflow extends WorkflowBase {
|
27
|
+
id: string;
|
28
|
+
projectId: string;
|
29
|
+
createdBy: string;
|
30
|
+
updatedBy: string;
|
31
|
+
author: Author;
|
32
|
+
dateCreated: number;
|
33
|
+
dateUpdated: number;
|
34
|
+
latestVersion: string;
|
35
|
+
type: string;
|
36
|
+
}
|
@@ -0,0 +1 @@
|
|
1
|
+
export {};
|
package/package.json
CHANGED
@@ -1,4 +1,5 @@
|
|
1
1
|
import { RocosError } from '../models/RocosError';
|
2
|
+
import type { Workflow, WorkflowBase } from '../models/workflow/Workflow';
|
2
3
|
import { BaseServiceAbstract } from './BaseServiceAbstract';
|
3
4
|
import { IBaseService } from '../models/IBaseService';
|
4
5
|
import { IRocosSDKConfig } from '../models/IRocosSDKConfig';
|
@@ -7,65 +8,60 @@ export declare class WorkflowService extends BaseServiceAbstract implements IBas
|
|
7
8
|
protected getError(e: Error): RocosError;
|
8
9
|
getStatus(): boolean;
|
9
10
|
/**
|
10
|
-
*
|
11
|
+
* Get workflows for project
|
11
12
|
*
|
12
13
|
* @param projectId - Project Id
|
13
|
-
* @param model - Payload
|
14
14
|
*/
|
15
|
-
|
15
|
+
list(projectId: string): Promise<Workflow[]>;
|
16
16
|
/**
|
17
|
-
*
|
17
|
+
* @deprecated This method is deprecated and will be removed in a future version.
|
18
|
+
* Use list instead.
|
19
|
+
*/
|
20
|
+
getAll: (projectId: string) => Promise<Workflow[]>;
|
21
|
+
/**
|
22
|
+
* Create a workflow
|
18
23
|
*
|
19
24
|
* @param projectId - Project Id
|
20
|
-
* @param
|
21
|
-
* @param includeStats - Include stats
|
22
|
-
* @param opsId - Ops Id
|
23
|
-
* @param workflowIds - Workflow Id's
|
25
|
+
* @param model - Workflow
|
24
26
|
*/
|
25
|
-
|
27
|
+
create(projectId: string, model: WorkflowBase): Promise<Workflow>;
|
26
28
|
/**
|
27
29
|
* Get a workflow
|
28
30
|
*
|
29
31
|
* @param projectId - Project Id
|
30
32
|
* @param workflowId - Workflow Id
|
31
|
-
* @param includeInstances - Include instances
|
32
33
|
*/
|
33
|
-
|
34
|
+
get(projectId: string, workflowId: string): Promise<Workflow>;
|
35
|
+
/**
|
36
|
+
* @deprecated This method is deprecated and will be removed in a future version.
|
37
|
+
* Use get instead.
|
38
|
+
*/
|
39
|
+
getOne: (projectId: string, workflowId: string) => Promise<Workflow>;
|
34
40
|
/**
|
35
41
|
* Update a workflow
|
36
42
|
*
|
37
43
|
* @param projectId - Project Id
|
38
44
|
* @param workflowId - Workflow Id
|
39
|
-
* @param model -
|
45
|
+
* @param model - Workflow
|
40
46
|
*/
|
41
|
-
|
47
|
+
update(projectId: string, workflowId: string, model: Workflow): Promise<Workflow>;
|
42
48
|
/**
|
43
49
|
* Delete a workflow
|
44
50
|
*
|
45
51
|
* @param projectId - Project Id
|
46
52
|
* @param workflowId - Workflow Id
|
47
53
|
*/
|
48
|
-
|
49
|
-
/**
|
50
|
-
* Get all workflows for a robot
|
51
|
-
*
|
52
|
-
* @param projectId - Project Id
|
53
|
-
* @param callsign - Robot callsign
|
54
|
-
*/
|
55
|
-
getAllOfRobot(projectId: string, callsign: string): Promise<any>;
|
54
|
+
delete(projectId: string, workflowId: string): Promise<void>;
|
56
55
|
/**
|
57
|
-
*
|
56
|
+
* Get deployed workflows on robot
|
58
57
|
*
|
59
58
|
* @param projectId - Project Id
|
60
59
|
* @param callsign - Robot callsign
|
61
|
-
* @param model - Payload
|
62
60
|
*/
|
63
|
-
|
61
|
+
getDeployedWorkflows(projectId: string, callsign: string): Promise<Workflow[]>;
|
64
62
|
/**
|
65
|
-
*
|
66
|
-
*
|
67
|
-
* @param projectId - Project Id
|
68
|
-
* @param callsign - Robot callsign
|
63
|
+
* @deprecated This method is deprecated and will be removed in a future version.
|
64
|
+
* Use getDeployedWorkflow instead.
|
69
65
|
*/
|
70
|
-
getDeployedOnRobot(projectId: string, callsign: string)
|
66
|
+
getDeployedOnRobot: (projectId: string, callsign: string) => Promise<Workflow[]>;
|
71
67
|
}
|
@@ -1,4 +1,4 @@
|
|
1
|
-
import {
|
1
|
+
import { API_PROJECT_DEPLOYED_WORKFLOW_URL, API_PROJECT_WORKFLOW_ID_URL, API_PROJECT_WORKFLOW_URL, } from '../constants/api';
|
2
2
|
import { RocosError, errorCodes } from '../models/RocosError';
|
3
3
|
import { BaseServiceAbstract } from './BaseServiceAbstract';
|
4
4
|
import { RocosLogger } from '../logger/RocosLogger';
|
@@ -6,6 +6,21 @@ import { formatServiceUrl } from '../helpers/formatServiceUrl';
|
|
6
6
|
export class WorkflowService extends BaseServiceAbstract {
|
7
7
|
constructor(config) {
|
8
8
|
super(config);
|
9
|
+
/**
|
10
|
+
* @deprecated This method is deprecated and will be removed in a future version.
|
11
|
+
* Use list instead.
|
12
|
+
*/
|
13
|
+
this.getAll = this.list;
|
14
|
+
/**
|
15
|
+
* @deprecated This method is deprecated and will be removed in a future version.
|
16
|
+
* Use get instead.
|
17
|
+
*/
|
18
|
+
this.getOne = this.get;
|
19
|
+
/**
|
20
|
+
* @deprecated This method is deprecated and will be removed in a future version.
|
21
|
+
* Use getDeployedWorkflow instead.
|
22
|
+
*/
|
23
|
+
this.getDeployedOnRobot = this.getDeployedWorkflows;
|
9
24
|
this.logger = RocosLogger.getInstance(`WorkflowService(${this.config.url})`);
|
10
25
|
}
|
11
26
|
getError(e) {
|
@@ -15,62 +30,39 @@ export class WorkflowService extends BaseServiceAbstract {
|
|
15
30
|
return true;
|
16
31
|
}
|
17
32
|
/**
|
18
|
-
*
|
33
|
+
* Get workflows for project
|
19
34
|
*
|
20
35
|
* @param projectId - Project Id
|
21
|
-
* @param model - Payload
|
22
36
|
*/
|
23
|
-
|
24
|
-
|
25
|
-
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
|
26
|
-
async createOne(projectId, model) {
|
27
|
-
return this.callPut(formatServiceUrl(API_PROJECT_WORKFLOW_URL, { url: this.config.url, projectId }, this.config.insecure), model, `Failed to create workflow for ${projectId}.`);
|
37
|
+
async list(projectId) {
|
38
|
+
return this.callGet(formatServiceUrl(API_PROJECT_WORKFLOW_URL, { url: this.config.url, projectId }, this.config.insecure), `Failed to get workflows for ${projectId}.`);
|
28
39
|
}
|
29
40
|
/**
|
30
|
-
*
|
41
|
+
* Create a workflow
|
31
42
|
*
|
32
43
|
* @param projectId - Project Id
|
33
|
-
* @param
|
34
|
-
* @param includeStats - Include stats
|
35
|
-
* @param opsId - Ops Id
|
36
|
-
* @param workflowIds - Workflow Id's
|
44
|
+
* @param model - Workflow
|
37
45
|
*/
|
38
|
-
|
39
|
-
|
40
|
-
const params = {
|
41
|
-
includeRocosGraph: includeRocosGraph ? 1 : 0,
|
42
|
-
includeStats: includeStats ? 1 : 0,
|
43
|
-
};
|
44
|
-
if (opsId) {
|
45
|
-
params.opsId = opsId;
|
46
|
-
}
|
47
|
-
if (workflowIds) {
|
48
|
-
params.workflowIds = workflowIds.join(',');
|
49
|
-
}
|
50
|
-
return this.callGet(formatServiceUrl(API_PROJECT_WORKFLOW_URL, { url: this.config.url, projectId }, this.config.insecure), `Failed to get workflows for ${projectId}.`, params);
|
46
|
+
async create(projectId, model) {
|
47
|
+
return this.callPut(formatServiceUrl(API_PROJECT_WORKFLOW_URL, { url: this.config.url, projectId }, this.config.insecure), model, `Failed to create workflow for ${projectId}.`);
|
51
48
|
}
|
52
49
|
/**
|
53
50
|
* Get a workflow
|
54
51
|
*
|
55
52
|
* @param projectId - Project Id
|
56
53
|
* @param workflowId - Workflow Id
|
57
|
-
* @param includeInstances - Include instances
|
58
54
|
*/
|
59
|
-
|
60
|
-
|
61
|
-
return this.callGet(formatServiceUrl(API_PROJECT_WORKFLOW_ID_URL, { url: this.config.url, projectId, workflowId }, this.config.insecure), `Failed to get workflow for ${projectId}, workflowId ${workflowId}.`, { includeInstances: includeInstances ? 1 : 0 });
|
55
|
+
async get(projectId, workflowId) {
|
56
|
+
return this.callGet(formatServiceUrl(API_PROJECT_WORKFLOW_ID_URL, { url: this.config.url, projectId, workflowId }, this.config.insecure), `Failed to get workflow for ${projectId}, workflowId ${workflowId}.`);
|
62
57
|
}
|
63
58
|
/**
|
64
59
|
* Update a workflow
|
65
60
|
*
|
66
61
|
* @param projectId - Project Id
|
67
62
|
* @param workflowId - Workflow Id
|
68
|
-
* @param model -
|
63
|
+
* @param model - Workflow
|
69
64
|
*/
|
70
|
-
|
71
|
-
// TODO: map the response object
|
72
|
-
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
|
73
|
-
async updateOne(projectId, workflowId, model) {
|
65
|
+
async update(projectId, workflowId, model) {
|
74
66
|
return this.callPut(formatServiceUrl(API_PROJECT_WORKFLOW_ID_URL, { url: this.config.url, projectId, workflowId }, this.config.insecure), model, `Failed to update workflow for ${projectId}, workflowId ${workflowId}.`);
|
75
67
|
}
|
76
68
|
/**
|
@@ -79,40 +71,16 @@ export class WorkflowService extends BaseServiceAbstract {
|
|
79
71
|
* @param projectId - Project Id
|
80
72
|
* @param workflowId - Workflow Id
|
81
73
|
*/
|
82
|
-
|
83
|
-
async deleteOne(projectId, workflowId) {
|
74
|
+
async delete(projectId, workflowId) {
|
84
75
|
return this.callDelete(formatServiceUrl(API_PROJECT_WORKFLOW_ID_URL, { url: this.config.url, projectId, workflowId }, this.config.insecure), `Failed to delete workflow for ${projectId}, workflowId ${workflowId}.`);
|
85
76
|
}
|
86
|
-
/**
|
87
|
-
* Get all workflows for a robot
|
88
|
-
*
|
89
|
-
* @param projectId - Project Id
|
90
|
-
* @param callsign - Robot callsign
|
91
|
-
*/
|
92
|
-
// TODO: map the response object
|
93
|
-
async getAllOfRobot(projectId, callsign) {
|
94
|
-
return this.callGet(formatServiceUrl(API_PROJECT_CALLSIGN_WORKFLOW_URL, { url: this.config.url, projectId, callsign }, this.config.insecure), `Failed to get workflows for ${projectId}, callsign ${callsign}.`);
|
95
|
-
}
|
96
|
-
/**
|
97
|
-
* Update workflows for a robot
|
98
|
-
*
|
99
|
-
* @param projectId - Project Id
|
100
|
-
* @param callsign - Robot callsign
|
101
|
-
* @param model - Payload
|
102
|
-
*/
|
103
|
-
// TODO: map the request model
|
104
|
-
// TODO: map the response object
|
105
|
-
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
|
106
|
-
async updateAllForRobot(projectId, callsign, model) {
|
107
|
-
return this.callPut(formatServiceUrl(API_PROJECT_CALLSIGN_WORKFLOW_URL, { url: this.config.url, projectId, callsign }, this.config.insecure), model, `Failed to update workflows for ${projectId}, callsign ${callsign}.`);
|
108
|
-
}
|
109
77
|
/**
|
110
78
|
* Get deployed workflows on robot
|
111
79
|
*
|
112
80
|
* @param projectId - Project Id
|
113
81
|
* @param callsign - Robot callsign
|
114
82
|
*/
|
115
|
-
async
|
116
|
-
return this.callGet(formatServiceUrl(
|
83
|
+
async getDeployedWorkflows(projectId, callsign) {
|
84
|
+
return this.callGet(formatServiceUrl(API_PROJECT_DEPLOYED_WORKFLOW_URL, { url: this.config.url, projectId, callsign }, this.config.insecure), `Failed to update workflows for ${projectId}, callsign ${callsign}.`);
|
117
85
|
}
|
118
86
|
}
|