@arkeytyp/valu-api 1.0.3 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,14 +1,16 @@
1
1
  The `valu-api` package enables developers to create custom iframe applications for Valu Social. It provides tools to invoke functions of registered Valu applications and subscribe to their events. With features like API versioning, event handling, and console command testing, developers can seamlessly integrate and extend functionality within the Valu Social ecosystem.
2
2
 
3
- # install
4
- ```
3
+ # Installation
4
+
5
+ ```bash
5
6
  npm install @arkeytyp/valu-api
6
7
  ```
7
8
 
8
9
  # Usage
9
10
 
10
- ## 1. Initialize ValuApi
11
- On your application startup, create an instance of ValuApi and subscribe to the API_READY event. This event will be triggered only when your application is launched as an iframe within the Valu Verse application.
11
+ ## Initialize ValuApi
12
+
13
+ On your application startup, create an instance of `ValuApi` and subscribe to the `API_READY` event. This event will be triggered only when your application is launched as an iframe within the Valu Verse application.
12
14
 
13
15
  ```javascript
14
16
  import { ValuApi } from 'valu-api';
@@ -19,23 +21,113 @@ valuApi.current.addEventListener(ValuApi.API_READY, async (e) => {
19
21
  });
20
22
  ```
21
23
 
22
- ## 2. Get an API Pointer
23
- Once the API is ready, you can create an APIPointer instance by specifying the name and version of the API you want to use. The version parameter is optional, and if omitted, the latest version will be used.
24
+ # Running Application Intents
25
+
26
+ Intents are a powerful way to communicate with other applications inside the Valu Social ecosystem. They allow your application to request actions from other registered Valu apps in a standardized way — for example, opening a chat, joining a meeting, or performing any predefined operation supported by another app.
27
+
28
+ Each Intent contains:
29
+
30
+ * **applicationId:** The target application’s ID.
31
+ * **action:** The action you want to perform (e.g., `open`, `connect-to-meeting`).
32
+ * **params:** Optional parameters for the action (e.g., room IDs, configuration data).
33
+
34
+ Here’s an example of creating and running an intent to connect to a video meeting:
35
+
36
+ ```javascript
37
+ import { Intent } from 'valu-api';
38
+
39
+ const intent = new Intent(
40
+ 'videochat', // Target application ID
41
+ 'connect-to-meeting', // Action to perform
42
+ {
43
+ roomId: '<room-id>', // Additional parameters
44
+ withLocalTracks: true
45
+ }
46
+ );
47
+
48
+ await valuApi.sendIntent(intent);
49
+ ```
50
+
51
+ # Handling Application Lifecycle
52
+
53
+ The `valu-api` package provides a way to handle **application lifecycle events** inside your iframe application. By implementing a `ValuApplication` class and registering it with `ValuApi`, you can easily respond to events such as when your app is created, receives a new intent, or is destroyed.
54
+
55
+ This allows you to **separate application logic from API wiring** and makes it simple to handle incoming intents and return values back to the caller.
56
+
57
+ ## 1. Create Your Application Class
58
+
59
+ Extend the `ValuApplication` class and override its lifecycle methods:
60
+
61
+ ```javascript
62
+ import { ValuApplication } from '@arkeytyp/valu-api';
63
+
64
+ class MyApp extends ValuApplication {
65
+ async onCreate(intent) {
66
+ console.log('App created with:', intent);
67
+ return { status: 'initialized' };
68
+ }
69
+
70
+ async onNewIntent(intent) {
71
+ console.log('New intent received:', intent);
72
+ return { handled: true, data: { message: 'Processed successfully' } };
73
+ }
74
+
75
+ async onDestroy() {
76
+ console.log('App is shutting down');
77
+ }
78
+ }
79
+ ```
80
+
81
+ ## 2. Register Your Application with ValuApi
24
82
 
25
- To get a pointer to the app API version 1:
83
+ Set your application instance within `ValuApi`:
26
84
 
27
85
  ```javascript
