@memberjunction/graphql-dataprovider 2.125.0 → 2.126.1
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.cjs +38 -38
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +2 -0
- package/dist/index.d.mts +2 -0
- package/dist/index.mjs +22 -22
- package/dist/index.mjs.map +1 -1
- package/package.json +7 -7
package/dist/index.d.cts
CHANGED
|
@@ -490,6 +490,7 @@ declare class GraphQLDataProvider extends ProviderBase implements IEntityDataPro
|
|
|
490
490
|
private _configData;
|
|
491
491
|
private _sessionId;
|
|
492
492
|
private _aiClient;
|
|
493
|
+
private _refreshPromise;
|
|
493
494
|
get ConfigData(): GraphQLProviderConfigData;
|
|
494
495
|
/**
|
|
495
496
|
* The core schema name constant. This should match the mjCoreSchema config value.
|
|
@@ -677,6 +678,7 @@ declare class GraphQLDataProvider extends ProviderBase implements IEntityDataPro
|
|
|
677
678
|
*/
|
|
678
679
|
ExecuteGQL(query: string, variables: any, refreshTokenIfNeeded?: boolean): Promise<any>;
|
|
679
680
|
RefreshToken(): Promise<void>;
|
|
681
|
+
private performTokenRefresh;
|
|
680
682
|
static RefreshToken(): Promise<void>;
|
|
681
683
|
protected CreateNewGraphQLClient(url: string, token: string, sessionId: string, mjAPIKey: string): GraphQLClient;
|
|
682
684
|
private _innerCurrentUserQueryString;
|
package/dist/index.d.mts
CHANGED
|
@@ -490,6 +490,7 @@ declare class GraphQLDataProvider extends ProviderBase implements IEntityDataPro
|
|
|
490
490
|
private _configData;
|
|
491
491
|
private _sessionId;
|
|
492
492
|
private _aiClient;
|
|
493
|
+
private _refreshPromise;
|
|
493
494
|
get ConfigData(): GraphQLProviderConfigData;
|
|
494
495
|
/**
|
|
495
496
|
* The core schema name constant. This should match the mjCoreSchema config value.
|
|
@@ -677,6 +678,7 @@ declare class GraphQLDataProvider extends ProviderBase implements IEntityDataPro
|
|
|
677
678
|
*/
|
|
678
679
|
ExecuteGQL(query: string, variables: any, refreshTokenIfNeeded?: boolean): Promise<any>;
|
|
679
680
|
RefreshToken(): Promise<void>;
|
|
681
|
+
private performTokenRefresh;
|
|
680
682
|
static RefreshToken(): Promise<void>;
|
|
681
683
|
protected CreateNewGraphQLClient(url: string, token: string, sessionId: string, mjAPIKey: string): GraphQLClient;
|
|
682
684
|
private _innerCurrentUserQueryString;
|
package/dist/index.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var Pe=Object.defineProperty;var
|
|
1
|
+
var Pe=Object.defineProperty;var f=(D,e)=>Pe(D,"name",{value:e,configurable:!0});var h;import{gql as p,GraphQLClient as he}from"graphql-request";import{gql as Ye}from"graphql-request";import{TransactionGroupBase as $e,TransactionResult as ve,LogError as l,LogStatusEx as N,ProviderConfigDataBase as Ne,ProviderBase as Ce,UserInfo as fe,ProviderType as be,BaseEntityResult as Se,EntityFieldTSType as E,TransactionItem as Re,UserRoleInfo as Te,SetProvider as Ve,IsVerboseLoggingEnabled as xe}from"@memberjunction/core";import{ViewInfo as Ie}from"@memberjunction/core-entities";import{openDB as Ge}from"@tempfix/idb";import{Observable as C,Subject as Me,Subscription as Qe}from"rxjs";import{createClient as Le}from"graphql-ws";import{v4 as Fe}from"uuid";import{SafeJSONParse as P,MJGlobal as Ae,MJEventType as Ue}from"@memberjunction/global";const z=class z{constructor(){this._fieldMap={__mj_CreatedAt:"_mj__CreatedAt",__mj_UpdatedAt:"_mj__UpdatedAt",__mj_DeletedAt:"_mj__DeletedAt"}}MapFields(e){if(e)for(const t in e)t in this._fieldMap&&(e[this._fieldMap[t]]=e[t],delete e[t]);return e}MapFieldName(e){return this._fieldMap[e]??e}ReverseMapFieldName(e){return Object.entries(this._fieldMap).find(([t,r])=>r===e)?.[0]??e}ReverseMapFields(e){const t=Object.fromEntries(Object.entries(this._fieldMap).map(([r,s])=>[s,r]));for(const r in e)r in t&&(e[t[r]]=e[r],delete e[r]);return e}};f(z,"FieldMapper");let v=z;const X=class X extends $e{constructor(e){super(),this._provider=e}async HandleSubmit(){const e=p`
|
|
2
2
|
mutation ExecuteTransactionGroup($group: TransactionInputType!) {
|
|
3
3
|
ExecuteTransactionGroup(group: $group) {
|
|
4
4
|
Success
|
|
@@ -6,7 +6,7 @@ var Pe=Object.defineProperty;var S=(D,e)=>Pe(D,"name",{value:e,configurable:!0})
|
|
|
6
6
|
ResultsJSON
|
|
7
7
|
}
|
|
8
8
|
}
|
|
9
|
-
`,t=[];for(const n of this.PendingTransactions)t.push({EntityName:n.BaseEntity.EntityInfo.Name,EntityObjectJSON:await n.BaseEntity.GetDataObjectJSON(),OperationType:n.OperationType});const r={group:{Items:t,Variables:this.Variables.map(n=>({Name:n.Name,ItemIndex:this.MapVariableEntityObjectToPosition(n),FieldName:n.FieldName,Type:n.Type}))}},s=await this._provider.ExecuteGQL(e,r);if(s&&s.ExecuteTransactionGroup){const n=s.ExecuteTransactionGroup,i=[];for(let o=0;o<this.PendingTransactions.length;o++){const a=n.ResultsJSON[o],u=P(a),g=this.PendingTransactions[o];i.push(new ve(g,u,u!==null))}return i}else throw new Error("Failed to execute transaction group")}};
|
|
9
|
+
`,t=[];for(const n of this.PendingTransactions)t.push({EntityName:n.BaseEntity.EntityInfo.Name,EntityObjectJSON:await n.BaseEntity.GetDataObjectJSON(),OperationType:n.OperationType});const r={group:{Items:t,Variables:this.Variables.map(n=>({Name:n.Name,ItemIndex:this.MapVariableEntityObjectToPosition(n),FieldName:n.FieldName,Type:n.Type}))}},s=await this._provider.ExecuteGQL(e,r);if(s&&s.ExecuteTransactionGroup){const n=s.ExecuteTransactionGroup,i=[];for(let o=0;o<this.PendingTransactions.length;o++){const a=n.ResultsJSON[o],u=P(a),g=this.PendingTransactions[o];i.push(new ve(g,u,u!==null))}return i}else throw new Error("Failed to execute transaction group")}};f(X,"GraphQLTransactionGroup");let b=X;const H=class H{constructor(e){this._dataProvider=e}async RunAIPrompt(e){try{const t=p`
|
|
10
10
|
mutation RunAIPrompt(
|
|
11
11
|
$promptId: String!,
|
|
12
12
|
$data: String,
|
|
@@ -142,7 +142,7 @@ var Pe=Object.defineProperty;var S=(D,e)=>Pe(D,"name",{value:e,configurable:!0})
|
|
|
142
142
|
error
|
|
143
143
|
}
|
|
144
144
|
}
|
|
145
|
-
`,s={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},n=await this._dataProvider.ExecuteGQL(t,s);if(!n?.EmbedText)throw new Error("Invalid response from server");const i=n.EmbedText;return{embeddings:Array.isArray(e.textToEmbed)?i.embeddings:i.embeddings[0],modelName:i.modelName,vectorDimensions:i.vectorDimensions,error:i.error}}catch(t){const r=t;return l(`Error generating embeddings: ${r}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:r.message||"Unknown error occurred"}}}};
|
|
145
|
+
`,s={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},n=await this._dataProvider.ExecuteGQL(t,s);if(!n?.EmbedText)throw new Error("Invalid response from server");const i=n.EmbedText;return{embeddings:Array.isArray(e.textToEmbed)?i.embeddings:i.embeddings[0],modelName:i.modelName,vectorDimensions:i.vectorDimensions,error:i.error}}catch(t){const r=t;return l(`Error generating embeddings: ${r}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:r.message||"Unknown error occurred"}}}};f(H,"GraphQLAIClient");let T=H;const Z=class Z extends Ne{get Token(){return this.Data.Token}set Token(e){this.Data.Token=e}get MJAPIKey(){return this.Data.MJAPIKey}set MJAPIKey(e){this.Data.MJAPIKey=e}get URL(){return this.Data.URL}get WSURL(){return this.Data.WSURL}get RefreshTokenFunction(){return this.Data.RefreshFunction}constructor(e,t,r,s,n,i,o,a){super({Token:e,URL:t,WSURL:r,MJAPIKey:a,RefreshTokenFunction:s},n,i,o)}};f(Z,"GraphQLProviderConfigData");let V=Z;const De=(h=class extends Ce{constructor(){super(),this._refreshPromise=null,this._innerCurrentUserQueryString=`CurrentUser {
|
|
146
146
|
${this.userInfoString()}
|
|
147
147
|
UserRoles_UserIDArray {
|
|
148
148
|
${this.userRoleInfoString()}
|
|
@@ -150,7 +150,7 @@ var Pe=Object.defineProperty;var S=(D,e)=>Pe(D,"name",{value:e,configurable:!0})
|
|
|
150
150
|
}
|
|
151
151
|
`,this._currentUserQuery=p`query CurrentUserAndRoles {
|
|
152
152
|
${this._innerCurrentUserQueryString}
|
|
153
|
-
}`,this._wsClient=null,this._wsClientCreatedAt=null,this._pushStatusSubjects=new Map,this._activeSubscriptionCount=0,this.WS_CLIENT_MAX_AGE_MS=30*60*1e3,this.SUBSCRIPTION_CLEANUP_INTERVAL_MS=5*60*1e3,this.SUBSCRIPTION_IDLE_TIMEOUT_MS=10*60*1e3,this._subscriptionCleanupTimer=null,this._isCleaningUp=!1,
|
|
153
|
+
}`,this._wsClient=null,this._wsClientCreatedAt=null,this._pushStatusSubjects=new Map,this._activeSubscriptionCount=0,this.WS_CLIENT_MAX_AGE_MS=30*60*1e3,this.SUBSCRIPTION_CLEANUP_INTERVAL_MS=5*60*1e3,this.SUBSCRIPTION_IDLE_TIMEOUT_MS=10*60*1e3,this._subscriptionCleanupTimer=null,this._isCleaningUp=!1,h._instance||(h._instance=this)}static get Instance(){return h._instance}get ConfigData(){return this._configData}sanitizeGraphQLName(e){if(!e||e.length===0)return"";let t=e.replace(/[^A-Za-z0-9_]/g,"");return t.startsWith("__")&&(t=t.substring(2)),t=t.replace(/_/g,""),t.length===0||/^[0-9]/.test(t)?"_"+t:t}getGraphQLTypeNameBase(e){const t=e.SchemaName.trim().toLowerCase()===h.MJ_CORE_SCHEMA.trim().toLowerCase()?"MJ":this.sanitizeGraphQLName(e.SchemaName),r=this.sanitizeGraphQLName(e.BaseTable);return`${t}${r}`}get AI(){return this._aiClient||(this._aiClient=new T(this)),this._aiClient}get DatabaseConnection(){throw new Error("DatabaseConnection not implemented for the GraphQLDataProvider")}get InstanceConnectionString(){return this._configData.URL}GenerateUUID(){return Fe()}get LocalStoragePrefix(){if(this._configData===void 0||this._configData.URL===void 0)throw new Error("GraphQLDataProvider: ConfigData is not set. Please call Config() first.");return this._configData.URL.replace(/[^a-zA-Z0-9]/g,"_")+"."}async GetStoredSessionID(){try{const e=this.LocalStorageProvider;if(e){const t=this.LocalStoragePrefix+"sessionId";return await e.GetItem(t)}return null}catch(e){return console.error("Error retrieving session ID from local storage:",e),null}}async SaveStoredSessionID(e){try{const t=this.LocalStorageProvider;if(t){const r=this.LocalStoragePrefix+"sessionId";await t.SetItem(r,e)}}catch{}}async GetPreferredUUID(e){const t=await this.GetStoredSessionID();return e||!t?this.GenerateUUID():t}async Config(e,t,r,s){try{const n=e.Token?`${e.Token.substring(0,20)}...${e.Token.substring(e.Token.length-10)}`:"NO TOKEN";return console.log("[GraphQL] Config called with token:",{tokenPreview:n,tokenLength:e.Token?.length,separateConnection:r,hasRefreshFunction:!!e.Data?.RefreshTokenFunction}),this._configData=e,r?(this._sessionId=await this.GetPreferredUUID(s),this._client=this.CreateNewGraphQLClient(e.URL,e.Token,this._sessionId,e.MJAPIKey),await this.SaveStoredSessionID(this._sessionId)):(h.Instance._configData=e,h.Instance._sessionId===void 0&&(h.Instance._sessionId=await this.GetPreferredUUID(s)),h.Instance._client||(h.Instance._client=this.CreateNewGraphQLClient(e.URL,e.Token,h.Instance._sessionId,e.MJAPIKey)),await h.Instance.SaveStoredSessionID(h.Instance._sessionId),this._sessionId=h.Instance._sessionId,this._client=h.Instance._client),super.Config(e)}catch(n){throw l(n),n}}get sessionId(){return this._sessionId}get AllowRefresh(){return!0}async GetCurrentUser(){const e=await this.ExecuteGQL(this._currentUserQuery,null);if(e){const t=this.ConvertBackToMJFields(e.CurrentUser),r=t.UserRoles_UserIDArray.map(s=>this.ConvertBackToMJFields(s));return t.UserRoles_UserIDArray=r,new fe(this,{...t,UserRoles:r})}}async RunReport(e,t){const r=p`
|
|
154
154
|
query GetReportDataQuery ($ReportID: String!) {
|
|
155
155
|
GetReportData(ReportID: $ReportID) {
|
|
156
156
|
Success
|
|
@@ -180,7 +180,7 @@ var Pe=Object.defineProperty;var S=(D,e)=>Pe(D,"name",{value:e,configurable:!0})
|
|
|
180
180
|
TotalRowCount
|
|
181
181
|
ExecutionTime
|
|
182
182
|
ErrorMessage
|
|
183
|
-
AppliedParameters`}TransformQueryPayload(e){try{return{QueryID:e.QueryID,QueryName:e.QueryName,Success:e.Success,Results:JSON.parse(e.Results),RowCount:e.RowCount,TotalRowCount:e.TotalRowCount,ExecutionTime:e.ExecutionTime,ErrorMessage:e.ErrorMessage,AppliedParameters:e.AppliedParameters?JSON.parse(e.AppliedParameters):void 0}}catch(t){return l(`Error transforming query payload: ${t}`),null}}async RunView(e,t){await this.PreProcessRunView(e,t);try{let r="",s="";if(e){const n={};let i,o;if(e.ViewEntity)o=e.ViewEntity,i=o.Entity;else{const{entityName:c,v:d}=await this.getEntityNameAndUserView(e,t);o=d,i=c}const a=this.Entities.find(c=>c.Name===i);if(!a)throw new Error(`Entity ${i} not found in metadata`);let u=!1;const g=this.getGraphQLTypeNameBase(a);e.ViewID?(r=`Run${g}ViewByID`,s="RunViewByIDInput",n.ViewID=e.ViewID):e.ViewName?(r=`Run${g}ViewByName`,s="RunViewByNameInput",n.ViewName=e.ViewName):(u=!0,r=`Run${g}DynamicView`,s="RunDynamicViewInput",n.EntityName=e.EntityName),n.ExtraFilter=e.ExtraFilter?e.ExtraFilter:"",n.OrderBy=e.OrderBy?e.OrderBy:"",n.UserSearchString=e.UserSearchString?e.UserSearchString:"",n.Fields=e.Fields,n.IgnoreMaxRows=e.IgnoreMaxRows?e.IgnoreMaxRows:!1,e.MaxRows!==void 0&&(n.MaxRows=e.MaxRows),e.StartRow!==void 0&&(n.StartRow=e.StartRow),n.ForceAuditLog=e.ForceAuditLog?e.ForceAuditLog:!1,n.ResultType=e.ResultType?e.ResultType:"simple",e.AuditLogDescription&&e.AuditLogDescription.length>0&&(n.AuditLogDescription=e.AuditLogDescription),u||(n.ExcludeUserViewRunID=e.ExcludeUserViewRunID?e.ExcludeUserViewRunID:"",n.ExcludeDataFromAllPriorViewRuns=e.ExcludeDataFromAllPriorViewRuns?e.ExcludeDataFromAllPriorViewRuns:!1,n.OverrideExcludeFilter=e.OverrideExcludeFilter?e.OverrideExcludeFilter:"",n.SaveViewResults=e.SaveViewResults?e.SaveViewResults:!1);const m=this.getViewRunTimeFieldList(a,o,e,u),
|
|
183
|
+
AppliedParameters`}TransformQueryPayload(e){try{return{QueryID:e.QueryID,QueryName:e.QueryName,Success:e.Success,Results:JSON.parse(e.Results),RowCount:e.RowCount,TotalRowCount:e.TotalRowCount,ExecutionTime:e.ExecutionTime,ErrorMessage:e.ErrorMessage,AppliedParameters:e.AppliedParameters?JSON.parse(e.AppliedParameters):void 0}}catch(t){return l(`Error transforming query payload: ${t}`),null}}async RunView(e,t){await this.PreProcessRunView(e,t);try{let r="",s="";if(e){const n={};let i,o;if(e.ViewEntity)o=e.ViewEntity,i=o.Entity;else{const{entityName:c,v:d}=await this.getEntityNameAndUserView(e,t);o=d,i=c}const a=this.Entities.find(c=>c.Name===i);if(!a)throw new Error(`Entity ${i} not found in metadata`);let u=!1;const g=this.getGraphQLTypeNameBase(a);e.ViewID?(r=`Run${g}ViewByID`,s="RunViewByIDInput",n.ViewID=e.ViewID):e.ViewName?(r=`Run${g}ViewByName`,s="RunViewByNameInput",n.ViewName=e.ViewName):(u=!0,r=`Run${g}DynamicView`,s="RunDynamicViewInput",n.EntityName=e.EntityName),n.ExtraFilter=e.ExtraFilter?e.ExtraFilter:"",n.OrderBy=e.OrderBy?e.OrderBy:"",n.UserSearchString=e.UserSearchString?e.UserSearchString:"",n.Fields=e.Fields,n.IgnoreMaxRows=e.IgnoreMaxRows?e.IgnoreMaxRows:!1,e.MaxRows!==void 0&&(n.MaxRows=e.MaxRows),e.StartRow!==void 0&&(n.StartRow=e.StartRow),n.ForceAuditLog=e.ForceAuditLog?e.ForceAuditLog:!1,n.ResultType=e.ResultType?e.ResultType:"simple",e.AuditLogDescription&&e.AuditLogDescription.length>0&&(n.AuditLogDescription=e.AuditLogDescription),u||(n.ExcludeUserViewRunID=e.ExcludeUserViewRunID?e.ExcludeUserViewRunID:"",n.ExcludeDataFromAllPriorViewRuns=e.ExcludeDataFromAllPriorViewRuns?e.ExcludeDataFromAllPriorViewRuns:!1,n.OverrideExcludeFilter=e.OverrideExcludeFilter?e.OverrideExcludeFilter:"",n.SaveViewResults=e.SaveViewResults?e.SaveViewResults:!1);const m=this.getViewRunTimeFieldList(a,o,e,u),R=p`
|
|
184
184
|
query RunViewQuery ($input: ${s}!) {
|
|
185
185
|
${r}(input: $input) {
|
|
186
186
|
Results {
|
|
@@ -194,7 +194,7 @@ var Pe=Object.defineProperty;var S=(D,e)=>Pe(D,"name",{value:e,configurable:!0})
|
|
|
194
194
|
Success
|
|
195
195
|
ErrorMessage
|
|
196
196
|
}
|
|
197
|
-
}`,y=await this.ExecuteGQL(
|
|
197
|
+
}`,y=await this.ExecuteGQL(R,{input:n});if(y&&y[r]){const c=y[r].Results;if(c&&c.length>0){const I=a.Fields.filter(S=>S.CodeName!==S.Name&&S.CodeName!==void 0);c.forEach(S=>{this.ConvertBackToMJFields(S),I.forEach(w=>{S[w.Name]=S[w.CodeName]})})}const d=y[r];return await this.PostProcessRunView(d,e,t),d}}else throw"No parameters passed to RunView";return null}catch(r){throw l(r),r}}async RunViews(e,t){await this.PreProcessRunViews(e,t);try{let r=[],s=[],n=[];for(const a of e){let u="",g="";const m={};let R=null,y=null;if(a.ViewEntity)y=a.ViewEntity,R=y.Get("Entity");else{const{entityName:S,v:w}=await this.getEntityNameAndUserView(a,t);y=w,R=S}const c=this.Entities.find(S=>S.Name===R);if(!c)throw new Error(`Entity ${R} not found in metadata`);s.push(c);let d=!1;const I=this.getGraphQLTypeNameBase(c);a.ViewID?(u=`Run${I}ViewByID`,g="RunViewByIDInput",m.ViewID=a.ViewID):a.ViewName?(u=`Run${I}ViewByName`,g="RunViewByNameInput",m.ViewName=a.ViewName):(d=!0,u=`Run${I}DynamicView`,g="RunDynamicViewInput",m.EntityName=a.EntityName),m.ExtraFilter=a.ExtraFilter||"",m.OrderBy=a.OrderBy||"",m.UserSearchString=a.UserSearchString||"",m.Fields=a.Fields,m.IgnoreMaxRows=a.IgnoreMaxRows||!1,a.MaxRows!==void 0&&(m.MaxRows=a.MaxRows),a.StartRow!==void 0&&(m.StartRow=a.StartRow),m.ForceAuditLog=a.ForceAuditLog||!1,m.ResultType=a.ResultType||"simple",a.AuditLogDescription&&a.AuditLogDescription.length>0&&(m.AuditLogDescription=a.AuditLogDescription),d||(m.ExcludeUserViewRunID=a.ExcludeUserViewRunID||"",m.ExcludeDataFromAllPriorViewRuns=a.ExcludeDataFromAllPriorViewRuns||!1,m.OverrideExcludeFilter=a.OverrideExcludeFilter||"",m.SaveViewResults=a.SaveViewResults||!1),r.push(m),n.push(...this.getViewRunTimeFieldList(c,y,a,d))}const i=p`
|
|
198
198
|
query RunViewsQuery ($input: [RunViewGenericInput!]!) {
|
|
199
199
|
RunViews(input: $input) {
|
|
200
200
|
Results {
|
|
@@ -212,7 +212,7 @@ var Pe=Object.defineProperty;var S=(D,e)=>Pe(D,"name",{value:e,configurable:!0})
|
|
|
212
212
|
Success
|
|
213
213
|
ErrorMessage
|
|
214
214
|
}
|
|
215
|
-
}`,o=await this.ExecuteGQL(i,{input:r});if(o&&o.RunViews){const a=o.RunViews;for(const[u,g]of a.entries())g.Results=g.Results.map(m=>{let
|
|
215
|
+
}`,o=await this.ExecuteGQL(i,{input:r});if(o&&o.RunViews){const a=o.RunViews;for(const[u,g]of a.entries())g.Results=g.Results.map(m=>{let R=JSON.parse(m.Data);return this.ConvertBackToMJFields(R),R});return await this.PostProcessRunViews(a,e,t),a}return null}catch(r){throw l(r),r}}async getEntityNameAndUserView(e,t){let r,s;if(e.EntityName)r=e.EntityName;else if(e.ViewID)s=await Ie.GetViewEntity(e.ViewID,t),r=s.Entity;else if(e.ViewName)s=await Ie.GetViewEntityByName(e.ViewName,t),r=s.Entity;else throw new Error("No EntityName, ViewID or ViewName passed to RunView");return{entityName:r,v:s}}getViewRunTimeFieldList(e,t,r,s){const n=[],i=new v;if(r.Fields){for(const o of e.PrimaryKeys)r.Fields.find(a=>a.trim().toLowerCase()===o.Name.toLowerCase())===void 0&&n.push(o.Name);r.Fields.forEach(o=>{n.push(i.MapFieldName(o))})}else if(s)e.Fields.forEach(o=>{o.IsBinaryFieldType||n.push(i.MapFieldName(o.CodeName))});else{for(const o of e.PrimaryKeys)n.find(a=>a.trim().toLowerCase()===o.Name.toLowerCase())===void 0&&n.push(o.Name);t.Columns.forEach(o=>{o.hidden===!1&&!n.find(a=>a.trim().toLowerCase()===o.EntityField?.Name.trim().toLowerCase())&&o.EntityField&&n.push(i.MapFieldName(o.EntityField.CodeName))})}return n}get ProviderType(){return be.Network}async GetRecordChanges(e,t){try{const r={EntityName:"Record Changes",ExtraFilter:`RecordID = '${t.Values()}' AND Entity = '${e}'`},s=await this.RunView(r);return s?s.Results.sort((n,i)=>n.ChangedAt>i.ChangedAt?-1:1):null}catch(r){throw l(r),r}}async GetRecordDependencies(e,t){try{const r=p`query GetRecordDependenciesQuery ($entityName: String!, $CompositeKey: CompositeKeyInputType!) {
|
|
216
216
|
GetRecordDependencies(entityName: $entityName, CompositeKey: $CompositeKey) {
|
|
217
217
|
EntityName
|
|
218
218
|
RelatedEntityName
|
|
@@ -263,32 +263,32 @@ var Pe=Object.defineProperty;var S=(D,e)=>Pe(D,"name",{value:e,configurable:!0})
|
|
|
263
263
|
Message
|
|
264
264
|
}
|
|
265
265
|
}
|
|
266
|
-
}`,i={EntityName:e.EntityName,SurvivingRecordCompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(e.SurvivingRecordCompositeKey.KeyValuePairs)},FieldMap:e.FieldMap?.map(a=>({FieldName:a.FieldName,Value:a.Value.toString()})),RecordsToMerge:e.RecordsToMerge.map(a=>a.Copy())};return(await this.ExecuteGQL(n,{request:i}))?.MergeRecords}catch(n){return l(n),{Success:!1,OverallStatus:n&&n.message?n.message:n,RecordStatus:[],RecordMergeLogID:"",Request:e}}}async Save(e,t,r){const s=new
|
|
266
|
+
}`,i={EntityName:e.EntityName,SurvivingRecordCompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(e.SurvivingRecordCompositeKey.KeyValuePairs)},FieldMap:e.FieldMap?.map(a=>({FieldName:a.FieldName,Value:a.Value.toString()})),RecordsToMerge:e.RecordsToMerge.map(a=>a.Copy())};return(await this.ExecuteGQL(n,{request:i}))?.MergeRecords}catch(n){return l(n),{Success:!1,OverallStatus:n&&n.message?n.message:n,RecordStatus:[],RecordMergeLogID:"",Request:e}}}async Save(e,t,r){const s=new Se;try{e.RegisterTransactionPreprocessing();const n={input:{}},i=e.IsSaved?"Update":"Create";s.StartedAt=new Date,s.Type=e.IsSaved?"update":"create",s.OriginalValues=e.Fields.map(y=>({FieldName:y.CodeName,Value:y.Value})),e.ResultHistory.push(s);const o=this.getGraphQLTypeNameBase(e.EntityInfo),a=`${i}${o}`,u=e.Fields.filter(y=>!y.ReadOnly||y.IsPrimaryKey&&e.IsSaved),g=new v,m=` ${a}(input: $input) {
|
|
267
267
|
${e.Fields.map(y=>g.MapFieldName(y.CodeName)).join(`
|
|
268
268
|
`)}
|
|
269
|
-
}`,
|
|
269
|
+
}`,R=p`mutation ${i}${o} ($input: ${a}Input!) {
|
|
270
270
|
${m}
|
|
271
271
|
}
|
|
272
|
-
`;for(let y=0;y<u.length;y++){const c=u[y];let d=c.Value;if(d)switch(c.EntityFieldInfo.TSType){case E.Date:d=d.getTime();break;case E.Boolean:typeof d!="boolean"&&(d=parseInt(d)!==0);break;case E.Number:if(typeof d!="number"){const
|
|
272
|
+
`;for(let y=0;y<u.length;y++){const c=u[y];let d=c.Value;if(d)switch(c.EntityFieldInfo.TSType){case E.Date:d=d.getTime();break;case E.Boolean:typeof d!="boolean"&&(d=parseInt(d)!==0);break;case E.Number:if(typeof d!="number"){const I=Number(d);isNaN(I)||(d=I)}break}d===null&&c.EntityFieldInfo.AllowsNull===!1&&(c.EntityFieldInfo.DefaultValue!==null?d=c.EntityFieldInfo.DefaultValue:c.FieldType===E.Number||c.FieldType===E.Boolean?d=0:d=""),n.input[c.CodeName]=d}if(i.trim().toLowerCase()==="update"&&r.SkipOldValuesCheck===!1){const y=[];e.Fields.forEach(c=>{let d=null;c.OldValue!==null&&c.OldValue!==void 0&&(c.EntityFieldInfo.TSType===E.Date?d=c.OldValue.getTime().toString():c.EntityFieldInfo.TSType===E.Boolean?d=c.OldValue===!0?"1":"0":typeof c.OldValue!="string"?d=c.OldValue.toString():d=c.OldValue),y.push({Key:c.CodeName,Value:d})}),n.input.OldValues___=y}if(e.TransactionGroup){const y=[{varName:"input",inputType:a+"Input!"}];return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new Re(e,s.Type==="create"?"Create":"Update",m,n,{mutationName:a,mutationInputTypes:y},(c,d)=>{s.EndedAt=new Date,d&&c?(s.Success=!0,s.NewValues=this.ConvertBackToMJFields(c)):(s.Success=!1,s.Message="Transaction failed")})),!0}else{const y=await this.ExecuteGQL(R,n);if(y&&y[a])return s.Success=!0,s.EndedAt=new Date,s.NewValues=this.ConvertBackToMJFields(y[a]),s.NewValues;throw new Error(`Save failed for ${e.EntityInfo.ClassName}`)}}catch(n){return s.Success=!1,s.EndedAt=new Date,s.Message=n.response?.errors?.length>0?n.response.errors[0].message:n.message,l(n),null}}async Load(e,t,r=null,s){try{const n={};let i="",o="";for(let y=0;y<t.KeyValuePairs.length;y++){const c=e.Fields.find(S=>S.Name.trim().toLowerCase()===t.KeyValuePairs[y].FieldName.trim().toLowerCase()).EntityFieldInfo,d=t.GetValueByIndex(y),I=c.GraphQLType;if(o.length>0&&(o+=", "),o+=`$${c.CodeName}: ${I}!`,i.length>0&&(i+=", "),i+=`${c.CodeName}: $${c.CodeName}`,c.TSType===E.Number){if(isNaN(t.GetValueByIndex(y)))throw new Error(`Primary Key value ${d} (${c.Name}) is not a valid number`);n[c.CodeName]=parseInt(d)}else n[c.CodeName]=d}const a=r&&r.length>0?this.getRelatedEntityString(e.EntityInfo,r):"",u=this.getGraphQLTypeNameBase(e.EntityInfo),g=new v,m=p`query Single${u}${a.length>0?"Full":""} (${o}) {
|
|
273
273
|
${u}(${i}) {
|
|
274
274
|
${e.Fields.filter(y=>!y.EntityFieldInfo.IsBinaryFieldType).map(y=>y.EntityFieldInfo.Name.trim().toLowerCase().startsWith("__mj_")?y.CodeName.replace("__mj_","_mj__"):y.CodeName).join(`
|
|
275
275
|
`)}
|
|
276
276
|
${a}
|
|
277
277
|
}
|
|
278
278
|
}
|
|
279
|
-
`,
|
|
279
|
+
`,R=await this.ExecuteGQL(m,n);return R&&R[u]?this.ConvertBackToMJFields(R[u]):null}catch(n){return l(n),null}}ConvertBackToMJFields(e){return new v().ReverseMapFields(e),e}getRelatedEntityString(e,t){let r="";for(let s=0;s<e.RelatedEntities.length;s++)if(t.indexOf(e.RelatedEntities[s].RelatedEntity)>=0){const n=e.RelatedEntities[s],i=this.Entities.find(a=>a.ID===n.RelatedEntityID);let o="";n.Type.toLowerCase().trim()==="many to many"?o=`${n.RelatedEntityCodeName}_${n.JoinEntityJoinField.replace(/\s/g,"")}`:o=`${n.RelatedEntityCodeName}_${n.RelatedEntityJoinField.replace(/\s/g,"")}`,r+=`
|
|
280
280
|
${o} {
|
|
281
281
|
${i.Fields.map(a=>a.CodeName).join(`
|
|
282
282
|
`)}
|
|
283
283
|
}
|
|
284
|
-
`}return r}async Delete(e,t,r){const s=new
|
|
285
|
-
`),u+=`${d.CodeName}`}i.push({varName:"options___",inputType:"DeleteOptionsInput!"}),n.options___=t||{SkipEntityAIActions:!1,SkipEntityActions:!1};const m="Delete"+this.getGraphQLTypeNameBase(e.EntityInfo),
|
|
284
|
+
`}return r}async Delete(e,t,r){const s=new Se;try{e.RegisterTransactionPreprocessing(),s.StartedAt=new Date,s.Type="delete",s.OriginalValues=e.Fields.map(c=>({FieldName:c.CodeName,Value:c.Value})),e.ResultHistory.push(s);const n={},i=[];let o="",a="",u="";for(let c of e.PrimaryKey.KeyValuePairs){const d=e.Fields.find(I=>I.Name.trim().toLowerCase()===c.FieldName.trim().toLowerCase());n[d.CodeName]=d.Value,i.push({varName:d.CodeName,inputType:d.EntityFieldInfo.GraphQLType+"!"}),o.length>0&&(o+=", "),o+=`${d.CodeName}: $${d.CodeName}`,a.length>0&&(a+=", "),a+=`$${d.CodeName}: ${d.EntityFieldInfo.GraphQLType}!`,u.length>0&&(u+=`
|
|
285
|
+
`),u+=`${d.CodeName}`}i.push({varName:"options___",inputType:"DeleteOptionsInput!"}),n.options___=t||{SkipEntityAIActions:!1,SkipEntityActions:!1};const m="Delete"+this.getGraphQLTypeNameBase(e.EntityInfo),R=p`${m}(${o}, options___: $options___) {
|
|
286
286
|
${u}
|
|
287
287
|
}
|
|
288
288
|
`,y=p`mutation ${m} (${a}, $options___: DeleteOptionsInput!) {
|
|
289
|
-
${
|
|
289
|
+
${R}
|
|
290
290
|
}
|
|
291
|
-
`;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new Re(e,"Delete",
|
|
291
|
+
`;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new Re(e,"Delete",R,n,{mutationName:m,mutationInputTypes:i},(c,d)=>{if(s.EndedAt=new Date,d&&c){let I=!0;for(const S of e.PrimaryKey.KeyValuePairs)S.Value!==c[S.FieldName]&&(I=!1);I?s.Success=!0:(s.Success=!1,s.Message="Transaction failed to commit")}else s.Success=!1,s.Message="Transaction failed to commit"})),!0;{const c=await this.ExecuteGQL(y,n);if(c&&c[m]){const d=c[m];for(let I of e.PrimaryKey.KeyValuePairs){let S=d[I.FieldName],w=I.Value;if(typeof w=="number"&&(w=w.toString()),typeof S=="number"&&(S=S.toString()),w!==S)throw new Error(`Primary key value mismatch in server Delete response. Field: ${I.FieldName}, Original: ${w}, Returned: ${S}`)}return s.Success=!0,s.EndedAt=new Date,!0}else throw new Error(`Delete failed for ${e.EntityInfo.Name}: ${e.PrimaryKey.ToString()} `)}}catch(n){return s.EndedAt=new Date,s.Success=!1,s.Message=n.response?.errors?.length>0?n.response.errors[0].message:n.message,l(n),!1}}async GetDatasetByName(e,t){const r=p`query GetDatasetByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
|
|
292
292
|
GetDatasetByName(DatasetName: $DatasetName, ItemFilters: $ItemFilters) {
|
|
293
293
|
DatasetID
|
|
294
294
|
DatasetName
|
|
@@ -346,16 +346,16 @@ var Pe=Object.defineProperty;var S=(D,e)=>Pe(D,"name",{value:e,configurable:!0})
|
|
|
346
346
|
ErrorMessage
|
|
347
347
|
Result
|
|
348
348
|
}
|
|
349
|
-
}`,r=await this.ExecuteGQL(t,{DataContextItemID:e});if(r&&r.GetDataContextItemData){if(r.GetDataContextItemData.Success)return JSON.parse(r.GetDataContextItemData.Result);throw new Error(r.GetDataContextItemData.ErrorMessage)}else throw new Error("GraphQL query failed")}catch(t){throw l(t),t}}static async ExecuteGQL(e,t,r=!0){return
|
|
349
|
+
}`,r=await this.ExecuteGQL(t,{DataContextItemID:e});if(r&&r.GetDataContextItemData){if(r.GetDataContextItemData.Success)return JSON.parse(r.GetDataContextItemData.Result);throw new Error(r.GetDataContextItemData.ErrorMessage)}else throw new Error("GraphQL query failed")}catch(t){throw l(t),t}}static async ExecuteGQL(e,t,r=!0){return h.Instance.ExecuteGQL(e,t,r)}async ExecuteGQL(e,t,r=!0){try{return await this._client.request(e,t)}catch(s){if(console.log("[GraphQL] ExecuteGQL error caught:",{hasResponse:!!s?.response,hasErrors:!!s?.response?.errors,errorCount:s?.response?.errors?.length,firstError:s?.response?.errors?.[0],errorCode:s?.response?.errors?.[0]?.extensions?.code,errorMessage:s?.response?.errors?.[0]?.message,fullError:s}),s&&s.response&&s.response.errors?.length>0){const i=s.response.errors[0]?.extensions?.code?.toUpperCase().trim();if(console.log("[GraphQL] Error code detected:",i),i==="JWT_EXPIRED"){if(r)return await this.RefreshToken(),await this.ExecuteGQL(e,t,!1);throw l("JWT_EXPIRED and refreshTokenIfNeeded is false"),s}else throw s}else throw l(s),s}}async RefreshToken(){const e=h.Instance&&h.Instance._configData===this._configData;if(e&&h.Instance._refreshPromise)return console.log("[GraphQL] Token refresh already in progress (singleton), waiting..."),h.Instance._refreshPromise;if(this._refreshPromise)return console.log("[GraphQL] Token refresh already in progress (instance), waiting..."),this._refreshPromise;console.log("[GraphQL] Starting token refresh..."),this._refreshPromise=this.performTokenRefresh(),e&&(h.Instance._refreshPromise=this._refreshPromise);try{await this._refreshPromise,console.log("[GraphQL] Token refresh completed successfully")}finally{this._refreshPromise=null,e&&h.Instance&&(h.Instance._refreshPromise=null)}}async performTokenRefresh(){if(this._configData.Data.RefreshTokenFunction){const e=await this._configData.Data.RefreshTokenFunction();if(e){this._configData.Token=e;const t=this.CreateNewGraphQLClient(this._configData.URL,this._configData.Token,this._sessionId,this._configData.MJAPIKey);this._client=t,h.Instance&&h.Instance._configData===this._configData&&(h.Instance._client=t)}else throw new Error("Refresh token function returned null or undefined token")}else throw new Error("No refresh token function provided")}static async RefreshToken(){return h.Instance.RefreshToken()}CreateNewGraphQLClient(e,t,r,s){const n=t?`${t.substring(0,20)}...${t.substring(t.length-10)}`:"NO TOKEN";console.log("[GraphQL] Creating new client:",{url:e,tokenPreview:n,tokenLength:t?.length,sessionId:r,hasMJAPIKey:!!s});const i={"x-session-id":r};return t&&(i.authorization="Bearer "+t),s&&(i["x-mj-api-key"]=s),new he(e,{headers:i})}userInfoString(){return this.infoString(new fe(null,null))}userRoleInfoString(){return this.infoString(new Te(null))}infoString(e){let t="";const r=Object.keys(e);for(const s of r)s.startsWith("__mj_")?t+=s.replace("__mj_","_mj__")+`
|
|
350
350
|
`:s.startsWith("_")||(t+=s+`
|
|
351
|
-
`);return t}get LocalStorageProvider(){return this._localStorageProvider||(this._localStorageProvider=new G),this._localStorageProvider}get Metadata(){return this}getOrCreateWSClient(){const e=Date.now();return this._wsClient&&this._wsClientCreatedAt&&e-this._wsClientCreatedAt>this.WS_CLIENT_MAX_AGE_MS&&this._activeSubscriptionCount===0&&this.disposeWSClient(),this._wsClient||(this._wsClient=
|
|
351
|
+
`);return t}get LocalStorageProvider(){return this._localStorageProvider||(this._localStorageProvider=new G),this._localStorageProvider}get Metadata(){return this}getOrCreateWSClient(){const e=Date.now();return this._wsClient&&this._wsClientCreatedAt&&e-this._wsClientCreatedAt>this.WS_CLIENT_MAX_AGE_MS&&this._activeSubscriptionCount===0&&this.disposeWSClient(),this._wsClient||(this._wsClient=Le({url:this.ConfigData.WSURL,connectionParams:{Authorization:"Bearer "+this.ConfigData.Token},keepAlive:3e4,retryAttempts:3,shouldRetry:()=>!0}),this._wsClientCreatedAt=e,this._subscriptionCleanupTimer||(this._subscriptionCleanupTimer=setInterval(()=>{this.cleanupStaleSubscriptions()},this.SUBSCRIPTION_CLEANUP_INTERVAL_MS))),this._wsClient}disposeWSClient(){if(this._wsClient){try{this._wsClient.dispose()}catch(e){console.error("[GraphQLDataProvider] Error disposing WebSocket client:",e)}this._wsClient=null,this._wsClientCreatedAt=null}}completeAllSubjects(){this._pushStatusSubjects.forEach((e,t)=>{try{e.subject.complete(),e.subscription.unsubscribe()}catch(r){console.error(`[GraphQLDataProvider] Error cleaning up subject for ${t}:`,r)}}),this._pushStatusSubjects.clear()}cleanupStaleSubscriptions(){if(!this._isCleaningUp){this._isCleaningUp=!0;try{const e=Date.now(),t=this._pushStatusSubjects.size,r=Array.from(this._pushStatusSubjects.entries()),s=[];r.forEach(([n,i])=>{const o=e-i.lastRequestedAt,a=e-i.lastEmissionAt;i.activeSubscribers===0&&o>=this.SUBSCRIPTION_IDLE_TIMEOUT_MS&&a>=this.SUBSCRIPTION_IDLE_TIMEOUT_MS&&(console.log(`[GraphQLDataProvider] Marking session ${n} for cleanup: activeSubscribers=${i.activeSubscribers}, timeSinceRequested=${Math.round(o/1e3)}s, timeSinceEmission=${Math.round(a/1e3)}s`),s.push(n))}),s.forEach(n=>{const i=this._pushStatusSubjects.get(n);if(i)try{i.subject.complete(),i.subscription.unsubscribe(),this._pushStatusSubjects.delete(n),console.log(`[GraphQLDataProvider] Cleaned up stale subscription for session: ${n}`)}catch(o){console.error(`[GraphQLDataProvider] Error cleaning up subscription for ${n}:`,o)}}),s.length>0&&console.log(`[GraphQLDataProvider] Cleaned up ${s.length} stale subscription(s)`),this._pushStatusSubjects.size===0&&this._wsClient&&this._wsClientCreatedAt&&e-this._wsClientCreatedAt>this.WS_CLIENT_MAX_AGE_MS&&(console.log("[GraphQLDataProvider] Disposing of idle WebSocket client"),this.disposeWSClient())}finally{this._isCleaningUp=!1}}}subscribe(e,t){return new C(r=>{const s=this.getOrCreateWSClient();this._activeSubscriptionCount++;const n=s.subscribe({query:e,variables:t},{next:i=>{r.next(i.data)},error:async i=>{const o=i;if(o?.extensions?.code==="JWT_EXPIRED"||o?.message?.includes("token has expired")||o?.message?.includes("JWT_EXPIRED")){console.log("[GraphQLDataProvider] WebSocket JWT token expired, refreshing and reconnecting...");try{await this.RefreshToken(),this.disposeWSClient(),r.complete()}catch(u){console.error("[GraphQLDataProvider] Failed to refresh token for WebSocket:",u),r.error(u)}}else r.error(i)},complete:()=>{r.complete()}});return()=>{this._activeSubscriptionCount--,n()}})}PushStatusUpdates(e=null){e||(e=this.sessionId);const t=Date.now(),r=this._pushStatusSubjects.get(e);if(r)return r.lastRequestedAt=t,new C(a=>{r.activeSubscribers++;const u=r.subject.subscribe(a);return()=>{const g=this._pushStatusSubjects.get(e);g&&g.activeSubscribers>0&&g.activeSubscribers--,u.unsubscribe()}});const s=p`subscription StatusUpdates($sessionId: String!) {
|
|
352
352
|
statusUpdates(sessionId: $sessionId) {
|
|
353
353
|
date
|
|
354
354
|
message
|
|
355
355
|
sessionId
|
|
356
356
|
}
|
|
357
357
|
}
|
|
358
|
-
`,n=new Me,i=this.getOrCreateWSClient(),o=new
|
|
358
|
+
`,n=new Me,i=this.getOrCreateWSClient(),o=new Qe;return o.add(new C(a=>{const u=i.subscribe({query:s,variables:{sessionId:e}},{next:g=>{const m=this._pushStatusSubjects.get(e);m&&(m.lastEmissionAt=Date.now()),a.next(g.data.statusUpdates.message)},error:async g=>{const m=g;if(m?.extensions?.code==="JWT_EXPIRED"||m?.message?.includes("token has expired")||m?.message?.includes("JWT_EXPIRED")){console.log("[GraphQLDataProvider] PushStatusUpdates JWT token expired, refreshing and reconnecting...");try{await this.RefreshToken(),this.disposeWSClient(),a.complete()}catch(y){console.error("[GraphQLDataProvider] Failed to refresh token for PushStatusUpdates:",y),a.error(y)}}else a.error(g)},complete:()=>{a.complete()}});return this._activeSubscriptionCount++,()=>{this._activeSubscriptionCount--,u()}}).subscribe({next:a=>n.next(a),error:a=>{n.error(a),this._pushStatusSubjects.delete(e)},complete:()=>{n.complete(),this._pushStatusSubjects.delete(e)}})),this._pushStatusSubjects.set(e,{subject:n,subscription:o,createdAt:t,lastRequestedAt:t,lastEmissionAt:t,activeSubscribers:0}),new C(a=>{const u=this._pushStatusSubjects.get(e);u&&u.activeSubscribers++;const g=n.subscribe(a);return()=>{const m=this._pushStatusSubjects.get(e);m&&m.activeSubscribers>0&&m.activeSubscribers--,g.unsubscribe()}})}disposeWebSocketResources(){this._subscriptionCleanupTimer&&(clearInterval(this._subscriptionCleanupTimer),this._subscriptionCleanupTimer=null),this.completeAllSubjects(),this._activeSubscriptionCount=0,this.disposeWSClient()}},f(h,"_GraphQLDataProvider"),h);De.MJ_CORE_SCHEMA="__mj";let we=De;const Y=class Y{constructor(){this._localStorage={}}async GetItem(e){return new Promise(t=>{this._localStorage.hasOwnProperty(e)?t(this._localStorage[e]):t(null)})}async SetItem(e,t){return new Promise(r=>{this._localStorage[e]=t,r()})}async Remove(e){return new Promise(t=>{this._localStorage.hasOwnProperty(e)&&delete this._localStorage[e],t()})}};f(Y,"BrowserStorageProviderBase");let x=Y;const _e="MJ_Metadata",$="Metadata_KVPairs",ee=class ee extends x{constructor(){super(),this.dbPromise=Ge(_e,1,{upgrade(e){e.objectStoreNames.contains($)||e.createObjectStore($)}})}async setItem(e,t){const s=(await this.dbPromise).transaction($,"readwrite");await s.objectStore($).put(t,e),await s.done}async getItem(e){return await(await this.dbPromise).transaction($).objectStore($).get(e)}async remove(e){const r=(await this.dbPromise).transaction($,"readwrite");await r.objectStore($).delete(e),await r.done}};f(ee,"BrowserIndexedDBStorageProvider");let G=ee;async function qe(D){const e=new we;return Ve(e),await e.Config(D),Ae.Instance.RaiseEvent({event:Ue.LoggedIn,eventCode:null,component:this,args:null}),e}f(qe,"setupGraphQLClient");const te=class te{};f(te,"SyncRolesAndUsersResult");let M=te;const re=class re{};f(re,"RoleInput");let Q=re;const se=class se{};f(se,"UserInput");let L=se;const ne=class ne{};f(ne,"RolesAndUsersInput");let F=ne;var Ee=(D=>(D.Create="Create",D.Update="Update",D.CreateOrUpdate="CreateOrUpdate",D.Delete="Delete",D.DeleteWithFilter="DeleteWithFilter",D))(Ee||{});const ie=class ie{};f(ie,"ActionItemInput");let A=ie;const ae=class ae{constructor(){this.Results=[]}};f(ae,"SyncDataResult");let U=ae;const oe=class oe{};f(oe,"ActionItemOutput");let _=oe;const ue=class ue{get Client(){return this._client}constructor(e,t,r,s){const n={"x-session-id":r};this._sessionId=r,t&&(n.authorization="Bearer "+t),s&&(n["x-mj-api-key"]=s),this._client=new he(e,{headers:n})}async GetData(e,t){try{const s=await this.Client.request(`query GetData($input: GetDataInputType!) {
|
|
359
359
|
GetData(input: $input) {
|
|
360
360
|
Success
|
|
361
361
|
ErrorMessages
|
|
@@ -746,7 +746,7 @@ var Pe=Object.defineProperty;var S=(D,e)=>Pe(D,"name",{value:e,configurable:!0})
|
|
|
746
746
|
error
|
|
747
747
|
}
|
|
748
748
|
}
|
|
749
|
-
`,s={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},n=await this.Client.request(t,s);if(!n?.EmbedTextSystemUser)return{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:"Failed to generate embeddings as system user"};const i=n.EmbedTextSystemUser;return{embeddings:Array.isArray(e.textToEmbed)?i.embeddings:i.embeddings[0],modelName:i.modelName,vectorDimensions:i.vectorDimensions,error:i.error}}catch(t){return l(`GraphQLSystemUserClient::EmbedText - Error generating embeddings - ${t}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:t.toString()}}}};
|
|
749
|
+
`,s={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},n=await this.Client.request(t,s);if(!n?.EmbedTextSystemUser)return{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:"Failed to generate embeddings as system user"};const i=n.EmbedTextSystemUser;return{embeddings:Array.isArray(e.textToEmbed)?i.embeddings:i.embeddings[0],modelName:i.modelName,vectorDimensions:i.vectorDimensions,error:i.error}}catch(t){return l(`GraphQLSystemUserClient::EmbedText - Error generating embeddings - ${t}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:t.toString()}}}};f(ue,"GraphQLSystemUserClient");let q=ue;const ce=class ce{};f(ce,"GetDataOutput");let O=ce;const le=class le{};f(le,"SimpleRemoteEntityOutput");let k=le;const de=class de{};f(de,"SimpleRemoteEntity");let B=de;const ye=class ye{};f(ye,"SimpleRemoteEntityField");let K=ye;const me=class me{constructor(e){this._dataProvider=e}async RunAction(e,t,r=!1){try{const s=this.serializeActionParameters(t),n=this.createActionVariables(e,s,r),i=await this.executeActionMutation(n);return this.processActionResult(i,t)}catch(s){return this.handleActionError(s,t)}}serializeActionParameters(e){if(e)return e.map(t=>{let r=t.Value;return r!=null&&typeof r=="object"&&(r=JSON.stringify(r)),{...t,Value:r}})}createActionVariables(e,t,r=!1){return{input:{ActionID:e,Params:t,SkipActionLog:r}}}async executeActionMutation(e){const t=p`
|
|
750
750
|
mutation RunAction($input: RunActionInput!) {
|
|
751
751
|
RunAction(input: $input) {
|
|
752
752
|
Success
|
|
@@ -763,7 +763,7 @@ var Pe=Object.defineProperty;var S=(D,e)=>Pe(D,"name",{value:e,configurable:!0})
|
|
|
763
763
|
ResultData
|
|
764
764
|
}
|
|
765
765
|
}
|
|
766
|
-
`;return await this._dataProvider.ExecuteGQL(t,{input:e})}processEntityActionResult(e){if(!e?.RunEntityAction)throw new Error("Invalid response from server");let t={};try{e.RunEntityAction.ResultData&&(t=JSON.parse(e.RunEntityAction.ResultData))}catch(r){l(`Failed to parse entity action result data: ${r}`)}return{Success:e.RunEntityAction.Success,Message:e.RunEntityAction.Message,RunParams:null,LogEntry:null,...t}}handleEntityActionError(e){const t=e;return l(`Error running entity action: ${t}`),{Success:!1,Message:`Error: ${t.message}`,RunParams:null,LogEntry:null}}};
|
|
766
|
+
`;return await this._dataProvider.ExecuteGQL(t,{input:e})}processEntityActionResult(e){if(!e?.RunEntityAction)throw new Error("Invalid response from server");let t={};try{e.RunEntityAction.ResultData&&(t=JSON.parse(e.RunEntityAction.ResultData))}catch(r){l(`Failed to parse entity action result data: ${r}`)}return{Success:e.RunEntityAction.Success,Message:e.RunEntityAction.Message,RunParams:null,LogEntry:null,...t}}handleEntityActionError(e){const t=e;return l(`Error running entity action: ${t}`),{Success:!1,Message:`Error: ${t.message}`,RunParams:null,LogEntry:null}}};f(me,"GraphQLActionClient");let J=me;const pe=class pe{constructor(e){this._dataProvider=e}async RunTest(e){let t;try{e.onProgress&&(t=this._dataProvider.PushStatusUpdates(this._dataProvider.sessionId).subscribe(i=>{try{const o=JSON.parse(i);o.resolver==="RunTestResolver"&&o.type==="TestExecutionProgress"&&o.status==="ok"&&o.data?.progress&&e.onProgress(o.data.progress)}catch(o){console.error("[GraphQLTestingClient] Failed to parse progress message:",o)}}));const r=p`
|
|
767
767
|
mutation RunTest(
|
|
768
768
|
$testId: String!,
|
|
769
769
|
$verbose: Boolean,
|
|
@@ -803,7 +803,7 @@ var Pe=Object.defineProperty;var S=(D,e)=>Pe(D,"name",{value:e,configurable:!0})
|
|
|
803
803
|
query IsTestRunning($testId: String!) {
|
|
804
804
|
IsTestRunning(testId: $testId)
|
|
805
805
|
}
|
|
806
|
-
`;return(await this._dataProvider.ExecuteGQL(t,{testId:e})).IsTestRunning}catch(t){return l(`Error checking test running status: ${t.message}`),!1}}processTestResult(e){if(!e)throw new Error("Invalid response from server");let t;try{t=P(e.result)}catch{t=e.result}return{success:e.success,errorMessage:e.errorMessage,executionTimeMs:e.executionTimeMs,result:t}}processSuiteResult(e){if(!e)throw new Error("Invalid response from server");let t;try{t=P(e.result)}catch{t=e.result}return{success:e.success,errorMessage:e.errorMessage,executionTimeMs:e.executionTimeMs,result:t}}handleError(e,t){const r=e.message;return l(`${t} failed: ${r}`),{success:!1,errorMessage:r,result:null}}};
|
|
806
|
+
`;return(await this._dataProvider.ExecuteGQL(t,{testId:e})).IsTestRunning}catch(t){return l(`Error checking test running status: ${t.message}`),!1}}processTestResult(e){if(!e)throw new Error("Invalid response from server");let t;try{t=P(e.result)}catch{t=e.result}return{success:e.success,errorMessage:e.errorMessage,executionTimeMs:e.executionTimeMs,result:t}}processSuiteResult(e){if(!e)throw new Error("Invalid response from server");let t;try{t=P(e.result)}catch{t=e.result}return{success:e.success,errorMessage:e.errorMessage,executionTimeMs:e.executionTimeMs,result:t}}handleError(e,t){const r=e.message;return l(`${t} failed: ${r}`),{success:!1,errorMessage:r,result:null}}};f(pe,"GraphQLTestingClient");let j=pe;const ge=class ge{constructor(e){this._dataProvider=e}async GetRegistryComponent(e){try{const t=p`
|
|
807
807
|
query GetRegistryComponent(
|
|
808
808
|
$registryName: String!,
|
|
809
809
|
$namespace: String!,
|
|
@@ -887,5 +887,5 @@ var Pe=Object.defineProperty;var S=(D,e)=>Pe(D,"name",{value:e,configurable:!0})
|
|
|
887
887
|
error
|
|
888
888
|
}
|
|
889
889
|
}
|
|
890
|
-
`,r=await this._dataProvider.ExecuteGQL(t,{feedback:e});return r&&r.SendComponentFeedback?r.SendComponentFeedback:{success:!1,error:"No response from server"}}catch(t){return l(t),{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}};
|
|
890
|
+
`,r=await this._dataProvider.ExecuteGQL(t,{feedback:e});return r&&r.SendComponentFeedback?r.SendComponentFeedback:{success:!1,error:"No response from server"}}catch(t){return l(t),{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}};f(ge,"GraphQLComponentRegistryClient");let W=ge;export{A as ActionItemInput,_ as ActionItemOutput,v as FieldMapper,O as GetDataOutput,T as GraphQLAIClient,J as GraphQLActionClient,W as GraphQLComponentRegistryClient,we as GraphQLDataProvider,V as GraphQLProviderConfigData,q as GraphQLSystemUserClient,j as GraphQLTestingClient,b as GraphQLTransactionGroup,Q as RoleInput,F as RolesAndUsersInput,B as SimpleRemoteEntity,K as SimpleRemoteEntityField,k as SimpleRemoteEntityOutput,Ee as SyncDataAction,U as SyncDataResult,M as SyncRolesAndUsersResult,L as UserInput,Ye as gql,qe as setupGraphQLClient};
|
|
891
891
|
//# sourceMappingURL=index.mjs.map
|