@dronedeploy/rocos-js-sdk 1.0.0-alpha-2 → 3.0.0-alpha.19

Sign up to get free protection for your applications and to get access to all the features.
Files changed (99) hide show
  1. package/IRocosSDK.d.ts +3 -26
  2. package/RocosSDK.d.ts +6 -1
  3. package/RocosSDK.js +11 -1
  4. package/api/streams/caller/CallerStreamAbstract.js +1 -1
  5. package/api/streams/command/CommandStreamAbstract.js +1 -1
  6. package/api/streams/search/SearchStreamAbstract.js +2 -2
  7. package/constants/api.d.ts +9 -5
  8. package/constants/api.js +9 -5
  9. package/grpc/conker_pb.grpc-client.js +1 -1
  10. package/grpc/conker_pb.js +1 -1
  11. package/grpc/filagree_pb.d.ts +5 -5
  12. package/grpc/filagree_pb.grpc-client.js +1 -1
  13. package/grpc/filagree_pb.js +6 -6
  14. package/grpc/google/protobuf/descriptor_pb.d.ts +2 -2
  15. package/grpc/google/protobuf/descriptor_pb.js +4 -4
  16. package/grpc/google/protobuf/empty_pb.js +1 -1
  17. package/grpc/pigeon_pb.grpc-client.js +1 -1
  18. package/grpc/pigeon_pb.js +1 -1
  19. package/grpc/rambo.uri.v1_pb.js +1 -1
  20. package/grpc/rambo.v1_pb.d.ts +1 -1
  21. package/grpc/rambo.v1_pb.grpc-client.js +1 -1
  22. package/grpc/rambo.v1_pb.js +2 -2
  23. package/grpc/serviette.uri.v1_pb.js +1 -1
  24. package/grpc/serviette.v1_pb.d.ts +2 -2
  25. package/grpc/serviette.v1_pb.grpc-client.js +1 -1
  26. package/grpc/serviette.v1_pb.js +3 -3
  27. package/grpc/slowlane_pb.d.ts +4 -4
  28. package/grpc/slowlane_pb.grpc-client.js +1 -1
  29. package/grpc/slowlane_pb.js +5 -5
  30. package/grpc/teletubby_pb.d.ts +2 -2
  31. package/grpc/teletubby_pb.grpc-client.js +1 -1
  32. package/grpc/teletubby_pb.js +8 -8
  33. package/helpers/getURLSearchParams.d.ts +2 -0
  34. package/helpers/getURLSearchParams.js +9 -0
  35. package/helpers/getURLSearchParams.spec.d.ts +1 -0
  36. package/helpers/getURLSearchParams.spec.js +19 -0
  37. package/helpers/index.d.ts +2 -0
  38. package/helpers/index.js +2 -0
  39. package/helpers/nanosecondToMillisecond.d.ts +1 -1
  40. package/helpers/nanosecondToMillisecond.js +10 -4
  41. package/helpers/nanosecondToMillisecond.spec.d.ts +1 -0
  42. package/helpers/nanosecondToMillisecond.spec.js +20 -0
  43. package/helpers/websandbox/connection.d.ts +67 -0
  44. package/helpers/websandbox/connection.js +133 -0
  45. package/helpers/websandbox/frame/frame.d.ts +12 -0
  46. package/helpers/websandbox/frame/frame.js +22 -0
  47. package/helpers/websandbox/frame/frame.source.d.ts +2 -0
  48. package/helpers/websandbox/frame/frame.source.js +5 -0
  49. package/helpers/websandbox/frame/index.d.ts +2 -0
  50. package/helpers/websandbox/frame/index.js +2 -0
  51. package/helpers/websandbox/frame/worker/index.d.ts +2 -0
  52. package/helpers/websandbox/frame/worker/index.js +2 -0
  53. package/helpers/websandbox/frame/worker/manager.d.ts +11 -0
  54. package/helpers/websandbox/frame/worker/manager.js +67 -0
  55. package/helpers/websandbox/frame/worker/manager.spec.d.ts +4 -0
  56. package/helpers/websandbox/frame/worker/manager.spec.js +127 -0
  57. package/helpers/websandbox/frame/worker/types.d.ts +11 -0
  58. package/helpers/websandbox/frame/worker/types.js +1 -0
  59. package/helpers/websandbox/frame/worker/worker.d.ts +1 -0
  60. package/helpers/websandbox/frame/worker/worker.js +74 -0
  61. package/helpers/websandbox/frame/worker/worker.source.d.ts +2 -0
  62. package/helpers/websandbox/frame/worker/worker.source.js +4 -0
  63. package/helpers/websandbox/index.d.ts +2 -0
  64. package/helpers/websandbox/index.js +2 -0
  65. package/helpers/websandbox/sandbox.d.ts +57 -0
  66. package/helpers/websandbox/sandbox.js +175 -0
  67. package/helpers/websandbox/types.d.ts +13 -0
  68. package/helpers/websandbox/types.js +1 -0
  69. package/models/RocosError.d.ts +1 -0
  70. package/models/RocosError.js +1 -0
  71. package/models/ServiceEnum.d.ts +2 -1
  72. package/models/ServiceEnum.js +1 -0
  73. package/models/asset-storage/AssetModelItem.d.ts +3 -0
  74. package/models/index.d.ts +1 -0
  75. package/models/index.js +1 -0
  76. package/models/maps/Map.d.ts +1 -3
  77. package/models/maps/Panorama.d.ts +36 -0
  78. package/models/maps/Panorama.js +1 -0
  79. package/models/workflow/Workflow.d.ts +36 -0
  80. package/models/workflow/Workflow.js +1 -0
  81. package/node/RocosSDKNode.d.ts +6 -1
  82. package/node/RocosSDKNode.js +7 -0
  83. package/package.json +5 -3
  84. package/services/AssetStorageService.d.ts +18 -3
  85. package/services/AssetStorageService.js +28 -4
  86. package/services/BaseServiceAbstract.d.ts +1 -1
  87. package/services/BaseServiceAbstract.js +2 -6
  88. package/services/BaseStreamService.js +1 -1
  89. package/services/EvaluatorService.d.ts +11 -0
  90. package/services/EvaluatorService.js +28 -0
  91. package/services/MapService.d.ts +36 -3
  92. package/services/MapService.js +47 -4
  93. package/services/TelemetryService.d.ts +1 -0
  94. package/services/TelemetryService.js +13 -1
  95. package/services/TelemetryService.spec.js +2 -2
  96. package/services/WorkflowService.d.ts +25 -29
  97. package/services/WorkflowService.js +30 -62
  98. package/services/index.d.ts +1 -0
  99. package/services/index.js +1 -0