28
- const appApi = valuApi.getApi('app', 1);
86
+ import { ValuApi } from '@arkeytyp/valu-api';
87
+
88
+ const valuApi = new ValuApi();
89
+ valuApi.setApplication(new MyApp());
90
+ ```
91
+
92
+ Once registered, the `ValuApi` will call the appropriate lifecycle methods when events are received from the host (e.g., app launch, new intent, app close).
93
+
94
+ ## Lifecycle Methods
95
+
96
+ * **`onCreate(intent)`** – Triggered when the application is first launched with an Intent. You can return an optional value to send back to the caller.
97
+ * **`onNewIntent(intent)`** – Triggered when a new Intent is sent to the application while it is already running. The return value will be sent back to whoever triggered the Intent.
98
+ * **`onDestroy()`** – Triggered when the application is about to be destroyed. Use this to clean up resources.
99
+
100
+ ### Lifecycle Flow
101
+
29
102
  ```
103
+ [onCreate] → [onNewIntent] (many times) → [onDestroy]
104
+ ```
105
+
106
+ # Using System API
30
107
 
31
- To use the latest version of the API:
108
+ The **System API** allows your iframe application to interact directly with the Valu Social platform and its internal applications.
109
+
110
+ This API provides a unified way to:
111
+
112
+ * Access core platform features (apps, chat, etc.)
113
+ * Call specific commands on these features
114
+ * Subscribe to real-time events emitted by the platform
115
+ * Run and test commands from the console for debugging
116
+
117
+ This makes it easy to extend the functionality of Valu Social and integrate your iframe application with other parts of the ecosystem.
118
+
119
+ ## 1. Get an API Pointer
120
+
121
+ Once the API is ready, you can create an `APIPointer` instance by specifying the name and version of the API you want to use. The version parameter is optional, and if omitted, the latest version will be used.
32
122
 
33
123
  ```javascript
34
- const appApi = valuApi.current.getApi('app');
124
+ const appApi = valuApi.getApi('app', 1); // Specific version
125
+ const appApiLatest = valuApi.current.getApi('app'); // Latest version
35
126
  ```
36
127
 
37
- ## 3. Invoke API Commands
38
- After obtaining the API pointer, you can invoke commands on the API. Here's an example of opening the text_chat on the app API:
128
+ ## 2. Invoke API Commands
129
+
130
+ After obtaining the API pointer, you can invoke commands on the API. Here's an example of opening the `text_chat` on the app API:
39
131
 
40
132
  ```javascript
41
133
  await appApi.run('open', 'text_chat');
@@ -48,8 +140,9 @@ const chatApi = valuApi.current.getApi('chat');
48
140
  await chatApi.run('open-channel', { roomId: 'room123', propId: 'prop456' });
49
141
  ```
50
142
 
51
- ## 4. Subscribe to Events
52
- You can subscribe to events emitted by the API. For example, if you want to listen for the app-open event:
143
+ ## 3. Subscribe to Events
144
+
145
+ You can subscribe to events emitted by the API. For example, if you want to listen for the `app-open` event:
53
146
 
54
147
  ```javascript
