@momo2555/koppeliajs 0.0.162 → 0.0.164

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.
@@ -12,6 +12,11 @@ import { Option } from "./option.js";
12
12
  import { logger, setDebugMode } from "./logger.js";
13
13
  import { CustomCallbacks } from "./customCallback.js";
14
14
  import { Song } from "./song.js";
15
+ /**
16
+ * The main Koppelia framework entry point.
17
+ * Implements a Singleton pattern to provide global access to the console, state, stages,
18
+ * devices, and game synchronization features across the Svelte application.
19
+ */
15
20
  export class Koppelia {
16
21
  _console;
17
22
  _state;
@@ -40,81 +45,111 @@ export class Koppelia {
40
45
  this._stage = new Stage(this._console);
41
46
  this._option = new Option(this._console);
42
47
  }
48
+ /**
49
+ * Retrieves the singleton instance of the Koppelia class.
50
+ * Instantiates it if it does not yet exist.
51
+ */
43
52
  static get instance() {
44
53
  if (!Koppelia._instance) {
45
54
  Koppelia._instance = new Koppelia();
46
55
  }
47
56
  return Koppelia._instance;
48
57
  }
58
+ /**
59
+ * Retrieves the global Svelte writable store representing the synchronized game state.
60
+ */
49
61
  get state() {
50
62
  return this._state.state;
51
63
  }
64
+ /**
65
+ * Merges a partial update into the current global state and broadcasts the change.
66
+ * @param stateUpdate A dictionary containing the keys/values to update.
67
+ */
52
68
  updateState(stateUpdate) {
53
69
  this._state.updateState(stateUpdate);
54
70
  }
71
+ /**
72
+ * Completely overwrites the global state with a new state object.
73
+ * @param newState The new state object to apply.
74
+ */
55
75
  setState(newState) {
56
76
  this._state.setState(newState);
57
77
  }
78
+ /**
79
+ * Checks if the underlying WebSocket console connection is fully established.
80
+ */
58
81
  get ready() {
59
82
  return this._console.ready;
60
83
  }
84
+ /**
85
+ * Enables or disables debug mode for extended console logging.
86
+ * @param enable True to enable debug logs, false to disable.
87
+ */
61
88
  setDebugMode(enable) {
62
89
  setDebugMode(enable);
63
90
  }
64
91
  /**
65
- * Add a callback that will be called when the connection to the console is entirely ready
66
- *
67
- * @param callback
92
+ * Registers a callback to execute when the console connection is fully ready.
93
+ * @param callback The function to execute.
68
94
  */
69
95
  onReady(callback) {
70
96
  this._console.onReady(callback);
71
97
  }
72
98
  /**
73
- * Init the default state of the game and the list of all stages
74
- *
75
- * @param defaultState Default state that be initialized
76
- * @param stages List of all stages
99
+ * Initializes the default state and the routing stages of the game.
100
+ * Specifically executes for "monitor" peers to ensure the primary game view sets the rules.
101
+ * @param defaultState The initial state structure.
102
+ * @param stages An array of valid stage names for application routing.
77
103
  */
78
104
  init(defaultState, stages) {
79
105
  this._console.onReady(() => {
80
106
  let type = get(routeType);
81
107
  if (type == "monitor") {
82
- this._state.setState(defaultState, true); // set the state
83
- this._stage.initStages(stages); // init the list of stages
108
+ this._state.setState(defaultState, true);
109
+ this._stage.initStages(stages);
84
110
  }
85
111
  });
86
112
  }
87
113
  /**
88
- * Go to a stage, the stage must be in the stage list
89
- * Before changing the staging all callbacks will be destroyed
90
- * If the stage list is empty the console will return an error
91
- * @param stageName
114
+ * Requests a transition to a specific stage (view) across the network.
115
+ * Note: All active console event listeners will be destroyed before transition.
116
+ * @param stageName The target stage to navigate to.
92
117
  */
93
118
  goto(stageName) {
94
119
  this._stage.goto(stageName);
95
120
  }
121
+ getCurrentStage() {
122
+ return this._stage.currentStage;
123
+ }
124
+ /**
125
+ * Normalizes a media URL to ensure cross-client compatibility.
126
+ * @param mediaUrl The raw media URL.
127
+ * @returns The corrected URL.
128
+ */
96
129
  fixMediaUrl(mediaUrl) {
97
130
  return this._console.fixMediaUrl(mediaUrl);
98
131
  }
132
+ /**
133
+ * Constructs the full URL for a given relative media path.
134
+ * @param path The relative media path.
135
+ * @returns The full URL string.
136
+ */
99
137
  getMediaLink(path) {
100
138
  return this._console.getMediaUrl(path);
101
139
  }
102
140
  /**
103
- * Get the list of devices in a callback
104
- * @param callback
141
+ * Asynchronously fetches the list of available connected devices from the master peer.
142
+ * @returns A promise resolving to an array of instantiated Device objects.
105
143
  */
106
144
  async getDevices() {
107
145
  return new Promise((resolve, reject) => {
108
- // create the message to request the devices
109
146
  let getDevicesRequest = new Message();
110
147
  getDevicesRequest.setRequest("getDevices");
111
148
  getDevicesRequest.setDestination(PeerType.MASTER, "");
112
- // send the message to the console
113
149
  this._console.sendMessage(getDevicesRequest, (response) => {
114
- // convert the response to al list of device objects
115
- let devices_raw = response.getParam("devices", []);
150
+ let devicesRaw = response.getParam("devices", []);
116
151
  let devices = [];
117
- for (let device_raw of devices_raw) {
152
+ for (let device_raw of devicesRaw) {
118
153
  let device = new Device(this._console);
119
154
  device.fromObject(device_raw);
120
155
  devices.push(device);
@@ -123,20 +158,40 @@ export class Koppelia {
123
158
  });
124
159
  });
125
160
  }
161
+ _onDeviceConnNotification(callback, notifName) {
162
+ return this._console.onRequest((request, params, from, address) => {
163
+ if (request == notifName) {
164
+ if (params.device !== undefined) {
165
+ let device = new Device(this._console);
166
+ device.fromObject(params.device);
167
+ callback(device);
168
+ }
169
+ }
170
+ });
171
+ }
172
+ onDeviceConnectedNotification(callback) {
173
+ return this._onDeviceConnNotification(callback, "deviceConnectionNotification");
174
+ }
175
+ onDeviceDisconnectedNotification(callback) {
176
+ return this._onDeviceConnNotification(callback, "deviceDisconnectionNotification");
177
+ }
178
+ unsubDeviceConnectionNotification(callbackId) {
179
+ this._console.unsubscribeCallback(callbackId);
180
+ }
126
181
  /**
127
- * Get the game ID of the current game
128
- * @returns the game id as a string
182
+ * Retrieves the unique identifier of the currently loaded game.
183
+ * @returns The game ID string provided by public environment variables.
129
184
  */
130
185
  getGameId() {
131
186
  return PUBLIC_GAME_ID;
132
187
  }
133
188
  /**
134
- * Get the list of plays, the plays returned by this function doesn't include the raw
135
- * You have to call a function in from the play object to download all the raw files
136
- * @param count limit of plays to get
137
- * @param index index from which to start fetching the plays
138
- * @param orderBy order by date or name
139
- * @returns the List of plays an array of objects of type Play,
189
+ * Asynchronously fetches a paginated list of Play sessions.
190
+ * Note: This only fetches metadata. Specific Play content must be downloaded via Play methods.
191
+ * @param count Maximum number of plays to retrieve (default: 10).
192
+ * @param index The starting offset index (default: 0).
193
+ * @param orderBy Sorting criteria, e.g., "date" or "name" (default: "date").
194
+ * @returns A promise resolving to an array of Play instances.
140
195
  */
141
196
  async getPlays(count = 10, index = 0, orderBy = "date") {
142
197
  return new Promise((resolve, reject) => {
@@ -157,6 +212,10 @@ export class Koppelia {
157
212
  });
158
213
  });
159
214
  }
215
+ /**
216
+ * Asynchronously fetches the list of registered residents/players.
217
+ * @returns A promise resolving to an array of Resident instances.
218
+ */
160
219
  async getResidents() {
161
220
  return new Promise((resolve, reject) => {
162
221
  let getResidentsRequest = new Message();
@@ -175,6 +234,11 @@ export class Koppelia {
175
234
  });
176
235
  });
177
236
  }
237
+ /**
238
+ * Asynchronously fetches a specific song by its unique ID.
239
+ * @param songId The ID of the song to retrieve.
240
+ * @returns A promise resolving to the corresponding Song instance.
241
+ */
178
242
  async getSongById(songId) {
179
243
  return new Promise((resolve, reject) => {
180
244
  let getSongRequest = new Message();
@@ -190,6 +254,10 @@ export class Koppelia {
190
254
  });
191
255
  });
192
256
  }
257
+ /**
258
+ * Asynchronously fetches a dictionary of all songs associated with the currently active play.
259
+ * @returns A promise resolving to a map of song IDs to Song instances.
260
+ */
193
261
  getCurrentPlaySongs() {
194
262
  return new Promise((resolve, reject) => {
195
263
  let getSongRequest = new Message();
@@ -209,8 +277,8 @@ export class Koppelia {
209
277
  });
210
278
  }
211
279
  /**
212
- * Get the current play that has been set
213
- * @returns the current play
280
+ * Asynchronously retrieves the currently active Play instance set on the server.
281
+ * @returns A promise resolving to the active Play.
214
282
  */
215
283
  async getCurrentPlay() {
216
284
  return new Promise((resolve, reject) => {
@@ -226,24 +294,23 @@ export class Koppelia {
226
294
  });
227
295
  }
228
296
  /**
229
- * This function enables the difficulty cursor, to change the difficulty live when playing from Koppeli'App
230
- * @param callback : callback to call when difficulty changes
297
+ * Enables a live difficulty cursor, allowing difficulty changes during gameplay.
298
+ * @param callback Function to execute when the difficulty changes.
231
299
  */
232
300
  async enableDifficultyCursor(callback) {
233
301
  }
234
302
  /**
235
- * @param id
236
- * @param onGrowChange
303
+ * Registers a new growable element on the network and listens for state changes.
304
+ * @param id The unique identifier for the growable element.
305
+ * @param onGrowChange Callback triggered when the 'grown' state of the element changes.
237
306
  */
238
307
  async registerNewGrowableElement(id, onGrowChange) {
239
308
  return new Promise((resolve, reject) => {
240
- // create the message to request the devices
241
309
  if (get(routeType) == "controller") {
242
310
  let addGrowableElRequest = new Message();
243
311
  addGrowableElRequest.setRequest("addGrowableElement");
244
312
  addGrowableElRequest.addParam("id", id);
245
313
  addGrowableElRequest.setDestination(PeerType.MASTER, "");
246
- // send the message to the console (only the controller sends the )
247
314
  this._console.sendMessage(addGrowableElRequest, (response) => {
248
315
  });
249
316
  }
@@ -261,26 +328,26 @@ export class Koppelia {
261
328
  });
262
329
  }
263
330
  /**
264
- * @param id
265
- * @param grown
331
+ * Updates the 'grown' state of a registered growable element across the network.
332
+ * @param id The unique identifier of the element.
333
+ * @param grown True if the element is in a grown state, false otherwise.
266
334
  */
267
335
  async updateGrowableElement(id, grown) {
268
336
  return new Promise((resolve, reject) => {
269
- // create the message to request the devices
270
337
  let addGrowableElRequest = new Message();
271
338
  addGrowableElRequest.setRequest("updateGrowableElement");
272
339
  addGrowableElRequest.addParam("id", id);
273
340
  addGrowableElRequest.addParam("grown", grown);
274
341
  addGrowableElRequest.setDestination(PeerType.MASTER, "");
275
- // send the message to the console
276
342
  this._console.sendMessage(addGrowableElRequest, (response) => {
277
343
  resolve();
278
344
  });
279
345
  });
280
346
  }
281
347
  /**
282
- * Add a new resizable text element and define the callback that will be executed when receive and a resizable
283
- * text update notification form koppelia application
348
+ * Registers a new resizable text element with a default font size (Monitor only).
349
+ * @param id The unique identifier for the text element.
350
+ * @param defaultSize The default font size.
284
351
  */
285
352
  async registerNewResizableText(id, defaultSize) {
286
353
  return new Promise((resolve, reject) => {
@@ -290,13 +357,18 @@ export class Koppelia {
290
357
  addGrowableElRequest.addParam("id", id);
291
358
  addGrowableElRequest.addParam("defaultSize", defaultSize);
292
359
  addGrowableElRequest.setDestination(PeerType.MASTER, "");
293
- // send the message to the console (only the controller sends the )
294
360
  this._console.sendMessage(addGrowableElRequest, (response) => {
295
361
  });
296
362
  }
297
363
  resolve();
298
364
  });
299
365
  }
366
+ /**
367
+ * Subscribes to size change notifications for a specific resizable text element.
368
+ * @param id The unique identifier of the text element.
369
+ * @param onTextResized Callback executed with the new font size.
370
+ * @returns The unique subscription ID used for unsubscribing.
371
+ */
300
372
  onResizableTextChanged(id, onTextResized) {
301
373
  return this._console.onRequest((req, params) => {
302
374
  if (req == "resizableTextNotification") {
@@ -308,21 +380,34 @@ export class Koppelia {
308
380
  }
309
381
  });
310
382
  }
383
+ /**
384
+ * Unsubscribes a previously registered resizable text listener.
385
+ * @param callbackId The subscription ID returned by onResizableTextChanged.
386
+ */
311
387
  unsubResizableText(callbackId) {
312
388
  this._console.unsubscribeCallback(callbackId);
313
389
  }
390
+ /**
391
+ * Retrieves the list of all registered resizable text elements from the master.
392
+ * @returns A promise resolving to an array of resizable element data objects.
393
+ */
314
394
  async getResizableTexts() {
315
395
  return new Promise((resolve, reject) => {
316
396
  let addGrowableElRequest = new Message();
317
397
  addGrowableElRequest.setRequest("getResizableTexts");
318
398
  addGrowableElRequest.setDestination(PeerType.MASTER, "");
319
- // send the message to the console (only the controller sends the )
320
399
  this._console.sendMessage(addGrowableElRequest, (response) => {
321
400
  let resizables = response.getParam("resizableTexts", []);
322
401
  resolve(resizables);
323
402
  });
324
403
  });
325
404
  }
405
+ /**
406
+ * Writes configuration data to the master peer, optionally binding it to the current play.
407
+ * @param config_id The unique identifier for this configuration data.
408
+ * @param config_value The dictionary containing the configuration payload.
409
+ * @param current_play Whether to bind this configuration to the active play session (default: true).
410
+ */
326
411
  async writeGameConfig(config_id, config_value, current_play = true) {
327
412
  let setGameConfigRequest = new Message();
328
413
  setGameConfigRequest.setRequest("setGameData");
@@ -332,6 +417,12 @@ export class Koppelia {
332
417
  setGameConfigRequest.setDestination(PeerType.MASTER, "");
333
418
  this._console.sendMessage(setGameConfigRequest);
334
419
  }
420
+ /**
421
+ * Retrieves persistent configuration data from the master peer.
422
+ * @param config_id The unique identifier of the configuration data to fetch.
423
+ * @param current_play True to fetch data bound specifically to the active play, false otherwise.
424
+ * @returns A promise resolving to the configuration dictionary.
425
+ */
335
426
  async getGameConfig(config_id, current_play) {
336
427
  return new Promise((resolve, reject) => {
337
428
  let getGameConfigRequest = new Message();
@@ -346,25 +437,33 @@ export class Koppelia {
346
437
  });
347
438
  }
348
439
  /**
349
- * @param sentence
440
+ * Broadcasts a Text-to-Speech synthesis request to the Maestro peer.
441
+ * @param sentence The text string to be spoken out loud.
350
442
  */
351
443
  say(sentence) {
352
- // create the message to request the devices
353
444
  let sayRequest = new Message();
354
445
  sayRequest.setRequest("sayRequest");
355
446
  sayRequest.addParam("sentence", sentence);
356
447
  sayRequest.setDestination(PeerType.MAESTRO, "");
357
- // send the message to the console
358
448
  this._console.sendMessage(sayRequest);
359
449
  }
360
450
  /**
361
- * Set a new or edit a game option
362
- * @param name Name fo the option
363
- * @param value Value of the option
451
+ * Assigns a basic value to a registered game option via the option manager.
452
+ * @param name The unique name of the option.
453
+ * @param value The value to set.
364
454
  */
365
455
  setOption(name, value) {
366
456
  this._option.setOption(name, value, null, {});
367
457
  }
458
+ /**
459
+ * Creates or updates an interactive slider option.
460
+ * @param name The unique identifier for the slider.
461
+ * @param label The display label for the UI.
462
+ * @param value The current numeric value.
463
+ * @param min The minimum allowed value.
464
+ * @param max The maximum allowed value.
465
+ * @param step The increment step size.
466
+ */
368
467
  createSliderOtption(name, label, value, min, max, step) {
369
468
  this._option.setOption(name, value, "slider", {
370
469
  "min": min,
@@ -373,26 +472,58 @@ export class Koppelia {
373
472
  "label": label,
374
473
  });
375
474
  }
475
+ /**
476
+ * Creates or updates an interactive toggle switch option.
477
+ * @param name The unique identifier for the switch.
478
+ * @param label The display label for the UI.
479
+ * @param value The current boolean state.
480
+ */
376
481
  createSwitchOption(name, label, value) {
377
482
  this._option.setOption(name, value, "switch", {
378
483
  "label": label,
379
484
  });
380
485
  }
486
+ /**
487
+ * Creates or updates a multiple-choice selection option.
488
+ * @param name The unique identifier for the option.
489
+ * @param label The display label for the UI.
490
+ * @param value The currently selected choice.
491
+ * @param choices An array of available string choices.
492
+ */
381
493
  createChoicesOption(name, label, value, choices) {
382
494
  this._option.setOption(name, value, "choices", {
383
495
  "choices": choices,
384
496
  "label": label,
385
497
  });
386
498
  }
499
+ /**
500
+ * Registers a callback listener to trigger whenever a specific option's value changes.
501
+ * @param name The name of the option to observe.
502
+ * @param callback The function to execute on change.
503
+ */
387
504
  onOptionChanged(name, callback) {
388
505
  this._option.onOptionChanged(name, callback);
389
506
  }
507
+ /**
508
+ * Executes a broadcasted network request to trigger a registered custom callback.
509
+ * @param callbackName The unique registered name of the custom callback.
510
+ * @param args Dictionary of arguments to pass to the callback.
511
+ */
390
512
  run(callbackName, args) {
391
513
  this._callbacks.runCustomCallback(callbackName, args);
392
514
  }
515
+ /**
516
+ * Registers a local function to listen for network execution of a custom callback.
517
+ * @param callbackName The identifier for this callback.
518
+ * @param callback The local function to execute.
519
+ */
393
520
  on(callbackName, callback) {
394
521
  this._callbacks.registerCustomCallback(callbackName, callback);
395
522
  }
523
+ /**
524
+ * Unregisters a locally listening custom callback.
525
+ * @param callbackName The identifier of the callback to remove.
526
+ */
396
527
  unsub(callbackName) {
397
528
  this._callbacks.unregisterCustomCallback(callbackName);
398
529
  }
@@ -12,62 +12,67 @@ export declare class KoppeliaWebsocket {
12
12
  websocketUrl: string;
13
13
  openCallback?: () => void;
14
14
  /**
15
- * Constructor of the Koppelia websocket class
16
- * @param websocketUrl
17
- * @param timeout
15
+ * Initializes the Koppelia WebSocket client.
16
+ * @param websocketUrl The URL of the WebSocket server to connect to.
17
+ * @param timeout The maximum time in milliseconds to wait for a response before timing out a request. Defaults to 20000ms.
18
18
  */
19
19
  constructor(websocketUrl: string, timeout?: number);
20
20
  /**
21
- * Send a new request: Add a request Id to the request and add it to the ongoing requests
22
- * Add an interval to timeout when there is no response after a certain amount of time
23
- * @param data
24
- * @param callback
21
+ * Sends a new message request through the WebSocket.
22
+ * Automatically generates a request ID, registers the request as ongoing, and sets a timeout.
23
+ * @param data The message payload to send.
24
+ * @param callback Optional callback to be executed when a response to this specific request is received.
25
25
  */
26
26
  send(data: Message, callback?: Callback): void;
27
27
  /**
28
- * Add a receive callback
29
- * @param callback
28
+ * Registers a global callback to be triggered whenever a message is received.
29
+ * @param callback The function to execute upon receiving a message.
30
30
  */
31
31
  onReceive(callback: Callback): void;
32
32
  /**
33
- * Define a callback for the websocket open event
34
- * @param callback
33
+ * Registers a callback to be triggered when the WebSocket connection successfully opens.
34
+ * @param callback The function to execute upon connection.
35
35
  */
36
36
  onOpen(callback: () => void): void;
37
+ /**
38
+ * Establishes the WebSocket connection.
39
+ * @param websockerUrl The URL of the WebSocket server.
40
+ */
37
41
  private _connectWebsocket;
38
42
  /**
39
- * Handle a websocket response
40
- * - Execute a callback of a reception if a request was send before (by checking ongoing request)
41
- * - Execute a callbacj for a genral reception response
42
- * @param data
43
- * @returns
43
+ * Handles incoming WebSocket responses.
44
+ * Checks if the message corresponds to an ongoing request. If so, triggers its specific callback.
45
+ * Otherwise, broadcasts the message to all global receive callbacks.
46
+ * @param data The raw data payload received from the WebSocket.
44
47
  */
45
48
  private _handleWebsocketResponse;
46
49
  /**
47
- * Init all websocker events
50
+ * Initializes all WebSocket event listeners (open, message, close).
51
+ * Handles automatic reconnection on connection close or error.
48
52
  */
49
53
  private _setupEvents;
50
54
  /**
51
- * Timeout the request if there is no response
52
- * To timout the response, the function simply delete the id from on going request list
53
- * @param requestId Id of the request
55
+ * Retrieves the index of an ongoing request in the internal list.
56
+ * @param requestId The unique identifier of the request.
57
+ * @returns The array index of the request, or -1 if not found.
54
58
  */
55
59
  private _getRequestIndex;
56
60
  /**
57
- * Delete the request from the list of onGoing Requests
58
- * @param requestId
61
+ * Removes a request from the ongoing requests list.
62
+ * Used both when a request is successfully resolved or when it times out.
63
+ * @param requestId The unique identifier of the request to remove.
59
64
  */
60
65
  private _deleteRequest;
61
66
  /**
62
- * get the Ongoing the request and get theh callback
63
- * @param requestId
64
- * @returns
67
+ * Retrieves an ongoing request object by its ID.
68
+ * @param requestId The unique identifier of the request.
69
+ * @returns The ongoing request object, or undefined if not found.
65
70
  */
66
71
  private _getOnGoingRequest;
67
72
  /**
68
- * Add a new request to ongoing requests
69
- * @param requestId
70
- * @param callback
73
+ * Registers a new request in the ongoing requests list.
74
+ * @param requestId The unique identifier generated for the request.
75
+ * @param callback Optional callback to trigger when the response arrives.
71
76
  */
72
77
  private _addNewRequest;
73
78
  }