@metagptx/web-sdk 0.0.58 → 0.0.59-beta.3

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
@@ -54,7 +54,7 @@ The SDK provides eight main modules and a Vite plugin:
54
54
  - **integrations**: Integration function invocations
55
55
  - **frame**: Frame communication operations for iframe/parent window messaging
56
56
  - **utils**: Utility functions for URL opening and window management
57
- - **ai**: AI-powered text and image generation
57
+ - **ai**: AI-powered text, image, video, and audio generation
58
58
  - **storage**: Object storage operations (buckets, files, upload/download)
59
59
  - **vitePlugin404**: Vite plugin for automatically adding a 404 page to React Router applications
60
60
 
@@ -591,7 +591,7 @@ client.utils.openUrl('https://stripe.com/checkout'); // Navigates to URL when no
591
591
 
592
592
  ### AI Module
593
593
 
594
- Provides AI-powered text and image generation capabilities with support for streaming responses, multimodal inputs, and image editing.
594
+ Provides AI-powered text, image, video, and audio generation capabilities with support for streaming responses, multimodal inputs, image editing, and text-to-speech.
595
595
 
596
596
  #### `ai.gentxt(params)`
597
597
 
@@ -720,6 +720,76 @@ const response = await client.ai.genimg({
720
720
  }, { timeout: 600_000 });
