@promte/app-library 0.1.7 → 0.1.10
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 +51 -0
- package/dist/index.d.ts +225 -2
- package/dist/index.mjs +637 -303
- package/dist/index.umd.cjs +1 -1
- package/package.json +3 -3
package/dist/index.umd.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
(function(w,$){typeof exports=="object"&&typeof module<"u"?$(exports,require("react/jsx-runtime"),require("react")):typeof define=="function"&&define.amd?define(["exports","react/jsx-runtime","react"],$):(w=typeof globalThis<"u"?globalThis:w||self,$(w.PromteAppLibrary={},w.jsxRuntime,w.react))})(this,function(w,$,u){"use strict";const C=u.createContext(null);function D({children:d,expectedParentOrigin:f,initTargetOrigin:S,retryInit:c={enabled:!0,intervalMs:500,maxAttempts:20}}){const[p,k]=u.useState(null),[v,P]=u.useState(null),[b,E]=u.useState(null),[T,e]=u.useState(null),[r,t]=u.useState(null),n=u.useMemo(()=>r?"booting":p?v?"ready":"waiting_for_token":"waiting_for_settings",[p,v,r]),o=n==="ready",a=u.useMemo(()=>S||f||"*",[S,f]),l=u.useCallback(()=>{var m;try{const h={type:"init"};(m=window.parent)==null||m.postMessage(h,a)}catch(h){t((h==null?void 0:h.message)||"Failed to post init")}},[a]);u.useEffect(()=>{l()},[l]),u.useEffect(()=>{if(!(c!=null&&c.enabled)||p)return;const m=c.intervalMs??500,h=c.maxAttempts??20;let s=0;const y=window.setInterval(()=>{if(p){window.clearInterval(y);return}if(s+=1,s>h){window.clearInterval(y);return}l()},m);return()=>window.clearInterval(y)},[c,p,l]),u.useEffect(()=>{const m=h=>{if(f&&h.origin!==f)return;const s=h.data;if(!(!s||typeof s!="object")){if(s.type==="set-settings"){const y=s.value;if(!(y!=null&&y.backendUrl)||y.parentOrigin&&f&&y.parentOrigin!==f)return;k(y),y!=null&&y.user&&e(y.user),t(null);return}if(s.type==="set-token"&&typeof s.value=="string"){P(s.value),t(null);return}if(s.type==="set-dark-mode"&&typeof s.value=="boolean"){E(s.value);return}if(s.type==="set-user"&&typeof s.value=="object"){e(s.value);return}}};return window.addEventListener("message",m),()=>window.removeEventListener("message",m)},[f]);const i=u.useMemo(()=>M(()=>p,()=>v),[p,v]),g=u.useMemo(()=>({settings:p,token:v,isDarkMode:b,user:T,ready:o,state:n,error:r,client:i}),[p,v,b,T,o,n,r,i]);return $.jsx(C.Provider,{value:g,children:d})}function F({children:d,settings:f,token:S,isDarkMode:c,user:p}){const k=u.useMemo(()=>M(()=>f,()=>S),[f,S]),v=!!S,P=u.useMemo(()=>({settings:f,token:S,isDarkMode:c,user:p,ready:v,state:v?"ready":"waiting_for_token",error:null,client:k}),[k,c,v,f,S,p]);return $.jsx(C.Provider,{value:P,children:d})}function j(){const d=u.useContext(C);if(!d)throw new Error("usePromte must be used inside <PromteAppProvider> or <PromteNativeProvider>");return d}function I(){return j().settings}function J(){return j().token}function G(){return j().isDarkMode}function V(){return j().user}function R(){return j().client}function z(d={}){const{ready:f}=j(),S=R(),[c,p]=u.useState([]),[k,v]=u.useState(!1),[P,b]=u.useState(null),E=u.useMemo(()=>(Array.isArray(d.type)?d.type:d.type?[d.type]:[]).filter(Boolean).map(n=>String(n)).join(","),[d.type]),T=d.configuredOnly===!0,e=d.auto!==!1,r=u.useCallback(async()=>{if(!f)return[];v(!0),b(null);try{const t=E?E.split(",").filter(Boolean):void 0,n=await S.models({type:t,configuredOnly:T});return p(n),n}catch(t){const n=t instanceof Error?t.message:String(t);throw b(n),t}finally{v(!1)}},[S,T,f,E]);return u.useEffect(()=>{!e||!f||r().catch(()=>{})},[e,f,r]),{models:c,loading:k,error:P,reload:r}}function M(d,f){const S=e=>typeof e=="string"&&(e.startsWith("gpt-5")||e.startsWith("gpt-6"));async function c(e,r){const t=d(),n=f();if(!t)throw new Error("Promte settings not received yet");if(!n)throw new Error("Promte token not received yet");const o=t.backendUrl.replace(/\/+$/,""),a=String(e||"").replace(/^\/+/,""),l=`${o}/${a}`;return await fetch(l,{...r,headers:{...r.headers||{},Authorization:`Bearer ${n}`}})}async function p(e,r){const t=await c(`/app-api/data/${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)}),n=await t.json().catch(()=>({}));if(!t.ok)throw new Error((n==null?void 0:n.error)||`Request failed (${t.status})`);return n==null?void 0:n.value}async function k(e){const r=new URLSearchParams;e.scope&&r.set("scope",e.scope),e.path&&r.set("path",e.path);const t=await c(`/app-api/data?${r.toString()}`,{method:"GET"}),n=await t.json().catch(()=>({}));if(!t.ok)throw new Error((n==null?void 0:n.error)||`Request failed (${t.status})`);return n==null?void 0:n.value}async function v(e){const r=new URLSearchParams,t=e==null?void 0:e.type,n=Array.isArray(t)?t:t?[t]:[];n.length>0&&r.set("type",n.join(",")),e!=null&&e.configuredOnly&&r.set("configuredOnly","true");const o=await c(`/app-api/models${r.toString()?`?${r.toString()}`:""}`,{method:"GET"}),a=await o.json().catch(()=>({}));if(!o.ok)throw new Error((a==null?void 0:a.error)||`Request failed (${o.status})`);return(Array.isArray(a==null?void 0:a.models)?a.models:[]).map(i=>{if(!i||typeof i!="object")return null;const g=typeof i.id=="string"?i.id.trim():"",m=typeof i.label=="string"?i.label.trim():g,h=i.type,s=i.configured===!0,y=typeof i.source=="string"&&i.source.trim()?i.source.trim():void 0;return!g||h!=="llm"&&h!=="embedding"&&h!=="image"&&h!=="stt"&&h!=="tts"?null:{id:g,label:m||g,type:h,configured:s,source:y}}).filter(i=>!!i)}async function P(e,r){const t=await c(e,r),o=(t.headers.get("content-type")||"").includes("application/json")?await t.json().catch(()=>({})):await t.text();if(!t.ok)throw new Error(typeof o=="string"?o||`Request failed (${t.status})`:(o==null?void 0:o.error)||(o==null?void 0:o.message)||`Request failed (${t.status})`);return o}const b=e=>e?e.split("/").map(r=>r.trim()).filter(Boolean).join("/"):"",E=(e,r)=>{const t=b(e),n=b(r);return t?n?`${t}/${n}`:t:n},T=(e,r)=>{const t={scope:e};return{async get(){const n=b(r);return k({...t,path:n||void 0})},async set(n){const o=b(r);return p("set",{...t,path:o||void 0,value:n})},async update(n){if(!n||typeof n!="object")throw new Error("update requires an object");const o={};for(const[a,l]of Object.entries(n)){const i=E(r,a);if(!i)throw new Error("update paths must be non-empty");o[i]=l}return p("update",{...t,updates:o})},async remove(){const n=b(r);return p("remove",{...t,path:n||void 0})},async push(n){const o=b(r);if(!o)throw new Error("push requires a path");return p("array-push",{...t,path:o,value:n})},ref(n){const o=E(r,n);if(!o)throw new Error("ref requires a path");return T(e,o)}}};return{isReady(){return!!d()&&!!f()},getBackendUrl(){var e;return((e=d())==null?void 0:e.backendUrl)??null},async models(e){return v(e)},async chatCompletions(e){var m;const{reasoningEffort:r,reasoning_effort:t,...n}=e,o=r??t,a={...n,stream:!1};o&&S(e.model)&&(a.reasoning_effort=o);const l=await c("/openai/chat/completions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)}),g=(l.headers.get("content-type")||"").includes("application/json")?await l.json():await l.text();if(!l.ok)throw new Error(typeof g=="string"?g:((m=g==null?void 0:g.error)==null?void 0:m.message)||`Request failed (${l.status})`);return g},async chatText(e){var t,n,o;const r=await this.chatCompletions(e);return((o=(n=(t=r==null?void 0:r.choices)==null?void 0:t[0])==null?void 0:n.message)==null?void 0:o.content)??""},embeddings:{async create(e){var o;const r=(o=e==null?void 0:e.model)==null?void 0:o.trim();if(!r)throw new Error("embeddings.create requires a model");const t=e==null?void 0:e.input;if(!(typeof t=="string"?t.length>0:Array.isArray(t)&&t.length>0&&t.every(a=>typeof a=="string")))throw new Error("embeddings.create requires input as a string or string[]");return P("/openai/embeddings",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,model:r,input:t})})}},audio:{async speechToken(){const e=await c("/app-api/audio/speech-token",{method:"POST"});if(!e.ok)throw new Error("Live talegenkendelse er ikke tilgængelig. Kontakt administratoren.");return e.json()},async voiceLiveSession(){const e=await c("/app-api/audio/voice-live-session",{method:"POST"});if(!e.ok){const r=await e.text();throw new Error(r||"Voice Live er ikke tilgængelig.")}return e.json()},async tts(e){var o;const r=(o=e==null?void 0:e.text)==null?void 0:o.trim();if(!r)throw new Error("audio.tts requires non-empty text");const t=await c("/app-api/audio/tts",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({text:r,voice:e.voice,lang:e.lang})});if(!t.ok){const a=await t.text();throw new Error(a||`Request failed (${t.status})`)}return{audio:await t.arrayBuffer(),contentType:t.headers.get("content-type")}},async stt(e){var x,U,A,O;if(!(e!=null&&e.file))throw new Error("audio.stt requires a file");const r=(x=e.language)==null?void 0:x.trim(),t=L=>{if(!L)return;const N=L.trim();if(!N)return;const B=N.toLowerCase(),_=B.split("-")[0];return _.length===2?_:B},n=typeof File<"u"&&e.file instanceof File,o=n&&e.file.name.split(".").pop()||"webm",a=e.ext||o,l=new FormData;n?l.set("file",e.file):l.set("file",e.file,`audio.${a}`);const i=t(r);i&&l.set("language",i),e.prompt&&l.set("prompt",e.prompt),e.responseFormat&&l.set("response_format",e.responseFormat);const g=new URLSearchParams({ext:a});r&&g.set("locale",r);const m=await c(`/app-api/audio/stt?${g.toString()}`,{method:"POST",body:l}),s=(m.headers.get("content-type")||"").includes("application/json")?await m.json():await m.text();if(!m.ok)throw new Error(typeof s=="string"?s:((U=s==null?void 0:s.error)==null?void 0:U.message)||`Request failed (${m.status})`);const y=typeof s=="string"?s:(s==null?void 0:s.text)||(s==null?void 0:s.original)||((O=(A=s==null?void 0:s.results)==null?void 0:A[0])==null?void 0:O.text)||"",W=typeof s=="object"&&typeof(s==null?void 0:s.language)=="string"?s.language:void 0;return{text:y,language:W,raw:s}},async voices(e){const r=new URLSearchParams;e!=null&&e.locale&&r.set("locale",e.locale);const t=await c(`/app-api/audio/tts/voices${r.toString()?`?${r}`:""}`,{method:"GET"}),n=await t.json().catch(()=>[]);if(!t.ok)throw new Error((n==null?void 0:n.error)||`Request failed (${t.status})`);return Array.isArray(n)?n:(n==null?void 0:n.voices)||[]}},web:{async scrapeUrl(e){var t;const r=(t=e==null?void 0:e.url)==null?void 0:t.trim();if(!r)throw new Error("web.scrapeUrl requires a url");return P("/app-api/web/scrape-url",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:r,maxChars:e.maxChars})})}},knowledge:{async search(e){var t;const r=(t=e==null?void 0:e.query)==null?void 0:t.trim();if(!r)throw new Error("knowledge.search requires a query");return P("/app-api/knowledge/search",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({workspaceId:e.workspaceId,query:r,maxResults:e.maxResults,generateSearchQuery:e.generateSearchQuery,sourceId:e.sourceId,includeSourceUrls:e.includeSourceUrls,queries:e.queries})})}},translatorLiveShare:{async create(e){return P("/app-api/translator/live-share",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({displayLanguage:e})})},async update(e,r){await P(`/app-api/translator/live-share/${encodeURIComponent(e)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)})},async revoke(e){await P(`/app-api/translator/live-share/${encodeURIComponent(e)}`,{method:"DELETE"})}},data(e="private"){return T(e,"")}}}w.PromteAppProvider=D,w.PromteNativeProvider=F,w.usePromte=j,w.usePromteClient=R,w.usePromteDarkMode=G,w.usePromteModels=z,w.usePromteSettings=I,w.usePromteToken=J,w.usePromteUser=V,Object.defineProperty(w,Symbol.toStringTag,{value:"Module"})});
|
|
1
|
+
(function(T,L){typeof exports=="object"&&typeof module<"u"?L(exports,require("react/jsx-runtime"),require("react")):typeof define=="function"&&define.amd?define(["exports","react/jsx-runtime","react"],L):(T=typeof globalThis<"u"?globalThis:T||self,L(T.PromteAppLibrary={},T.jsxRuntime,T.React))})(this,function(T,L,d){"use strict";var Ee=Object.defineProperty;var be=(T,L,d)=>L in T?Ee(T,L,{enumerable:!0,configurable:!0,writable:!0,value:d}):T[L]=d;var Y=(T,L,d)=>be(T,typeof L!="symbol"?L+"":L,d);const H=d.createContext(null),Q={loginEnabled:!1,methods:{password:!1,magicLink:!1,signup:!1},signedIn:!1,pendingPasswordReset:!1,expiredLink:!1};function ae({children:i,expectedParentOrigin:u,initTargetOrigin:f,retryInit:E={enabled:!0,intervalMs:500,maxAttempts:20}}){const[s,P]=d.useState(null),[y,M]=d.useState(null),[O,I]=d.useState(null),[$,j]=d.useState(null),[C,U]=d.useState(null),[e,t]=d.useState(null),[n,r]=d.useState(Q),o=d.useRef(new Map),a=d.useMemo(()=>C?"booting":s?!y&&!s.fetchProxy?"waiting_for_token":"ready":"waiting_for_settings",[s,y,C]),m=a==="ready",g=d.useMemo(()=>f||u||"*",[f,u]),w=d.useCallback(()=>{var A;try{const b={type:"init",fetchProxy:!0};(A=window.parent)==null||A.postMessage(b,g)}catch(b){U((b==null?void 0:b.message)||"Failed to post init")}},[g]);d.useEffect(()=>{w()},[w]),d.useEffect(()=>{if(!(E!=null&&E.enabled)||s)return;const A=E.intervalMs??500,b=E.maxAttempts??20;let c=0;const v=window.setInterval(()=>{if(s){window.clearInterval(v);return}if(c+=1,c>b){window.clearInterval(v);return}w()},A);return()=>window.clearInterval(v)},[E,s,w]),d.useEffect(()=>{const A=b=>{if(u&&b.origin!==u)return;const c=b.data;if(!(!c||typeof c!="object")){if(c.type==="set-settings"){const v=c.value;if(!(v!=null&&v.backendUrl)||v.parentOrigin&&u&&v.parentOrigin!==u)return;P(v),t(b.source===window.parent?b.origin:null),v!=null&&v.user&&j(v.user),U(null);return}if(c.type==="set-token"&&typeof c.value=="string"){M(c.value),U(null);return}if(c.type==="set-dark-mode"&&typeof c.value=="boolean"){I(c.value);return}if(c.type==="set-user"&&typeof c.value=="object"){j(c.value);return}if(b.source===window.parent){if(c.type==="set-auth"&&c.value&&typeof c.value=="object"){r({...Q,...c.value});return}if(c.type==="promte-auth-result"&&typeof c.requestId=="string"){const v=o.current.get(c.requestId);if(!v)return;o.current.delete(c.requestId),c.ok?v.resolve():v.reject(new Error(typeof c.error=="string"?c.error:"server_error"));return}}}};return window.addEventListener("message",A),()=>window.removeEventListener("message",A)},[u]);const k=d.useMemo(()=>te(()=>s,()=>y,()=>s!=null&&s.fetchProxy&&e&&window.parent!==window?{target:window.parent,origin:e}:null),[s,y,e]),D=(s==null?void 0:s.allowDownloads)!==!1;d.useEffect(()=>{var ne,re,oe;if(!e||window.parent===window)return;const A=new Set,b=(p,l,x)=>{const B=`${p}:${l}`;if(!A.has(B)){A.add(B),console.error(`[Promte] ${x}`);try{window.parent.postMessage({type:"promte-blocked",kind:p,detail:l},e)}catch{}}},c=p=>{try{const l=new URL(p,window.location.href);return/^https?:$/.test(l.protocol)&&l.origin!==window.location.origin?l:null}catch{return null}},v=window.open,_=p=>{var F,se;if(p.defaultPrevented||p.button!==0||p.metaKey||p.ctrlKey||p.shiftKey||p.altKey)return;const l=(se=(F=p.target)==null?void 0:F.closest)==null?void 0:se.call(F,"a[href]");if(!l)return;if(l.hasAttribute("download")||/^(?:blob|data):/i.test(l.href)){D||b("download",l.getAttribute("download")||"","The app tried to download a file, but file downloads from apps are turned off in governance.");return}const x=c(l.href);if(!x)return;p.preventDefault();const B=v.call(window,x.href,"_blank");if(B)try{B.opener=null}catch{}else b("link",x.href,`The link to ${x.href} could not open in a new tab. Governance may only allow approved web addresses for this app.`)};window.open=function(p,l,x){const B=v.call(window,p,l,x),F=p===void 0?null:c(String(p));return!B&&F&&!/noopener|noreferrer/i.test(x||"")&&b("link",F.href,`The link to ${F.href} could not open in a new tab. Governance may only allow approved web addresses for this app.`),B};const N=p=>{const l=p.blockedURI;if(!/^https?:/i.test(l))return;let x=l;try{x=new URL(l).origin}catch{}b("address",x,`A request to ${l} was blocked (${p.effectiveDirective}). Governance may only allow approved web addresses for this app.`)},J=p=>{const l=p.detail;b("governance",String((l==null?void 0:l.message)||""),`Governance blocked an action in the app${l!=null&&l.message?`: ${l.message}`:"."}`)},S=navigator.mediaDevices,z=(ne=S==null?void 0:S.getUserMedia)==null?void 0:ne.bind(S),V=(re=S==null?void 0:S.getDisplayMedia)==null?void 0:re.bind(S),X=p=>l=>{throw((l==null?void 0:l.name)==="NotAllowedError"||(l==null?void 0:l.name)==="SecurityError")&&b("device",p,`The app was not allowed to use the ${p} here.`),l};S&&z&&(S.getUserMedia=p=>z(p).catch(X(p!=null&&p.video?"camera":"microphone"))),S&&V&&(S.getDisplayMedia=p=>V(p).catch(X("screen")));const G=navigator.clipboard,W=(oe=G==null?void 0:G.writeText)==null?void 0:oe.bind(G);return G&&W&&(G.writeText=p=>W(p).catch(X("clipboard"))),document.addEventListener("click",_),document.addEventListener("securitypolicyviolation",N),window.addEventListener("promte:governance-blocked",J),()=>{document.removeEventListener("click",_),document.removeEventListener("securitypolicyviolation",N),window.removeEventListener("promte:governance-blocked",J),window.open=v,S&&z&&(S.getUserMedia=z),S&&V&&(S.getDisplayMedia=V),G&&W&&(G.writeText=W)}},[e,D]);const h=d.useCallback((A,b={})=>{if(!e||window.parent===window)return Promise.reject(new Error("not_available"));const c=`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;return new Promise((v,_)=>{const N=window.setTimeout(()=>{o.current.delete(c),_(new Error("timeout"))},6e4);o.current.set(c,{resolve:()=>{window.clearTimeout(N),v()},reject:J=>{window.clearTimeout(N),_(J)}}),window.parent.postMessage({type:"promte-auth",requestId:c,action:A,...b},e)})},[e]),K=d.useMemo(()=>({settings:s,token:y,isDarkMode:O,user:$,ready:m,state:a,error:C,client:k,auth:n,authRequest:h}),[s,y,O,$,m,a,C,k,n,h]);return L.jsx(H.Provider,{value:K,children:i})}function ie({children:i,settings:u,token:f,isDarkMode:E,user:s}){const P=d.useMemo(()=>te(()=>u,()=>f),[u,f]),y=!!f,M=d.useMemo(()=>({settings:u,token:f,isDarkMode:E,user:s,ready:y,state:y?"ready":"waiting_for_token",error:null,client:P,auth:Q,authRequest:()=>Promise.reject(new Error("not_available"))}),[P,E,y,u,f,s]);return L.jsx(H.Provider,{value:M,children:i})}function R(){const i=d.useContext(H);if(!i)throw new Error("usePromte must be used inside <PromteAppProvider> or <PromteNativeProvider>");return i}function ce(){return R().settings}function ue(){return R().token}function le(){return R().isDarkMode}function de(){return R().user}function Z(){return R().client}function pe(){const{auth:i,authRequest:u}=R();return d.useMemo(()=>({...i,signIn:(f,E)=>u("signIn",{email:f,password:E}),signUp:(f,E)=>u("signUp",{email:f,password:E}),sendLoginLink:f=>u("sendLoginLink",{email:f}),sendPasswordReset:f=>u("sendPasswordReset",{email:f}),completePasswordReset:f=>u("completePasswordReset",{password:f}),signOut:()=>u("signOut")}),[i,u])}function fe(i={}){const{ready:u}=R(),f=Z(),[E,s]=d.useState([]),[P,y]=d.useState(!1),[M,O]=d.useState(null),I=d.useMemo(()=>(Array.isArray(i.type)?i.type:i.type?[i.type]:[]).filter(Boolean).map(e=>String(e)).join(","),[i.type]),$=i.configuredOnly===!0,j=i.auto!==!1,C=d.useCallback(async()=>{if(!u)return[];y(!0),O(null);try{const U=I?I.split(",").filter(Boolean):void 0,e=await f.models({type:U,configuredOnly:$});return s(e),e}catch(U){const e=U instanceof Error?U.message:String(U);throw O(e),U}finally{y(!1)}},[f,$,u,I]);return d.useEffect(()=>{!j||!u||C().catch(()=>{})},[j,u,C]),{models:E,loading:P,error:M,reload:C}}class q extends Error{constructor(f,E,s){super(s||f);Y(this,"code");Y(this,"status");this.name="PromteEmailError",this.code=f,this.status=E}}const we="promte-fetch-request",he="promte-fetch-response",me=new Set([101,103,204,205,304]);function ge(){return typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}function ee(i){return i.reason??new DOMException("The operation was aborted.","AbortError")}function ye(i,u){if(i==null)return null;if(typeof i=="string"||i instanceof Blob||i instanceof ArrayBuffer||ArrayBuffer.isView(i))return i;if(i instanceof URLSearchParams)return u.has("content-type")||u.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"),i.toString();if(i instanceof FormData){const f=[];return i.forEach((E,s)=>f.push([s,E])),{form:f}}throw new TypeError("This request body cannot be sent through Promte.")}function ve({target:i,origin:u},f,E){return new Promise((s,P)=>{const y=E.signal;if(y!=null&&y.aborted)return P(ee(y));const M=ge(),O=new Headers(E.headers);O.delete("authorization");let I;try{I=ye(E.body,O)}catch(e){return P(e)}const $=()=>{window.removeEventListener("message",C),y==null||y.removeEventListener("abort",j)},j=()=>{$(),P(ee(y))},C=e=>{if(e.source!==i||e.origin!==u)return;const t=e.data;if(!t||t.type!==he||t.id!==M)return;if($(),typeof t.error=="string")return P(new TypeError(t.error));const n=Number(t.status);if(!Number.isInteger(n)||n<200||n>599)return P(new TypeError("Promte returned an invalid response."));try{s(new Response(me.has(n)?null:t.body??null,{status:n,statusText:typeof t.statusText=="string"?t.statusText:"",headers:Array.isArray(t.headers)?t.headers:[]}))}catch{P(new TypeError("Promte returned an invalid response."))}};window.addEventListener("message",C),y==null||y.addEventListener("abort",j,{once:!0});const U=[];O.forEach((e,t)=>U.push([t,e]));try{i.postMessage({type:we,id:M,path:f,method:(E.method||"GET").toUpperCase(),headers:U,body:I},u)}catch(e){$(),P(e)}})}function te(i,u,f=()=>null){const E=e=>typeof e=="string"&&(e.startsWith("gpt-5")||e.startsWith("gpt-6"));async function s(e,t){const n=i(),r=u();if(!n)throw new Error("Promte settings not received yet");const o=n.backendUrl.replace(/\/+$/,""),a=String(e||"").replace(/^\/+/,""),m=`${o}/${a}`,g=f();if(!g&&!r)throw new Error("Promte token not received yet");const w=g?await ve(g,a,t):await fetch(m,{...t,headers:{...t.headers||{},Authorization:`Bearer ${r}`}});return w.status===403&&typeof window<"u"&&w.clone().json().then(k=>{(k==null?void 0:k.code)==="app_policy_blocked"&&window.dispatchEvent(new CustomEvent("promte:governance-blocked",{detail:{endpoint:e,message:typeof k.error=="string"?k.error:""}}))}).catch(()=>{}),w.headers.get("X-Promte-Governance-Warning")&&(typeof window<"u"&&window.dispatchEvent(new CustomEvent("promte:governance-warning",{detail:{endpoint:e}})),console.warn("Promte governance: this request triggered a warning policy.")),w}const P=new Map,y={async list(){const e=await s("/app-api/shared-assets",{method:"GET"});if(!e.ok)throw new Error(`Request failed (${e.status})`);return(await e.json()).assets},async get(e,t={}){const n=await s(`/app-api/shared-assets/${encodeURIComponent(e)}`,{method:"GET",signal:t.signal});if(!n.ok)throw new Error(n.status===404?`The shared asset ${e} does not exist.`:`Request failed (${n.status})`);return n.blob()},async text(e){return(await y.get(e)).text()},url(e){let t=P.get(e);return t||(t=y.get(e).then(n=>URL.createObjectURL(n)),t.catch(()=>P.delete(e)),P.set(e,t)),t}};async function M(e,t){const n=await s(`/app-api/data/${e}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Error((r==null?void 0:r.error)||`Request failed (${n.status})`);return r==null?void 0:r.value}async function O(e){const t=new URLSearchParams;e.scope&&t.set("scope",e.scope),e.path&&t.set("path",e.path),e.owner&&t.set("owner",e.owner);const n=await s(`/app-api/data?${t.toString()}`,{method:"GET"}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Error((r==null?void 0:r.error)||`Request failed (${n.status})`);return r==null?void 0:r.value}async function I(e){const t=new URLSearchParams,n=e==null?void 0:e.type,r=Array.isArray(n)?n:n?[n]:[];r.length>0&&t.set("type",r.join(",")),e!=null&&e.configuredOnly&&t.set("configuredOnly","true");const o=await s(`/app-api/models${t.toString()?`?${t.toString()}`:""}`,{method:"GET"}),a=await o.json().catch(()=>({}));if(!o.ok)throw new Error((a==null?void 0:a.error)||`Request failed (${o.status})`);return(Array.isArray(a==null?void 0:a.models)?a.models:[]).map(g=>{if(!g||typeof g!="object")return null;const w=typeof g.id=="string"?g.id.trim():"",k=typeof g.label=="string"?g.label.trim():w,D=g.type,h=g.configured===!0,K=typeof g.source=="string"&&g.source.trim()?g.source.trim():void 0;return!w||D!=="llm"&&D!=="embedding"&&D!=="image"&&D!=="stt"&&D!=="tts"?null:{id:w,label:k||w,type:D,configured:h,source:K}}).filter(g=>!!g)}async function $(e,t){const n=await s(e,t),o=(n.headers.get("content-type")||"").includes("application/json")?await n.json().catch(()=>({})):await n.text();if(!n.ok)throw new Error(typeof o=="string"?o||`Request failed (${n.status})`:(o==null?void 0:o.error)||(o==null?void 0:o.message)||`Request failed (${n.status})`);return o}const j=e=>e?e.split("/").map(t=>t.trim()).filter(Boolean).join("/"):"",C=(e,t)=>{const n=j(e),r=j(t);return n?r?`${n}/${r}`:n:r},U=(e,t,n)=>{const r={scope:e,...n?{owner:n}:{}};return{async getAll(){if(e!=="shared")throw new Error('getAll is only available for client.data("shared")');const o=j(t),a=await s(`/app-api/data/shared${o?`?path=${encodeURIComponent(o)}`:""}`,{method:"GET"}),m=await a.json().catch(()=>({}));if(!a.ok)throw new Error((m==null?void 0:m.error)||`Request failed (${a.status})`);return Array.isArray(m==null?void 0:m.items)?m.items:[]},async get(){const o=j(t);return O({...r,path:o||void 0})},async set(o){const a=j(t);return M("set",{...r,path:a||void 0,value:o})},async update(o){if(!o||typeof o!="object")throw new Error("update requires an object");const a={};for(const[m,g]of Object.entries(o)){const w=C(t,m);if(!w)throw new Error("update paths must be non-empty");a[w]=g}return M("update",{...r,updates:a})},async remove(){const o=j(t);return M("remove",{...r,path:o||void 0})},async push(o){const a=j(t);if(!a)throw new Error("push requires a path");return M("array-push",{...r,path:a,value:o})},ref(o){const a=C(t,o);if(!a)throw new Error("ref requires a path");return U(e,a,n)}}};return{functions:{async invoke(e,t){if(!/^[a-z][a-z0-9-]{0,63}$/.test(e))throw new Error("Choose a valid function name or configured binding alias.");const n=await s("/app-api/functions/invoke",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:e,input:t})}),r=await n.json().catch(()=>({}));if(!n.ok)throw new Error((r==null?void 0:r.error)||`Function call failed (${n.status})`);return r.output}},isReady(){return!!i()&&(!!u()||!!f())},getBackendUrl(){var e;return((e=i())==null?void 0:e.backendUrl)??null},async models(e){return I(e)},async chatCompletions(e){var k;const{reasoningEffort:t,reasoning_effort:n,...r}=e,o=t??n,a={...r,stream:!1};o&&E(e.model)&&(a.reasoning_effort=o);const m=await s("/openai/chat/completions",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)}),w=(m.headers.get("content-type")||"").includes("application/json")?await m.json():await m.text();if(!m.ok)throw new Error(typeof w=="string"?w:(typeof(w==null?void 0:w.error)=="string"?w.error:(k=w==null?void 0:w.error)==null?void 0:k.message)||`Request failed (${m.status})`);return w},async chatText(e){var n,r,o;const t=await this.chatCompletions(e);return((o=(r=(n=t==null?void 0:t.choices)==null?void 0:n[0])==null?void 0:r.message)==null?void 0:o.content)??""},embeddings:{async create(e){var o;const t=(o=e==null?void 0:e.model)==null?void 0:o.trim();if(!t)throw new Error("embeddings.create requires a model");const n=e==null?void 0:e.input;if(!(typeof n=="string"?n.length>0:Array.isArray(n)&&n.length>0&&n.every(a=>typeof a=="string")))throw new Error("embeddings.create requires input as a string or string[]");return $("/openai/embeddings",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...e,model:t,input:n})})}},audio:{async speechToken(){const e=await s("/app-api/audio/speech-token",{method:"POST"});if(!e.ok)throw new Error("Live talegenkendelse er ikke tilgængelig. Kontakt administratoren.");return e.json()},async voiceLiveSession(){const e=await s("/app-api/audio/voice-live-session",{method:"POST"});if(!e.ok){const t=await e.text();throw new Error(t||"Voice Live er ikke tilgængelig.")}return e.json()},async tts(e){var o;const t=(o=e==null?void 0:e.text)==null?void 0:o.trim();if(!t)throw new Error("audio.tts requires non-empty text");const n=await s("/app-api/audio/tts",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({text:t,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 b,c,v,_;if(!(e!=null&&e.file))throw new Error("audio.stt requires a file");const t=(b=e.language)==null?void 0:b.trim(),n=N=>{if(!N)return;const J=N.trim();if(!J)return;const S=J.toLowerCase(),z=S.split("-")[0];return z.length===2?z:S},r=typeof File<"u"&&e.file instanceof File,o=r&&e.file.name.split(".").pop()||"webm",a=e.ext||o,m=new FormData;r?m.set("file",e.file):m.set("file",e.file,`audio.${a}`);const g=n(t);g&&m.set("language",g),e.prompt&&m.set("prompt",e.prompt),e.responseFormat&&m.set("response_format",e.responseFormat);const w=new URLSearchParams({ext:a});t&&w.set("locale",t);const k=await s(`/app-api/audio/stt?${w.toString()}`,{method:"POST",body:m}),h=(k.headers.get("content-type")||"").includes("application/json")?await k.json():await k.text();if(!k.ok)throw new Error(typeof h=="string"?h:(typeof(h==null?void 0:h.error)=="string"?h.error:(c=h==null?void 0:h.error)==null?void 0:c.message)||`Request failed (${k.status})`);const K=typeof h=="string"?h:(h==null?void 0:h.text)||(h==null?void 0:h.original)||((_=(v=h==null?void 0:h.results)==null?void 0:v[0])==null?void 0:_.text)||"",A=typeof h=="object"&&typeof(h==null?void 0:h.language)=="string"?h.language:void 0;return{text:K,language:A,raw:h}},async voices(e){const t=new URLSearchParams;e!=null&&e.locale&&t.set("locale",e.locale);const n=await s(`/app-api/audio/tts/voices${t.toString()?`?${t}`:""}`,{method:"GET"}),r=await n.json().catch(()=>[]);if(!n.ok)throw new Error((r==null?void 0:r.error)||`Request failed (${n.status})`);return Array.isArray(r)?r:(r==null?void 0:r.voices)||[]}},web:{async scrapeUrl(e){var n;const t=(n=e==null?void 0:e.url)==null?void 0:n.trim();if(!t)throw new Error("web.scrapeUrl requires a url");return $("/app-api/web/scrape-url",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:t,maxChars:e.maxChars})})}},knowledge:{async search(e){var n;const t=(n=e==null?void 0:e.query)==null?void 0:n.trim();if(!t)throw new Error("knowledge.search requires a query");return $("/app-api/knowledge/search",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({workspaceId:e.workspaceId,query:t,maxResults:e.maxResults,generateSearchQuery:e.generateSearchQuery,sourceId:e.sourceId,includeSourceUrls:e.includeSourceUrls,queries:e.queries})})}},assistant:{async ask(e){var n;const t=(n=e==null?void 0:e.question)==null?void 0:n.trim();if(!(e!=null&&e.assistantId))throw new Error("assistant.ask requires an assistantId");if(!t)throw new Error("assistant.ask requires a question");return $("/app-api/assistant/ask",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({assistantId:e.assistantId,question:t,conversationId:e.conversationId})})}},translatorLiveShare:{async create(e){return $("/app-api/translator/live-share",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({displayLanguage:e})})},async update(e,t){await $(`/app-api/translator/live-share/${encodeURIComponent(e)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)})},async revoke(e){await $(`/app-api/translator/live-share/${encodeURIComponent(e)}`,{method:"DELETE"})}},guardrails:{async check(e){return $("/app-api/guardrails/check",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({value:e})})}},email:{async send(e){const t=await s("/app-api/email/send",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),n=await t.json().catch(()=>({}));if(!t.ok){const r=(n==null?void 0:n.code)||(t.status===401?"sign_in_required":"server_error");throw new q(r,t.status,n!=null&&n.error&&n.error!==r?n.error:void 0)}return n}},data(e="private",t){return U(e,"",t==null?void 0:t.owner)},assets:y,files(e="private"){const t=(r={})=>new URLSearchParams({scope:e,...r}).toString(),n=async r=>{const o=await r.json().catch(()=>({}));return new Error((o==null?void 0:o.error)||`Request failed (${r.status})`)};return{async upload(r,o={}){const a=o.name||r.name;if(!a)throw new Error("A file name is required.");const m=o.contentType||r.type||"application/octet-stream",g=await s(`/app-api/files?${t({name:a,contentType:m})}`,{method:"POST",headers:{"Content-Type":"application/octet-stream"},body:r,signal:o.signal});if(!g.ok)throw await n(g);return(await g.json()).file},async list(r={}){const o=await s(`/app-api/files?${t(r.prefix?{prefix:r.prefix}:{})}`,{method:"GET"});if(!o.ok)throw await n(o);return(await o.json()).files},async download(r,o={}){const a=await s(`/app-api/files/${encodeURIComponent(r)}?${t()}`,{method:"GET",signal:o.signal});if(!a.ok)throw await n(a);return a.blob()},async remove(r){const o=await s(`/app-api/files/${encodeURIComponent(r)}?${t()}`,{method:"DELETE"});if(!o.ok)throw await n(o)}}}}}T.PromteAppProvider=ae,T.PromteEmailError=q,T.PromteNativeProvider=ie,T.usePromte=R,T.usePromteAuth=pe,T.usePromteClient=Z,T.usePromteDarkMode=le,T.usePromteModels=fe,T.usePromteSettings=ce,T.usePromteToken=ue,T.usePromteUser=de,Object.defineProperty(T,Symbol.toStringTag,{value:"Module"})});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@promte/app-library",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.10",
|
|
4
4
|
"private": false,
|
|
5
5
|
"type": "module",
|
|
6
6
|
"files": [
|
|
@@ -20,8 +20,8 @@
|
|
|
20
20
|
"build": "tsc && vite build"
|
|
21
21
|
},
|
|
22
22
|
"peerDependencies": {
|
|
23
|
-
"react": "^18.2.0",
|
|
24
|
-
"react-dom": "^18.2.0"
|
|
23
|
+
"react": "^18.2.0 || ^19.0.0",
|
|
24
|
+
"react-dom": "^18.2.0 || ^19.0.0"
|
|
25
25
|
},
|
|
26
26
|
"devDependencies": {
|
|
27
27
|
"@types/react": "^18.0.28",
|