@promte/app-library 0.1.1 → 0.1.2

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/dist/index.d.ts CHANGED
@@ -1,11 +1,69 @@
1
1
  import { default as default_2 } from 'react';
2
2
  import { JSX as JSX_2 } from 'react/jsx-runtime';
3
3
 
4
+ export declare type AppDataRef = {
5
+ get(): Promise<any>;
6
+ set(value: any): Promise<any>;
7
+ update(updates: AppDataUpdateMap): Promise<any>;
8
+ remove(): Promise<any>;
9
+ push(value: any): Promise<any>;
10
+ ref(path: string): AppDataRef;
11
+ };
12
+
13
+ export declare type AppDataScope = "private" | "public";
14
+
15
+ export declare type AppDataUpdateMap = Record<string, any>;
16
+
17
+ export declare type AudioSttRequest = {
18
+ file: File | Blob;
19
+ language?: string;
20
+ prompt?: string;
21
+ ext?: string;
22
+ };
23
+
24
+ export declare type AudioSttResponse = {
25
+ text: string;
26
+ raw: any;
27
+ };
28
+
29
+ export declare type AudioTtsRequest = {
30
+ text: string;
31
+ voice?: string;
32
+ lang?: string;
33
+ };
34
+
35
+ export declare type AudioTtsResponse = {
36
+ audio: ArrayBuffer;
37
+ contentType: string | null;
38
+ };
39
+
40
+ export declare type AudioVoiceInfo = {
41
+ short_name?: string;
42
+ locale?: string;
43
+ local_name?: string;
44
+ locale_english_name?: string;
45
+ locale_native_name?: string;
46
+ gender?: string;
47
+ voice_type?: string;
48
+ name?: string;
49
+ display_name?: string;
50
+ style_list?: string[];
51
+ sample_rate_hertz?: string;
52
+ status?: string;
53
+ words_per_minute?: string;
54
+ };
55
+
56
+ export declare type AudioVoicesRequest = {
57
+ locale?: string;
58
+ };
59
+
4
60
  export declare type ChatCompletionsRequest = {
5
61
  model: string;
6
62
  messages: ChatMessage[];
7
63
  stream?: false;
8
64
  temperature?: number;
65
+ reasoningEffort?: ReasoningEffort;
66
+ reasoning_effort?: ReasoningEffort;
9
67
  };
10
68
 
11
69
  export declare type ChatCompletionsResponse = any;
@@ -33,12 +91,19 @@ export declare type PromteClient = {
33
91
  getBackendUrl(): string | null;
34
92
  chatCompletions(req: ChatCompletionsRequest): Promise<ChatCompletionsResponse>;
35
93
  chatText(req: ChatCompletionsRequest): Promise<string>;
94
+ audio: {
95
+ tts(req: AudioTtsRequest): Promise<AudioTtsResponse>;
96
+ stt(req: AudioSttRequest): Promise<AudioSttResponse>;
97
+ voices(req?: AudioVoicesRequest): Promise<AudioVoiceInfo[]>;
98
+ };
99
+ data(scope?: AppDataScope): AppDataRef;
36
100
  };
37
101
 