721
721
  ```
722
722
 
723
+ #### `ai.genvideo(params, options?)`
724
+
725
+ Generate videos using AI models. Supports text-to-video and image-to-video (using an image as the first frame). Video generation is async — the API polls internally until completion.
726
+
727
+ **HTTP Details:**
728
+ - **Method:** `POST`
729
+ - **Path:** `/api/v1/aihub/genvideo`
730
+ - **Parameters:**
731
+ - `prompt` (required): Text prompt describing the desired video
732
+ - `model` (required): Model identifier (e.g., `'wan2.6-t2v'` for text-to-video, `'wan2.6-i2v'` for image-to-video)
733
+ - `size` (optional): Video size (default: `"1280x720"`)
734
+ - `seconds` (optional): Video duration in seconds (default: `"8"`)
735
+ - `image` (optional): Base64 Data URI image as the first frame reference (for image-to-video)
736
+ - **Options:**
737
+ - `timeout` (optional): Request timeout in milliseconds (default: 600000ms / 10 minutes). Video generation is slow; consider setting a longer timeout (e.g., `600_000` ms or more)
738
+
739
+ **Response:** `response.data.url` is the CDN URL of the generated video.
740
+
741
+ **Example - Text-to-Video:**
742
+ ```typescript
743
+ const video = await client.ai.genvideo(
744
+ { prompt: 'Ocean waves at sunset', model: 'wan2.6-t2v' },
745
+ { timeout: 600_000 }
746
+ );
747
+ const videoUrl = video.data.url;
748
+ ```
749
+
750
+ **Example - Image-to-Video (use image as first frame):**
751
+ ```typescript
752
+ const videoFromImage = await client.ai.genvideo(
753
+ { prompt: 'Animate the scene', model: 'wan2.6-i2v', image: 'data:image/png;base64,...' },
754
+ { timeout: 600_000 }
755
+ );
756
+ const videoUrl = videoFromImage.data.url;
757
+ ```
758
+
759
+ #### `ai.genaudio(params, options?)`
760
+
761
+ Generate audio (text-to-speech) using AI models. Voice is auto-selected based on model and gender — no manual voice selection needed.
762
+
763
+ **HTTP Details:**
764
+ - **Method:** `POST`
765
+ - **Path:** `/api/v1/aihub/genaudio`
766
+ - **Parameters:**
767
+ - `text` (required): Text content to convert to speech
768
+ - `model` (required): Model identifier (e.g., `'qwen3-tts-flash'`, `'eleven-v3-alpha'`)
769
+ - `gender` (optional): Voice gender — `"male"` or `"female"` (default: `"female"`)
770
+ - **Options:**
771
+ - `timeout` (optional): Request timeout in milliseconds (default: 60000ms / 1 minute)
772
+
773
+ **Response:** `response.data.url` is the CDN URL of the generated audio (mp3).
774
+
775
+ **Example - Female voice (default):**
776
+ ```typescript
777
+ const audio = await client.ai.genaudio(
778
+ { text: 'Welcome to our website', model: 'qwen3-tts-flash', gender: 'female' },
779
+ { timeout: 60_000 }
780
+ );
781
+ const audioUrl = audio.data.url;
782
+ ```
783
+
784
+ **Example - Male voice:**
785
+ ```typescript
786
+ const maleAudio = await client.ai.genaudio(
787
+ { text: 'Product introduction', model: 'eleven-v3-alpha', gender: 'male' },
788
+ { timeout: 60_000 }
789
+ );
790
+ const audioUrl = maleAudio.data.url;
791
+ ```
792
+
723
793
  ---
724
794
 
725
795
  ### Storage Module
@@ -1150,12 +1220,16 @@ import type {
1150
1220
  CreateBucketParams,
1151
1221
  CreateBucketResponse,
1152
1222
  DownloadParams,
1223
+ GenAudioParams,
1224
+ GenAudioResponse,
1153
1225
  GenImgParams,
1154
1226
  GenImgResponse,
1155
1227
  GenTxtNonStreamParams,
1156
1228
  GenTxtParams,
1157
1229
  GenTxtResponse,
1158
1230
  GenTxtStreamParams,
1231
+ GenVideoParams,
1232
+ GenVideoResponse,
1159
1233
  GetDownloadUrlParams,
1160
1234
  GetDownloadUrlResponse,
1161
1235
  GetObjectInfoParams,
@@ -1196,6 +1270,10 @@ import type {
1196
1270
  - **`GenTxtResponse`**: Text generation response
1197
1271
  - **`GenImgParams`**: Image generation parameters
1198
1272
  - **`GenImgResponse`**: Image generation response
1273
+ - **`GenVideoParams`**: Video generation parameters
1274
+ - **`GenVideoResponse`**: Video generation response (CDN URL)
1275
+ - **`GenAudioParams`**: Audio generation (TTS) parameters
1276
+ - **`GenAudioResponse`**: Audio generation response (CDN URL)
1199
1277
  - **`StreamChunk`**: Chunk received during streaming
1200
1278
  - **`StreamResult`**: Complete streaming result
1201
1279
  - **`ImageContent`**: Image content for multimodal messages
package/dist/index.d.ts CHANGED
@@ -87,6 +87,12 @@ declare const createClient: (config?: ClientConfig) => {
87
87
  genimg: (genParams: GenImgParams, options?: AiOptions) => Promise<{
88
88
  data: GenImgResponse;
89
89
  }>;
90
+ genvideo: (genParams: GenVideoParams, options?: AiOptions) => Promise<{
91
+ data: GenVideoResponse;
92
+ }>;
93
+ genaudio: (genParams: GenAudioParams, options?: AiOptions) => Promise<{
94
+ data: GenAudioResponse;
95
+ }>;
90
96
  };
91
97
  storage: {
92
98
  createBucket: (createParams: CreateBucketParams) => Promise<{
@@ -115,7 +121,7 @@ declare const createClient: (config?: ClientConfig) => {
115
121
  };
116
122
  };
117
123
  //#endregion
118
- //#region src/modules/ai.d.ts
124
+ //#region src/modules/ai.types.d.ts
119
125
  /**
120
126
  * Message content for multimodal input
121
127
  */
@@ -221,19 +227,53 @@ interface GenImgResponse {
221
227
  /** Generated image URLs or Base64 Data URIs */
222
228
  images: string[];
223
229
  }
230
+ /**
231
+ * Parameters for video generation (text-to-video or image-to-video)
232
+ */
233
+ interface GenVideoParams {
234
+ /** Text prompt describing the desired video */
235
+ prompt: string;
236
+ /** Model to use for generation (e.g., 'wan2.6-t2v', 'wan2.6-i2v') */
237
+ model: string;
238
+ /** Video size (default: "1280x720") */
239
+ size?: string;
240
+ /** Video duration in seconds (default: "8") */
241
+ seconds?: string;
242
+ /** Base64 Data URI image as the first frame reference (for image-to-video) */
243
+ image?: string;
244
+ }
245
+ /**
246
+ * Response from genvideo
247
+ */
248
+ interface GenVideoResponse {
249
+ /** CDN URL of the generated video */
250
+ url: string;
251
+ }
252
+ /**
253
+ * Parameters for audio generation (text-to-speech)
254
+ */
255
+ interface GenAudioParams {
256
+ /** Text content to convert to speech */
257
+ text: string;
258
+ /** Model to use for generation (e.g., 'qwen3-tts-flash', 'eleven-v3-alpha') */
259
+ model: string;
260
+ /** Voice gender (default: "female") */
261
+ gender?: 'male' | 'female';
262
+ }
263
+ /**
264
+ * Response from genaudio
265
+ */
266
+ interface GenAudioResponse {
267
+ /** CDN URL of the generated audio (mp3) */
268
+ url: string;
269
+ }
224
270
  /**
225
271
  * Options for AI module methods
226
272
  */
227
273
  interface AiOptions {
228
- /** Request timeout in milliseconds (default: 60000 for gentxt, 600000 for genimg) */
274
+ /** Request timeout in milliseconds (default: 60000 for gentxt, 600000 for genimg/genvideo) */
229
275
  timeout?: number;
230
276
  }
231
- /**
232
- * Creates an AI module for text and image generation
233
- * @param params - Configuration object
234
- * @param params.requestInstance - Axios instance for making HTTP requests
235
- * @returns Object containing gentxt and genimg methods
236
- */
237
277
  //#endregion
238
278
  //#region src/types/index.d.ts
239
279
  /**
@@ -457,4 +497,4 @@ interface DownloadParams {
457
497
  */
458
498
 
459
499
  //#endregion
460
- export { type AiOptions, type AnyType, type ApiCallParams, type BucketInfo, type BucketVisibility, type ChatMessage, type ClientConfig, type CreateBucketParams, type CreateBucketResponse, type DownloadParams, type GenImgParams, type GenImgResponse, type GenTxtNonStreamParams, type GenTxtParams, type GenTxtResponse, type GenTxtStreamParams, type GetDownloadUrlParams, type GetDownloadUrlResponse, type GetObjectInfoParams, type GetObjectInfoResponse, type GetUploadUrlParams, type GetUploadUrlResponse, type ImageContent, type IntegrationFunction, type IntegrationParams, type ListBucketsResponse, type ListObjectsParams, type ListObjectsResponse, type MessageContent, type ObjectInfo, type RenameObjectParams, type RenameObjectResponse, type RequestConfig, type StreamChunk, type StreamResult, type TextContent, type UploadParams, type UploadResult, createClient };
500
+ export { type AiOptions, type AnyType, type ApiCallParams, type BucketInfo, type BucketVisibility, type ChatMessage, type ClientConfig, type CreateBucketParams, type CreateBucketResponse, type DownloadParams, type GenAudioParams, type GenAudioResponse, type GenImgParams, type GenImgResponse, type GenTxtNonStreamParams, type GenTxtParams, type GenTxtResponse, type GenTxtStreamParams, type GenVideoParams, type GenVideoResponse, type GetDownloadUrlParams, type GetDownloadUrlResponse, type GetObjectInfoParams, type GetObjectInfoResponse, type GetUploadUrlParams, type GetUploadUrlResponse, type ImageContent, type IntegrationFunction, type IntegrationParams, type ListBucketsResponse, type ListObjectsParams, type ListObjectsResponse, type MessageContent, type ObjectInfo, type RenameObjectParams, type RenameObjectResponse, type RequestConfig, type StreamChunk, type StreamResult, type TextContent, type UploadParams, type UploadResult, createClient };
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
1
  import e from"axios";import t from"qs";const n=e=>{let t=e.response?.status;if(t&&t>=400&&t!==401)try{typeof window<`u`&&window.top&&window.top?.postMessage({type:`mgx-appview-error`,targetName:window.name,data:{errMsg:e.response?.data?.message||e.response?.data?.detail||`Server Error`,stack:JSON.stringify({url:e.response?.config?.url,data:e.response?.data,status:e.response?.status})}},`*`)}catch(e){console.warn(`Failed to notify parent window about API error:`,e)}},r=(r={})=>{let{onUnauthorized:i,...a}=r,o=typeof globalThis<`u`&&`localStorage`in globalThis&&typeof globalThis.localStorage?.getItem==`function`?globalThis.localStorage.getItem(`token`)??void 0:void 0,s={timeout:6e4,paramsSerializer:e=>t.stringify(e,{arrayFormat:`brackets`}),...a,headers:{"Content-Type":`application/json`,"App-Host":globalThis?.window?.location?.origin??``,...o?{Authorization:`Bearer ${o}`}:{},...a.headers}},c=e.create(s);return c.interceptors.request.use(e=>e,e=>Promise.reject(e)),c.interceptors.response.use(e=>e,e=>{let t=e.response?.status;return t===401&&i&&i(),n(e),Promise.reject(e)}),c},i=[`stripe.com`],a=e=>typeof e==`string`?e.startsWith(`_`)||e.startsWith(`$`)||e===`constructor`||e===`toString`||e===`valueOf`||e===`inspect`||e===`toJSON`:!0,o=()=>{let e=window.location?.href??``,t=``;e.startsWith(`/`)?t=e:e&&(t=e.replace(/^[a-z][a-z0-9+.-]*:\/\/[^/]+/i,``));let n=new URLSearchParams({from_url:t});window.location.href=`/api/v1/auth/login?${n.toString()}`},s=()=>globalThis?.window?.name?.includes(`devIframe`),c=e=>e?i.some(t=>e.toString().includes(t)):!1,l=e=>{let{requestInstance:t}=e;return{async login(){let e=new URLSearchParams(window.location.search),t=e.get(`token`);t&&typeof globalThis<`u`&&`localStorage`in globalThis?(globalThis.localStorage?.setItem(`token`,t),globalThis.localStorage?.setItem(`isLougOutManual`,`false`),window.location.href=`/`):setTimeout(()=>{o()})},async me(){return t.get(`/api/v1/auth/me`)},async logout(){typeof globalThis<`u`&&`localStorage`in globalThis&&(globalThis.localStorage?.removeItem(`token`),globalThis.localStorage?.setItem(`isLougOutManual`,`true`));let e=await t.get(`/api/v1/auth/logout`);return typeof globalThis<`u`&&`window`in globalThis&&(globalThis.window.opener=null),window.location.href=`/`,e},toLogin:o}},u=e=>{let{requestInstance:t,entityName:n}=e,r=`/api/v1/entities/${n}`,i=e=>{if(!e)return;let t={...e};return e.fields&&Array.isArray(e.fields)&&(t.fields=e.fields.join(`,`)),e.query&&typeof e.query==`object`&&(t.query=JSON.stringify(e.query)),t};return{async query(e){let n=i(e);return t.get(r,{params:n})},async queryAll(e){let n=i(e);return t.get(`${r}/all`,{params:n})},async get(e){let{id:n,...a}=e,o=i(a);return t.get(`${r}/${n}`,{params:o})},async create(e){return t.post(r,e.data)},async update(e){return t.put(`${r}/${e.id}`,e.data)},async delete(e){return t.delete(`${r}/${e.id}`)},async deleteBatch(e){return t.delete(`${r}/batch`,{data:{ids:e.ids}})},async createBatch(e){return t.post(`${r}/batch`,e.data)},async updateBatch(e){return t.put(`${r}/batch`,e.data)}}},d=e=>{let{requestInstance:t}=e,n=new Map;return new Proxy({},{get(e,r){if(!a(r))return n.has(r)||n.set(r,u({requestInstance:t,entityName:r})),n.get(r)}})},f=e=>{let{requestInstance:t}=e;return{async invoke(e){let{url:n,method:r=`GET`,data:i,options:a={}}=e;if(typeof window<`u`&&a?.responseType===`stream`){let e;try{typeof globalThis<`u`&&`localStorage`in globalThis&&typeof globalThis.localStorage?.getItem==`function`&&(e=globalThis.localStorage.getItem(`token`)??void 0)}catch{}let t={"Content-Type":`application/json`,"App-Host":globalThis?.window?.location?.origin??``,...e?{Authorization:`Bearer ${e}`}:{},...a.headers||{}},o;i&&[`POST`,`PUT`,`PATCH`].includes(r.toUpperCase())&&(o=JSON.stringify(i));let s=await fetch(n,{method:r.toUpperCase(),headers:t,body:o});return s}let o={method:r.toUpperCase(),url:n,...a};return i&&[`POST`,`PUT`,`PATCH`].includes(o.method)?o.data=i:i&&[`GET`,`DELETE`].includes(o.method)&&(o.params=i),t.request(o)}}},p=e=>{let{requestInstance:t}=e;return new Proxy({},{get(e,n){if(!a(n))return new Proxy({},{get(e,r){if(!a(r))return(e={})=>{let i=`/api/integrations/core/${r}`;n!==`core`&&(i=`/api/integrations/providers/${n}/${r}`);let{payload:a={},option:o={}}=e,s=a instanceof FormData?{...o,headers:{...o.headers,"Content-Type":void 0}}:o;return t.post(i,a,s)}}})}})};let m=null;const h=e=>{if(m)return;let{requestInstance:t}=e,n=async e=>{let n=globalThis?.localStorage?.getItem(`token`);if(n)return;let r=e.token,i=await t.post(`/api/v1/auth/token/exchange`,{platform_token:r});i.status===200&&i.data.token&&(globalThis?.localStorage?.setItem(`token`,i.data.token),window.location.href=`/`)},r=e=>{switch(e.data.type){case`mgx-token-saved`:n(e.data.data);break;default:break}};m={requestInstance:t,handleMessage:r},globalThis?.window?.addEventListener(`message`,r)},g=()=>{let e=(e,t,n,r)=>{if(globalThis?.window===void 0||!globalThis?.window?.top){console.warn(`postMessage: window.top is not available`);return}try{let{targetOrigin:i=`*`,targetName:a=globalThis?.window?.name??``}=n||{},o={type:e,targetName:a,data:t};(r??globalThis?.window?.top)?.postMessage(o,i)}catch(e){console.warn(`Failed to send postMessage:`,e)}};return{postMessage:e}};let _=!1;const v=e=>{h(e);let{postMessage:t}=g(),n=()=>{if(_)return;_=!0;let e=globalThis?.localStorage?.getItem(`token`),n=globalThis?.localStorage?.getItem(`isLougOutManual`)===`true`,r=window.self!==window.top&&window.name?.includes(`devIframe`);!e&&!n&&r&&(t(`mgx-token-request`,{domain:globalThis?.window?.location?.href??``},{},globalThis?.window?.opener),t(`mgx-token-request`,{domain:globalThis?.window?.location?.href??``}))};return n(),{createPage(e){let{path:n,prompt:r}=e;t(`mgx-create-page`,{path:n??globalThis?.window?.location?.pathname??``,prompt:r})}}},y=()=>{let{postMessage:e}=g(),t=t=>{if(t){if(globalThis?.window===void 0){console.warn(`openUrl: window is not available`);return}if(c(t)&&s()){e(`mgx-open-url`,{url:t.toString()},{},globalThis?.window?.opener);return}globalThis.window.location.href=t.toString()}};return{openUrl:t}},b=e=>{let{requestInstance:t}=e;async function n(e,t,n,r){let i=e.body?.getReader();if(!i){let e=Error(`Response body is not readable`);throw r?.(e),e}let a=new TextDecoder,o=``,s=``;try{for(;;){let{done:e,value:n}=await i.read();if(e)break;s+=a.decode(n,{stream:!0});let c=s.split(`