55
148
  appApi.addEventListener('app-open', (event) => {
@@ -57,10 +150,9 @@ appApi.addEventListener('app-open', (event) => {
57
150
  });
58
151
  ```
59
152
 
60
- ## 5. Run Console Commands (For Testing)
61
- You can use the runConsoleCommand method to execute commands directly in the console environment. This method processes the output and returns a resolved promise on success or an error message if the command fails.
153
+ ## 4. Run Console Commands (For Testing)
62
154
 
63
- To run a console command, use:
155
+ You can use the `runConsoleCommand` method to execute commands directly in the console environment. This method processes the output and returns a resolved promise on success or an error message if the command fails.
64
156
 
65
157
  ```javascript
66
158
  let command = 'app open text_chat';
@@ -73,32 +165,25 @@ console.log(reply);
73
165
  ```
74
166
 
75
167
  ## Example Workflow
76
- Here's an example of a simple workflow using valu-api:
77
168
 
78
169
  ```javascript
79
170
  import { ValuApi } from 'valu-api';
80
171
 
81
172
  const valuApi = new ValuApi();
82
173
 
83
- // Wait for the API to be ready
84
174
  valuApi.current.addEventListener(ValuApi.API_READY, async () => {
85
175
  console.log("API IS READY!!!");
86
176
 
87
- // Get API pointer
88
177
  const appApi = valuApi.current.getApi('app');
89
178
 
90
- // Run a command on the app API
91
179
  await appApi.run('open', 'text_chat');
92
180
 
93
- // Subscribe to events
94
181
  appApi.addEventListener('app-open', (event) => {
95
182
  console.log('App opened:', event);
96
183
  });
97
184
 
98
- // Run console command for testing
99
185
  let command = 'app open text_chat';
100
186
  let reply = await valuApi.current.runConsoleCommand(command);
101
187
  console.log(reply);
102
188
  });
103
- ```
104
-
189
+ ```
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@arkeytyp/valu-api",
3
- "version": "1.0.3",
3
+ "version": "1.1.0",
4
4
  "description": "A package for developing iframe applications for Valu Social. Allows invoking functions of registered Valu applications and subscribing to events, as well as other features that enable developers creating own ifram apps for the value social",
5
5
  "main": "src/ValuApi.js",
6
6
  "scripts": {
package/src/Intent.js ADDED
@@ -0,0 +1,57 @@
1
+
2
+ export class Intent {
3
+
4
+ // Predefined actions
5
+ static ACTION_VIEW = 'view';
6
+ static ACTION_OPEN = 'open';
7
+
8
+
9
+ // Private fields
10
+ #applicationId;
11
+ #action;
12
+ #params;
13
+
14
+ /** @returns {string} */
15
+ get applicationId() {
16
+ return this.#applicationId;
17
+ }
18
+
19
+ /** @returns {string} */
20
+ get action() {
21
+ return this.#action;
22
+ }
23
+
24
+ /** @returns {Object} */
25
+ get params() {
26
+ return this.#params;
27
+ }
28
+
29
+
30
+
31
+ constructor(applicationId, action = Intent.ACTION_OPEN, params = {}) {
32
+ this.#applicationId = applicationId;
33
+ this.#action = action;
34
+ this.#params = params;
35
+ }
36
+
37
+ /**
38
+ * Validates if a given object is a valid Intent instance.
39
+ * @param {any} obj
40
+ * @returns {boolean}
41
+ */
42
+ static isValid(obj) {
43
+ return (
44
+ obj instanceof Intent &&
45
+ typeof obj.applicationId === 'string' &&
46
+ typeof obj.action === 'string'
47
+ );
48
+ }
49
+
50
+ /**
51
+ * Returns a stringified representation of the intent.
52
+ * @returns {string}
53
+ */
54
+ toString() {
55
+ return `[Intent] applicationId="${this.applicationId}", action="${this.action}", params=${JSON.stringify(this.params)}`;
56
+ }
57
+ }
package/src/ValuApi.js CHANGED
@@ -1,6 +1,11 @@
1
1
  import {EventEmitter} from "./EventEmitter.js";
2
2
  import {APIPointer} from "./APIPointer.js";
3
3
  import {guid4, nextId} from "./Utils.js";
4
+ import {Intent} from "./Intent";
5
+
6
+ export { ValuApplication } from "./ValuApplication.js";
7
+ export { Intent } from "./Intent.js";
8
+ export { APIPointer } from "./APIPointer.js";
4
9
 
5
10
 
6
11
  /**
@@ -16,6 +21,11 @@ export class ValuApi {
16
21
  #eventEmitter;
17
22
  #valuApplication = {};
18
23
  #requests = new Map();
24
+ #lastIntent;
25
+
26
+ /** @type ValuApplication */
27
+ #applicationInstance = null;
28
+
19
29
 
20
30
  get connected() {
21
31
  return this.#valuApplication.origin !== undefined;
@@ -58,6 +68,21 @@ export class ValuApi {
58
68
  return apiPointer;
59
69
  }
60
70
 
71
+ /**
72
+ * Registers an application instance to handle lifecycle events.
73
+ *
74
+ * Developers should create a class that extends {@link ValuApplication} and implement
75
+ * its lifecycle methods.
76
+ * This instance will receive all lifecycle callbacks sent from the Valu Social host application.
77
+ */
78
+ setApplication(appInstance) {
79
+ this.#applicationInstance = appInstance;
80
+
81
+ if(this.#lastIntent) {
82
+ this.#applicationInstance.onCreate(this.#lastIntent).catch(console.error);
83
+ }
84
+ }
85
+
61
86
  async #registerApiPointer(apiName, version, guid) {
62
87
  let deferredPromise = this.#createDeferred();
63
88
 
@@ -74,8 +99,6 @@ export class ValuApi {
74
99
 
75
100
  #postToValuApp(name, message) {
76
101
  const data = { name: name, message: message};
77
-
78
- // console.log('Posting to Valu: ', name, ' ', message, ' source: ', this.#valuApplication.source);
79
102
  this.#valuApplication.source.postMessage(data, this.#valuApplication.origin);
80
103
  }
81
104
 
@@ -91,6 +114,37 @@ export class ValuApi {
91
114
  });
92
115
  }
93
116
 
117
+ /**
118
+ * Sends an intent to the Valu application.
119
+ *
120
+ * This method posts the intent data to the Valu application and returns a promise
121
+ * that resolves or rejects when the corresponding response is received.
122
+ *
123
+ * Internally, it creates a deferred promise and assigns a unique `requestId` to track
124
+ * the response for this specific intent execution.
125
+ *
126
+ * @param {Intent} intent - The intent object containing the target application ID, action, and parameters.
127
+ * @returns {Promise<unknown>} A promise that resolves with the response from the Valu application.
128
+ *
129
+ * @example
130
+ * const intent = new Intent('chatApp', Intent.ACTION_OPEN, { roomId: '1234' });
131
+ * const result = await api.sendIntent(intent);
132
+ * console.log(result);
133
+ */
134
+ async sendIntent(intent) {
135
+ let deferredPromise = this.#createDeferred();
136
+
137
+ this.#postToValuApp('api:run-intent', {
138
+ applicationId: intent.applicationId,
139
+ action: intent.action,
140
+ params: intent.params,
141
+ requestId: deferredPromise.id,
142
+ });
143
+
144
+ this.#requests[deferredPromise.id] = deferredPromise;
145
+ return deferredPromise.promise;
146
+ }
147
+
94
148
  /**
95
149
  * Executes a given console command and returns the result of an API function.
96
150
  *
@@ -138,15 +192,24 @@ export class ValuApi {
138
192
  switch (event.data.name) {
139
193
  case 'api:ready': {
140
194
  this.#valuApplication = {
141
- id : message,
195
+ id : message.applicationId,
142
196
  source: event.source,
143
197
  origin: event.origin,
144
198
  }
145
199
 
146
200
  this.#eventEmitter.emit(ValuApi.API_READY);
201
+
202
+ const intent = new Intent(message.applicationId, message.action, message.params);
203
+ this.#applicationInstance?.onCreate(intent);
204
+ this.#lastIntent = intent;
147
205
  break;
148
206
  }
149
207
 
208
+ case 'api:new-intent': {
209
+ const intent = new Intent(message.applicationId, message.action, message.params);
210
+ this.#applicationInstance?.onNewIntent(intent);
211
+ }
212
+
150
213
  case 'api:run-console-completed': {
151
214
  const requestId = event.data.requestId;
152
215
  const deferred = this.#requests[requestId];
@@ -0,0 +1,31 @@
1
+
2
+ /**
3
+ * Abstract base class for Valu iframe applications.
4
+ *
5
+ * Developers should extend this class to implement application-specific logic
6
+ * for handling lifecycle events within the Valu Social ecosystem.
7
+ *
8
+ * The Valu API will automatically call these lifecycle methods when the host
9
+ * application sends corresponding events (e.g., app launch, new intent, destroy).
10
+ */
11
+
12
+ export class ValuApplication {
13
+ /**
14
+ * Called when the app is first launched with an Intent.
15
+ * @param {Intent} intent
16
+ * @returns {Promise<any>}
17
+ */
18
+ async onCreate(intent) {}
19
+
20
+ /**
21
+ * Called when the app receives an Intent while already running (docked).
22
+ * @param {Intent} intent
23
+ * @returns {Promise<any>} - The result will be sent back to the caller
24
+ */
25
+ async onNewIntent(intent) {}
26
+
27
+ /**
28
+ * Called when the app is about to be destroyed.
29
+ */
30
+ async onDestroy() {}
31
+ }
@@ -4,6 +4,19 @@ declare module '@arkeytyp/valu-api' {
4
4
 
5
5
  get connected(): boolean;
6
6
 
7
+ /**
8
+ * Registers an application instance to handle lifecycle events.
9
+ * @param appInstance An instance of a class extending ValuApplication.
10
+ */
11
+ setApplication(appInstance: ValuApplication): void;
12
+
13
+ /**
14
+ * Sends an intent to another Valu application and returns the response.
15
+ * @param intent The Intent object containing the target application ID, action, and parameters.
16
+ * @returns A promise resolving to the response from the target application.
17
+ */
18
+ sendIntent(intent: Intent): Promise<any>;
19
+
7
20
  addEventListener(event: string, callback: (data: any) => void): void;
8
21
  removeEventListener(event: string, callback: (data: any) => void): void;
9
22
  getApi(apiName: string, version?: number): Promise<APIPointer>;
@@ -19,4 +32,79 @@ declare module '@arkeytyp/valu-api' {
19
32
  removeEventListener(event: string, callback: (data: any) => void): void;
20
33
  run(functionName: string, params?: any): Promise<any>;
21
34
  }
35
+
36
+ export type IntentParams = Record<string, any>;
37
+
38
+ export class Intent {
39
+ // Predefined actions
40
+ static ACTION_VIEW: string;
41
+ static ACTION_OPEN: string;
42
+
43
+ // Fields
44
+ private readonly _applicationId: string;
45
+ private readonly _action: string;
46
+ private readonly _params: IntentParams;
47
+
48
+ /**
49
+ * @param applicationId The ID of the application this intent targets.
50
+ * @param action The action to perform (defaults to 'open').
51
+ * @param params Optional parameters for the action.
52
+ */
53
+ constructor(applicationId: string, action?: string, params?: IntentParams);
54
+
55
+ /** Application ID this intent targets */
56
+ get applicationId(): string;
57
+
58
+ /** Action this intent performs */
59
+ get action(): string;
60
+
61
+ /** Additional parameters for this intent */
62
+ get params(): IntentParams;
63
+
64
+ /**
65
+ * Validates if a given object is a valid Intent instance.
66
+ * @param obj Any object to validate.
67
+ * @returns True if the object is a valid Intent instance.
68
+ */
69
+ static isValid(obj: any): boolean;
70
+
71
+ /**
72
+ * Returns a stringified representation of the intent.
73
+ */
74
+ toString(): string;
75
+ }
76
+
77
+ /**
78
+ * Abstract base class for Valu iframe applications.
79
+ *
80
+ * Developers should extend this class to implement application-specific logic
81
+ * for handling lifecycle events within the Valu Social ecosystem.
82
+ *
83
+ * The Valu API will automatically call these lifecycle methods when the host
84
+ * application sends corresponding events (e.g., app launch, new intent, destroy).
85
+ */
86
+ export class ValuApplication {
87
+ /**
88
+ * Called when the app is first launched with an Intent.
89
+ *
90
+ * @param intent - The Intent that triggered the app launch.
91
+ * @returns A value or a Promise resolving to a value that will be sent back to the caller.
92
+ */
93
+ onCreate(intent: Intent): Promise<any> | any;
94
+
95
+ /**
96
+ * Called when the app receives an Intent while already running (docked).
97
+ *
98
+ * @param intent - The incoming Intent.
99
+ * @returns A value or a Promise resolving to a value that will be sent back to whoever triggered the Intent.
100
+ */
101
+ onNewIntent(intent: Intent): Promise<any> | any;
102
+
103
+ /**
104
+ * Called when the app is about to be destroyed.
105
+ *
106
+ * Use this to clean up resources (e.g., closing connections, clearing timers).
107
+ */
108
+ onDestroy(): void;
109
+ }
22
110
  }