38
102
  declare type PromteCtxValue = {
39
103
  settings: PromteSettings | null;
40
104
  token: string | null;
41
105
  isDarkMode: boolean | null;
106
+ user: PromteUser | null;
42
107
  ready: boolean;
43
108
  state: PromteHandshakeState;
44
109
  error: string | null;
@@ -52,8 +117,18 @@ export declare type PromteSettings = {
52
117
  version: number;
53
118
  backendUrl: string;
54
119
  parentOrigin?: string;
120
+ user?: PromteUser;
121
+ };
122
+
123
+ export declare type PromteUser = {
124
+ email?: string;
125
+ isAdmin?: boolean;
126
+ role?: string;
127
+ workspaceId?: string;
55
128
  };
56
129
 
130
+ export declare type ReasoningEffort = "minimal" | "low" | "medium" | "high";
131
+
57
132
  export declare function usePromte(): PromteCtxValue;
58
133
 
59
134
  export declare function usePromteClient(): PromteClient;
@@ -64,4 +139,6 @@ export declare function usePromteSettings(): PromteSettings;
64
139
 
65
140
  export declare function usePromteToken(): string;
66
141
 
142
+ export declare function usePromteUser(): PromteUser;
143
+
67
144
  export { }
package/dist/index.mjs CHANGED
@@ -1,145 +1,298 @@
1
- import { jsx as T } from "react/jsx-runtime";
2
- import { createContext as U, useState as w, useMemo as p, useCallback as j, useEffect as g, useContext as x } from "react";
3
- const P = U(null);
4
- function L({
5
- children: u,
6
- expectedParentOrigin: o,
7
- initTargetOrigin: f,
8
- retryInit: n = { enabled: !0, intervalMs: 500, maxAttempts: 20 }
1
+ import { jsx as M } from "react/jsx-runtime";
2
+ import { createContext as A, useState as E, useMemo as j, useCallback as D, useEffect as R, useContext as L } from "react";
3
+ const U = A(null);
4
+ function z({
5
+ children: y,
6
+ expectedParentOrigin: h,
7
+ initTargetOrigin: v,
8
+ retryInit: f = { enabled: !0, intervalMs: 500, maxAttempts: 20 }
9
9
  }) {
10
- const [t, c] = w(null), [e, i] = w(null), [v, E] = w(null), [m, k] = w(null), y = p(() => m ? "booting" : t ? e ? "ready" : "waiting_for_token" : "waiting_for_settings", [t, e, m]), b = y === "ready", M = p(() => f || o || "*", [f, o]), d = j(() => {
11
- var l;
10
+ const [u, P] = E(null), [p, x] = E(null), [k, e] = E(null), [r, n] = E(null), [t, o] = E(null), i = j(() => t ? "booting" : u ? p ? "ready" : "waiting_for_token" : "waiting_for_settings", [u, p, t]), l = i === "ready", w = j(() => v || h || "*", [v, h]), d = D(() => {
11
+ var g;
12
12
  try {
13
- const s = { type: "init" };
14
- (l = window.parent) == null || l.postMessage(s, M);
15
- } catch (s) {
16
- k((s == null ? void 0 : s.message) || "Failed to post init");
13
+ const m = { type: "init" };
14
+ (g = window.parent) == null || g.postMessage(m, w);
15
+ } catch (m) {
16
+ o((m == null ? void 0 : m.message) || "Failed to post init");
17
17
  }
18
- }, [M]);
19
- g(() => {
18
+ }, [w]);
19
+ R(() => {
20
20
  d();
21
- }, [d]), g(() => {
22
- if (!(n != null && n.enabled) || t) return;
23
- const l = n.intervalMs ?? 500, s = n.maxAttempts ?? 20;
24
- let r = 0;
25
- const a = window.setInterval(() => {
26
- if (t) {
27
- window.clearInterval(a);
21
+ }, [d]), R(() => {
22
+ if (!(f != null && f.enabled) || u) return;
23
+ const g = f.intervalMs ?? 500, m = f.maxAttempts ?? 20;
24
+ let a = 0;
25
+ const c = window.setInterval(() => {
26
+ if (u) {
27
+ window.clearInterval(c);
28
28
  return;
29
29
  }
30
- if (r += 1, r > s) {
31
- window.clearInterval(a);
30
+ if (a += 1, a > m) {
31
+ window.clearInterval(c);
32
32
  return;
33
33
  }
34
34
  d();
35
- }, l);
36
- return () => window.clearInterval(a);
37
- }, [n, t, d]), g(() => {
38
- const l = (s) => {
39
- if (o && s.origin !== o) return;
40
- const r = s.data;
41
- if (!(!r || typeof r != "object")) {
42
- if (r.type === "set-settings") {
43
- const a = r.value;
44
- if (!(a != null && a.backendUrl) || a.parentOrigin && o && a.parentOrigin !== o)
35
+ }, g);
36
+ return () => window.clearInterval(c);
37
+ }, [f, u, d]), R(() => {
38
+ const g = (m) => {
39
+ if (h && m.origin !== h) return;
40
+ const a = m.data;
41
+ if (!(!a || typeof a != "object")) {
42
+ if (a.type === "set-settings") {
43
+ const c = a.value;
44
+ if (!(c != null && c.backendUrl) || c.parentOrigin && h && c.parentOrigin !== h)
45
45
  return;
46
- c(a), k(null);
46
+ P(c), c != null && c.user && n(c.user), o(null);
47
47
  return;
48
48
  }
49
- if (r.type === "set-token" && typeof r.value == "string") {
50
- i(r.value), k(null);
49
+ if (a.type === "set-token" && typeof a.value == "string") {
50
+ x(a.value), o(null);
51
51
  return;
52
52
  }
53
- if (r.type === "set-dark-mode" && typeof r.value == "boolean") {
54
- E(r.value);
53
+ if (a.type === "set-dark-mode" && typeof a.value == "boolean") {
54
+ e(a.value);
55
+ return;
56
+ }
57
+ if (a.type === "set-user" && typeof a.value == "object") {
58
+ n(a.value);
55
59
  return;
56
60
  }
57
61
  }
58
62
  };
59
- return window.addEventListener("message", l), () => window.removeEventListener("message", l);
60
- }, [o]);
61
- const C = p(() => D(
62
- () => t,
63
- () => e
64
- ), [t, e]), A = p(
63
+ return window.addEventListener("message", g), () => window.removeEventListener("message", g);
64
+ }, [h]);
65
+ const s = j(() => F(
66
+ () => u,
67
+ () => p
68
+ ), [u, p]), T = j(
65
69
  () => ({
66
- settings: t,
67
- token: e,
68
- isDarkMode: v,
69
- ready: b,
70
- state: y,
71
- error: m,
72
- client: C
70
+ settings: u,
71
+ token: p,
72
+ isDarkMode: k,
73
+ user: r,
74
+ ready: l,
75
+ state: i,
76
+ error: t,
77
+ client: s
73
78
  }),
74
- [t, e, v, b, y, m, C]
79
+ [u, p, k, r, l, i, t, s]
75
80
  );
76
- return /* @__PURE__ */ T(P.Provider, { value: A, children: u });
81
+ return /* @__PURE__ */ M(U.Provider, { value: T, children: y });
77
82
  }
78
- function h() {
79
- const u = x(P);
80
- if (!u)
83
+ function b() {
84
+ const y = L(U);
85
+ if (!y)
81
86
  throw new Error("usePromte must be used inside <PromteAppProvider>");
82
- return u;
87
+ return y;
83
88
  }
84
- function R() {
85
- return h().settings;
89
+ function G() {
90
+ return b().settings;
86
91
  }
87
- function B() {
88
- return h().token;
92
+ function J() {
93
+ return b().token;
89
94
  }
90
- function F() {
91
- return h().isDarkMode;
95
+ function N() {
96
+ return b().isDarkMode;
92
97
  }
93
- function $() {
94
- return h().client;
98
+ function O() {
99
+ return b().user;
95
100
  }
96
- function D(u, o) {
97
- async function f(n, t) {
98
- const c = u(), e = o();
99
- if (!c) throw new Error("Promte settings not received yet");
100
- if (!e) throw new Error("Promte token not received yet");
101
- const i = new URL(c.backendUrl + "/" + n).toString();
102
- return await fetch(i, {
103
- ...t,
101
+ function I() {
102
+ return b().client;
103
+ }
104
+ function F(y, h) {
105
+ const v = (e) => typeof e == "string" && e.startsWith("gpt-5");
106
+ async function f(e, r) {
107
+ const n = y(), t = h();
108
+ if (!n) throw new Error("Promte settings not received yet");
109
+ if (!t) throw new Error("Promte token not received yet");
110
+ const o = new URL(n.backendUrl + "/" + e).toString();
111
+ return await fetch(o, {
112
+ ...r,
104
113
  headers: {
105
- ...t.headers || {},
106
- Authorization: `Bearer ${e}`
114
+ ...r.headers || {},
115
+ Authorization: `Bearer ${t}`
107
116
  }
108
117
  });
109
118
  }
119
+ async function u(e, r) {
120
+ const n = await f(`/app-api/data/${e}`, {
121
+ method: "POST",
122
+ headers: { "Content-Type": "application/json" },
123
+ body: JSON.stringify(r)
124
+ }), t = await n.json().catch(() => ({}));
125
+ if (!n.ok)
126
+ throw new Error(
127
+ (t == null ? void 0 : t.error) || `Request failed (${n.status})`
128
+ );
129
+ return t == null ? void 0 : t.value;
130
+ }
131
+ async function P(e) {
132
+ const r = new URLSearchParams();
133
+ e.scope && r.set("scope", e.scope), e.path && r.set("path", e.path);
134
+ const n = await f(`/app-api/data?${r.toString()}`, {
135
+ method: "GET"
136
+ }), t = await n.json().catch(() => ({}));
137
+ if (!n.ok)
138
+ throw new Error((t == null ? void 0 : t.error) || `Request failed (${n.status})`);
139
+ return t == null ? void 0 : t.value;
140
+ }
141
+ const p = (e) => e ? e.split("/").map((r) => r.trim()).filter(Boolean).join("/") : "", x = (e, r) => {
142
+ const n = p(e), t = p(r);
143
+ return n ? t ? `${n}/${t}` : n : t;
144
+ }, k = (e, r) => {
145
+ const n = { scope: e };
146
+ return {
147
+ async get() {
148
+ const t = p(r);
149
+ return P({ ...n, path: t || void 0 });
150
+ },
151
+ async set(t) {
152
+ const o = p(r);
153
+ return u("set", {
154
+ ...n,
155
+ path: o || void 0,
156
+ value: t
157
+ });
158
+ },
159
+ async update(t) {
160
+ if (!t || typeof t != "object")
161
+ throw new Error("update requires an object");
162
+ const o = {};
163
+ for (const [i, l] of Object.entries(t)) {
164
+ const w = x(r, i);
165
+ if (!w)
166
+ throw new Error("update paths must be non-empty");
167
+ o[w] = l;
168
+ }
169
+ return u("update", { ...n, updates: o });
170
+ },
171
+ async remove() {
172
+ const t = p(r);
173
+ return u("remove", { ...n, path: t || void 0 });
174
+ },
175
+ async push(t) {
176
+ const o = p(r);
177
+ if (!o) throw new Error("push requires a path");
178
+ return u("array-push", { ...n, path: o, value: t });
179
+ },
180
+ ref(t) {
181
+ const o = x(r, t);
182
+ if (!o) throw new Error("ref requires a path");
183
+ return k(e, o);
184
+ }
185
+ };
186
+ };
110
187
  return {
111
188
  isReady() {
112
- return !!u() && !!o();
189
+ return !!y() && !!h();
113
190
  },
114
191
  getBackendUrl() {
115
- var n;
116
- return ((n = u()) == null ? void 0 : n.backendUrl) ?? null;
192
+ var e;
193
+ return ((e = y()) == null ? void 0 : e.backendUrl) ?? null;
117
194
  },
118
- async chatCompletions(n) {
119
- var i;
120
- const t = await f("/openai/chat/completions", {
195
+ async chatCompletions(e) {
196
+ var s;
197
+ const {
198
+ reasoningEffort: r,
199
+ reasoning_effort: n,
200
+ ...t
201
+ } = e, o = r ?? n, i = {
202
+ ...t,
203
+ stream: !1
204
+ };
205
+ o && v(e.model) && (i.reasoning_effort = o);
206
+ const l = await f("/openai/chat/completions", {
121
207
  method: "POST",
122
208
  headers: { "Content-Type": "application/json" },
123
- body: JSON.stringify({ ...n, stream: !1 })
124
- }), e = (t.headers.get("content-type") || "").includes("application/json") ? await t.json() : await t.text();
125
- if (!t.ok)
209
+ body: JSON.stringify(i)
210
+ }), d = (l.headers.get("content-type") || "").includes("application/json") ? await l.json() : await l.text();
211
+ if (!l.ok)
126
212
  throw new Error(
127
- typeof e == "string" ? e : ((i = e == null ? void 0 : e.error) == null ? void 0 : i.message) || `Request failed (${t.status})`
213
+ typeof d == "string" ? d : ((s = d == null ? void 0 : d.error) == null ? void 0 : s.message) || `Request failed (${l.status})`
128
214
  );
129
- return e;
215
+ return d;
216
+ },
217
+ async chatText(e) {
218
+ var n, t, o;
219
+ const r = await this.chatCompletions(e);
220
+ return ((o = (t = (n = r == null ? void 0 : r.choices) == null ? void 0 : n[0]) == null ? void 0 : t.message) == null ? void 0 : o.content) ?? "";
221
+ },
222
+ audio: {
223
+ async tts(e) {
224
+ var o;
225
+ const r = (o = e == null ? void 0 : e.text) == null ? void 0 : o.trim();
226
+ if (!r) throw new Error("audio.tts requires non-empty text");
227
+ const n = await f("/app-api/audio/tts", {
228
+ method: "POST",
229
+ headers: { "Content-Type": "application/json" },
230
+ body: JSON.stringify({
231
+ text: r,
232
+ voice: e.voice,
233
+ lang: e.lang
234
+ })
235
+ });
236
+ if (!n.ok) {
237
+ const i = await n.text();
238
+ throw new Error(i || `Request failed (${n.status})`);
239
+ }
240
+ return {
241
+ audio: await n.arrayBuffer(),
242
+ contentType: n.headers.get("content-type")
243
+ };
244
+ },
245
+ async stt(e) {
246
+ var g, m, a;
247
+ if (!(e != null && e.file)) throw new Error("audio.stt requires a file");
248
+ const r = (c) => {
249
+ if (!c) return;
250
+ const $ = c.trim();
251
+ if (!$) return;
252
+ const C = $.toLowerCase(), S = C.split("-")[0];
253
+ return S.length === 2 ? S : C;
254
+ }, n = typeof File < "u" && e.file instanceof File, t = n && e.file.name.split(".").pop() || "webm", o = e.ext || t, i = new FormData();
255
+ n ? i.set("file", e.file) : i.set("file", e.file, `audio.${o}`);
256
+ const l = r(e.language);
257
+ l && i.set("language", l), e.prompt && i.set("prompt", e.prompt);
258
+ const w = await f(
259
+ `/app-api/audio/stt?ext=${encodeURIComponent(o)}`,
260
+ {
261
+ method: "POST",
262
+ body: i
263
+ }
264
+ ), s = (w.headers.get("content-type") || "").includes("application/json") ? await w.json() : await w.text();
265
+ if (!w.ok)
266
+ throw new Error(
267
+ typeof s == "string" ? s : ((g = s == null ? void 0 : s.error) == null ? void 0 : g.message) || `Request failed (${w.status})`
268
+ );
269
+ return { text: typeof s == "string" ? s : (s == null ? void 0 : s.text) || (s == null ? void 0 : s.original) || ((a = (m = s == null ? void 0 : s.results) == null ? void 0 : m[0]) == null ? void 0 : a.text) || "", raw: s };
270
+ },
271
+ async voices(e) {
272
+ const r = new URLSearchParams();
273
+ e != null && e.locale && r.set("locale", e.locale);
274
+ const n = await f(
275
+ `/app-api/audio/tts/voices${r.toString() ? `?${r}` : ""}`,
276
+ { method: "GET" }
277
+ ), t = await n.json().catch(() => []);
278
+ if (!n.ok)
279
+ throw new Error(
280
+ (t == null ? void 0 : t.error) || `Request failed (${n.status})`
281
+ );
282
+ return Array.isArray(t) ? t : (t == null ? void 0 : t.voices) || [];
283
+ }
130
284
  },
131
- async chatText(n) {
132
- var c, e, i;
133
- const t = await this.chatCompletions(n);
134
- return ((i = (e = (c = t == null ? void 0 : t.choices) == null ? void 0 : c[0]) == null ? void 0 : e.message) == null ? void 0 : i.content) ?? "";
285
+ data(e = "private") {
286
+ return k(e, "");
135
287
  }
136
288
  };
137
289
  }
138
290
  export {
139
- L as PromteAppProvider,
140
- h as usePromte,
141
- $ as usePromteClient,
142
- F as usePromteDarkMode,
143
- R as usePromteSettings,
144
- B as usePromteToken
291
+ z as PromteAppProvider,
292
+ b as usePromte,
293
+ I as usePromteClient,
294
+ N as usePromteDarkMode,
295
+ G as usePromteSettings,
296
+ J as usePromteToken,
297
+ O as usePromteUser
145
298
  };
@@ -1 +1 @@
1
- (function(r,m){typeof exports=="object"&&typeof module<"u"?m(exports,require("react/jsx-runtime"),require("react")):typeof define=="function"&&define.amd?define(["exports","react/jsx-runtime","react"],m):(r=typeof globalThis<"u"?globalThis:r||self,m(r.PromteAppLibrary={},r.jsxRuntime,r.react))})(this,function(r,m,o){"use strict";const g=o.createContext(null);function E({children:l,expectedParentOrigin:u,initTargetOrigin:w,retryInit:n={enabled:!0,intervalMs:500,maxAttempts:20}}){const[e,f]=o.useState(null),[t,c]=o.useState(null),[y,U]=o.useState(null),[h,k]=o.useState(null),P=o.useMemo(()=>h?"booting":e?t?"ready":"waiting_for_token":"waiting_for_settings",[e,t,h]),M=P==="ready",b=o.useMemo(()=>w||u||"*",[w,u]),v=o.useCallback(()=>{var d;try{const i={type:"init"};(d=window.parent)==null||d.postMessage(i,b)}catch(i){k((i==null?void 0:i.message)||"Failed to post init")}},[b]);o.useEffect(()=>{v()},[v]),o.useEffect(()=>{if(!(n!=null&&n.enabled)||e)return;const d=n.intervalMs??500,i=n.maxAttempts??20;let s=0;const a=window.setInterval(()=>{if(e){window.clearInterval(a);return}if(s+=1,s>i){window.clearInterval(a);return}v()},d);return()=>window.clearInterval(a)},[n,e,v]),o.useEffect(()=>{const d=i=>{if(u&&i.origin!==u)return;const s=i.data;if(!(!s||typeof s!="object")){if(s.type==="set-settings"){const a=s.value;if(!(a!=null&&a.backendUrl)||a.parentOrigin&&u&&a.parentOrigin!==u)return;f(a),k(null);return}if(s.type==="set-token"&&typeof s.value=="string"){c(s.value),k(null);return}if(s.type==="set-dark-mode"&&typeof s.value=="boolean"){U(s.value);return}}};return window.addEventListener("message",d),()=>window.removeEventListener("message",d)},[u]);const C=o.useMemo(()=>D(()=>e,()=>t),[e,t]),L=o.useMemo(()=>({settings:e,token:t,isDarkMode:y,ready:M,state:P,error:h,client:C}),[e,t,y,M,P,h,C]);return m.jsx(g.Provider,{value:L,children:l})}function p(){const l=o.useContext(g);if(!l)throw new Error("usePromte must be used inside <PromteAppProvider>");return l}function S(){return p().settings}function j(){return p().token}function T(){return p().isDarkMode}function A(){return p().client}function D(l,u){async function w(n,e){const f=l(),t=u();if(!f)throw new Error("Promte settings not received yet");if(!t)throw new Error("Promte token not received yet");const c=new URL(f.backendUrl+"/"+n).toString();return await fetch(c,{...e,headers:{...e.headers||{},Authorization:`Bearer ${t}`}})}return{isReady(){return!!l()&&!!u()},getBackendUrl(){var n;return((n=l())==null?void 0:n.backendUrl)??null},async chatCompletions(n){var c;const e=await w("/openai/chat/completions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...n,stream:!1})}),t=(e.headers.get("content-type")||"").includes("application/json")?await e.json():await e.text();if(!e.ok)throw new Error(typeof t=="string"?t:((c=t==null?void 0:t.error)==null?void 0:c.message)||`Request failed (${e.status})`);return t},async chatText(n){var f,t,c;const e=await this.chatCompletions(n);return((c=(t=(f=e==null?void 0:e.choices)==null?void 0:f[0])==null?void 0:t.message)==null?void 0:c.content)??""}}}r.PromteAppProvider=E,r.usePromte=p,r.usePromteClient=A,r.usePromteDarkMode=T,r.usePromteSettings=S,r.usePromteToken=j,Object.defineProperty(r,Symbol.toStringTag,{value:"Module"})});
1
+ (function(f,P){typeof exports=="object"&&typeof module<"u"?P(exports,require("react/jsx-runtime"),require("react")):typeof define=="function"&&define.amd?define(["exports","react/jsx-runtime","react"],P):(f=typeof globalThis<"u"?globalThis:f||self,P(f.PromteAppLibrary={},f.jsxRuntime,f.react))})(this,function(f,P,c){"use strict";const x=c.createContext(null);function U({children:k,expectedParentOrigin:y,initTargetOrigin:j,retryInit:l={enabled:!0,intervalMs:500,maxAttempts:20}}){const[p,T]=c.useState(null),[m,S]=c.useState(null),[b,e]=c.useState(null),[o,n]=c.useState(null),[t,r]=c.useState(null),a=c.useMemo(()=>t?"booting":p?m?"ready":"waiting_for_token":"waiting_for_settings",[p,m,t]),d=a==="ready",h=c.useMemo(()=>j||y||"*",[j,y]),g=c.useCallback(()=>{var v;try{const w={type:"init"};(v=window.parent)==null||v.postMessage(w,h)}catch(w){r((w==null?void 0:w.message)||"Failed to post init")}},[h]);c.useEffect(()=>{g()},[g]),c.useEffect(()=>{if(!(l!=null&&l.enabled)||p)return;const v=l.intervalMs??500,w=l.maxAttempts??20;let i=0;const u=window.setInterval(()=>{if(p){window.clearInterval(u);return}if(i+=1,i>w){window.clearInterval(u);return}g()},v);return()=>window.clearInterval(u)},[l,p,g]),c.useEffect(()=>{const v=w=>{if(y&&w.origin!==y)return;const i=w.data;if(!(!i||typeof i!="object")){if(i.type==="set-settings"){const u=i.value;if(!(u!=null&&u.backendUrl)||u.parentOrigin&&y&&u.parentOrigin!==y)return;T(u),u!=null&&u.user&&n(u.user),r(null);return}if(i.type==="set-token"&&typeof i.value=="string"){S(i.value),r(null);return}if(i.type==="set-dark-mode"&&typeof i.value=="boolean"){e(i.value);return}if(i.type==="set-user"&&typeof i.value=="object"){n(i.value);return}}};return window.addEventListener("message",v),()=>window.removeEventListener("message",v)},[y]);const s=c.useMemo(()=>B(()=>p,()=>m),[p,m]),R=c.useMemo(()=>({settings:p,token:m,isDarkMode:b,user:o,ready:d,state:a,error:t,client:s}),[p,m,b,o,d,a,t,s]);return P.jsx(x.Provider,{value:R,children:k})}function E(){const k=c.useContext(x);if(!k)throw new Error("usePromte must be used inside <PromteAppProvider>");return k}function A(){return E().settings}function D(){return E().token}function L(){return E().isDarkMode}function F(){return E().user}function _(){return E().client}function B(k,y){const j=e=>typeof e=="string"&&e.startsWith("gpt-5");async function l(e,o){const n=k(),t=y();if(!n)throw new Error("Promte settings not received yet");if(!t)throw new Error("Promte token not received yet");const r=new URL(n.backendUrl+"/"+e).toString();return await fetch(r,{...o,headers:{...o.headers||{},Authorization:`Bearer ${t}`}})}async function p(e,o){const n=await l(`/app-api/data/${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)}),t=await n.json().catch(()=>({}));if(!n.ok)throw new Error((t==null?void 0:t.error)||`Request failed (${n.status})`);return t==null?void 0:t.value}async function T(e){const o=new URLSearchParams;e.scope&&o.set("scope",e.scope),e.path&&o.set("path",e.path);const n=await l(`/app-api/data?${o.toString()}`,{method:"GET"}),t=await n.json().catch(()=>({}));if(!n.ok)throw new Error((t==null?void 0:t.error)||`Request failed (${n.status})`);return t==null?void 0:t.value}const m=e=>e?e.split("/").map(o=>o.trim()).filter(Boolean).join("/"):"",S=(e,o)=>{const n=m(e),t=m(o);return n?t?`${n}/${t}`:n:t},b=(e,o)=>{const n={scope:e};return{async get(){const t=m(o);return T({...n,path:t||void 0})},async set(t){const r=m(o);return p("set",{...n,path:r||void 0,value:t})},async update(t){if(!t||typeof t!="object")throw new Error("update requires an object");const r={};for(const[a,d]of Object.entries(t)){const h=S(o,a);if(!h)throw new Error("update paths must be non-empty");r[h]=d}return p("update",{...n,updates:r})},async remove(){const t=m(o);return p("remove",{...n,path:t||void 0})},async push(t){const r=m(o);if(!r)throw new Error("push requires a path");return p("array-push",{...n,path:r,value:t})},ref(t){const r=S(o,t);if(!r)throw new Error("ref requires a path");return b(e,r)}}};return{isReady(){return!!k()&&!!y()},getBackendUrl(){var e;return((e=k())==null?void 0:e.backendUrl)??null},async chatCompletions(e){var s;const{reasoningEffort:o,reasoning_effort:n,...t}=e,r=o??n,a={...t,stream:!1};r&&j(e.model)&&(a.reasoning_effort=r);const d=await l("/openai/chat/completions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)}),g=(d.headers.get("content-type")||"").includes("application/json")?await d.json():await d.text();if(!d.ok)throw new Error(typeof g=="string"?g:((s=g==null?void 0:g.error)==null?void 0:s.message)||`Request failed (${d.status})`);return g},async chatText(e){var n,t,r;const o=await this.chatCompletions(e);return((r=(t=(n=o==null?void 0:o.choices)==null?void 0:n[0])==null?void 0:t.message)==null?void 0:r.content)??""},audio:{async tts(e){var r;const o=(r=e==null?void 0:e.text)==null?void 0:r.trim();if(!o)throw new Error("audio.tts requires non-empty text");const n=await l("/app-api/audio/tts",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({text:o,voice:e.voice,lang:e.lang})});if(!n.ok){const a=await n.text();throw new Error(a||`Request failed (${n.status})`)}return{audio:await n.arrayBuffer(),contentType:n.headers.get("content-type")}},async stt(e){var v,w,i;if(!(e!=null&&e.file))throw new Error("audio.stt requires a file");const o=u=>{if(!u)return;const C=u.trim();if(!C)return;const M=C.toLowerCase(),$=M.split("-")[0];return $.length===2?$:M},n=typeof File<"u"&&e.file instanceof File,t=n&&e.file.name.split(".").pop()||"webm",r=e.ext||t,a=new FormData;n?a.set("file",e.file):a.set("file",e.file,`audio.${r}`);const d=o(e.language);d&&a.set("language",d),e.prompt&&a.set("prompt",e.prompt);const h=await l(`/app-api/audio/stt?ext=${encodeURIComponent(r)}`,{method:"POST",body:a}),s=(h.headers.get("content-type")||"").includes("application/json")?await h.json():await h.text();if(!h.ok)throw new Error(typeof s=="string"?s:((v=s==null?void 0:s.error)==null?void 0:v.message)||`Request failed (${h.status})`);return{text:typeof s=="string"?s:(s==null?void 0:s.text)||(s==null?void 0:s.original)||((i=(w=s==null?void 0:s.results)==null?void 0:w[0])==null?void 0:i.text)||"",raw:s}},async voices(e){const o=new URLSearchParams;e!=null&&e.locale&&o.set("locale",e.locale);const n=await l(`/app-api/audio/tts/voices${o.toString()?`?${o}`:""}`,{method:"GET"}),t=await n.json().catch(()=>[]);if(!n.ok)throw new Error((t==null?void 0:t.error)||`Request failed (${n.status})`);return Array.isArray(t)?t:(t==null?void 0:t.voices)||[]}},data(e="private"){return b(e,"")}}}f.PromteAppProvider=U,f.usePromte=E,f.usePromteClient=_,f.usePromteDarkMode=L,f.usePromteSettings=A,f.usePromteToken=D,f.usePromteUser=F,Object.defineProperty(f,Symbol.toStringTag,{value:"Module"})});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@promte/app-library",
3
- "version": "0.1.1",
3
+ "version": "0.1.2",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "files": [