2
- `);s=c.pop()||``;for(let e of c){if(!e.startsWith(`data: `))continue;let n=e.slice(6).trim();if(n===`[DONE]`)continue;try{let e=JSON.parse(n);if(e.content?.startsWith(`[ERROR]`)){let t=Error(e.content);throw r?.(t),t}e.content&&(o+=e.content,t?.({content:e.content}))}catch(e){if(e.message?.startsWith(`[ERROR]`))throw e}}}if(s.startsWith(`data: `)){let e=s.slice(6).trim();if(e!==`[DONE]`)try{let n=JSON.parse(e);if(n.content?.startsWith(`[ERROR]`)){let e=Error(n.content);throw r?.(e),e}n.content&&(o+=n.content,t?.({content:n.content}))}catch(e){if(e.message?.startsWith(`[ERROR]`))throw e}}let e={content:o};return n?.(e),e}catch(e){throw e instanceof Error&&r?.(e),e}}async function r(e){let{messages:r,model:i,stream:a,timeout:o}=e,s=`/api/v1/aihub/gentxt`,c={messages:r,model:i,stream:a};if(a){let r=e,{onChunk:i,onComplete:a,onError:l}=r;if(typeof window<`u`){let e;try{typeof globalThis<`u`&&`localStorage`in globalThis&&typeof globalThis.localStorage?.getItem==`function`&&(e=globalThis.localStorage.getItem(`token`)??void 0)}catch{}let t={"Content-Type":`application/json`,"App-Host":globalThis?.window?.location?.origin??``,...e?{Authorization:`Bearer ${e}`}:{}},r=new AbortController,u=o?setTimeout(()=>r.abort(),o):void 0;try{let e=await fetch(s,{method:`POST`,headers:t,body:JSON.stringify(c),signal:r.signal});if(u&&clearTimeout(u),!e.ok){let t=Error(`HTTP error! status: ${e.status}`);throw l?.(t),t}return await n(e,i,a,l)}catch(e){throw u&&clearTimeout(u),e instanceof Error&&l?.(e),e}}let u=await t.request({method:`POST`,url:s,data:c,responseType:`stream`,timeout:o});return{content:u.data}}return t.request({method:`POST`,url:s,data:c,timeout:o})}async function i(e,n={}){let{prompt:r,model:i,size:a=`1024x1024`,quality:o=`standard`,n:s=1,image:c}=e,{timeout:l=6e5}=n,u=`/api/v1/aihub/genimg`,d={prompt:r,model:i,size:a,n:s};return c||(d.quality=o),c&&(d.image=c),t.request({method:`POST`,url:u,data:d,timeout:l})}return{gentxt:r,genimg:i}};function x(e){return new Promise(t=>{let n=document.createElement(`input`);n.type=`file`,e&&(n.accept=e),n.onchange=()=>{let e=n.files?.[0]??null;t(e)},n.oncancel=()=>{t(null)};let r=()=>{setTimeout(()=>{n.files?.length||t(null),window.removeEventListener(`focus`,r)},300)};window.addEventListener(`focus`,r),n.click()})}const S=e=>{let{requestInstance:t}=e;async function n(e){return t.request({method:`POST`,url:`/api/v1/storage/create-bucket`,data:e})}async function r(){return t.request({method:`GET`,url:`/api/v1/storage/list-buckets`})}async function i(e){return t.request({method:`GET`,url:`/api/v1/storage/list-objects`,params:e})}async function a(e){return t.request({method:`GET`,url:`/api/v1/storage/get-object-info`,params:e})}async function o(e){return t.request({method:`POST`,url:`/api/v1/storage/rename-object`,data:e})}async function s(e){return t.request({method:`POST`,url:`/api/v1/storage/upload-url`,data:e})}async function c(e){return t.request({method:`POST`,url:`/api/v1/storage/download-url`,data:e})}async function l(e){let{bucket_name:t,accept:n}=e,{file:r,object_key:i}=e;if(!r){if(typeof window>`u`||typeof document>`u`)throw TypeError(`File picker is only available in browser environment. Please provide a file.`);let e=await x(n);if(!e)throw Error(`File selection cancelled`);r=e}i||=r.name;let{data:a}=await s({bucket_name:t,object_key:i}),o=await fetch(a.upload_url,{method:`PUT`,body:r,headers:{"Content-Type":r.type||`application/octet-stream`}});if(!o.ok)throw Error(`Upload failed with status ${o.status}: ${o.statusText}`);return{bucket_name:t,object_key:i,size:r.size,file_name:r.name}}async function u(e){let{data:t}=await c(e);if(typeof window<`u`&&typeof document<`u`){let n=document.createElement(`a`);n.href=t.download_url;let r=e.object_key.split(`/`).pop()||`download`;n.download=r,document.body.appendChild(n),n.click(),document.body.removeChild(n)}return t.download_url}return{createBucket:n,listBuckets:r,listObjects:i,getObjectInfo:a,renameObject:o,getUploadUrl:s,getDownloadUrl:c,upload:l,download:u}},C=(e={})=>{let t=r({baseURL:`/`,...e}),n=l({requestInstance:t}),i=d({requestInstance:t}),a=f({requestInstance:t}),o=p({requestInstance:t}),s=v({requestInstance:t}),c=y(),u=b({requestInstance:t}),m=S({requestInstance:t});return{auth:n,entities:i,apiCall:a,integrations:o,frame:s,utils:c,ai:u,storage:m}};export{C as createClient};
2
+ `);s=c.pop()||``;for(let e of c){if(!e.startsWith(`data: `))continue;let n=e.slice(6).trim();if(n===`[DONE]`)continue;try{let e=JSON.parse(n);if(e.content?.startsWith(`[ERROR]`)){let t=Error(e.content);throw r?.(t),t}e.content&&(o+=e.content,t?.({content:e.content}))}catch(e){if(e.message?.startsWith(`[ERROR]`))throw e}}}if(s.startsWith(`data: `)){let e=s.slice(6).trim();if(e!==`[DONE]`)try{let n=JSON.parse(e);if(n.content?.startsWith(`[ERROR]`)){let e=Error(n.content);throw r?.(e),e}n.content&&(o+=n.content,t?.({content:n.content}))}catch(e){if(e.message?.startsWith(`[ERROR]`))throw e}}let e={content:o};return n?.(e),e}catch(e){throw e instanceof Error&&r?.(e),e}}async function r(e){let{messages:r,model:i,stream:a,timeout:o}=e,s=`/api/v1/aihub/gentxt`,c={messages:r,model:i,stream:a};if(a){let r=e,{onChunk:i,onComplete:a,onError:l}=r;if(typeof window<`u`){let e;try{typeof globalThis<`u`&&`localStorage`in globalThis&&typeof globalThis.localStorage?.getItem==`function`&&(e=globalThis.localStorage.getItem(`token`)??void 0)}catch{}let t={"Content-Type":`application/json`,"App-Host":globalThis?.window?.location?.origin??``,...e?{Authorization:`Bearer ${e}`}:{}},r=new AbortController,u=o?setTimeout(()=>r.abort(),o):void 0;try{let e=await fetch(s,{method:`POST`,headers:t,body:JSON.stringify(c),signal:r.signal});if(u&&clearTimeout(u),!e.ok){let t=Error(`HTTP error! status: ${e.status}`);throw l?.(t),t}return await n(e,i,a,l)}catch(e){throw u&&clearTimeout(u),e instanceof Error&&l?.(e),e}}let u=await t.request({method:`POST`,url:s,data:c,responseType:`stream`,timeout:o});return{content:u.data}}return t.request({method:`POST`,url:s,data:c,timeout:o})}async function i(e,n={}){let{prompt:r,model:i,size:a=`1024x1024`,quality:o=`standard`,n:s=1,image:c}=e,{timeout:l=6e5}=n,u=`/api/v1/aihub/genimg`,d={prompt:r,model:i,size:a,n:s};return c||(d.quality=o),c&&(d.image=c),t.request({method:`POST`,url:u,data:d,timeout:l})}async function a(e,n={}){let{prompt:r,model:i,size:a=`1280x720`,seconds:o=`8`,image:s}=e,{timeout:c=6e5}=n,l=`/api/v1/aihub/genvideo`,u={prompt:r,model:i,size:a,seconds:o};return s&&(u.image=s),t.request({method:`POST`,url:l,data:u,timeout:c})}async function o(e,n={}){let{text:r,model:i,gender:a=`female`}=e,{timeout:o=6e4}=n,s=`/api/v1/aihub/genaudio`,c={text:r,model:i,gender:a};return t.request({method:`POST`,url:s,data:c,timeout:o})}return{gentxt:r,genimg:i,genvideo:a,genaudio:o}};function x(e){return new Promise(t=>{let n=document.createElement(`input`);n.type=`file`,e&&(n.accept=e),n.onchange=()=>{let e=n.files?.[0]??null;t(e)},n.oncancel=()=>{t(null)};let r=()=>{setTimeout(()=>{n.files?.length||t(null),window.removeEventListener(`focus`,r)},300)};window.addEventListener(`focus`,r),n.click()})}const S=e=>{let{requestInstance:t}=e;async function n(e){return t.request({method:`POST`,url:`/api/v1/storage/create-bucket`,data:e})}async function r(){return t.request({method:`GET`,url:`/api/v1/storage/list-buckets`})}async function i(e){return t.request({method:`GET`,url:`/api/v1/storage/list-objects`,params:e})}async function a(e){return t.request({method:`GET`,url:`/api/v1/storage/get-object-info`,params:e})}async function o(e){return t.request({method:`POST`,url:`/api/v1/storage/rename-object`,data:e})}async function s(e){return t.request({method:`POST`,url:`/api/v1/storage/upload-url`,data:e})}async function c(e){return t.request({method:`POST`,url:`/api/v1/storage/download-url`,data:e})}async function l(e){let{bucket_name:t,accept:n}=e,{file:r,object_key:i}=e;if(!r){if(typeof window>`u`||typeof document>`u`)throw TypeError(`File picker is only available in browser environment. Please provide a file.`);let e=await x(n);if(!e)throw Error(`File selection cancelled`);r=e}i||=r.name;let{data:a}=await s({bucket_name:t,object_key:i}),o=await fetch(a.upload_url,{method:`PUT`,body:r,headers:{"Content-Type":r.type||`application/octet-stream`}});if(!o.ok)throw Error(`Upload failed with status ${o.status}: ${o.statusText}`);return{bucket_name:t,object_key:i,size:r.size,file_name:r.name}}async function u(e){let{data:t}=await c(e);if(typeof window<`u`&&typeof document<`u`){let n=document.createElement(`a`);n.href=t.download_url;let r=e.object_key.split(`/`).pop()||`download`;n.download=r,document.body.appendChild(n),n.click(),document.body.removeChild(n)}return t.download_url}return{createBucket:n,listBuckets:r,listObjects:i,getObjectInfo:a,renameObject:o,getUploadUrl:s,getDownloadUrl:c,upload:l,download:u}},C=(e={})=>{let t=r({baseURL:`/`,...e}),n=l({requestInstance:t}),i=d({requestInstance:t}),a=f({requestInstance:t}),o=p({requestInstance:t}),s=v({requestInstance:t}),c=y(),u=b({requestInstance:t}),m=S({requestInstance:t});return{auth:n,entities:i,apiCall:a,integrations:o,frame:s,utils:c,ai:u,storage:m}};export{C as createClient};
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@metagptx/web-sdk",
3
3
  "type": "module",
4
- "version": "0.0.58",
4
+ "version": "0.0.59-beta.3",
5
5
  "packageManager": "pnpm@10.15.0+sha512.486ebc259d3e999a4e8691ce03b5cac4a71cbeca39372a9b762cb500cfdf0873e2cb16abe3d951b1ee2cf012503f027b98b6584e4df22524e0c7450d9ec7aa7b",
6
6
  "description": "TypeScript SDK for interacting with FuncSea API",
7
7
  "author": "MetaGPTX",
@@ -37,7 +37,7 @@
37
37
  "test": "vitest run",
38
38
  "test:coverage": "vitest --coverage run",
39
39
  "typecheck": "tsc --noEmit",
40
- "release": "bumpp && npm publish",
40
+ "release": "bumpp && npm publish --tag beta",
41
41
  "lint": "eslint",
42
42
  "lint:fix": "eslint --fix",
43
43
  "precommit": "npm run typecheck && lint-staged && npm run test:coverage",