@@ -1,5 +1,5 @@
1
1
  /* eslint-disable */
2
- // @generated by protobuf-ts 2.9.1 with parameter ts_nocheck,eslint_disable,add_pb_suffix,client_grpc1,optimize_code_size
2
+ // @generated by protobuf-ts 2.9.1 with parameter ts_nocheck,eslint_disable,add_pb_suffix,client_grpc1,optimize_code_size,long_type_string
3
3
  // @generated from protobuf file "teletubby.proto" (package "teletubby.v1", syntax proto3)
4
4
  // tslint:disable
5
5
  // @ts-nocheck
@@ -60,14 +60,14 @@ class TelemetryMessage$Type extends MessageType {
60
60
  { no: 1, name: "source", kind: "scalar", T: 9 /*ScalarType.STRING*/ },
61
61
  { no: 2, name: "payload", kind: "scalar", T: 12 /*ScalarType.BYTES*/ },
62
62
  { no: 3, name: "callsign", kind: "scalar", T: 9 /*ScalarType.STRING*/ },
63
- { no: 4, name: "created", kind: "scalar", T: 3 /*ScalarType.INT64*/, L: 0 /*LongType.BIGINT*/ },
64
- { no: 5, name: "seq", kind: "scalar", T: 4 /*ScalarType.UINT64*/, L: 0 /*LongType.BIGINT*/ },
63
+ { no: 4, name: "created", kind: "scalar", T: 3 /*ScalarType.INT64*/ },
64
+ { no: 5, name: "seq", kind: "scalar", T: 4 /*ScalarType.UINT64*/ },
65
65
  { no: 6, name: "meta", kind: "map", K: 9 /*ScalarType.STRING*/, V: { kind: "scalar", T: 9 /*ScalarType.STRING*/ } },
66
66
  { no: 7, name: "uid", kind: "scalar", T: 9 /*ScalarType.STRING*/ }
67
67
  ]);
68
68
  }
