rystem.playframework.client 0.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.
@@ -0,0 +1,116 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PlayFrameworkSettings = void 0;
4
+ /**
5
+ * Configuration for PlayFramework client.
6
+ */
7
+ class PlayFrameworkSettings {
8
+ /**
9
+ * Factory name (for multi-factory endpoints).
10
+ */
11
+ factoryName;
12
+ /**
13
+ * Base API URL (e.g., "https://api.example.com/api/ai").
14
+ */
15
+ baseUrl;
16
+ /**
17
+ * Default headers to include in all requests.
18
+ */
19
+ defaultHeaders;
20
+ /**
21
+ * Request timeout in milliseconds (default: 60000ms = 60s).
22
+ */
23
+ timeout;
24
+ /**
25
+ * Maximum number of SSE reconnection attempts on network failure (default: 3).
26
+ * Set to 0 to disable automatic reconnection.
27
+ */
28
+ maxReconnectAttempts;
29
+ /**
30
+ * Base delay in milliseconds between reconnection attempts (default: 1000ms).
31
+ * Uses exponential backoff: delay * 2^attempt.
32
+ */
33
+ reconnectBaseDelay;
34
+ /**
35
+ * Header enrichers (e.g., add Authorization header dynamically).
36
+ */
37
+ headersEnrichers;
38
+ /**
39
+ * Error handlers for retry logic.
40
+ */
41
+ errorHandlers;
42
+ constructor(factoryName, baseUrl) {
43
+ this.factoryName = factoryName;
44
+ this.baseUrl = baseUrl;
45
+ this.defaultHeaders = {
46
+ "Content-Type": "application/json"
47
+ };
48
+ this.timeout = 60000; // 60 seconds
49
+ this.maxReconnectAttempts = 3;
50
+ this.reconnectBaseDelay = 1000;
51
+ this.headersEnrichers = [];
52
+ this.errorHandlers = [];
53
+ }
54
+ /**
55
+ * Add a header enricher function (e.g., dynamic Authorization token).
56
+ */
57
+ addHeadersEnricher(enricher) {
58
+ this.headersEnrichers.push(enricher);
59
+ return this;
60
+ }
61
+ /**
62
+ * Add an error handler for retry logic.
63
+ */
64
+ addErrorHandler(handler) {
65
+ this.errorHandlers.push(handler);
66
+ return this;
67
+ }
68
+ /**
69
+ * Enrich headers with all registered enrichers.
70
+ */
71
+ async enrichHeaders(url, method, headers, body) {
72
+ const requestHeaders = new Headers();
73
+ const setHeaders = (currentHeaders) => {
74
+ if (currentHeaders instanceof Headers) {
75
+ currentHeaders.forEach((value, key) => {
76
+ requestHeaders.set(key, value);
77
+ });
78
+ }
79
+ else if (Array.isArray(currentHeaders)) {
80
+ currentHeaders.forEach(([key, value]) => {
81
+ requestHeaders.set(key, value);
82
+ });
83
+ }
84
+ else {
85
+ for (const [key, value] of Object.entries(currentHeaders)) {
86
+ requestHeaders.set(key, value);
87
+ }
88
+ }
89
+ };
90
+ // Default headers (lowest priority)
91
+ setHeaders(this.defaultHeaders);
92
+ // Provided headers (override defaults)
93
+ if (headers) {
94
+ setHeaders(headers);
95
+ }
96
+ // Enrichers (highest priority)
97
+ for (const enricher of this.headersEnrichers) {
98
+ setHeaders(await enricher(url, method, requestHeaders, body));
99
+ }
100
+ return requestHeaders;
101
+ }
102
+ /**
103
+ * Manage errors with all registered handlers. Returns true if should retry.
104
+ */
105
+ async manageError(url, method, headers, body, error) {
106
+ if (this.errorHandlers.length === 0) {
107
+ return false;
108
+ }
109
+ let retry = true;
110
+ for (const handler of this.errorHandlers) {
111
+ retry &&= await handler(url, method, headers, body, error);
112
+ }
113
+ return retry;
114
+ }
115
+ }
116
+ exports.PlayFrameworkSettings = PlayFrameworkSettings;
@@ -0,0 +1,68 @@
1
+ import { AIContent } from "../models/ClientInteractionResult";
2
+ /**
3
+ * Utility class for converting various inputs to AIContent format.
4
+ * Provides helpers for files, camera, geolocation, etc.
5
+ */
6
+ export declare class AIContentConverter {
7
+ /**
8
+ * Converts a File/Blob to Base64 DataContent.
9
+ * @param file - File or Blob to convert.
10
+ * @returns AIContent with Base64 data.
11
+ *
12
+ * @example
13
+ * const fileInput = document.querySelector('input[type="file"]') as HTMLInputElement;
14
+ * const file = fileInput.files[0];
15
+ * const content = await AIContentConverter.fromFile(file);
16
+ */
17
+ static fromFile(file: File | Blob): Promise<AIContent>;
18
+ /**
19
+ * Converts plain text to TextContent.
20
+ * @param text - Text string.
21
+ * @returns AIContent with text.
22
+ *
23
+ * @example
24
+ * const content = AIContentConverter.fromText("Hello world");
25
+ */
26
+ static fromText(text: string): AIContent;
27
+ /**
28
+ * Captures camera frame and returns Base64 DataContent.
29
+ * @param constraints - MediaStreamConstraints for camera (default: { video: true }).
30
+ * @param width - Canvas width (default: 640).
31
+ * @param height - Canvas height (default: 480).
32
+ * @returns AIContent with Base64 JPEG image.
33
+ *
34
+ * @example
35
+ * const content = await AIContentConverter.fromCamera();
36
+ */
37
+ static fromCamera(constraints?: MediaStreamConstraints, width?: number, height?: number): Promise<AIContent>;
38
+ /**
39
+ * Gets user's geolocation as TextContent (JSON format).
40
+ * @param options - GeolocationOptions.
41
+ * @returns AIContent with JSON coordinates.
42
+ *
43
+ * @example
44
+ * const content = await AIContentConverter.fromGeolocation();
45
+ * // Result: { type: "text", text: '{"latitude":45.1234,"longitude":7.5678}' }
46
+ */
47
+ static fromGeolocation(options?: PositionOptions): Promise<AIContent>;
48
+ /**
49
+ * Converts multiple files to DataContent array.
50
+ * @param files - FileList or File array.
51
+ * @returns Array of AIContent.
52
+ *
53
+ * @example
54
+ * const files = fileInput.files;
55
+ * const contents = await AIContentConverter.fromMultipleFiles(files);
56
+ */
57
+ static fromMultipleFiles(files: FileList | File[]): Promise<AIContent[]>;
58
+ /**
59
+ * Records audio from microphone and returns Base64 DataContent.
60
+ * @param durationMs - Recording duration in milliseconds (default: 5000).
61
+ * @param mimeType - Audio MIME type (default: "audio/webm").
62
+ * @returns AIContent with Base64 audio.
63
+ *
64
+ * @example
65
+ * const content = await AIContentConverter.fromMicrophone(3000);
66
+ */
67
+ static fromMicrophone(durationMs?: number, mimeType?: string): Promise<AIContent>;
68
+ }
@@ -0,0 +1,170 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AIContentConverter = void 0;
4
+ /**
5
+ * Utility class for converting various inputs to AIContent format.
6
+ * Provides helpers for files, camera, geolocation, etc.
7
+ */
8
+ class AIContentConverter {
9
+ /**
10
+ * Converts a File/Blob to Base64 DataContent.
11
+ * @param file - File or Blob to convert.
12
+ * @returns AIContent with Base64 data.
13
+ *
14
+ * @example
15
+ * const fileInput = document.querySelector('input[type="file"]') as HTMLInputElement;
16
+ * const file = fileInput.files[0];
17
+ * const content = await AIContentConverter.fromFile(file);
18
+ */
19
+ static async fromFile(file) {
20
+ return new Promise((resolve, reject) => {
21
+ const reader = new FileReader();
22
+ reader.onload = () => {
23
+ const result = reader.result;
24
+ // Extract Base64 part after "data:...;base64,"
25
+ const base64 = result.split(",")[1];
26
+ resolve({
27
+ type: "data",
28
+ data: base64,
29
+ mediaType: file.type || "application/octet-stream"
30
+ });
31
+ };
32
+ reader.onerror = () => {
33
+ reject(new Error("Failed to read file"));
34
+ };
35
+ reader.readAsDataURL(file);
36
+ });
37
+ }
38
+ /**
39
+ * Converts plain text to TextContent.
40
+ * @param text - Text string.
41
+ * @returns AIContent with text.
42
+ *
43
+ * @example
44
+ * const content = AIContentConverter.fromText("Hello world");
45
+ */
46
+ static fromText(text) {
47
+ return {
48
+ type: "text",
49
+ text
50
+ };
51
+ }
52
+ /**
53
+ * Captures camera frame and returns Base64 DataContent.
54
+ * @param constraints - MediaStreamConstraints for camera (default: { video: true }).
55
+ * @param width - Canvas width (default: 640).
56
+ * @param height - Canvas height (default: 480).
57
+ * @returns AIContent with Base64 JPEG image.
58
+ *
59
+ * @example
60
+ * const content = await AIContentConverter.fromCamera();
61
+ */
62
+ static async fromCamera(constraints = { video: true }, width = 640, height = 480) {
63
+ const stream = await navigator.mediaDevices.getUserMedia(constraints);
64
+ try {
65
+ const video = document.createElement("video");
66
+ video.srcObject = stream;
67
+ video.play();
68
+ // Wait for video to be ready
69
+ await new Promise((resolve) => {
70
+ video.onloadedmetadata = resolve;
71
+ });
72
+ // Capture frame
73
+ const canvas = document.createElement("canvas");
74
+ canvas.width = width;
75
+ canvas.height = height;
76
+ const ctx = canvas.getContext("2d");
77
+ ctx.drawImage(video, 0, 0, width, height);
78
+ // Convert to Base64
79
+ const dataUrl = canvas.toDataURL("image/jpeg", 0.9);
80
+ const base64 = dataUrl.split(",")[1];
81
+ return {
82
+ type: "data",
83
+ data: base64,
84
+ mediaType: "image/jpeg"
85
+ };
86
+ }
87
+ finally {
88
+ // Stop camera
89
+ stream.getTracks().forEach((track) => track.stop());
90
+ }
91
+ }
92
+ /**
93
+ * Gets user's geolocation as TextContent (JSON format).
94
+ * @param options - GeolocationOptions.
95
+ * @returns AIContent with JSON coordinates.
96
+ *
97
+ * @example
98
+ * const content = await AIContentConverter.fromGeolocation();
99
+ * // Result: { type: "text", text: '{"latitude":45.1234,"longitude":7.5678}' }
100
+ */
101
+ static async fromGeolocation(options) {
102
+ return new Promise((resolve, reject) => {
103
+ navigator.geolocation.getCurrentPosition((position) => {
104
+ const coordinates = {
105
+ latitude: position.coords.latitude,
106
+ longitude: position.coords.longitude,
107
+ accuracy: position.coords.accuracy,
108
+ altitude: position.coords.altitude,
109
+ altitudeAccuracy: position.coords.altitudeAccuracy,
110
+ heading: position.coords.heading,
111
+ speed: position.coords.speed
112
+ };
113
+ resolve({
114
+ type: "text",
115
+ text: JSON.stringify(coordinates)
116
+ });
117
+ }, (error) => {
118
+ reject(new Error(`Geolocation error: ${error.message}`));
119
+ }, options);
120
+ });
121
+ }
122
+ /**
123
+ * Converts multiple files to DataContent array.
124
+ * @param files - FileList or File array.
125
+ * @returns Array of AIContent.
126
+ *
127
+ * @example
128
+ * const files = fileInput.files;
129
+ * const contents = await AIContentConverter.fromMultipleFiles(files);
130
+ */
131
+ static async fromMultipleFiles(files) {
132
+ const fileArray = Array.from(files);
133
+ return Promise.all(fileArray.map((file) => this.fromFile(file)));
134
+ }
135
+ /**
136
+ * Records audio from microphone and returns Base64 DataContent.
137
+ * @param durationMs - Recording duration in milliseconds (default: 5000).
138
+ * @param mimeType - Audio MIME type (default: "audio/webm").
139
+ * @returns AIContent with Base64 audio.
140
+ *
141
+ * @example
142
+ * const content = await AIContentConverter.fromMicrophone(3000);
143
+ */
144
+ static async fromMicrophone(durationMs = 5000, mimeType = "audio/webm") {
145
+ const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
146
+ try {
147
+ const mediaRecorder = new MediaRecorder(stream, { mimeType });
148
+ const chunks = [];
149
+ mediaRecorder.ondataavailable = (event) => {
150
+ if (event.data.size > 0) {
151
+ chunks.push(event.data);
152
+ }
153
+ };
154
+ mediaRecorder.start();
155
+ // Wait for duration
156
+ await new Promise((resolve) => setTimeout(resolve, durationMs));
157
+ // Set onstop handler BEFORE calling stop to avoid race condition
158
+ await new Promise((resolve) => {
159
+ mediaRecorder.onstop = () => resolve();
160
+ mediaRecorder.stop();
161
+ });
162
+ const audioBlob = new Blob(chunks, { type: mimeType });
163
+ return this.fromFile(audioBlob);
164
+ }
165
+ finally {
166
+ stream.getTracks().forEach((track) => track.stop());
167
+ }
168
+ }
169
+ }
170
+ exports.AIContentConverter = AIContentConverter;
package/package.json ADDED
@@ -0,0 +1,44 @@
1
+ {
2
+ "name": "rystem.playframework.client",
3
+ "version": "0.1.0",
4
+ "author": "Alessandro Rapiti <alessandro.rapiti44@gmail.com>",
5
+ "license": "MIT",
6
+ "description": "TypeScript client for Rystem PlayFramework HTTP API with step-by-step and token-level streaming support.",
7
+ "main": "./lib/index.js",
8
+ "module": "./lib/index.js",
9
+ "types": "./lib/index.d.ts",
10
+ "exports": {
11
+ ".": {
12
+ "types": "./lib/index.d.ts",
13
+ "import": "./lib/index.js",
14
+ "require": "./lib/index.js",
15
+ "default": "./lib/index.js"
16
+ }
17
+ },
18
+ "sideEffects": false,
19
+ "keywords": [
20
+ "rystem",
21
+ "playframework",
22
+ "ai",
23
+ "streaming",
24
+ "sse",
25
+ "typescript",
26
+ "client"
27
+ ],
28
+ "repository": {
29
+ "type": "git",
30
+ "url": "https://github.com/KeyserDSoze/Rystem.git"
31
+ },
32
+ "devDependencies": {
33
+ "@types/node": "^22.15.16",
34
+ "@typescript-eslint/parser": "8.24.1",
35
+ "typescript": "5.7.3"
36
+ },
37
+ "scripts": {
38
+ "build": "tsc",
39
+ "prepublishOnly": "npm run build"
40
+ },
41
+ "files": [
42
+ "/lib"
43
+ ]
44
+ }