@metagptx/web-sdk 0.0.21 → 0.0.23

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
@@ -26,12 +26,13 @@ const user = await client.auth.me();
26
26
 
27
27
  ## Modules
28
28
 
29
- The SDK provides four main modules:
29
+ The SDK provides five main modules:
30
30
 
31
31
  - **auth**: User authentication operations
32
32
  - **entities**: Dynamic entity CRUD operations
33
33
  - **apiCall**: Custom API calls
34
34
  - **integrations**: Integration function invocations
35
+ - **frame**: Frame communication operations for iframe/parent window messaging
35
36
 
36
37
  ## API Reference
37
38
 
@@ -443,6 +444,79 @@ const response = await client.integrations.storage.uploadFile({
443
444
 
444
445
  ---
445
446
 
447
+ ### Frame Module
448
+
449
+ Provides utilities for communicating between iframe and parent window using postMessage API.
450
+
451
+ #### `frame.postMessage(type, data?, options?)`
452
+
453
+ Send a message to the parent window using `window.top.postMessage`.
454
+
455
+ **Parameters:**
456
+ - `type` (required): Message type identifier (must be a valid `FrameMessageType`)
457
+ - `data` (optional): Message data payload (must match the data type for the given message type)
458
+ - `options` (optional): Configuration options
459
+ - `targetOrigin` (optional): Target origin for the message (defaults to `'*'`)
460
+ - `targetName` (optional): Target window name (defaults to `window.name`)
461
+
462
+ **Default Message Types:**
463
+ - `'mgx-appview-error'`: Error message with `errMsg` and `stack` fields
464
+ - `'mgx-create-page'`: Create page message with `path` field
465
+
466
+ **TypeScript Support:**
467
+ You can extend the `FrameMessageTypes` interface to add custom message types:
468
+
469
+ ```typescript
470
+ import type { FrameMessageTypes } from '@metagptx/web-sdk';
471
+
472
+ interface CustomMessageTypes extends FrameMessageTypes {
473
+ 'custom-type': { customField: string };
474
+ }
475
+ ```
476
+
477
+ **Example:**
478
+ ```typescript
479
+ // Send an error message
480
+ client.frame.postMessage('mgx-appview-error', {
481
+ errMsg: 'Error message',
482
+ stack: 'Error stack trace',
483
+ });
484
+
485
+ // Send a message with custom origin
486
+ client.frame.postMessage('mgx-appview-error', {
487
+ errMsg: 'Error message',
488
+ stack: 'Error stack trace',
489
+ }, {
490
+ targetOrigin: 'https://example.com',
491
+ });
492
+
493
+ // Send a message with custom target name
494
+ client.frame.postMessage('mgx-appview-error', {
495
+ errMsg: 'Error message',
496
+ stack: 'Error stack trace',
497
+ }, {
498
+ targetName: 'custom-window',
499
+ });
500
+ ```
501
+
502
+ #### `frame.createPage(path?)`
503
+
504
+ Create a page by sending a `'mgx-create-page'` message to the parent window. This is a convenience method that uses `postMessage` internally.
505
+
506
+ **Parameters:**
507
+ - `path` (optional): Page path to create. If not provided, uses `window.location.pathname`
508
+
509
+ **Example:**
510
+ ```typescript
511
+ // Create page with current path
512
+ client.frame.createPage();
513
+
514
+ // Create page with specific path
515
+ client.frame.createPage('/custom/path');
516
+ ```
517
+
518
+ ---
519
+
446
520
  ## Configuration
447
521
 
448
522
  ### Client Configuration Options
package/dist/index.d.ts CHANGED
@@ -68,6 +68,10 @@ declare const createClient: (config?: ClientConfig) => {
68
68
  invoke<T = any>(params: ApiCallParams): Promise<axios0.AxiosResponse<T, any, {}>>;
69
69
  };
70
70
  integrations: Record<string, Record<string, IntegrationFunction>>;
71
+ frame: {
72
+ postMessage<T extends FrameMessageType>(type: T, data?: FrameMessageData<T>, options?: PostMessageOptions): void;
73
+ createPage(path?: string): void;
74
+ };
71
75
  };
72
76
  //#endregion
73
77
  //#region src/types/index.d.ts
@@ -93,6 +97,59 @@ interface ApiCallParams {
93
97
  * @returns Object containing invoke method for API calls
94
98
  */
95
99
  //#endregion
100
+ //#region src/modules/frame.d.ts
101
+ /**
102
+ * Default message type definitions
103
+ * Extend this interface to add custom message types
104
+ */
105
+ interface DefaultFrameMessageTypes {
106
+ 'mgx-appview-error': {
107
+ errMsg: string;
108
+ stack: string;
109
+ };
110
+ 'mgx-create-page': {
111
+ path: string;
112
+ };
113
+ }
114
+ /**
115
+ * Message type map interface
116
+ * Extend this interface to add custom message types and their corresponding data types
117
+ * @example
118
+ * ```typescript
119
+ * interface CustomMessageTypes extends FrameMessageTypes {
120
+ * 'custom-type': { customField: string };
121
+ * }
122
+ * ```
123
+ */
124
+ interface FrameMessageTypes extends DefaultFrameMessageTypes {}
125
+ /**
126
+ * Extract message type keys from FrameMessageTypes
127
+ */
128
+ type FrameMessageType = keyof FrameMessageTypes;
129
+ /**
130
+ * Extract data type for a specific message type
131
+ */
132
+ type FrameMessageData<T extends FrameMessageType> = FrameMessageTypes[T];
133
+ /**
134
+ * PostMessage options interface
135
+ */
136
+ interface PostMessageOptions {
137
+ /**
138
+ * Target origin for the message
139
+ * @default '*'
140
+ */
141
+ targetOrigin?: string;
142
+ /**
143
+ * Target window name
144
+ * @default window.name
145
+ */
146
+ targetName?: string;
147
+ }
148
+ /**
149
+ * Creates a frame module for frame-related operations
150
+ * @returns Object containing frame operation methods
151
+ */
152
+ //#endregion
96
153
  //#region src/modules/integrations.d.ts
97
154
  /**
98
155
  * Integration function parameters interface
@@ -113,4 +170,4 @@ type IntegrationFunction = (params?: IntegrationParams) => Promise<AnyType>;
113
170
  */
114
171
 
115
172
  //#endregion
116
- export { type AnyType, type ApiCallParams, type ClientConfig, type IntegrationFunction, type IntegrationParams, type RequestConfig, createClient };
173
+ export { type AnyType, type ApiCallParams, type ClientConfig, type DefaultFrameMessageTypes, type FrameMessageData, type FrameMessageType, type FrameMessageTypes, type IntegrationFunction, type IntegrationParams, type PostMessageOptions, type RequestConfig, createClient };
package/dist/index.js CHANGED
@@ -1 +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||``,stack:e.response?.data?.error||JSON.stringify(e?.response||{})}},`*`)}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`,...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=e=>typeof e==`string`?e.startsWith(`_`)||e.startsWith(`$`)||e===`constructor`||e===`toString`||e===`valueOf`||e===`inspect`||e===`toJSON`:!0,a=()=>{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()}`},o=e=>{let{requestInstance:t}=e;return{async login(){let e=new URLSearchParams(window.location.search),t=e.get(`token`);return t&&typeof globalThis<`u`&&`localStorage`in globalThis&&(globalThis.localStorage?.setItem(`token`,t),window.location.href=`/`),t},async me(){return t.get(`/api/v1/auth/me`)},async logout(){typeof globalThis<`u`&&`localStorage`in globalThis&&globalThis.localStorage?.removeItem(`token`);let e=await t.get(`/api/v1/auth/logout`);return window.location.href=`/`,e},toLogin:a}},s=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)}}},c=e=>{let{requestInstance:t}=e,n=new Map;return new Proxy({},{get(e,r){if(!i(r))return n.has(r)||n.set(r,s({requestInstance:t,entityName:r})),n.get(r)}})},l=e=>{let{requestInstance:t}=e;return{async invoke(e){let{url:n,method:r=`GET`,data:i,options:a={}}=e,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)}}},u=e=>{let{requestInstance:t}=e;return new Proxy({},{get(e,n){if(!i(n))return new Proxy({},{get(e,r){if(!i(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)}}})}})},d=(e={})=>{let t=r({baseURL:`/`,...e}),n=o({requestInstance:t}),i=c({requestInstance:t}),a=l({requestInstance:t}),s=u({requestInstance:t});return{auth:n,entities:i,apiCall:a,integrations:s}};export{d as createClient};
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`,...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=e=>typeof e==`string`?e.startsWith(`_`)||e.startsWith(`$`)||e===`constructor`||e===`toString`||e===`valueOf`||e===`inspect`||e===`toJSON`:!0,a=()=>{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()}`},o=e=>{let{requestInstance:t}=e;return{async login(){let e=new URLSearchParams(window.location.search),t=e.get(`token`);return t&&typeof globalThis<`u`&&`localStorage`in globalThis&&(globalThis.localStorage?.setItem(`token`,t),window.location.href=`/`),t},async me(){return t.get(`/api/v1/auth/me`)},async logout(){typeof globalThis<`u`&&`localStorage`in globalThis&&globalThis.localStorage?.removeItem(`token`);let e=await t.get(`/api/v1/auth/logout`);return window.location.href=`/`,e},toLogin:a}},s=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)}}},c=e=>{let{requestInstance:t}=e,n=new Map;return new Proxy({},{get(e,r){if(!i(r))return n.has(r)||n.set(r,s({requestInstance:t,entityName:r})),n.get(r)}})},l=e=>{let{requestInstance:t}=e;return{async invoke(e){let{url:n,method:r=`GET`,data:i,options:a={}}=e,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)}}},u=e=>{let{requestInstance:t}=e;return new Proxy({},{get(e,n){if(!i(n))return new Proxy({},{get(e,r){if(!i(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)}}})}})},d=()=>({postMessage(e,t,n){if(typeof window>`u`||!window.top){console.warn(`postMessage: window.top is not available`);return}try{let{targetOrigin:r=`*`,targetName:i=window.name}=n||{},a={type:e,targetName:i,data:t};window.top.postMessage(a,r)}catch(e){console.warn(`Failed to send postMessage:`,e)}},createPage(e){let t=e??window.location.pathname;this.postMessage(`mgx-create-page`,{path:t})}}),f=(e={})=>{let t=r({baseURL:`/`,...e}),n=o({requestInstance:t}),i=c({requestInstance:t}),a=l({requestInstance:t}),s=u({requestInstance:t}),f=d();return{auth:n,entities:i,apiCall:a,integrations:s,frame:f}};export{f 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.21",
4
+ "version": "0.0.23",
5
5
  "packageManager": "pnpm@10.15.0+sha512.486ebc259d3e999a4e8691ce03b5cac4a71cbeca39372a9b762cb500cfdf0873e2cb16abe3d951b1ee2cf012503f027b98b6584e4df22524e0c7450d9ec7aa7b",
6
6
  "description": "TypeScript SDK for interacting with FuncSea API",
7
7
  "author": "MetaGPTX",