@memberjunction/graphql-dataprovider 5.2.0 → 5.3.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 -36
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +7 -0
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +7 -0
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +75 -73
- package/dist/index.mjs.map +1 -1
- package/package.json +7 -7
package/dist/index.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var F=Object.defineProperty;var h=(S,e)=>F(S,"name",{value:e,configurable:!0});var y=require("graphql-request"),u=require("@memberjunction/core"),b=require("@memberjunction/core-entities"),v=require("rxjs"),G=require("graphql-ws"),V=require("uuid"),C=require("@memberjunction/global"),_=require("@tempfix/idb");class ${static{h(this,"FieldMapper")}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}}class x extends u.TransactionGroupBase{static{h(this,"GraphQLTransactionGroup")}constructor(e){super(),this._provider=e}async HandleSubmit(){const e=y.gql`
|
|
2
2
|
mutation ExecuteTransactionGroup($group: TransactionInputType!) {
|
|
3
3
|
ExecuteTransactionGroup(group: $group) {
|
|
4
4
|
Success
|
|
@@ -6,7 +6,7 @@
|
|
|
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,a=[];for(let i=0;i<this.PendingTransactions.length;i++){const o=n.ResultsJSON[i],c=C.SafeJSONParse(o),l=this.PendingTransactions[i];a.push(new u.TransactionResult(l,c,c!==null))}return a}else throw new Error("Failed to execute transaction group")}}class
|
|
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,a=[];for(let i=0;i<this.PendingTransactions.length;i++){const o=n.ResultsJSON[i],c=C.SafeJSONParse(o),l=this.PendingTransactions[i];a.push(new u.TransactionResult(l,c,c!==null))}return a}else throw new Error("Failed to execute transaction group")}}class N{static{h(this,"GraphQLAIClient")}static{this.FIRE_AND_FORGET_TIMEOUT_MS=900*1e3}constructor(e){this._dataProvider=e}async RunAIPrompt(e){try{const t=y.gql`
|
|
10
10
|
mutation RunAIPrompt(
|
|
11
11
|
$promptId: String!,
|
|
12
12
|
$data: String,
|
|
@@ -104,7 +104,7 @@
|
|
|
104
104
|
result
|
|
105
105
|
}
|
|
106
106
|
}
|
|
107
|
-
`,a=this.prepareAgentVariables(e,t,r),i=await this._dataProvider.ExecuteGQL(n,a);return this.processAgentResult(i.RunAIAgent?.result)}catch(n){return this.handleAgentError(n)}finally{s&&s.unsubscribe()}}prepareAgentVariables(e,t,r){const s={agentId:e.agent.ID,messages:JSON.stringify(e.conversationMessages),sessionId:this._dataProvider.sessionId};return e.data!==void 0&&(s.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.payload!==void 0&&(s.payload=typeof e.payload=="object"?JSON.stringify(e.payload):e.payload),e.lastRunId!==void 0&&(s.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(s.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(s.configurationId=e.configurationId),e.conversationDetailId!==void 0&&(s.conversationDetailId=e.conversationDetailId,s.createArtifacts=!0,s.createNotification=!0),t!==void 0&&(s.sourceArtifactId=t),r!==void 0&&(s.sourceArtifactVersionId=r),s}processAgentResult(e){return C.SafeJSONParse(e)}handleAgentError(e){const
|
|
107
|
+
`,a=this.prepareAgentVariables(e,t,r),i=await this._dataProvider.ExecuteGQL(n,a);return this.processAgentResult(i.RunAIAgent?.result)}catch(n){return this.handleAgentError(n)}finally{s&&s.unsubscribe()}}prepareAgentVariables(e,t,r){const s={agentId:e.agent.ID,messages:JSON.stringify(e.conversationMessages),sessionId:this._dataProvider.sessionId};return e.data!==void 0&&(s.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.payload!==void 0&&(s.payload=typeof e.payload=="object"?JSON.stringify(e.payload):e.payload),e.lastRunId!==void 0&&(s.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(s.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(s.configurationId=e.configurationId),e.conversationDetailId!==void 0&&(s.conversationDetailId=e.conversationDetailId,s.createArtifacts=!0,s.createNotification=!0),t!==void 0&&(s.sourceArtifactId=t),r!==void 0&&(s.sourceArtifactVersionId=r),s}processAgentResult(e){return C.SafeJSONParse(e)}handleAgentError(e){const r=e?.message||String(e);u.LogError(`Error running AI agent: ${r}`);const s=r.includes("Failed to fetch")||r.includes("NetworkError"),n=r.includes("timed out")||r.includes("timeout");let a;return s?a="Lost connection to the server. The agent may still be running. Please refresh to check the latest status.":a=r,{success:!1,agentRun:void 0,errorMessage:a}}async RunAIAgentFromConversationDetail(e){let t,r;try{let s,n;const a=new Promise((f,p)=>{s=f,n=p});r=setTimeout(()=>{n(new Error("The agent may still be running on the server but the connection timed out after 15 minutes. Please refresh the page to check the latest status."))},N.FIRE_AND_FORGET_TIMEOUT_MS),t=this._dataProvider.PushStatusUpdates(this._dataProvider.sessionId).subscribe(f=>{try{const p=JSON.parse(f);if(e.onProgress&&p.resolver==="RunAIAgentResolver"&&p.type==="ExecutionProgress"&&p.status==="ok"&&p.data?.progress){const d={...p.data.progress,metadata:{...p.data.progress.metadata||{},agentRunId:p.data.agentRunId}};e.onProgress(d)}p.resolver==="RunAIAgentResolver"&&p.type==="StreamingContent"&&p.status==="ok"&&p.data?.type==="complete"&&p.data?.conversationDetailId===e.conversationDetailId&&(r&&clearTimeout(r),p.data.result?s(C.SafeJSONParse(p.data.result)):s({success:p.data.success!==!1,agentRun:void 0}))}catch(p){console.error("[GraphQLAIClient] Failed to parse progress message:",p)}});const i=y.gql`
|
|
108
108
|
mutation RunAIAgentFromConversationDetail(
|
|
109
109
|
$conversationDetailId: String!,
|
|
110
110
|
$agentId: String!,
|
|
@@ -118,7 +118,8 @@
|
|
|
118
118
|
$createArtifacts: Boolean,
|
|
119
119
|
$createNotification: Boolean,
|
|
120
120
|
$sourceArtifactId: String,
|
|
121
|
-
$sourceArtifactVersionId: String
|
|
121
|
+
$sourceArtifactVersionId: String,
|
|
122
|
+
$fireAndForget: Boolean
|
|
122
123
|
) {
|
|
123
124
|
RunAIAgentFromConversationDetail(
|
|
124
125
|
conversationDetailId: $conversationDetailId,
|
|
@@ -133,7 +134,8 @@
|
|
|
133
134
|
createArtifacts: $createArtifacts,
|
|
134
135
|
createNotification: $createNotification,
|
|
135
136
|
sourceArtifactId: $sourceArtifactId,
|
|
136
|
-
sourceArtifactVersionId: $sourceArtifactVersionId
|
|
137
|
+
sourceArtifactVersionId: $sourceArtifactVersionId,
|
|
138
|
+
fireAndForget: $fireAndForget
|
|
137
139
|
) {
|
|
138
140
|
success
|
|
139
141
|
errorMessage
|
|
@@ -141,7 +143,7 @@
|
|
|
141
143
|
result
|
|
142
144
|
}
|
|
143
145
|
}
|
|
144
|
-
`,
|
|
146
|
+
`,o={conversationDetailId:e.conversationDetailId,agentId:e.agentId,sessionId:this._dataProvider.sessionId,fireAndForget:!0};e.maxHistoryMessages!==void 0&&(o.maxHistoryMessages=e.maxHistoryMessages),e.data!==void 0&&(o.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.payload!==void 0&&(o.payload=typeof e.payload=="object"?JSON.stringify(e.payload):e.payload),e.lastRunId!==void 0&&(o.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(o.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(o.configurationId=e.configurationId),e.createArtifacts!==void 0&&(o.createArtifacts=e.createArtifacts),e.createNotification!==void 0&&(o.createNotification=e.createNotification),e.sourceArtifactId!==void 0&&(o.sourceArtifactId=e.sourceArtifactId),e.sourceArtifactVersionId!==void 0&&(o.sourceArtifactVersionId=e.sourceArtifactVersionId);const l=(await this._dataProvider.ExecuteGQL(i,o)).RunAIAgentFromConversationDetail;return l?.success?await a:(r&&clearTimeout(r),{success:!1,agentRun:void 0,errorMessage:l?.errorMessage||"Server rejected the agent execution request"})}catch(s){return r&&clearTimeout(r),this.handleAgentError(s)}finally{r&&clearTimeout(r),t&&t.unsubscribe()}}async ExecuteSimplePrompt(e){try{const t=y.gql`
|
|
145
147
|
mutation ExecuteSimplePrompt(
|
|
146
148
|
$systemPrompt: String!,
|
|
147
149
|
$messages: String,
|
|
@@ -179,7 +181,7 @@
|
|
|
179
181
|
error
|
|
180
182
|
}
|
|
181
183
|
}
|
|
182
|
-
`,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 a=n.EmbedText;return{embeddings:Array.isArray(e.textToEmbed)?a.embeddings:a.embeddings[0],modelName:a.modelName,vectorDimensions:a.vectorDimensions,error:a.error}}catch(t){const r=t;return u.LogError(`Error generating embeddings: ${r}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:r.message||"Unknown error occurred"}}}}const P="default";class L{static{
|
|
184
|
+
`,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 a=n.EmbedText;return{embeddings:Array.isArray(e.textToEmbed)?a.embeddings:a.embeddings[0],modelName:a.modelName,vectorDimensions:a.vectorDimensions,error:a.error}}catch(t){const r=t;return u.LogError(`Error generating embeddings: ${r}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:r.message||"Unknown error occurred"}}}}const P="default";class L{static{h(this,"BrowserStorageProviderBase")}constructor(){this._storage=new Map}getCategoryMap(e){const t=e||P;let r=this._storage.get(t);return r||(r=new Map,this._storage.set(t,r)),r}async GetItem(e,t){return this.getCategoryMap(t||P).get(e)??null}async SetItem(e,t,r){this.getCategoryMap(r||P).set(e,t)}async Remove(e,t){this.getCategoryMap(t||P).delete(e)}async ClearCategory(e){const t=e||P;this._storage.delete(t)}async GetCategoryKeys(e){const t=this._storage.get(e||P);return t?Array.from(t.keys()):[]}}const q="MJ_Metadata",O=3,T=["mj:default","mj:Metadata","mj:RunViewCache","mj:RunQueryCache","mj:DatasetCache"],M="Metadata_KVPairs";class U extends L{static{h(this,"BrowserIndexedDBStorageProvider")}constructor(){super(),this._dbReady=!1,this.dbPromise=_.openDB(q,O,{upgrade(e){try{e.objectStoreNames.contains(M)&&e.deleteObjectStore(M);for(const t of T)e.objectStoreNames.contains(t)||e.createObjectStore(t)}catch(t){u.LogErrorEx({error:t,message:t?.message})}}}),this.dbPromise.then(()=>{this._dbReady=!0}).catch(e=>{u.LogErrorEx({error:e,message:"IndexedDB initialization failed: "+e?.message})})}isKnownCategory(e){const t=`mj:${e}`;return T.includes(t)}getStoreName(e){const t=e||P;return this.isKnownCategory(t)?`mj:${t}`:"mj:default"}getStoreKey(e,t){const r=t||P;return this.isKnownCategory(r)?e:`[${r}]:${e}`}async SetItem(e,t,r){try{const s=await this.dbPromise,n=this.getStoreName(r),a=this.getStoreKey(e,r),i=s.transaction(n,"readwrite");await i.objectStore(n).put(t,a),await i.done}catch(s){u.LogErrorEx({error:s,message:s?.message}),await super.SetItem(e,t,r)}}async GetItem(e,t){try{const r=await this.dbPromise,s=this.getStoreName(t),n=this.getStoreKey(e,t);return await r.transaction(s).objectStore(s).get(n)??null}catch(r){return u.LogErrorEx({error:r,message:r?.message}),await super.GetItem(e,t)}}async Remove(e,t){try{const r=await this.dbPromise,s=this.getStoreName(t),n=this.getStoreKey(e,t),a=r.transaction(s,"readwrite");await a.objectStore(s).delete(n),await a.done}catch(r){u.LogErrorEx({error:r,message:r?.message}),await super.Remove(e,t)}}async ClearCategory(e){try{const t=await this.dbPromise,r=e||P,s=this.getStoreName(e);if(this.isKnownCategory(r)){const n=t.transaction(s,"readwrite");await n.objectStore(s).clear(),await n.done}else{const n=`[${r}]:`,a=t.transaction("mj:default","readwrite"),i=a.objectStore("mj:default"),o=await i.getAllKeys();for(const c of o)typeof c=="string"&&c.startsWith(n)&&await i.delete(c);await a.done}}catch(t){u.LogErrorEx({error:t,message:t?.message}),await super.ClearCategory(e)}}async GetCategoryKeys(e){try{const t=await this.dbPromise,r=e||P,s=this.getStoreName(e),i=await t.transaction(s,"readonly").objectStore(s).getAllKeys();if(this.isKnownCategory(r))return i.map(c=>String(c));const o=`[${r}]:`;return i.map(c=>String(c)).filter(c=>c.startsWith(o)).map(c=>c.slice(o.length))}catch(t){return u.LogErrorEx({error:t,message:t?.message}),await super.GetCategoryKeys(e)}}}class k extends u.ProviderConfigDataBase{static{h(this,"GraphQLProviderConfigData")}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 UserAPIKey(){return this.Data.UserAPIKey}set UserAPIKey(e){this.Data.UserAPIKey=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,a,i,o,c){super({Token:e,URL:t,WSURL:r,MJAPIKey:o,UserAPIKey:c,RefreshTokenFunction:s},n,a,i)}}class I extends u.ProviderBase{static{h(this,"GraphQLDataProvider")}constructor(){super(),this._refreshPromise=null,this._innerCurrentUserQueryString=`CurrentUser {
|
|
183
185
|
${this.userInfoString()}
|
|
184
186
|
MJUserRoles_UserIDArray {
|
|
185
187
|
${this.userRoleInfoString()}
|
|
@@ -187,7 +189,7 @@
|
|
|
187
189
|
}
|
|
188
190
|
`,this._currentUserQuery=y.gql`query CurrentUserAndRoles {
|
|
189
191
|
${this._innerCurrentUserQueryString}
|
|
190
|
-
}`,this._wsClient=null,this._wsClientCreatedAt=null,this._pushStatusSubjects=new Map,this._activeSubscriptionCount=0,this.WS_CLIENT_MAX_AGE_MS=1800*1e3,this.SUBSCRIPTION_CLEANUP_INTERVAL_MS=300*1e3,this.SUBSCRIPTION_IDLE_TIMEOUT_MS=600*1e3,this._subscriptionCleanupTimer=null,this._isCleaningUp=!1,
|
|
192
|
+
}`,this._wsClient=null,this._wsClientCreatedAt=null,this._pushStatusSubjects=new Map,this._activeSubscriptionCount=0,this.WS_CLIENT_MAX_AGE_MS=1800*1e3,this.SUBSCRIPTION_CLEANUP_INTERVAL_MS=300*1e3,this.SUBSCRIPTION_IDLE_TIMEOUT_MS=600*1e3,this._subscriptionCleanupTimer=null,this._isCleaningUp=!1,I._instance||(I._instance=this)}static get Instance(){return I._instance}get ConfigData(){return this._configData}get AI(){return this._aiClient||(this._aiClient=new N(this)),this._aiClient}get DatabaseConnection(){throw new Error("DatabaseConnection not implemented for the GraphQLDataProvider")}get InstanceConnectionString(){return this._configData.URL}GenerateUUID(){return V.v4()}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{return this._configData=e,r?(this._sessionId=await this.GetPreferredUUID(s),this._client=this.CreateNewGraphQLClient(e.URL,e.Token,this._sessionId,e.MJAPIKey,e.UserAPIKey),await this.SaveStoredSessionID(this._sessionId)):(I.Instance._configData=e,I.Instance._sessionId===void 0&&(I.Instance._sessionId=await this.GetPreferredUUID(s)),I.Instance._client||(I.Instance._client=this.CreateNewGraphQLClient(e.URL,e.Token,I.Instance._sessionId,e.MJAPIKey,e.UserAPIKey)),await I.Instance.SaveStoredSessionID(I.Instance._sessionId),this._sessionId=I.Instance._sessionId,this._client=I.Instance._client),super.Config(e)}catch(n){throw u.LogError(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.MJUserRoles_UserIDArray.map(s=>this.ConvertBackToMJFields(s));return t.MJUserRoles_UserIDArray=r,new u.UserInfo(this,{...t,UserRoles:r})}}async RunReport(e,t){const r=y.gql`
|
|
191
193
|
query GetReportDataQuery ($ReportID: String!) {
|
|
192
194
|
GetReportData(ReportID: $ReportID) {
|
|
193
195
|
Success
|
|
@@ -245,7 +247,7 @@
|
|
|
245
247
|
}
|
|
246
248
|
}
|
|
247
249
|
}
|
|
248
|
-
`,a=(await this.ExecuteGQL(s,{input:r}))?.RunQueriesWithCacheCheck;if(!a)return{success:!1,results:[],errorMessage:"No response from server"};const i=a.results.map(o=>{if((o.status==="stale"||o.status==="no_validation")&&o.Results){const c=JSON.parse(o.Results);return{queryIndex:o.queryIndex,queryId:o.queryId,status:o.status,results:c,maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}}return{queryIndex:o.queryIndex,queryId:o.queryId,status:o.status,maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}});return{success:a.success,results:i,errorMessage:a.errorMessage}}catch(r){return u.LogError(`Error in RunQueriesWithCacheCheck: ${r}`),{success:!1,results:[],errorMessage:r instanceof Error?r.message:String(r)}}}async InternalRunView(e,t){try{let r="",s="";if(e){const n={};let a,i;if(e.ViewEntity)i=e.ViewEntity,a=i.Entity;else{const{entityName:m,v:
|
|
250
|
+
`,a=(await this.ExecuteGQL(s,{input:r}))?.RunQueriesWithCacheCheck;if(!a)return{success:!1,results:[],errorMessage:"No response from server"};const i=a.results.map(o=>{if((o.status==="stale"||o.status==="no_validation")&&o.Results){const c=JSON.parse(o.Results);return{queryIndex:o.queryIndex,queryId:o.queryId,status:o.status,results:c,maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}}return{queryIndex:o.queryIndex,queryId:o.queryId,status:o.status,maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}});return{success:a.success,results:i,errorMessage:a.errorMessage}}catch(r){return u.LogError(`Error in RunQueriesWithCacheCheck: ${r}`),{success:!1,results:[],errorMessage:r instanceof Error?r.message:String(r)}}}async InternalRunView(e,t){try{let r="",s="";if(e){const n={};let a,i;if(e.ViewEntity)i=e.ViewEntity,a=i.Entity;else{const{entityName:m,v:R}=await this.getEntityNameAndUserView(e,t);i=R,a=m}const o=this.Entities.find(m=>m.Name===a);if(!o)throw new Error(`Entity ${a} not found in metadata`);let c=!1;const l=u.getGraphQLTypeNameBase(o);e.ViewID?(r=`Run${l}ViewByID`,s="RunViewByIDInput",n.ViewID=e.ViewID):e.ViewName?(r=`Run${l}ViewByName`,s="RunViewByNameInput",n.ViewName=e.ViewName):(c=!0,r=`Run${l}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),c||(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),e.Aggregates&&e.Aggregates.length>0&&(n.Aggregates=e.Aggregates.map(m=>({expression:m.expression,alias:m.alias})));const f=this.getViewRunTimeFieldList(o,i,e,c),p=e.Aggregates&&e.Aggregates.length>0?`
|
|
249
251
|
AggregateResults {
|
|
250
252
|
alias
|
|
251
253
|
expression
|
|
@@ -256,7 +258,7 @@
|
|
|
256
258
|
query RunViewQuery ($input: ${s}!) {
|
|
257
259
|
${r}(input: $input) {
|
|
258
260
|
Results {
|
|
259
|
-
${
|
|
261
|
+
${f.join(`
|
|
260
262
|
`)}
|
|
261
263
|
}
|
|
262
264
|
UserViewRunID
|
|
@@ -264,9 +266,9 @@
|
|
|
264
266
|
TotalRowCount
|
|
265
267
|
ExecutionTime
|
|
266
268
|
Success
|
|
267
|
-
ErrorMessage${
|
|
269
|
+
ErrorMessage${p}
|
|
268
270
|
}
|
|
269
|
-
}`;n.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Sending RunView with aggregates:",{entityName:a,queryName:r,aggregateCount:n.Aggregates.length,aggregates:n.Aggregates});const g=await this.ExecuteGQL(d,{input:n});if(g&&g[r]){const m=g[r].AggregateResults;n.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Received aggregate results:",{entityName:a,aggregateResultCount:m?.length||0,aggregateResults:m,aggregateExecutionTime:g[r].AggregateExecutionTime});const
|
|
271
|
+
}`;n.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Sending RunView with aggregates:",{entityName:a,queryName:r,aggregateCount:n.Aggregates.length,aggregates:n.Aggregates});const g=await this.ExecuteGQL(d,{input:n});if(g&&g[r]){const m=g[r].AggregateResults;n.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Received aggregate results:",{entityName:a,aggregateResultCount:m?.length||0,aggregateResults:m,aggregateExecutionTime:g[r].AggregateExecutionTime});const R=g[r].Results;if(R&&R.length>0){const w=o.Fields.filter(D=>D.CodeName!==D.Name&&D.CodeName!==void 0);R.forEach(D=>{this.ConvertBackToMJFields(D),w.forEach(A=>{D[A.Name]=D[A.CodeName]})})}return g[r]}}else throw"No parameters passed to RunView";return null}catch(r){throw u.LogError(r),r}}async InternalRunViews(e,t){try{let r=[],s=[],n=[];for(const l of e){let f="",p="";const d={};let g=null,m=null;if(l.ViewEntity)m=l.ViewEntity,g=m.Get("Entity");else{const{entityName:D,v:A}=await this.getEntityNameAndUserView(l,t);m=A,g=D}const R=this.Entities.find(D=>D.Name===g);if(!R)throw new Error(`Entity ${g} not found in metadata`);s.push(R);let E=!1;const w=u.getGraphQLTypeNameBase(R);l.ViewID?(f=`Run${w}ViewByID`,p="RunViewByIDInput",d.ViewID=l.ViewID):l.ViewName?(f=`Run${w}ViewByName`,p="RunViewByNameInput",d.ViewName=l.ViewName):(E=!0,f=`Run${w}DynamicView`,p="RunDynamicViewInput",d.EntityName=l.EntityName),d.ExtraFilter=l.ExtraFilter||"",d.OrderBy=l.OrderBy||"",d.UserSearchString=l.UserSearchString||"",d.Fields=l.Fields,d.IgnoreMaxRows=l.IgnoreMaxRows||!1,l.MaxRows!==void 0&&(d.MaxRows=l.MaxRows),l.StartRow!==void 0&&(d.StartRow=l.StartRow),d.ForceAuditLog=l.ForceAuditLog||!1,d.ResultType=l.ResultType||"simple",l.AuditLogDescription&&l.AuditLogDescription.length>0&&(d.AuditLogDescription=l.AuditLogDescription),E||(d.ExcludeUserViewRunID=l.ExcludeUserViewRunID||"",d.ExcludeDataFromAllPriorViewRuns=l.ExcludeDataFromAllPriorViewRuns||!1,d.OverrideExcludeFilter=l.OverrideExcludeFilter||"",d.SaveViewResults=l.SaveViewResults||!1),l.Aggregates&&l.Aggregates.length>0&&(d.Aggregates=l.Aggregates.map(D=>({expression:D.expression,alias:D.alias}))),r.push(d),n.push(...this.getViewRunTimeFieldList(R,m,l,E))}const i=e.some(l=>l.Aggregates&&l.Aggregates.length>0)?`
|
|
270
272
|
AggregateResults {
|
|
271
273
|
alias
|
|
272
274
|
expression
|
|
@@ -291,7 +293,7 @@
|
|
|
291
293
|
Success
|
|
292
294
|
ErrorMessage${i}
|
|
293
295
|
}
|
|
294
|
-
}`,c=await this.ExecuteGQL(o,{input:r});if(c&&c.RunViews){const l=c.RunViews;for(const[
|
|
296
|
+
}`,c=await this.ExecuteGQL(o,{input:r});if(c&&c.RunViews){const l=c.RunViews;for(const[f,p]of l.entries())p.Results=p.Results.map(d=>{let g=JSON.parse(d.Data);return this.ConvertBackToMJFields(g),g});return l}return null}catch(r){throw u.LogError(r),r}}async RunViewsWithCacheCheck(e,t){try{const r=e.map(o=>({params:{EntityName:o.params.EntityName||"",ExtraFilter:o.params.ExtraFilter||"",OrderBy:o.params.OrderBy||"",Fields:o.params.Fields,UserSearchString:o.params.UserSearchString||"",IgnoreMaxRows:o.params.IgnoreMaxRows||!1,MaxRows:o.params.MaxRows,StartRow:o.params.StartRow,ForceAuditLog:o.params.ForceAuditLog||!1,AuditLogDescription:o.params.AuditLogDescription||"",ResultType:o.params.ResultType||"simple"},cacheStatus:o.cacheStatus?{maxUpdatedAt:o.cacheStatus.maxUpdatedAt,rowCount:o.cacheStatus.rowCount}:null})),s=y.gql`
|
|
295
297
|
query RunViewsWithCacheCheckQuery($input: [RunViewWithCacheCheckInput!]!) {
|
|
296
298
|
RunViewsWithCacheCheck(input: $input) {
|
|
297
299
|
success
|
|
@@ -324,7 +326,7 @@
|
|
|
324
326
|
}
|
|
325
327
|
}
|
|
326
328
|
}
|
|
327
|
-
`,a=(await this.ExecuteGQL(s,{input:r}))?.RunViewsWithCacheCheck;if(!a)return{success:!1,results:[],errorMessage:"No response from server"};const i=a.results.map((o,c)=>{const l=e[c];if(o.status==="differential"&&o.differentialData){const
|
|
329
|
+
`,a=(await this.ExecuteGQL(s,{input:r}))?.RunViewsWithCacheCheck;if(!a)return{success:!1,results:[],errorMessage:"No response from server"};const i=a.results.map((o,c)=>{const l=e[c];if(o.status==="differential"&&o.differentialData){const f=o.differentialData.updatedRows.map(p=>{const d=JSON.parse(p.Data);return this.ConvertBackToMJFields(d),d});return{viewIndex:o.viewIndex,status:o.status,results:void 0,differentialData:{updatedRows:f,deletedRecordIDs:o.differentialData.deletedRecordIDs},maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}}if(o.status==="stale"&&o.Results){const f=o.Results.map(p=>{const d=JSON.parse(p.Data);return this.ConvertBackToMJFields(d),d});return{viewIndex:o.viewIndex,status:o.status,results:f,maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}}return{viewIndex:o.viewIndex,status:o.status,results:void 0,maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}});return{success:a.success,results:i,errorMessage:a.errorMessage}}catch(r){return u.LogError(r),{success:!1,results:[],errorMessage:r instanceof Error?r.message:String(r)}}}async getEntityNameAndUserView(e,t){let r,s;if(e.EntityName)r=e.EntityName;else if(e.ViewID)s=await b.ViewInfo.GetViewEntity(e.ViewID,t),r=s.Entity;else if(e.ViewName)s=await b.ViewInfo.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=[],a=new $;if(r.Fields){for(const i of e.PrimaryKeys)r.Fields.find(o=>o.trim().toLowerCase()===i.Name.toLowerCase())===void 0&&n.push(i.Name);r.Fields.forEach(i=>{n.push(a.MapFieldName(i))})}else if(s)e.Fields.forEach(i=>{i.IsBinaryFieldType||n.push(a.MapFieldName(i.CodeName))});else{for(const i of e.PrimaryKeys)n.find(o=>o.trim().toLowerCase()===i.Name.toLowerCase())===void 0&&n.push(i.Name);t.Columns.forEach(i=>{i.hidden===!1&&!n.find(o=>o.trim().toLowerCase()===i.EntityField?.Name.trim().toLowerCase())&&i.EntityField&&n.push(a.MapFieldName(i.EntityField.CodeName))})}return n}get ProviderType(){return u.ProviderType.Network}async GetRecordChanges(e,t){try{const r={EntityName:"MJ: Record Changes",ExtraFilter:`RecordID = '${t.Values()}' AND Entity = '${e}'`},s=await this.RunView(r);return s?s.Results.sort((n,a)=>n.ChangedAt>a.ChangedAt?-1:1):null}catch(r){throw u.LogError(r),r}}async GetRecordDependencies(e,t){try{const r=y.gql`query GetRecordDependenciesQuery ($entityName: String!, $CompositeKey: CompositeKeyInputType!) {
|
|
328
330
|
GetRecordDependencies(entityName: $entityName, CompositeKey: $CompositeKey) {
|
|
329
331
|
EntityName
|
|
330
332
|
RelatedEntityName
|
|
@@ -375,32 +377,32 @@
|
|
|
375
377
|
Message
|
|
376
378
|
}
|
|
377
379
|
}
|
|
378
|
-
}`,a={EntityName:e.EntityName,SurvivingRecordCompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(e.SurvivingRecordCompositeKey.KeyValuePairs)},FieldMap:e.FieldMap?.map(o=>({FieldName:o.FieldName,Value:o.Value.toString()})),RecordsToMerge:e.RecordsToMerge.map(o=>o.Copy())};return(await this.ExecuteGQL(n,{request:a}))?.MergeRecords}catch(n){return u.LogError(n),{Success:!1,OverallStatus:n&&n.message?n.message:n,RecordStatus:[],RecordMergeLogID:"",Request:e}}}async Save(e,t,r){if(r?.IsParentEntitySave){const n=new u.BaseEntityResult;return n.StartedAt=new Date,n.EndedAt=new Date,n.Type=e.IsSaved?"update":"create",n.Success=!0,n.NewValues=e.GetAll(),e.ResultHistory.push(n),n.NewValues}const s=new u.BaseEntityResult;try{e.RegisterTransactionPreprocessing();const n={input:{}},a=e.IsSaved?"Update":"Create";s.StartedAt=new Date,s.Type=e.IsSaved?"update":"create",s.OriginalValues=e.Fields.map(d=>({FieldName:d.CodeName,Value:d.Value})),e.ResultHistory.push(s);const i=u.getGraphQLTypeNameBase(e.EntityInfo),o=`${a}${i}`,c=e.Fields.filter(d=>!d.ReadOnly||d.IsPrimaryKey&&e.IsSaved),l=new $,
|
|
380
|
+
}`,a={EntityName:e.EntityName,SurvivingRecordCompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(e.SurvivingRecordCompositeKey.KeyValuePairs)},FieldMap:e.FieldMap?.map(o=>({FieldName:o.FieldName,Value:o.Value.toString()})),RecordsToMerge:e.RecordsToMerge.map(o=>o.Copy())};return(await this.ExecuteGQL(n,{request:a}))?.MergeRecords}catch(n){return u.LogError(n),{Success:!1,OverallStatus:n&&n.message?n.message:n,RecordStatus:[],RecordMergeLogID:"",Request:e}}}async Save(e,t,r){if(r?.IsParentEntitySave){const n=new u.BaseEntityResult;return n.StartedAt=new Date,n.EndedAt=new Date,n.Type=e.IsSaved?"update":"create",n.Success=!0,n.NewValues=e.GetAll(),e.ResultHistory.push(n),n.NewValues}const s=new u.BaseEntityResult;try{e.RegisterTransactionPreprocessing();const n={input:{}},a=e.IsSaved?"Update":"Create";s.StartedAt=new Date,s.Type=e.IsSaved?"update":"create",s.OriginalValues=e.Fields.map(d=>({FieldName:d.CodeName,Value:d.Value})),e.ResultHistory.push(s);const i=u.getGraphQLTypeNameBase(e.EntityInfo),o=`${a}${i}`,c=e.Fields.filter(d=>!d.ReadOnly||d.IsPrimaryKey&&e.IsSaved),l=new $,f=` ${o}(input: $input) {
|
|
379
381
|
${e.Fields.map(d=>l.MapFieldName(d.CodeName)).join(`
|
|
380
382
|
`)}
|
|
381
|
-
}`,
|
|
382
|
-
${
|
|
383
|
+
}`,p=y.gql`mutation ${a}${i} ($input: ${o}Input!) {
|
|
384
|
+
${f}
|
|
383
385
|
}
|
|
384
|
-
`;for(let d=0;d<c.length;d++){const g=c[d];let m=e.Get(g.Name);if(m)switch(g.EntityFieldInfo.TSType){case u.EntityFieldTSType.Date:m=m.getTime();break;case u.EntityFieldTSType.Boolean:typeof m!="boolean"&&(m=parseInt(m)!==0);break;case u.EntityFieldTSType.Number:if(typeof m!="number"){const
|
|
386
|
+
`;for(let d=0;d<c.length;d++){const g=c[d];let m=e.Get(g.Name);if(m)switch(g.EntityFieldInfo.TSType){case u.EntityFieldTSType.Date:m=m.getTime();break;case u.EntityFieldTSType.Boolean:typeof m!="boolean"&&(m=parseInt(m)!==0);break;case u.EntityFieldTSType.Number:if(typeof m!="number"){const R=Number(m);isNaN(R)||(m=R)}break}m===null&&g.EntityFieldInfo.AllowsNull===!1&&(g.EntityFieldInfo.DefaultValue!==null?m=g.EntityFieldInfo.DefaultValue:g.FieldType===u.EntityFieldTSType.Number||g.FieldType===u.EntityFieldTSType.Boolean?m=0:m=""),n.input[g.CodeName]=m}if(a.trim().toLowerCase()==="update"&&r.SkipOldValuesCheck===!1){const d=[];e.Fields.forEach(g=>{let m=null;g.OldValue!==null&&g.OldValue!==void 0&&(g.EntityFieldInfo.TSType===u.EntityFieldTSType.Date?m=g.OldValue.getTime().toString():g.EntityFieldInfo.TSType===u.EntityFieldTSType.Boolean?m=g.OldValue===!0?"1":"0":typeof g.OldValue!="string"?m=g.OldValue.toString():m=g.OldValue),d.push({Key:g.CodeName,Value:m})}),n.input.OldValues___=d}if(e.TransactionGroup){const d=[{varName:"input",inputType:o+"Input!"}];return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new u.TransactionItem(e,s.Type==="create"?"Create":"Update",f,n,{mutationName:o,mutationInputTypes:d},(g,m)=>{s.EndedAt=new Date,m&&g?(s.Success=!0,s.NewValues=this.ConvertBackToMJFields(g)):(s.Success=!1,s.Message="Transaction failed")})),!0}else{const d=await this.ExecuteGQL(p,n);if(d&&d[o])return s.Success=!0,s.EndedAt=new Date,s.NewValues=this.ConvertBackToMJFields(d[o]),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,u.LogError(n),null}}async Load(e,t,r=null,s){try{const n={};let a="",i="";for(let d=0;d<t.KeyValuePairs.length;d++){const g=e.Fields.find(E=>E.Name.trim().toLowerCase()===t.KeyValuePairs[d].FieldName.trim().toLowerCase()).EntityFieldInfo,m=t.GetValueByIndex(d),R=g.GraphQLType;if(i.length>0&&(i+=", "),i+=`$${g.CodeName}: ${R}!`,a.length>0&&(a+=", "),a+=`${g.CodeName}: $${g.CodeName}`,g.TSType===u.EntityFieldTSType.Number){if(isNaN(t.GetValueByIndex(d)))throw new Error(`Primary Key value ${m} (${g.Name}) is not a valid number`);n[g.CodeName]=parseInt(m)}else n[g.CodeName]=m}const o=r&&r.length>0?this.getRelatedEntityString(e.EntityInfo,r):"",c=u.getGraphQLTypeNameBase(e.EntityInfo),l=new $,f=y.gql`query Single${c}${o.length>0?"Full":""} (${i}) {
|
|
385
387
|
${c}(${a}) {
|
|
386
388
|
${e.Fields.filter(d=>!d.EntityFieldInfo.IsBinaryFieldType).map(d=>d.EntityFieldInfo.Name.trim().toLowerCase().startsWith("__mj_")?d.CodeName.replace("__mj_","_mj__"):d.CodeName).join(`
|
|
387
389
|
`)}
|
|
388
390
|
${o}
|
|
389
391
|
}
|
|
390
392
|
}
|
|
391
|
-
`,
|
|
393
|
+
`,p=await this.ExecuteGQL(f,n);return p&&p[c]?this.ConvertBackToMJFields(p[c]):null}catch(n){return u.LogError(n),null}}ConvertBackToMJFields(e){return new $().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],a=this.Entities.find(o=>o.ID===n.RelatedEntityID);let i="";n.Type.toLowerCase().trim()==="many to many"?i=`${n.RelatedEntityCodeName}_${n.JoinEntityJoinField.replace(/\s/g,"")}`:i=`${n.RelatedEntityCodeName}_${n.RelatedEntityJoinField.replace(/\s/g,"")}`,r+=`
|
|
392
394
|
${i} {
|
|
393
395
|
${a.Fields.map(o=>o.CodeName).join(`
|
|
394
396
|
`)}
|
|
395
397
|
}
|
|
396
|
-
`}return r}async Delete(e,t,r){const s=new u.BaseEntityResult;try{e.RegisterTransactionPreprocessing(),s.StartedAt=new Date,s.Type="delete",s.OriginalValues=e.Fields.map(g=>({FieldName:g.CodeName,Value:g.Value})),e.ResultHistory.push(s);const n={},a=[];let i="",o="",c="";for(let g of e.PrimaryKey.KeyValuePairs){const m=e.Fields.find(
|
|
397
|
-
`),c+=`${m.CodeName}`}a.push({varName:"options___",inputType:"DeleteOptionsInput!"}),n.options___={SkipEntityAIActions:t?.SkipEntityAIActions??!1,SkipEntityActions:t?.SkipEntityActions??!1,ReplayOnly:t?.ReplayOnly??!1,IsParentEntityDelete:t?.IsParentEntityDelete??!1};const
|
|
398
|
+
`}return r}async Delete(e,t,r){const s=new u.BaseEntityResult;try{e.RegisterTransactionPreprocessing(),s.StartedAt=new Date,s.Type="delete",s.OriginalValues=e.Fields.map(g=>({FieldName:g.CodeName,Value:g.Value})),e.ResultHistory.push(s);const n={},a=[];let i="",o="",c="";for(let g of e.PrimaryKey.KeyValuePairs){const m=e.Fields.find(R=>R.Name.trim().toLowerCase()===g.FieldName.trim().toLowerCase());n[m.CodeName]=m.Value,a.push({varName:m.CodeName,inputType:m.EntityFieldInfo.GraphQLType+"!"}),i.length>0&&(i+=", "),i+=`${m.CodeName}: $${m.CodeName}`,o.length>0&&(o+=", "),o+=`$${m.CodeName}: ${m.EntityFieldInfo.GraphQLType}!`,c.length>0&&(c+=`
|
|
399
|
+
`),c+=`${m.CodeName}`}a.push({varName:"options___",inputType:"DeleteOptionsInput!"}),n.options___={SkipEntityAIActions:t?.SkipEntityAIActions??!1,SkipEntityActions:t?.SkipEntityActions??!1,ReplayOnly:t?.ReplayOnly??!1,IsParentEntityDelete:t?.IsParentEntityDelete??!1};const f="Delete"+u.getGraphQLTypeNameBase(e.EntityInfo),p=y.gql`${f}(${i}, options___: $options___) {
|
|
398
400
|
${c}
|
|
399
401
|
}
|
|
400
|
-
`,d=y.gql`mutation ${
|
|
401
|
-
${
|
|
402
|
+
`,d=y.gql`mutation ${f} (${o}, $options___: DeleteOptionsInput!) {
|
|
403
|
+
${p}
|
|
402
404
|
}
|
|
403
|
-
`;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new u.TransactionItem(e,"Delete",
|
|
405
|
+
`;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new u.TransactionItem(e,"Delete",p,n,{mutationName:f,mutationInputTypes:a},(g,m)=>{if(s.EndedAt=new Date,m&&g){let R=!0;for(const E of e.PrimaryKey.KeyValuePairs)E.Value!==g[E.FieldName]&&(R=!1);R?s.Success=!0:(s.Success=!1,s.Message="Transaction failed to commit")}else s.Success=!1,s.Message="Transaction failed to commit"})),!0;{const g=await this.ExecuteGQL(d,n);if(g&&g[f]){const m=g[f];for(let R of e.PrimaryKey.KeyValuePairs){let E=m[R.FieldName],w=R.Value;if(typeof w=="number"&&(w=w.toString()),typeof E=="number"&&(E=E.toString()),w!==E)throw new Error(`Primary key value mismatch in server Delete response. Field: ${R.FieldName}, Original: ${w}, Returned: ${E}`)}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,u.LogError(n),!1}}async GetDatasetByName(e,t){const r=y.gql`query GetDatasetByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
|
|
404
406
|
GetDatasetByName(DatasetName: $DatasetName, ItemFilters: $ItemFilters) {
|
|
405
407
|
DatasetID
|
|
406
408
|
DatasetName
|
|
@@ -418,7 +420,7 @@
|
|
|
418
420
|
LatestUpdateDate
|
|
419
421
|
EntityUpdateDates
|
|
420
422
|
}
|
|
421
|
-
}`,s=await this.ExecuteGQL(r,{DatasetName:e,ItemFilters:t});return s&&s.GetDatasetStatusByName&&s.GetDatasetStatusByName.Success?{DatasetID:s.GetDatasetStatusByName.DatasetID,DatasetName:s.GetDatasetStatusByName.DatasetName,Success:s.GetDatasetStatusByName.Success,Status:s.GetDatasetStatusByName.Status,LatestUpdateDate:new Date(s.GetDatasetStatusByName.LatestUpdateDate),EntityUpdateDates:JSON.parse(s.GetDatasetStatusByName.EntityUpdateDates)}:{DatasetID:"",DatasetName:e,Success:!1,Status:"Unknown",LatestUpdateDate:null,EntityUpdateDates:null}}async CreateTransactionGroup(){return new
|
|
423
|
+
}`,s=await this.ExecuteGQL(r,{DatasetName:e,ItemFilters:t});return s&&s.GetDatasetStatusByName&&s.GetDatasetStatusByName.Success?{DatasetID:s.GetDatasetStatusByName.DatasetID,DatasetName:s.GetDatasetStatusByName.DatasetName,Success:s.GetDatasetStatusByName.Success,Status:s.GetDatasetStatusByName.Status,LatestUpdateDate:new Date(s.GetDatasetStatusByName.LatestUpdateDate),EntityUpdateDates:JSON.parse(s.GetDatasetStatusByName.EntityUpdateDates)}:{DatasetID:"",DatasetName:e,Success:!1,Status:"Unknown",LatestUpdateDate:null,EntityUpdateDates:null}}async CreateTransactionGroup(){return new x(this)}async GetRecordFavoriteStatus(e,t,r){if(!r.Validate().IsValid)return!1;const n=this.Entities.find(o=>o.Name===t);if(!n)throw new Error(`Entity ${t} not found in metadata`);const a=y.gql`query GetRecordFavoriteStatus($params: UserFavoriteSearchParams!) {
|
|
422
424
|
GetRecordFavoriteStatus(params: $params) {
|
|
423
425
|
Success
|
|
424
426
|
IsFavorite
|
|
@@ -458,16 +460,16 @@
|
|
|
458
460
|
ErrorMessage
|
|
459
461
|
Result
|
|
460
462
|
}
|
|
461
|
-
}`,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 u.LogError(t),t}}static async ExecuteGQL(e,t,r=!0){return
|
|
463
|
+
}`,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 u.LogError(t),t}}static async ExecuteGQL(e,t,r=!0){return I.Instance.ExecuteGQL(e,t,r)}async ExecuteGQL(e,t,r=!0){try{return await this._client.request(e,t)}catch(s){if(console.error("[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)if(s.response.errors[0]?.extensions?.code?.toUpperCase().trim()==="JWT_EXPIRED"){if(r)return await this.RefreshToken(),await this.ExecuteGQL(e,t,!1);throw u.LogError("JWT_EXPIRED and refreshTokenIfNeeded is false"),s}else throw s;else throw u.LogError(s),s}}async RefreshToken(){const e=I.Instance&&I.Instance._configData===this._configData;if(e&&I.Instance._refreshPromise)return I.Instance._refreshPromise;if(this._refreshPromise)return this._refreshPromise;console.log("[GraphQL] Starting token refresh..."),this._refreshPromise=this.performTokenRefresh(),e&&(I.Instance._refreshPromise=this._refreshPromise);try{await this._refreshPromise,console.log("[GraphQL] Token refresh completed successfully")}finally{this._refreshPromise=null,e&&I.Instance&&(I.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._configData.UserAPIKey);this._client=t,I.Instance&&I.Instance._configData===this._configData&&(I.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 I.Instance.RefreshToken()}CreateNewGraphQLClient(e,t,r,s,n){const a={"x-session-id":r};return t&&(a.authorization="Bearer "+t),s&&(a["x-mj-api-key"]=s),n&&(a["x-api-key"]=n),new y.GraphQLClient(e,{headers:a})}userInfoString(){return this.infoString(new u.UserInfo(null,null))}userRoleInfoString(){return this.infoString(new u.UserRoleInfo(null))}infoString(e){let t="";const r=Object.keys(e);for(const s of r)s.startsWith("__mj_")?t+=s.replace("__mj_","_mj__")+`
|
|
462
464
|
`:s.startsWith("_")||(t+=s+`
|
|
463
|
-
`);return t}get LocalStorageProvider(){return this._localStorageProvider||(typeof indexedDB<"u"?this._localStorageProvider=new
|
|
465
|
+
`);return t}get LocalStorageProvider(){return this._localStorageProvider||(typeof indexedDB<"u"?this._localStorageProvider=new U:this._localStorageProvider=new u.InMemoryLocalStorageProvider),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=G.createClient({url:this.ConfigData.WSURL,connectionParams:{Authorization:"Bearer "+this.ConfigData.Token},keepAlive:3e4,retryAttempts:3,shouldRetry:h(()=>!0,"shouldRetry")}),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,a])=>{const i=e-a.lastRequestedAt,o=e-a.lastEmissionAt;a.activeSubscribers===0&&i>=this.SUBSCRIPTION_IDLE_TIMEOUT_MS&&o>=this.SUBSCRIPTION_IDLE_TIMEOUT_MS&&(console.log(`[GraphQLDataProvider] Marking session ${n} for cleanup: activeSubscribers=${a.activeSubscribers}, timeSinceRequested=${Math.round(i/1e3)}s, timeSinceEmission=${Math.round(o/1e3)}s`),s.push(n))}),s.forEach(n=>{const a=this._pushStatusSubjects.get(n);if(a)try{a.subject.complete(),a.subscription.unsubscribe(),this._pushStatusSubjects.delete(n),console.log(`[GraphQLDataProvider] Cleaned up stale subscription for session: ${n}`)}catch(i){console.error(`[GraphQLDataProvider] Error cleaning up subscription for ${n}:`,i)}}),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 v.Observable(r=>{const s=this.getOrCreateWSClient();this._activeSubscriptionCount++;const n=s.subscribe({query:e,variables:t},{next:h(a=>{r.next(a.data)},"next"),error:h(async a=>{const i=a;if(i?.extensions?.code==="JWT_EXPIRED"||i?.message?.includes("token has expired")||i?.message?.includes("JWT_EXPIRED")){console.log("[GraphQLDataProvider] WebSocket JWT token expired, refreshing and reconnecting...");try{await this.RefreshToken(),this.disposeWSClient(),r.complete()}catch(c){console.error("[GraphQLDataProvider] Failed to refresh token for WebSocket:",c),r.error(c)}}else r.error(a)},"error"),complete:h(()=>{r.complete()},"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 v.Observable(o=>{r.activeSubscribers++;const c=r.subject.subscribe(o);return()=>{const l=this._pushStatusSubjects.get(e);l&&l.activeSubscribers>0&&l.activeSubscribers--,c.unsubscribe()}});const s=y.gql`subscription StatusUpdates($sessionId: String!) {
|
|
464
466
|
statusUpdates(sessionId: $sessionId) {
|
|
465
467
|
date
|
|
466
468
|
message
|
|
467
469
|
sessionId
|
|
468
470
|
}
|
|
469
471
|
}
|
|
470
|
-
`,n=new v.Subject,a=this.getOrCreateWSClient(),i=new v.Subscription;return i.add(new v.Observable(o=>{const c=a.subscribe({query:s,variables:{sessionId:e}},{next:
|
|
472
|
+
`,n=new v.Subject,a=this.getOrCreateWSClient(),i=new v.Subscription;return i.add(new v.Observable(o=>{const c=a.subscribe({query:s,variables:{sessionId:e}},{next:h(l=>{const f=this._pushStatusSubjects.get(e);f&&(f.lastEmissionAt=Date.now()),o.next(l.data.statusUpdates.message)},"next"),error:h(async l=>{const f=l;if(f?.extensions?.code==="JWT_EXPIRED"||f?.message?.includes("token has expired")||f?.message?.includes("JWT_EXPIRED")){console.log("[GraphQLDataProvider] PushStatusUpdates JWT token expired, refreshing and reconnecting...");try{await this.RefreshToken(),this.disposeWSClient(),o.complete()}catch(d){console.error("[GraphQLDataProvider] Failed to refresh token for PushStatusUpdates:",d),o.error(d)}}else o.error(l)},"error"),complete:h(()=>{o.complete()},"complete")});return this._activeSubscriptionCount++,()=>{this._activeSubscriptionCount--,c()}}).subscribe({next:h(o=>n.next(o),"next"),error:h(o=>{n.error(o),this._pushStatusSubjects.delete(e)},"error"),complete:h(()=>{n.complete(),this._pushStatusSubjects.delete(e)},"complete")})),this._pushStatusSubjects.set(e,{subject:n,subscription:i,createdAt:t,lastRequestedAt:t,lastEmissionAt:t,activeSubscribers:0}),new v.Observable(o=>{const c=this._pushStatusSubjects.get(e);c&&c.activeSubscribers++;const l=n.subscribe(o);return()=>{const f=this._pushStatusSubjects.get(e);f&&f.activeSubscribers>0&&f.activeSubscribers--,l.unsubscribe()}})}disposeWebSocketResources(){this._subscriptionCleanupTimer&&(clearInterval(this._subscriptionCleanupTimer),this._subscriptionCleanupTimer=null),this.completeAllSubjects(),this._activeSubscriptionCount=0,this.disposeWSClient()}async FindISAChildEntity(e,t,r){if(!e.IsParentType)return null;const s=`query FindISAChildEntity($EntityName: String!, $RecordID: String!) {
|
|
471
473
|
FindISAChildEntity(EntityName: $EntityName, RecordID: $RecordID) {
|
|
472
474
|
Success
|
|
473
475
|
ChildEntityName
|
|
@@ -479,7 +481,7 @@
|
|
|
479
481
|
ChildEntityNames
|
|
480
482
|
ErrorMessage
|
|
481
483
|
}
|
|
482
|
-
}`;try{const n=await this.ExecuteGQL(s,{EntityName:e.Name,RecordID:t});return n?.FindISAChildEntities?.Success&&n.FindISAChildEntities.ChildEntityNames?n.FindISAChildEntities.ChildEntityNames.map(a=>({ChildEntityName:a})):[]}catch(n){return u.LogError(`FindISAChildEntities failed for ${e.Name}: ${n}`),[]}}}async function K(
|
|
484
|
+
}`;try{const n=await this.ExecuteGQL(s,{EntityName:e.Name,RecordID:t});return n?.FindISAChildEntities?.Success&&n.FindISAChildEntities.ChildEntityNames?n.FindISAChildEntities.ChildEntityNames.map(a=>({ChildEntityName:a})):[]}catch(n){return u.LogError(`FindISAChildEntities failed for ${e.Name}: ${n}`),[]}}}async function K(S){const e=new I;return u.SetProvider(e),await e.Config(S),await u.StartupManager.Instance.Startup(),C.MJGlobal.Instance.RaiseEvent({event:C.MJEventType.LoggedIn,eventCode:null,component:this,args:null}),e}h(K,"setupGraphQLClient");class B{static{h(this,"SyncRolesAndUsersResult")}}class j{static{h(this,"RoleInput")}}class J{static{h(this,"UserInput")}}class W{static{h(this,"RolesAndUsersInput")}}var Q=(S=>(S.Create="Create",S.Update="Update",S.CreateOrUpdate="CreateOrUpdate",S.Delete="Delete",S.DeleteWithFilter="DeleteWithFilter",S))(Q||{});class z{static{h(this,"ActionItemInput")}}class H{static{h(this,"SyncDataResult")}constructor(){this.Results=[]}}class X{static{h(this,"ActionItemOutput")}}class Y{static{h(this,"GraphQLSystemUserClient")}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 y.GraphQLClient(e,{headers:n})}async GetData(e,t){try{const s=await this.Client.request(`query GetData($input: GetDataInputType!) {
|
|
483
485
|
GetData(input: $input) {
|
|
484
486
|
Success
|
|
485
487
|
ErrorMessages
|
|
@@ -870,7 +872,7 @@
|
|
|
870
872
|
error
|
|
871
873
|
}
|
|
872
874
|
}
|
|
873
|
-
`,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 a=n.EmbedTextSystemUser;return{embeddings:Array.isArray(e.textToEmbed)?a.embeddings:a.embeddings[0],modelName:a.modelName,vectorDimensions:a.vectorDimensions,error:a.error}}catch(t){return u.LogError(`GraphQLSystemUserClient::EmbedText - Error generating embeddings - ${t}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:t.toString()}}}}class Z{static{
|
|
875
|
+
`,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 a=n.EmbedTextSystemUser;return{embeddings:Array.isArray(e.textToEmbed)?a.embeddings:a.embeddings[0],modelName:a.modelName,vectorDimensions:a.vectorDimensions,error:a.error}}catch(t){return u.LogError(`GraphQLSystemUserClient::EmbedText - Error generating embeddings - ${t}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:t.toString()}}}}class Z{static{h(this,"GetDataOutput")}}class ee{static{h(this,"SimpleRemoteEntityOutput")}}class te{static{h(this,"SimpleRemoteEntity")}}class re{static{h(this,"SimpleRemoteEntityField")}}class se{static{h(this,"GraphQLActionClient")}constructor(e){this._dataProvider=e}async RunAction(e,t,r=!1){try{const s=this.serializeActionParameters(t),n=this.createActionVariables(e,s,r),a=await this.executeActionMutation(n);return this.processActionResult(a,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=y.gql`
|
|
874
876
|
mutation RunAction($input: RunActionInput!) {
|
|
875
877
|
RunAction(input: $input) {
|
|
876
878
|
Success
|
|
@@ -887,7 +889,7 @@
|
|
|
887
889
|
ResultData
|
|
888
890
|
}
|
|
889
891
|
}
|
|
890
|
-
`;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){u.LogError(`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 u.LogError(`Error running entity action: ${t}`),{Success:!1,Message:`Error: ${t.message}`,RunParams:null,LogEntry:null}}}class ne{static{
|
|
892
|
+
`;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){u.LogError(`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 u.LogError(`Error running entity action: ${t}`),{Success:!1,Message:`Error: ${t.message}`,RunParams:null,LogEntry:null}}}class ne{static{h(this,"GraphQLEncryptionClient")}constructor(e){this._dataProvider=e}async CreateAPIKey(e){try{const t=this.createAPIKeyVariables(e),r=await this.executeCreateAPIKeyMutation(t);return this.processCreateAPIKeyResult(r)}catch(t){return this.handleCreateAPIKeyError(t)}}createAPIKeyVariables(e){return{input:{Label:e.Label,Description:e.Description,ExpiresAt:e.ExpiresAt?.toISOString(),ScopeIDs:e.ScopeIDs}}}async executeCreateAPIKeyMutation(e){const t=y.gql`
|
|
891
893
|
mutation CreateAPIKey($input: CreateAPIKeyInput!) {
|
|
892
894
|
CreateAPIKey(input: $input) {
|
|
893
895
|
Success
|
|
@@ -903,7 +905,7 @@
|
|
|
903
905
|
Error
|
|
904
906
|
}
|
|
905
907
|
}
|
|
906
|
-
`,s=await this._dataProvider.ExecuteGQL(t,{apiKeyId:e});return s?.RevokeAPIKey?{Success:s.RevokeAPIKey.Success,Error:s.RevokeAPIKey.Error}:{Success:!1,Error:"Invalid response from server"}}catch(t){const r=t;return u.LogError(`Error revoking API key: ${r.message}`),{Success:!1,Error:`Error: ${r.message}`}}}}class ae{static{
|
|
908
|
+
`,s=await this._dataProvider.ExecuteGQL(t,{apiKeyId:e});return s?.RevokeAPIKey?{Success:s.RevokeAPIKey.Success,Error:s.RevokeAPIKey.Error}:{Success:!1,Error:"Invalid response from server"}}catch(t){const r=t;return u.LogError(`Error revoking API key: ${r.message}`),{Success:!1,Error:`Error: ${r.message}`}}}}class ae{static{h(this,"GraphQLTestingClient")}constructor(e){this._dataProvider=e}async RunTest(e){let t;try{e.onProgress&&(t=this._dataProvider.PushStatusUpdates(this._dataProvider.sessionId).subscribe(o=>{try{const c=JSON.parse(o);c.resolver==="RunTestResolver"&&c.type==="TestExecutionProgress"&&c.status==="ok"&&c.data?.progress&&e.onProgress(c.data.progress)}catch(c){console.error("[GraphQLTestingClient] Failed to parse progress message:",c)}}));const r=y.gql`
|
|
907
909
|
mutation RunTest(
|
|
908
910
|
$testId: String!,
|
|
909
911
|
$verbose: Boolean,
|
|
@@ -957,7 +959,7 @@
|
|
|
957
959
|
query IsTestRunning($testId: String!) {
|
|
958
960
|
IsTestRunning(testId: $testId)
|
|
959
961
|
}
|
|
960
|
-
`;return(await this._dataProvider.ExecuteGQL(t,{testId:e})).IsTestRunning}catch(t){return u.LogError(`Error checking test running status: ${t.message}`),!1}}processTestResult(e){if(!e)throw new Error("Invalid response from server");let t;try{t=C.SafeJSONParse(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=C.SafeJSONParse(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 u.LogError(`${t} failed: ${r}`),{success:!1,errorMessage:r,result:null}}}class oe{static{
|
|
962
|
+
`;return(await this._dataProvider.ExecuteGQL(t,{testId:e})).IsTestRunning}catch(t){return u.LogError(`Error checking test running status: ${t.message}`),!1}}processTestResult(e){if(!e)throw new Error("Invalid response from server");let t;try{t=C.SafeJSONParse(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=C.SafeJSONParse(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 u.LogError(`${t} failed: ${r}`),{success:!1,errorMessage:r,result:null}}}class oe{static{h(this,"GraphQLComponentRegistryClient")}constructor(e){this._dataProvider=e}async GetRegistryComponent(e){try{const t=y.gql`
|
|
961
963
|
query GetRegistryComponent(
|
|
962
964
|
$registryName: String!,
|
|
963
965
|
$namespace: String!,
|
|
@@ -1041,7 +1043,7 @@
|
|
|
1041
1043
|
error
|
|
1042
1044
|
}
|
|
1043
1045
|
}
|
|
1044
|
-
`,r=await this._dataProvider.ExecuteGQL(t,{feedback:e});return r&&r.SendComponentFeedback?r.SendComponentFeedback:{success:!1,error:"No response from server"}}catch(t){return u.LogError(t),{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}}class ie{static{
|
|
1046
|
+
`,r=await this._dataProvider.ExecuteGQL(t,{feedback:e});return r&&r.SendComponentFeedback?r.SendComponentFeedback:{success:!1,error:"No response from server"}}catch(t){return u.LogError(t),{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}}class ie{static{h(this,"GraphQLVersionHistoryClient")}constructor(e){this._dataProvider=e}async CreateLabel(e){let t;try{e.OnProgress&&(t=this._dataProvider.PushStatusUpdates(this._dataProvider.sessionId).subscribe(a=>{try{const i=JSON.parse(a);i.resolver==="VersionHistoryResolver"&&i.type==="CreateLabelProgress"&&i.status==="ok"&&i.data&&e.OnProgress(i.data)}catch{}}));const r=y.gql`
|
|
1045
1047
|
mutation CreateVersionLabel($input: CreateVersionLabelInput!, $sessionId: String) {
|
|
1046
1048
|
CreateVersionLabel(input: $input, sessionId: $sessionId) {
|
|
1047
1049
|
Success
|
|
@@ -1057,7 +1059,7 @@
|
|
|
1057
1059
|
}
|
|
1058
1060
|
}
|
|
1059
1061
|
}
|
|
1060
|
-
`,s={input:this.buildInput(e),sessionId:this._dataProvider.sessionId},n=await this._dataProvider.ExecuteGQL(r,s);return this.processResult(n)}catch(r){const s=r instanceof Error?r.message:String(r);return u.LogError(`GraphQLVersionHistoryClient.CreateLabel error: ${s}`),{Success:!1,Error:s}}finally{t&&t.unsubscribe()}}buildInput(e){const t={Name:e.Name};return e.Description!=null&&(t.Description=e.Description),e.Scope!=null&&(t.Scope=e.Scope),e.EntityName!=null&&(t.EntityName=e.EntityName),e.ParentID!=null&&(t.ParentID=e.ParentID),e.ExternalSystemID!=null&&(t.ExternalSystemID=e.ExternalSystemID),e.IncludeDependencies!=null&&(t.IncludeDependencies=e.IncludeDependencies),e.MaxDepth!=null&&(t.MaxDepth=e.MaxDepth),e.ExcludeEntities!=null&&(t.ExcludeEntities=e.ExcludeEntities),e.RecordKeys&&e.RecordKeys.length>0&&(t.RecordKeys=e.RecordKeys.map(r=>({Key:r.Key,Value:r.Value}))),t}processResult(e){const t=e?.CreateVersionLabel;if(!t)return{Success:!1,Error:"Invalid response from server."};const r=Array.isArray(t.CaptureErrors)?t.CaptureErrors.map(s=>({EntityName:s.EntityName??"",RecordID:s.RecordID??"",ErrorMessage:s.ErrorMessage??""})):void 0;return{Success:t.Success,LabelID:t.LabelID,LabelName:t.LabelName,ItemsCaptured:t.ItemsCaptured,SyntheticSnapshotsCreated:t.SyntheticSnapshotsCreated,Error:t.Error,CaptureErrors:r}}}class ue{static{
|
|
1062
|
+
`,s={input:this.buildInput(e),sessionId:this._dataProvider.sessionId},n=await this._dataProvider.ExecuteGQL(r,s);return this.processResult(n)}catch(r){const s=r instanceof Error?r.message:String(r);return u.LogError(`GraphQLVersionHistoryClient.CreateLabel error: ${s}`),{Success:!1,Error:s}}finally{t&&t.unsubscribe()}}buildInput(e){const t={Name:e.Name};return e.Description!=null&&(t.Description=e.Description),e.Scope!=null&&(t.Scope=e.Scope),e.EntityName!=null&&(t.EntityName=e.EntityName),e.ParentID!=null&&(t.ParentID=e.ParentID),e.ExternalSystemID!=null&&(t.ExternalSystemID=e.ExternalSystemID),e.IncludeDependencies!=null&&(t.IncludeDependencies=e.IncludeDependencies),e.MaxDepth!=null&&(t.MaxDepth=e.MaxDepth),e.ExcludeEntities!=null&&(t.ExcludeEntities=e.ExcludeEntities),e.RecordKeys&&e.RecordKeys.length>0&&(t.RecordKeys=e.RecordKeys.map(r=>({Key:r.Key,Value:r.Value}))),t}processResult(e){const t=e?.CreateVersionLabel;if(!t)return{Success:!1,Error:"Invalid response from server."};const r=Array.isArray(t.CaptureErrors)?t.CaptureErrors.map(s=>({EntityName:s.EntityName??"",RecordID:s.RecordID??"",ErrorMessage:s.ErrorMessage??""})):void 0;return{Success:t.Success,LabelID:t.LabelID,LabelName:t.LabelName,ItemsCaptured:t.ItemsCaptured,SyntheticSnapshotsCreated:t.SyntheticSnapshotsCreated,Error:t.Error,CaptureErrors:r}}}class ue{static{h(this,"GraphQLFileStorageClient")}constructor(e){this._dataProvider=e}async ListObjects(e,t="",r){try{const s=y.gql`
|
|
1061
1063
|
query ListStorageObjects($input: ListStorageObjectsInput!) {
|
|
1062
1064
|
ListStorageObjects(input: $input) {
|
|
1063
1065
|
objects {
|
|
@@ -1141,5 +1143,5 @@
|
|
|
1141
1143
|
failedAccounts
|
|
1142
1144
|
}
|
|
1143
1145
|
}
|
|
1144
|
-
`,n={input:{AccountIDs:e,Query:t,MaxResultsPerAccount:r?.maxResultsPerAccount,FileTypes:r?.fileTypes,SearchContent:r?.searchContent}},a=await this._dataProvider.ExecuteGQL(s,n);if(!a?.SearchAcrossAccounts)throw new Error("Invalid response from server");const i=a.SearchAcrossAccounts;return{accountResults:i.accountResults.map(o=>({accountId:o.accountID,accountName:o.accountName,success:o.success,errorMessage:o.errorMessage,results:o.results.map(c=>({path:c.path,name:c.name,size:c.size,contentType:c.contentType,lastModified:new Date(c.lastModified),relevance:c.relevance,excerpt:c.excerpt,matchInFilename:c.matchInFilename,objectId:c.objectId})),totalMatches:o.totalMatches,hasMore:o.hasMore,nextPageToken:o.nextPageToken})),totalResultsReturned:i.totalResultsReturned,successfulAccounts:i.successfulAccounts,failedAccounts:i.failedAccounts}}catch(s){const n=s;return u.LogError(`Error searching across accounts: ${n}`),{accountResults:[],totalResultsReturned:0,successfulAccounts:0,failedAccounts:e.length}}}}Object.defineProperty(exports,"gql",{enumerable:!0,get:
|
|
1146
|
+
`,n={input:{AccountIDs:e,Query:t,MaxResultsPerAccount:r?.maxResultsPerAccount,FileTypes:r?.fileTypes,SearchContent:r?.searchContent}},a=await this._dataProvider.ExecuteGQL(s,n);if(!a?.SearchAcrossAccounts)throw new Error("Invalid response from server");const i=a.SearchAcrossAccounts;return{accountResults:i.accountResults.map(o=>({accountId:o.accountID,accountName:o.accountName,success:o.success,errorMessage:o.errorMessage,results:o.results.map(c=>({path:c.path,name:c.name,size:c.size,contentType:c.contentType,lastModified:new Date(c.lastModified),relevance:c.relevance,excerpt:c.excerpt,matchInFilename:c.matchInFilename,objectId:c.objectId})),totalMatches:o.totalMatches,hasMore:o.hasMore,nextPageToken:o.nextPageToken})),totalResultsReturned:i.totalResultsReturned,successfulAccounts:i.successfulAccounts,failedAccounts:i.failedAccounts}}catch(s){const n=s;return u.LogError(`Error searching across accounts: ${n}`),{accountResults:[],totalResultsReturned:0,successfulAccounts:0,failedAccounts:e.length}}}}Object.defineProperty(exports,"gql",{enumerable:!0,get:h(function(){return y.gql},"get")}),exports.ActionItemInput=z,exports.ActionItemOutput=X,exports.BrowserIndexedDBStorageProvider=U,exports.BrowserStorageProviderBase=L,exports.FieldMapper=$,exports.GetDataOutput=Z,exports.GraphQLAIClient=N,exports.GraphQLActionClient=se,exports.GraphQLComponentRegistryClient=oe,exports.GraphQLDataProvider=I,exports.GraphQLEncryptionClient=ne,exports.GraphQLFileStorageClient=ue,exports.GraphQLProviderConfigData=k,exports.GraphQLSystemUserClient=Y,exports.GraphQLTestingClient=ae,exports.GraphQLTransactionGroup=x,exports.GraphQLVersionHistoryClient=ie,exports.RoleInput=j,exports.RolesAndUsersInput=W,exports.SimpleRemoteEntity=te,exports.SimpleRemoteEntityField=re,exports.SimpleRemoteEntityOutput=ee,exports.SyncDataAction=Q,exports.SyncDataResult=H,exports.SyncRolesAndUsersResult=B,exports.UserInput=J,exports.setupGraphQLClient=K;
|
|
1145
1147
|
//# sourceMappingURL=index.cjs.map
|