@momo2555/koppeliajs 0.0.161 → 0.0.163

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.
@@ -10,9 +10,9 @@ export class KoppeliaWebsocket {
10
10
  openCallback;
11
11
  /* ------ PUBLIC ------ */
12
12
  /**
13
- * Constructor of the Koppelia websocket class
14
- * @param websocketUrl
15
- * @param timeout
13
+ * Initializes the Koppelia WebSocket client.
14
+ * @param websocketUrl The URL of the WebSocket server to connect to.
15
+ * @param timeout The maximum time in milliseconds to wait for a response before timing out a request. Defaults to 20000ms.
16
16
  */
17
17
  constructor(websocketUrl, timeout = DEFAULT_WS_TIMEOUT) {
18
18
  if (!import.meta.env.SSR) {
@@ -28,51 +28,51 @@ export class KoppeliaWebsocket {
28
28
  this.websocketUrl = websocketUrl;
29
29
  }
30
30
  /**
31
- * Send a new request: Add a request Id to the request and add it to the ongoing requests
32
- * Add an interval to timeout when there is no response after a certain amount of time
33
- * @param data
34
- * @param callback
31
+ * Sends a new message request through the WebSocket.
32
+ * Automatically generates a request ID, registers the request as ongoing, and sets a timeout.
33
+ * @param data The message payload to send.
34
+ * @param callback Optional callback to be executed when a response to this specific request is received.
35
35
  */
36
36
  send(data, callback) {
37
37
  if (this.socket === undefined) {
38
- logger.log("KoppeliaWebsocket::send(): Koppelia websocket client was not instancieated");
38
+ logger.log("KoppeliaWebsocket::send(): Koppelia websocket client was not instantiated");
39
39
  return;
40
40
  }
41
- // Create a request id
42
41
  data.generateRequestId();
43
42
  this._addNewRequest(data.getRequestId(), callback);
44
- // Send the request
45
43
  const serializedMessage = JSON.stringify(data.toObject());
46
44
  logger.log("sending message", serializedMessage);
47
45
  this.socket.send(serializedMessage);
48
- // set a timeout
49
46
  window.setTimeout(() => this._deleteRequest(data.getRequestId()), this.timeout);
50
47
  ;
51
48
  }
52
49
  /**
53
- * Add a receive callback
54
- * @param callback
50
+ * Registers a global callback to be triggered whenever a message is received.
51
+ * @param callback The function to execute upon receiving a message.
55
52
  */
56
53
  onReceive(callback) {
57
54
  this.receiveCallbacks.push(callback);
58
55
  }
59
56
  /**
60
- * Define a callback for the websocket open event
61
- * @param callback
57
+ * Registers a callback to be triggered when the WebSocket connection successfully opens.
58
+ * @param callback The function to execute upon connection.
62
59
  */
63
60
  onOpen(callback) {
64
61
  this.openCallback = callback;
65
62
  }
66
63
  /* ------ PRIVATE ------ */
64
+ /**
65
+ * Establishes the WebSocket connection.
66
+ * @param websockerUrl The URL of the WebSocket server.
67
+ */
67
68
  _connectWebsocket(websockerUrl) {
68
69
  this.socket = new WebSocket(websockerUrl);
69
70
  }
70
71
  /**
71
- * Handle a websocket response
72
- * - Execute a callback of a reception if a request was send before (by checking ongoing request)
73
- * - Execute a callbacj for a genral reception response
74
- * @param data
75
- * @returns
72
+ * Handles incoming WebSocket responses.
73
+ * Checks if the message corresponds to an ongoing request. If so, triggers its specific callback.
74
+ * Otherwise, broadcasts the message to all global receive callbacks.
75
+ * @param data The raw data payload received from the WebSocket.
76
76
  */
77
77
  _handleWebsocketResponse(data) {
78
78
  if (data === undefined) {
@@ -81,13 +81,10 @@ export class KoppeliaWebsocket {
81
81
  let message = new Message();
82
82
  message.parse(data);
83
83
  if (message.getRequestId() !== undefined) {
84
- // There is a request id, check if it's a response
85
84
  let onGoing = this._getOnGoingRequest(message.getRequestId());
86
85
  if (onGoing) {
87
- // check if the callback exists
88
86
  if (onGoing.callback)
89
87
  onGoing.callback(message);
90
- // otherwise do not execute callback and delete the request from ongoing
91
88
  this._deleteRequest(message.getRequestId());
92
89
  return;
93
90
  }
@@ -97,53 +94,52 @@ export class KoppeliaWebsocket {
97
94
  }
98
95
  }
99
96
  /**
100
- * Init all websocker events
97
+ * Initializes all WebSocket event listeners (open, message, close).
98
+ * Handles automatic reconnection on connection close or error.
101
99
  */
102
100
  _setupEvents() {
103
101
  if (this.socket === undefined) {
104
- logger.log("KoppeliaWebsocket::_setupEvents(): Koppelia websocket client was not instancieated");
102
+ logger.log("KoppeliaWebsocket::_setupEvents(): Koppelia websocket client was not instantiated");
105
103
  return;
106
104
  }
107
- // handle web socker opening
108
105
  this.socket.addEventListener('open', (e) => {
109
106
  if (this.openCallback)
110
107
  this.openCallback();
111
108
  });
112
- // handle web socket reception
113
109
  this.socket.addEventListener('message', (e) => {
114
110
  let data = JSON.parse(e.data);
115
111
  this._handleWebsocketResponse(data);
116
112
  });
117
- // handle connection close (if an error occure)
118
113
  this.socket.onclose = (event) => {
119
- logger.log(`Connection closed ${event.reason}, code=${event.code}, retry onnection ...`);
114
+ logger.log(`Connection closed ${event.reason}, code=${event.code}, retry connection ...`);
120
115
  setTimeout(() => { this._connectWebsocket(this.websocketUrl); this._setupEvents(); }, 1000);
121
116
  };
122
117
  }
123
118
  /**
124
- * Timeout the request if there is no response
125
- * To timout the response, the function simply delete the id from on going request list
126
- * @param requestId Id of the request
119
+ * Retrieves the index of an ongoing request in the internal list.
120
+ * @param requestId The unique identifier of the request.
121
+ * @returns The array index of the request, or -1 if not found.
127
122
  */
128
123
  _getRequestIndex(requestId) {
129
124
  return this.onGoingRequests.findIndex((element) => {
130
125
  if (!element) {
131
- return false; // Skip empty slots
126
+ return false;
132
127
  }
133
128
  return element.requestId === requestId;
134
129
  });
135
130
  }
136
131
  /**
137
- * Delete the request from the list of onGoing Requests
138
- * @param requestId
132
+ * Removes a request from the ongoing requests list.
133
+ * Used both when a request is successfully resolved or when it times out.
134
+ * @param requestId The unique identifier of the request to remove.
139
135
  */
140
136
  _deleteRequest(requestId) {
141
137
  this.onGoingRequests = this.onGoingRequests.filter((element) => element.requestId !== requestId);
142
138
  }
143
139
  /**
144
- * get the Ongoing the request and get theh callback
145
- * @param requestId
146
- * @returns
140
+ * Retrieves an ongoing request object by its ID.
141
+ * @param requestId The unique identifier of the request.
142
+ * @returns The ongoing request object, or undefined if not found.
147
143
  */
148
144
  _getOnGoingRequest(requestId) {
149
145
  let requestIndex = this._getRequestIndex(requestId);
@@ -152,9 +148,9 @@ export class KoppeliaWebsocket {
152
148
  return this.onGoingRequests[requestIndex];
153
149
  }
154
150
  /**
155
- * Add a new request to ongoing requests
156
- * @param requestId
157
- * @param callback
151
+ * Registers a new request in the ongoing requests list.
152
+ * @param requestId The unique identifier generated for the request.
153
+ * @param callback Optional callback to trigger when the response arrives.
158
154
  */
159
155
  _addNewRequest(requestId, callback) {
160
156
  this.onGoingRequests.push({ requestId: requestId, callback: callback });
@@ -25,7 +25,7 @@ export declare enum MessageType {
25
25
  ERROR = "error",
26
26
  CLOSE = "close"
27
27
  }
28
- type MessagetHeader = {
28
+ type MessageHeader = {
29
29
  id: string;
30
30
  type: string;
31
31
  from: string;
@@ -45,76 +45,93 @@ type DirectRequest = {
45
45
  };
46
46
  };
47
47
  /**
48
- * The koppelia protocol
48
+ * Defines the core Koppelia protocol message structure used for all network communications.
49
49
  */
50
50
  export declare class Message {
51
- header: MessagetHeader;
51
+ header: MessageHeader;
52
52
  data: MessageData;
53
53
  request: DirectRequest;
54
54
  event: MessageEvent;
55
55
  constructor();
56
56
  /**
57
- * Parse a json request received from the network
58
- * @param data
57
+ * Parses a raw JSON request received from the network into the Message object.
58
+ * @param data The raw data object to parse.
59
59
  */
60
60
  parse(data: AnyRequest): void;
61
61
  /**
62
- * Convert the request to json, to be sent on the network
63
- * @returns
62
+ * Serializes the Message object into a plain JavaScript object for network transmission.
63
+ * @returns The serialized message object.
64
64
  */
65
65
  toObject(): AnyRequest;
66
66
  /**
67
- * Set the source device, type and address (if there is address)
68
- * @param type
69
- * @param address
67
+ * Sets the routing source information for the message.
68
+ * @param type The peer type initiating the message.
69
+ * @param address The specific address of the source (defaults to empty string).
70
70
  */
71
71
  setSource(type: PeerType, address?: string): void;
72
72
  /**
73
- * Set the destination device, type and address
74
- * @param type
75
- * @param address
73
+ * Sets the routing destination information for the message.
74
+ * @param type The intended peer type receiver.
75
+ * @param address The specific address of the destination (defaults to empty string).
76
76
  */
77
77
  setDestination(type: PeerType, address?: string): void;
78
78
  /**
79
- * Get event name of the request, if it is an event
80
- * @returns
79
+ * Retrieves the event name of the message.
80
+ * @returns The event string.
81
81
  */
82
82
  getEvent(): MessageEvent;
83
83
  /**
84
- * Set the type of the request
85
- * @param type
84
+ * Sets the primary type of the message.
85
+ * @param type The MessageType to assign.
86
86
  */
87
87
  setType(type: MessageType): void;
88
88
  /**
89
- * Set an event to the request
90
- * @param event
89
+ * Configures the message as an event request.
90
+ * @param event The name of the event.
91
91
  */
92
92
  setEvent(event: MessageEvent): void;
93
93
  /**
94
- * Add a param if the request is request type
95
- * @param key
96
- * @param value
94
+ * Adds a parameter to the request payload.
95
+ * @param key The parameter key.
96
+ * @param value The parameter value.
97
97
  */
98
98
  addParam(key: string, value: any): void;
99
99
  /**
100
- * Add data to the request
101
- * @param key
102
- * @param value
100
+ * Adds a key-value pair to the message data payload.
101
+ * @param key The data key.
102
+ * @param value The data value.
103
103
  */
104
104
  addData(key: string, value: any): void;
105
105
  /**
106
- *
107
- * @param data
106
+ * Overwrites the entire data payload of the message.
107
+ * @param data The new MessageData object.
108
108
  */
109
109
  setData(data: MessageData): void;
110
110
  /**
111
- * Set a new request with a request name
112
- * @param execName name of
111
+ * Configures the message as a direct request and sets its execution target name.
112
+ * @param execName The name of the action/command to execute.
113
113
  */
114
114
  setRequest(execName: string): void;
115
+ /**
116
+ * Retrieves a specific parameter from the request payload.
117
+ * @param paramName The key of the parameter to fetch.
118
+ * @param def The default value to return if the parameter is not found (defaults to null).
119
+ * @returns The parameter value, or the default value.
120
+ */
115
121
  getParam(paramName: string, def?: any): any;
122
+ /**
123
+ * Configures the message as an identification broadcast.
124
+ * @param peerToIdentify The peer type identifying itself.
125
+ */
116
126
  setIdentification(peerToIdentify: PeerType): void;
127
+ /**
128
+ * Generates and assigns a unique UUID for the message header.
129
+ */
117
130
  generateRequestId(): void;
131
+ /**
132
+ * Retrieves the unique identifier of the message.
133
+ * @returns The generated UUID string.
134
+ */
118
135
  getRequestId(): string;
119
136
  }
120
137
  export {};
@@ -1,4 +1,4 @@
1
- import { v4 as uuidv4 } from 'uuid';
1
+ import { v4 as uuidv4 } from "uuid";
2
2
  export var PeerType;
3
3
  (function (PeerType) {
4
4
  PeerType["MAESTRO"] = "maestro";
@@ -11,7 +11,6 @@ export var PeerType;
11
11
  PeerType["NONE"] = "none";
12
12
  PeerType["BROADCAST"] = "broadcast";
13
13
  })(PeerType || (PeerType = {}));
14
- ;
15
14
  export var MessageType;
16
15
  (function (MessageType) {
17
16
  MessageType["EMPTY"] = "empty";
@@ -27,7 +26,7 @@ export var MessageType;
27
26
  MessageType["CLOSE"] = "close";
28
27
  })(MessageType || (MessageType = {}));
29
28
  /**
30
- * The koppelia protocol
29
+ * Defines the core Koppelia protocol message structure used for all network communications.
31
30
  */
32
31
  export class Message {
33
32
  header;
@@ -47,13 +46,13 @@ export class Message {
47
46
  this.data = {};
48
47
  this.request = {
49
48
  exec: "",
50
- params: {}
49
+ params: {},
51
50
  };
52
51
  this.event = "";
53
52
  }
54
53
  /**
55
- * Parse a json request received from the network
56
- * @param data
54
+ * Parses a raw JSON request received from the network into the Message object.
55
+ * @param data The raw data object to parse.
57
56
  */
58
57
  parse(data) {
59
58
  if (data.header !== undefined) {
@@ -79,88 +78,94 @@ export class Message {
79
78
  }
80
79
  }
81
80
  /**
82
- * Convert the request to json, to be sent on the network
83
- * @returns
81
+ * Serializes the Message object into a plain JavaScript object for network transmission.
82
+ * @returns The serialized message object.
84
83
  */
85
84
  toObject() {
86
85
  return {
87
86
  header: this.header,
88
87
  request: this.request,
89
88
  data: this.data,
90
- event: this.event
89
+ event: this.event,
91
90
  };
92
91
  }
93
92
  /**
94
- * Set the source device, type and address (if there is address)
95
- * @param type
96
- * @param address
93
+ * Sets the routing source information for the message.
94
+ * @param type The peer type initiating the message.
95
+ * @param address The specific address of the source (defaults to empty string).
97
96
  */
98
97
  setSource(type, address = "") {
99
98
  this.header.from = type;
100
99
  this.header.from_addr = address;
101
100
  }
102
101
  /**
103
- * Set the destination device, type and address
104
- * @param type
105
- * @param address
102
+ * Sets the routing destination information for the message.
103
+ * @param type The intended peer type receiver.
104
+ * @param address The specific address of the destination (defaults to empty string).
106
105
  */
107
106
  setDestination(type, address = "") {
108
107
  this.header.to = type;
109
108
  this.header.to_addr = address;
110
109
  }
111
110
  /**
112
- * Get event name of the request, if it is an event
113
- * @returns
111
+ * Retrieves the event name of the message.
112
+ * @returns The event string.
114
113
  */
115
114
  getEvent() {
116
115
  return this.event;
117
116
  }
118
117
  /**
119
- * Set the type of the request
120
- * @param type
118
+ * Sets the primary type of the message.
119
+ * @param type The MessageType to assign.
121
120
  */
122
121
  setType(type) {
123
122
  this.header.type = type;
124
123
  }
125
124
  /**
126
- * Set an event to the request
127
- * @param event
125
+ * Configures the message as an event request.
126
+ * @param event The name of the event.
128
127
  */
129
128
  setEvent(event) {
130
129
  this.header.type = MessageType.REQUEST;
131
130
  this.event = event;
132
131
  }
133
132
  /**
134
- * Add a param if the request is request type
135
- * @param key
136
- * @param value
133
+ * Adds a parameter to the request payload.
134
+ * @param key The parameter key.
135
+ * @param value The parameter value.
137
136
  */
138
137
  addParam(key, value) {
139
138
  this.request.params[key] = value;
140
139
  }
141
140
  /**
142
- * Add data to the request
143
- * @param key
144
- * @param value
141
+ * Adds a key-value pair to the message data payload.
142
+ * @param key The data key.
143
+ * @param value The data value.
145
144
  */
146
145
  addData(key, value) {
147
146
  this.data[key] = value;
148
147
  }
149
148
  /**
150
- *
151
- * @param data
149
+ * Overwrites the entire data payload of the message.
150
+ * @param data The new MessageData object.
152
151
  */
153
152
  setData(data) {
154
153
  this.data = data;
155
154
  }
156
155
  /**
157
- * Set a new request with a request name
158
- * @param execName name of
156
+ * Configures the message as a direct request and sets its execution target name.
157
+ * @param execName The name of the action/command to execute.
159
158
  */
160
159
  setRequest(execName) {
161
160
  this.header.type = MessageType.REQUEST;
162
161
  this.request.exec = execName;
163
162
  }
163
+ /**
164
+ * Retrieves a specific parameter from the request payload.
165
+ * @param paramName The key of the parameter to fetch.
166
+ * @param def The default value to return if the parameter is not found (defaults to null).
167
+ * @returns The parameter value, or the default value.
168
+ */
164
169
  getParam(paramName, def = null) {
165
170
  if (paramName in this.request.params) {
166
171
  return this.request.params[paramName];
@@ -169,13 +174,24 @@ export class Message {
169
174
  return def;
170
175
  }
171
176
  }
177
+ /**
178
+ * Configures the message as an identification broadcast.
179
+ * @param peerToIdentify The peer type identifying itself.
180
+ */
172
181
  setIdentification(peerToIdentify) {
173
182
  this.header.type = MessageType.IDENTIFICATION;
174
183
  this.header.from = peerToIdentify;
175
184
  }
185
+ /**
186
+ * Generates and assigns a unique UUID for the message header.
187
+ */
176
188
  generateRequestId() {
177
189
  this.header.id = uuidv4();
178
190
  }
191
+ /**
192
+ * Retrieves the unique identifier of the message.
193
+ * @returns The generated UUID string.
194
+ */
179
195
  getRequestId() {
180
196
  return this.header.id;
181
197
  }
@@ -3,38 +3,53 @@ export type Options = {
3
3
  [key: string]: any;
4
4
  };
5
5
  export type OptionChangedCallback = (value: any) => void;
6
+ /**
7
+ * Manages game configuration options, allowing retrieval from the server and local modifications.
8
+ */
6
9
  export declare class Option {
7
10
  private _options;
8
11
  private _console;
9
12
  private _callbacks;
13
+ /**
14
+ * Initializes the game options manager.
15
+ * @param console The Console instance used for network communication.
16
+ */
10
17
  constructor(console: Console);
18
+ /**
19
+ * Retrieves the current dictionary of options.
20
+ */
11
21
  get options(): Options;
12
22
  /**
13
- * Update the game options from the server
23
+ * Fetches all current game options from the server and populates the local cache.
24
+ * @returns A promise that resolves when the options have been successfully received and processed.
14
25
  */
15
26
  updateFromServer(): Promise<void>;
16
27
  /**
17
- * Set a new or edit a game option
18
- * @param name Name fo the option
19
- * @param value Value of the option
28
+ * Requests the master peer to create or update a game option.
29
+ * @param name The unique identifier of the option.
30
+ * @param value The value to assign to the option.
31
+ * @param type Optional type definition for the option (e.g., string, number).
32
+ * @param config Optional additional configuration metadata for the option.
20
33
  */
21
34
  setOption(name: string, value: any, type?: string | null, config?: {
22
35
  [key: string]: any;
23
36
  }): void;
24
37
  /**
25
- * Set a callback when an option has changed
26
- * @param name
27
- * @param callback
38
+ * Registers a callback to be executed whenever a specific option is updated.
39
+ * @param name The name of the option to observe.
40
+ * @param callback The function to trigger upon modification.
28
41
  */
29
42
  onOptionChanged(name: string, callback: OptionChangedCallback): void;
30
43
  /**
31
- * Init all events
32
- * @param from
33
- * @param any
44
+ * Initializes core events: fetching options on readiness and listening for option change notifications.
34
45
  */
35
46
  private _initEvents;
36
47
  /**
37
- * callback when a new option is received
48
+ * Internal handler to process incoming options from the server and trigger associated callbacks.
49
+ * @param from The origin peer sending the option.
50
+ * @param receivedOption The name/key of the option received.
51
+ * @param valueOption The payload containing the option's new value.
52
+ * @param runCallbacks If true, executes any registered callbacks for this option.
38
53
  */
39
54
  private _onReceiveState;
40
55
  }
@@ -1,21 +1,32 @@
1
1
  import { Console } from "./console.js";
2
2
  import { Message, PeerType } from "./message.js";
3
3
  import { get, writable } from "svelte/store";
4
+ /**
5
+ * Manages game configuration options, allowing retrieval from the server and local modifications.
6
+ */
4
7
  export class Option {
5
8
  _options;
6
9
  _console;
7
10
  _callbacks;
11
+ /**
12
+ * Initializes the game options manager.
13
+ * @param console The Console instance used for network communication.
14
+ */
8
15
  constructor(console) {
9
16
  this._options = {};
10
17
  this._console = console;
11
18
  this._callbacks = {};
12
19
  this._initEvents();
13
20
  }
21
+ /**
22
+ * Retrieves the current dictionary of options.
23
+ */
14
24
  get options() {
15
25
  return this._options;
16
26
  }
17
27
  /**
18
- * Update the game options from the server
28
+ * Fetches all current game options from the server and populates the local cache.
29
+ * @returns A promise that resolves when the options have been successfully received and processed.
19
30
  */
20
31
  async updateFromServer() {
21
32
  return new Promise((resolve, reject) => {
@@ -31,9 +42,11 @@ export class Option {
31
42
  });
32
43
  }
33
44
  /**
34
- * Set a new or edit a game option
35
- * @param name Name fo the option
36
- * @param value Value of the option
45
+ * Requests the master peer to create or update a game option.
46
+ * @param name The unique identifier of the option.
47
+ * @param value The value to assign to the option.
48
+ * @param type Optional type definition for the option (e.g., string, number).
49
+ * @param config Optional additional configuration metadata for the option.
37
50
  */
38
51
  setOption(name, value, type = null, config = {}) {
39
52
  let setOptionRequest = new Message();
@@ -44,27 +57,22 @@ export class Option {
44
57
  setOptionRequest.addParam("type", type);
45
58
  setOptionRequest.addParam("config", config);
46
59
  this._console.sendMessage(setOptionRequest);
47
- // this._options[name] = value;
48
60
  }
49
61
  /**
50
- * Set a callback when an option has changed
51
- * @param name
52
- * @param callback
62
+ * Registers a callback to be executed whenever a specific option is updated.
63
+ * @param name The name of the option to observe.
64
+ * @param callback The function to trigger upon modification.
53
65
  */
54
66
  onOptionChanged(name, callback) {
55
67
  this._callbacks[name] = callback;
56
68
  }
57
69
  /**
58
- * Init all events
59
- * @param from
60
- * @param any
70
+ * Initializes core events: fetching options on readiness and listening for option change notifications.
61
71
  */
62
72
  _initEvents() {
63
- // Get the state when the console is ready
64
73
  this._console.onReady(() => {
65
74
  this.updateFromServer();
66
75
  });
67
- // update the state when receive a change from console
68
76
  this._console.onRequest((request, params, from) => {
69
77
  if (request == "gameOptionNotification") {
70
78
  let value = {};
@@ -80,7 +88,11 @@ export class Option {
80
88
  });
81
89
  }
82
90
  /**
83
- * callback when a new option is received
91
+ * Internal handler to process incoming options from the server and trigger associated callbacks.
92
+ * @param from The origin peer sending the option.
93
+ * @param receivedOption The name/key of the option received.
94
+ * @param valueOption The payload containing the option's new value.
95
+ * @param runCallbacks If true, executes any registered callbacks for this option.
84
96
  */
85
97
  _onReceiveState(from, receivedOption, valueOption, runCallbacks = false) {
86
98
  this._options[receivedOption] = valueOption["value"];