69
69
  create(value) {
70
- const message = { source: "", payload: new Uint8Array(0), callsign: "", created: 0n, seq: 0n, meta: {}, uid: "" };
70
+ const message = { source: "", payload: new Uint8Array(0), callsign: "", created: "0", seq: "0", meta: {}, uid: "" };
71
71
  globalThis.Object.defineProperty(message, MESSAGE_TYPE, { enumerable: false, value: this });
72
72
  if (value !== undefined)
73
73
  reflectionMergePartial(this, message, value);
@@ -88,10 +88,10 @@ class TelemetryMessage$Type extends MessageType {
88
88
  message.callsign = reader.string();
89
89
  break;
90
90
  case /* int64 created */ 4:
91
- message.created = reader.int64().toBigInt();
91
+ message.created = reader.int64().toString();
92
92
  break;
93
93
  case /* uint64 seq */ 5:
94
- message.seq = reader.uint64().toBigInt();
94
+ message.seq = reader.uint64().toString();
95
95
  break;
96
96
  case /* map<string, string> meta */ 6:
97
97
  this.binaryReadMap6(message.meta, reader, options);
@@ -137,10 +137,10 @@ class TelemetryMessage$Type extends MessageType {
137
137
  if (message.callsign !== "")
138
138
  writer.tag(3, WireType.LengthDelimited).string(message.callsign);
139
139
  /* int64 created = 4; */
140
- if (message.created !== 0n)
140
+ if (message.created !== "0")
141
141
  writer.tag(4, WireType.Varint).int64(message.created);
142
142
  /* uint64 seq = 5; */
143
- if (message.seq !== 0n)
143
+ if (message.seq !== "0")
144
144
  writer.tag(5, WireType.Varint).uint64(message.seq);
145
145
  /* map<string, string> meta = 6; */
146
146
  for (let k of Object.keys(message.meta))
@@ -0,0 +1,2 @@
1
+ export type QueryParams = Record<string, string | number | boolean> | URLSearchParams;
2
+ export declare const getURLSearchParams: (params: QueryParams) => URLSearchParams;
@@ -0,0 +1,9 @@
1
+ export const getURLSearchParams = (params) => {
2
+ if (params instanceof URLSearchParams)
3
+ return params;
4
+ const stringParams = Object.entries(params ?? {}).reduce((acc, [key, value]) => {
5
+ acc[key] = value.toString();
6
+ return acc;
7
+ }, {});
8
+ return new URLSearchParams(stringParams);
9
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,19 @@
1
+ import { getURLSearchParams } from './getURLSearchParams';
2
+ describe('getURLSearchParams', () => {
3
+ it('Should return the original param if URLSearchParams', () => {
4
+ const param = new URLSearchParams();
5
+ const searchParam = getURLSearchParams(param);
6
+ expect(searchParam).toBe(param);
7
+ });
8
+ it('Should a new URLSearchParams ', () => {
9
+ const param = {
10
+ foo: 'bar',
11
+ bar: true,
12
+ foobar: 123,
13
+ };
14
+ const searchParam = getURLSearchParams(param);
15
+ expect(searchParam.get('foo')).toBe('bar');
16
+ expect(searchParam.get('bar')).toBe('true');
17
+ expect(searchParam.get('foobar')).toBe('123');
18
+ });
19
+ });
@@ -1,3 +1,5 @@
1
1
  export * from './average';
2
2
  export * from './standardDeviation';
3
3
  export * from './generateUUID';
4
+ export * from './getURLSearchParams';
5
+ export * from './websandbox';
package/helpers/index.js CHANGED
@@ -1,3 +1,5 @@
1
1
  export * from './average';
2
2
  export * from './standardDeviation';
3
3
  export * from './generateUUID';
4
+ export * from './getURLSearchParams';
5
+ export * from './websandbox';
@@ -1 +1 @@
1
- export declare const nanosecondToMillisecond: (nanoNum: number | bigint) => number;
1
+ export declare const nanosecondToMillisecond: (nano: number | string) => number;
@@ -1,6 +1,12 @@
1
- export const nanosecondToMillisecond = (nanoNum) => {
2
- if (typeof nanoNum === 'bigint') {
3
- return Number(nanoNum / 1000000n);
1
+ function isNumber(n) {
2
+ return typeof n === 'number';
3
+ }
4
+ export const nanosecondToMillisecond = (nano) => {
5
+ if (isNumber(nano)) {
6
+ return nano / 1e6;
4
7
  }
5
- return nanoNum / 1e6;
8
+ if (nano.length < 16) {
9
+ return Number(nano) / 1e6;
10
+ }
11
+ return Number(nano.slice(0, -6) + '.' + nano.slice(-6));
6
12
  };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,20 @@
1
+ import { nanosecondToMillisecond } from './nanosecondToMillisecond';
2
+ describe('nanosecondToMillisecond', () => {
3
+ it.each `
4
+ input | expected
5
+ ${'0.0001'} | ${0.0000000001}
6
+ ${'1'} | ${0.000001}
7
+ ${'1000000'} | ${1}
8
+ ${'10000000'} | ${10}
9
+ ${'-100000006'} | ${-100.000006}
10
+ ${'1000000000000000000'} | ${1000000000000}
11
+ ${'1234567891011100001'} | ${1234567891011.100001}
12
+ ${'1234567891011100000'} | ${1234567891011.1}
13
+ ${0.0001} | ${0.0000000001}
14
+ ${1} | ${0.000001}
15
+ ${1000000} | ${1}
16
+ ${1000000000000001} | ${1000000000.000001}
17
+ `('should convert $input to $expected', ({ input, expected }) => {
18
+ expect(nanosecondToMillisecond(input)).toBe(expected);
19
+ });
20
+ });
@@ -0,0 +1,67 @@
1
+ import { APIDeclaration } from './types';
2
+ export interface ConnectionOptions {
3
+ allowedSenderOrigin?: string;
4
+ debugMode: boolean;
5
+ }
6
+ type ListenerCallback = (e: MessageEvent<Message>) => void;
7
+ declare enum MessageType {
8
+ RESPONSE = "response",
9
+ MESSAGE = "message"
10
+ }
11
+ interface BaseMessageData {
12
+ type: MessageType;
13
+ callId: string;
14
+ }
15
+ interface ResponseData extends BaseMessageData {
16
+ type: MessageType.RESPONSE;
17
+ success: boolean;
18
+ result: unknown;
19
+ }
20
+ interface MessageData extends BaseMessageData {
21
+ type: MessageType.MESSAGE;
22
+ methodName: string;
23
+ arguments: unknown[];
24
+ }
25
+ type Message = MessageData | ResponseData;
26
+ export default class Connection<Local extends APIDeclaration<Local>, Remote extends APIDeclaration<Remote>> {
27
+ private readonly name;
28
+ private incrementalID;
29
+ private readonly options;
30
+ private readonly postMessageInternal;
31
+ private callbacks;
32
+ private serviceMethods;
33
+ constructor(name: string, postMessage: typeof window.postMessage, methods: Local, registerOnMessageListener: (listener: ListenerCallback) => void, options?: Partial<ConnectionOptions>);
34
+ /** Call a remote method
35
+ *
36
+ * returns a promise that resolves when the remote responds
37
+ *
38
+ * @param name - name of remote method to call
39
+ * @param args - arguments to pass to remote method
40
+ */
41
+ callRemoteMethod<Method extends keyof Remote>(name: Method, ...args: Parameters<Remote[Method]>): Promise<ReturnType<Remote[Method]>>;
42
+ private onMessageListener;
43
+ private callLocalMethod;
44
+ /** Respond to remote call
45
+ *
46
+ * @param id - remote call ID
47
+ * @param result - result to pass to calling function
48
+ * @param success - whether the call was successful
49
+ */
50
+ private responseOtherSide;
51
+ /** Store a callback to be called when the remote responds
52
+ *
53
+ * @param success - callback to be called on success
54
+ * @param failure - callback to be called on failure
55
+ */
56
+ private registerCallback;
57
+ /** Calls and deletes stored callback
58
+ *
59
+ * @param callId - ID of callback to call
60
+ * @param success - whether the call was successful
61
+ * @param result - result of remote call
62
+ */
63
+ private popCallback;
64
+ private postMessage;
65
+ private log;
66
+ }
67
+ export {};
@@ -0,0 +1,133 @@
1
+ var MessageType;
2
+ (function (MessageType) {
3
+ MessageType["RESPONSE"] = "response";
4
+ MessageType["MESSAGE"] = "message";
5
+ })(MessageType || (MessageType = {}));
6
+ const defaultOptions = {
7
+ allowedSenderOrigin: undefined,
8
+ debugMode: false,
9
+ };
10
+ export default class Connection {
11
+ constructor(name, postMessage, methods, registerOnMessageListener, options = {}) {
12
+ this.callbacks = new Map();
13
+ this.serviceMethods = new Map();
14
+ this.name = name;
15
+ this.options = { ...defaultOptions, ...options };
16
+ this.log('Created connection w/ allowedOrigin:', this.options.allowedSenderOrigin);
17
+ this.serviceMethods = new Map(Object.entries(methods));
18
+ // Assign a random starting ID to this connection
19
+ const [id] = crypto.getRandomValues(new Uint32Array(1));
20
+ this.incrementalID = id;
21
+ this.postMessageInternal = postMessage;
22
+ registerOnMessageListener((e) => this.onMessageListener(e));
23
+ }
24
+ /** Call a remote method
25
+ *
26
+ * returns a promise that resolves when the remote responds
27
+ *
28
+ * @param name - name of remote method to call
29
+ * @param args - arguments to pass to remote method
30
+ */
31
+ callRemoteMethod(name, ...args) {
32
+ this.log('Calling Remote Method', {
33
+ name,
34
+ args,
35
+ });
36
+ return new Promise((resolve, reject) => {
37
+ const id = this.registerCallback(resolve, reject);
38
+ this.postMessage({
39
+ callId: id,
40
+ type: MessageType.MESSAGE,
41
+ methodName: name,
42
+ arguments: args,
43
+ });
44
+ });
45
+ }
46
+ onMessageListener(e) {
47
+ this.log('Received message', e);
48
+ const { data } = e;
49
+ const { allowedSenderOrigin } = this.options;
50
+ if (allowedSenderOrigin && e.origin !== allowedSenderOrigin) {
51
+ console.warn(`Received message from invalid origin: ${e.origin}`);
52
+ }
53
+ switch (data.type) {
54
+ case MessageType.RESPONSE:
55
+ this.popCallback(data.callId, data.success, data.result);
56
+ return;
57
+ case MessageType.MESSAGE:
58
+ this.callLocalMethod(data.methodName, data.arguments)
59
+ .then((res) => this.responseOtherSide(data.callId, res))
60
+ .catch((err) => this.responseOtherSide(data.callId, err, false));
61
+ }
62
+ }
63
+ async callLocalMethod(methodName, args) {
64
+ this.log('calling local method', methodName, args);
65
+ const method = this.serviceMethods.get(methodName);
66
+ if (!method) {
67
+ throw new Error(`service method ${methodName} not found`);
68
+ }
69
+ return method(...args);
70
+ }
71
+ /** Respond to remote call
72
+ *
73
+ * @param id - remote call ID
74
+ * @param result - result to pass to calling function
75
+ * @param success - whether the call was successful
76
+ */
77
+ responseOtherSide(id, result, success = true) {
78
+ this.log('responding to remote call', { id, result, success });
79
+ const doPost = (result) => {
80
+ this.postMessage({
81
+ callId: id,
82
+ type: MessageType.RESPONSE,
83
+ success,
84
+ result,
85
+ });
86
+ };
87
+ try {
88
+ doPost(result);
89
+ }
90
+ catch (err) {
91
+ if (err instanceof DOMException) {
92
+ doPost(JSON.parse(JSON.stringify(result)));
93
+ }
94
+ }
95
+ }
96
+ /** Store a callback to be called when the remote responds
97
+ *
98
+ * @param success - callback to be called on success
99
+ * @param failure - callback to be called on failure
100
+ */
101
+ registerCallback(success, failure) {
102
+ const id = (++this.incrementalID).toString();
103
+ this.log('registering callback for id', id);
104
+ this.callbacks.set(id, { success, failure });
105
+ return id;
106
+ }
107
+ /** Calls and deletes stored callback
108
+ *
109
+ * @param callId - ID of callback to call
110
+ * @param success - whether the call was successful
111
+ * @param result - result of remote call
112
+ */
113
+ popCallback(callId, success, result) {
114
+ this.log('calling callback for id', callId, { success, result });
115
+ const callbacks = this.callbacks.get(callId);
116
+ if (success) {
117
+ callbacks?.success(result);
118
+ }
119
+ else {
120
+ callbacks?.failure(result);
121
+ }
122
+ this.callbacks.delete(callId);
123
+ }
124
+ postMessage(data, targetOrigin = '*') {
125
+ this.log('sending message', { data, targetOrigin });
126
+ this.postMessageInternal(data, targetOrigin);
127
+ }
128
+ log(...args) {
129
+ if (this.options.debugMode) {
130
+ console.debug(`[${this.name}]`, ...args);
131
+ }
132
+ }
133
+ }
@@ -0,0 +1,12 @@
1
+ import { Task } from '../types';
2
+ export interface FrameMethods {
3
+ startTask: (task: Task) => unknown;
4
+ }
5
+ declare class Frame {
6
+ private connection;
7
+ private workerManager;
8
+ constructor();
9
+ private runCode;
10
+ }
11
+ declare const frame: Frame;
12
+ export default frame;
@@ -0,0 +1,22 @@
1
+ // this file is bundled via webpack and included in the iframe source
2
+ import Connection from '../connection';
3
+ import WorkerManager from './worker';
4
+ class Frame {
5
+ constructor() {
6
+ const isDebugMode = !!window?.debugMode;
7
+ this.connection = new Connection('FRAME', window.parent.postMessage.bind(window.parent), {
8
+ startTask: this.runCode.bind(this),
9
+ }, (listener) => {
10
+ window.addEventListener('message', listener);
11
+ }, {
12
+ debugMode: isDebugMode,
13
+ });
14
+ void this.connection.callRemoteMethod('iframeInitialised');
15
+ this.workerManager = new WorkerManager();
16
+ }
17
+ async runCode(task) {
18
+ return this.workerManager.execute(task);
19
+ }
20
+ }
21
+ const frame = new Frame();
22
+ export default frame;
@@ -0,0 +1,2 @@
1
+ declare const source: string;
2
+ export default source;
@@ -0,0 +1,5 @@
1
+ // Auto-generated file
2
+ /* eslint-disable */
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.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
+ export default source;
@@ -0,0 +1,2 @@
1
+ import source from './frame.source';
2
+ export default source;
@@ -0,0 +1,2 @@
1
+ import source from './frame.source';
2
+ export default source;
@@ -0,0 +1,2 @@
1
+ import Manager from './manager';
2
+ export default Manager;
@@ -0,0 +1,2 @@
1
+ import Manager from './manager';
2
+ export default Manager;
@@ -0,0 +1,11 @@
1
+ import { Task } from '../../types';
2
+ export default class Manager {
3
+ private worker;
4
+ private messageListeners;
5
+ constructor();
6
+ execute(task: Task): Promise<unknown>;
7
+ terminate(): void;
8
+ private runTask;
9
+ private createWorker;
10
+ private removeMessageListener;
11
+ }
@@ -0,0 +1,67 @@
1
+ // this token (__WORKER_SOURCE__) is replaced by webpack with the source of the worker
2
+ const WORKER_SOURCE = '__WORKER_SOURCE__';
3
+ export default class Manager {
4
+ constructor() {
5
+ this.messageListeners = new Map();
6
+ this.worker = this.createWorker();
7
+ }
8
+ async execute(task) {
9
+ const workerTask = {
10
+ ...task,
11
+ contextVariable: task.contextVariable ?? 'ctx',
12
+ };
13
+ const result = this.runTask(workerTask);
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);
29
+ });
30
+ }
31
+ terminate() {
32
+ for (const listener of this.messageListeners.values()) {
33
+ this.worker.removeEventListener('message', listener);
34
+ }
35
+ this.worker.terminate();
36
+ this.worker = this.createWorker();
37
+ }
38
+ runTask(task) {
39
+ return new Promise((resolve, reject) => {
40
+ const listener = (event) => {
41
+ const { data } = event;
42
+ if (data.id === task.id) {
43
+ if (data.success) {
44
+ resolve(data.result);
45
+ }
46
+ else {
47
+ reject(data.result);
48
+ }
49
+ }
50
+ };
51
+ this.messageListeners.set(task.id, listener);
52
+ this.worker.addEventListener('message', listener);
53
+ this.worker.postMessage(task);
54
+ });
55
+ }
56
+ createWorker() {
57
+ const blob = URL.createObjectURL(new Blob([WORKER_SOURCE], { type: 'application/javascript' }));
58
+ return new Worker(blob);
59
+ }
60
+ removeMessageListener(id) {
61
+ const listener = this.messageListeners.get(id);
62
+ if (!listener) {
63
+ return;
64
+ }
65
+ this.worker.removeEventListener('message', listener);
66
+ }
67
+ }
@@ -0,0 +1,4 @@
1
+ /**
2
+ * @jest-environment jsdom
3
+ */
4
+ export {};
@@ -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
+ });
@@ -0,0 +1,11 @@
1
+ export interface WorkerResult {
2
+ id: string;
3
+ result: unknown;
4
+ success: boolean;
5
+ }
6
+ export interface WorkerTask {
7
+ id: string;
8
+ code: string;
9
+ contextVariable: string;
10
+ context?: unknown;
11
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ export {};