@memberjunction/graphql-dataprovider 2.129.0 → 2.130.0

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 CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var Re=Object.defineProperty;var S=(E,e)=>Re(E,"name",{value:e,configurable:!0});var m=require("graphql-request"),u=require("@memberjunction/core"),pe=require("@memberjunction/core-entities"),$=require("rxjs"),Ie=require("graphql-ws"),Ee=require("uuid"),w=require("@memberjunction/global"),De=require("@tempfix/idb");const W=class W{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}};S(W,"FieldMapper");let C=W;const z=class z extends u.TransactionGroupBase{constructor(e){super(),this._provider=e}async HandleSubmit(){const e=m.gql`
1
+ "use strict";var Ie=Object.defineProperty;var f=(E,e)=>Ie(E,"name",{value:e,configurable:!0});var m=require("graphql-request"),c=require("@memberjunction/core"),pe=require("@memberjunction/core-entities"),v=require("rxjs"),Re=require("graphql-ws"),Ee=require("uuid"),w=require("@memberjunction/global"),De=require("@tempfix/idb");const W=class W{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(W,"FieldMapper");let P=W;const z=class z extends c.TransactionGroupBase{constructor(e){super(),this._provider=e}async HandleSubmit(){const e=m.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 a of this.PendingTransactions)t.push({EntityName:a.BaseEntity.EntityInfo.Name,EntityObjectJSON:await a.BaseEntity.GetDataObjectJSON(),OperationType:a.OperationType});const r={group:{Items:t,Variables:this.Variables.map(a=>({Name:a.Name,ItemIndex:this.MapVariableEntityObjectToPosition(a),FieldName:a.FieldName,Type:a.Type}))}},s=await this._provider.ExecuteGQL(e,r);if(s&&s.ExecuteTransactionGroup){const a=s.ExecuteTransactionGroup,o=[];for(let i=0;i<this.PendingTransactions.length;i++){const n=a.ResultsJSON[i],c=w.SafeJSONParse(n),p=this.PendingTransactions[i];o.push(new u.TransactionResult(p,c,c!==null))}return o}else throw new Error("Failed to execute transaction group")}};S(z,"GraphQLTransactionGroup");let v=z;const X=class X{constructor(e){this._dataProvider=e}async RunAIPrompt(e){try{const t=m.gql`
9
+ `,t=[];for(const a of this.PendingTransactions)t.push({EntityName:a.BaseEntity.EntityInfo.Name,EntityObjectJSON:await a.BaseEntity.GetDataObjectJSON(),OperationType:a.OperationType});const r={group:{Items:t,Variables:this.Variables.map(a=>({Name:a.Name,ItemIndex:this.MapVariableEntityObjectToPosition(a),FieldName:a.FieldName,Type:a.Type}))}},s=await this._provider.ExecuteGQL(e,r);if(s&&s.ExecuteTransactionGroup){const a=s.ExecuteTransactionGroup,o=[];for(let i=0;i<this.PendingTransactions.length;i++){const n=a.ResultsJSON[i],u=w.SafeJSONParse(n),p=this.PendingTransactions[i];o.push(new c.TransactionResult(p,u,u!==null))}return o}else throw new Error("Failed to execute transaction group")}};f(z,"GraphQLTransactionGroup");let C=z;const H=class H{constructor(e){this._dataProvider=e}async RunAIPrompt(e){try{const t=m.gql`
10
10
  mutation RunAIPrompt(
11
11
  $promptId: String!,
12
12
  $data: String,
@@ -65,7 +65,7 @@
65
65
  chatResult
66
66
  }
67
67
  }
68
- `,r=this.preparePromptVariables(e),s=await this._dataProvider.ExecuteGQL(t,r);return this.processPromptResult(s)}catch(t){return this.handlePromptError(t)}}preparePromptVariables(e){const t={promptId:e.promptId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.templateData!==void 0&&(t.templateData=typeof e.templateData=="object"?JSON.stringify(e.templateData):e.templateData),e.messages!==void 0&&(t.messages=JSON.stringify(e.messages)),e.overrideModelId!==void 0&&(t.overrideModelId=e.overrideModelId),e.overrideVendorId!==void 0&&(t.overrideVendorId=e.overrideVendorId),e.configurationId!==void 0&&(t.configurationId=e.configurationId),e.skipValidation!==void 0&&(t.skipValidation=e.skipValidation),e.responseFormat!==void 0&&(t.responseFormat=e.responseFormat),e.temperature!==void 0&&(t.temperature=e.temperature),e.topP!==void 0&&(t.topP=e.topP),e.topK!==void 0&&(t.topK=e.topK),e.minP!==void 0&&(t.minP=e.minP),e.frequencyPenalty!==void 0&&(t.frequencyPenalty=e.frequencyPenalty),e.presencePenalty!==void 0&&(t.presencePenalty=e.presencePenalty),e.seed!==void 0&&(t.seed=e.seed),e.stopSequences!==void 0&&(t.stopSequences=e.stopSequences),e.includeLogProbs!==void 0&&(t.includeLogProbs=e.includeLogProbs),e.topLogProbs!==void 0&&(t.topLogProbs=e.topLogProbs),e.rerunFromPromptRunID!==void 0&&(t.rerunFromPromptRunID=e.rerunFromPromptRunID),e.systemPromptOverride!==void 0&&(t.systemPromptOverride=e.systemPromptOverride),t}processPromptResult(e){if(!e?.RunAIPrompt)throw new Error("Invalid response from server");const t=e.RunAIPrompt;let r,s,a;try{t.parsedResult&&(r=JSON.parse(t.parsedResult))}catch{r=t.parsedResult}try{t.validationResult&&(s=JSON.parse(t.validationResult))}catch{s=t.validationResult}try{t.chatResult&&(a=JSON.parse(t.chatResult))}catch{a=t.chatResult}return{success:t.success,output:t.output,parsedResult:r,error:t.error,executionTimeMs:t.executionTimeMs,tokensUsed:t.tokensUsed,promptRunId:t.promptRunId,rawResult:t.rawResult,validationResult:s,chatResult:a}}handlePromptError(e){const t=e;return u.LogError(`Error running AI prompt: ${t}`),{success:!1,error:t.message||"Unknown error occurred"}}async RunAIAgent(e,t,r){let s;try{e.onProgress&&(s=this._dataProvider.PushStatusUpdates(this._dataProvider.sessionId).subscribe(n=>{try{u.LogStatusEx({message:"[GraphQLAIClient] Received statusUpdate message",verboseOnly:!0,additionalArgs:[n]});const c=JSON.parse(n);if(u.LogStatusEx({message:"[GraphQLAIClient] Parsed message",verboseOnly:!0,additionalArgs:[c]}),c.resolver==="RunAIAgentResolver"&&c.type==="ExecutionProgress"&&c.status==="ok"&&c.data?.progress){u.LogStatusEx({message:"[GraphQLAIClient] Forwarding progress to callback",verboseOnly:!0,additionalArgs:[c.data.progress]});const p={...c.data.progress,metadata:{...c.data.progress.metadata||{},agentRunId:c.data.agentRunId}};e.onProgress(p)}else u.LogStatusEx({message:"[GraphQLAIClient] Message does not match filter criteria",verboseOnly:!0,additionalArgs:[{resolver:c.resolver,type:c.type,status:c.status,hasProgress:!!c.data?.progress}]})}catch(c){console.error("[GraphQLAIClient] Failed to parse progress message:",c,"Raw message:",n)}}));const a=m.gql`
68
+ `,r=this.preparePromptVariables(e),s=await this._dataProvider.ExecuteGQL(t,r);return this.processPromptResult(s)}catch(t){return this.handlePromptError(t)}}preparePromptVariables(e){const t={promptId:e.promptId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.templateData!==void 0&&(t.templateData=typeof e.templateData=="object"?JSON.stringify(e.templateData):e.templateData),e.messages!==void 0&&(t.messages=JSON.stringify(e.messages)),e.overrideModelId!==void 0&&(t.overrideModelId=e.overrideModelId),e.overrideVendorId!==void 0&&(t.overrideVendorId=e.overrideVendorId),e.configurationId!==void 0&&(t.configurationId=e.configurationId),e.skipValidation!==void 0&&(t.skipValidation=e.skipValidation),e.responseFormat!==void 0&&(t.responseFormat=e.responseFormat),e.temperature!==void 0&&(t.temperature=e.temperature),e.topP!==void 0&&(t.topP=e.topP),e.topK!==void 0&&(t.topK=e.topK),e.minP!==void 0&&(t.minP=e.minP),e.frequencyPenalty!==void 0&&(t.frequencyPenalty=e.frequencyPenalty),e.presencePenalty!==void 0&&(t.presencePenalty=e.presencePenalty),e.seed!==void 0&&(t.seed=e.seed),e.stopSequences!==void 0&&(t.stopSequences=e.stopSequences),e.includeLogProbs!==void 0&&(t.includeLogProbs=e.includeLogProbs),e.topLogProbs!==void 0&&(t.topLogProbs=e.topLogProbs),e.rerunFromPromptRunID!==void 0&&(t.rerunFromPromptRunID=e.rerunFromPromptRunID),e.systemPromptOverride!==void 0&&(t.systemPromptOverride=e.systemPromptOverride),t}processPromptResult(e){if(!e?.RunAIPrompt)throw new Error("Invalid response from server");const t=e.RunAIPrompt;let r,s,a;try{t.parsedResult&&(r=JSON.parse(t.parsedResult))}catch{r=t.parsedResult}try{t.validationResult&&(s=JSON.parse(t.validationResult))}catch{s=t.validationResult}try{t.chatResult&&(a=JSON.parse(t.chatResult))}catch{a=t.chatResult}return{success:t.success,output:t.output,parsedResult:r,error:t.error,executionTimeMs:t.executionTimeMs,tokensUsed:t.tokensUsed,promptRunId:t.promptRunId,rawResult:t.rawResult,validationResult:s,chatResult:a}}handlePromptError(e){const t=e;return c.LogError(`Error running AI prompt: ${t}`),{success:!1,error:t.message||"Unknown error occurred"}}async RunAIAgent(e,t,r){let s;try{e.onProgress&&(s=this._dataProvider.PushStatusUpdates(this._dataProvider.sessionId).subscribe(n=>{try{c.LogStatusEx({message:"[GraphQLAIClient] Received statusUpdate message",verboseOnly:!0,additionalArgs:[n]});const u=JSON.parse(n);if(c.LogStatusEx({message:"[GraphQLAIClient] Parsed message",verboseOnly:!0,additionalArgs:[u]}),u.resolver==="RunAIAgentResolver"&&u.type==="ExecutionProgress"&&u.status==="ok"&&u.data?.progress){c.LogStatusEx({message:"[GraphQLAIClient] Forwarding progress to callback",verboseOnly:!0,additionalArgs:[u.data.progress]});const p={...u.data.progress,metadata:{...u.data.progress.metadata||{},agentRunId:u.data.agentRunId}};e.onProgress(p)}else c.LogStatusEx({message:"[GraphQLAIClient] Message does not match filter criteria",verboseOnly:!0,additionalArgs:[{resolver:u.resolver,type:u.type,status:u.status,hasProgress:!!u.data?.progress}]})}catch(u){console.error("[GraphQLAIClient] Failed to parse progress message:",u,"Raw message:",n)}}));const a=m.gql`
69
69
  mutation RunAIAgent(
70
70
  $agentId: String!,
71
71
  $messages: String!,
@@ -104,7 +104,44 @@
104
104
  result
105
105
  }
106
106
  }
107
- `,o=this.prepareAgentVariables(e,t,r),i=await this._dataProvider.ExecuteGQL(a,o);return this.processAgentResult(i.RunAIAgent?.result)}catch(a){return this.handleAgentError(a)}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 w.SafeJSONParse(e)}handleAgentError(e){const t=e;return u.LogError(`Error running AI agent: ${t}`),{success:!1,agentRun:void 0}}async ExecuteSimplePrompt(e){try{const t=m.gql`
107
+ `,o=this.prepareAgentVariables(e,t,r),i=await this._dataProvider.ExecuteGQL(a,o);return this.processAgentResult(i.RunAIAgent?.result)}catch(a){return this.handleAgentError(a)}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 w.SafeJSONParse(e)}handleAgentError(e){const t=e;return c.LogError(`Error running AI agent: ${t}`),{success:!1,agentRun:void 0}}async RunAIAgentFromConversationDetail(e){let t;try{e.onProgress&&(t=this._dataProvider.PushStatusUpdates(this._dataProvider.sessionId).subscribe(o=>{try{const i=JSON.parse(o);if(i.resolver==="RunAIAgentResolver"&&i.type==="ExecutionProgress"&&i.status==="ok"&&i.data?.progress){const n={...i.data.progress,metadata:{...i.data.progress.metadata||{},agentRunId:i.data.agentRunId}};e.onProgress(n)}}catch(i){console.error("[GraphQLAIClient] Failed to parse progress message:",i)}}));const r=m.gql`
108
+ mutation RunAIAgentFromConversationDetail(
109
+ $conversationDetailId: String!,
110
+ $agentId: String!,
111
+ $sessionId: String!,
112
+ $maxHistoryMessages: Int,
113
+ $data: String,
114
+ $payload: String,
115
+ $lastRunId: String,
116
+ $autoPopulateLastRunPayload: Boolean,
117
+ $configurationId: String,
118
+ $createArtifacts: Boolean,
119
+ $createNotification: Boolean,
120
+ $sourceArtifactId: String,
121
+ $sourceArtifactVersionId: String
122
+ ) {
123
+ RunAIAgentFromConversationDetail(
124
+ conversationDetailId: $conversationDetailId,
125
+ agentId: $agentId,
126
+ sessionId: $sessionId,
127
+ maxHistoryMessages: $maxHistoryMessages,
128
+ data: $data,
129
+ payload: $payload,
130
+ lastRunId: $lastRunId,
131
+ autoPopulateLastRunPayload: $autoPopulateLastRunPayload,
132
+ configurationId: $configurationId,
133
+ createArtifacts: $createArtifacts,
134
+ createNotification: $createNotification,
135
+ sourceArtifactId: $sourceArtifactId,
136
+ sourceArtifactVersionId: $sourceArtifactVersionId
137
+ ) {
138
+ success
139
+ errorMessage
140
+ executionTimeMs
141
+ result
142
+ }
143
+ }
144
+ `,s={conversationDetailId:e.conversationDetailId,agentId:e.agentId,sessionId:this._dataProvider.sessionId};e.maxHistoryMessages!==void 0&&(s.maxHistoryMessages=e.maxHistoryMessages),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.createArtifacts!==void 0&&(s.createArtifacts=e.createArtifacts),e.createNotification!==void 0&&(s.createNotification=e.createNotification),e.sourceArtifactId!==void 0&&(s.sourceArtifactId=e.sourceArtifactId),e.sourceArtifactVersionId!==void 0&&(s.sourceArtifactVersionId=e.sourceArtifactVersionId);const a=await this._dataProvider.ExecuteGQL(r,s);return this.processAgentResult(a.RunAIAgentFromConversationDetail?.result)}catch(r){return this.handleAgentError(r)}finally{t&&t.unsubscribe()}}async ExecuteSimplePrompt(e){try{const t=m.gql`
108
145
  mutation ExecuteSimplePrompt(
109
146
  $systemPrompt: String!,
110
147
  $messages: String,
@@ -127,7 +164,7 @@
127
164
  executionTimeMs
128
165
  }
129
166
  }
130
- `,r={systemPrompt:e.systemPrompt};e.messages&&e.messages.length>0&&(r.messages=JSON.stringify(e.messages)),e.preferredModels&&(r.preferredModels=e.preferredModels),e.modelPower&&(r.modelPower=e.modelPower),e.responseFormat&&(r.responseFormat=e.responseFormat);const s=await this._dataProvider.ExecuteGQL(t,r);if(!s?.ExecuteSimplePrompt)throw new Error("Invalid response from server");const a=s.ExecuteSimplePrompt;let o;if(a.resultObject)try{o=JSON.parse(a.resultObject)}catch{o=a.resultObject}return{success:a.success,result:a.result,resultObject:o,modelName:a.modelName,error:a.error,executionTimeMs:a.executionTimeMs}}catch(t){const r=t;return u.LogError(`Error executing simple prompt: ${r}`),{success:!1,modelName:"Unknown",error:r.message||"Unknown error occurred"}}}async EmbedText(e){try{const t=m.gql`
167
+ `,r={systemPrompt:e.systemPrompt};e.messages&&e.messages.length>0&&(r.messages=JSON.stringify(e.messages)),e.preferredModels&&(r.preferredModels=e.preferredModels),e.modelPower&&(r.modelPower=e.modelPower),e.responseFormat&&(r.responseFormat=e.responseFormat);const s=await this._dataProvider.ExecuteGQL(t,r);if(!s?.ExecuteSimplePrompt)throw new Error("Invalid response from server");const a=s.ExecuteSimplePrompt;let o;if(a.resultObject)try{o=JSON.parse(a.resultObject)}catch{o=a.resultObject}return{success:a.success,result:a.result,resultObject:o,modelName:a.modelName,error:a.error,executionTimeMs:a.executionTimeMs}}catch(t){const r=t;return c.LogError(`Error executing simple prompt: ${r}`),{success:!1,modelName:"Unknown",error:r.message||"Unknown error occurred"}}}async EmbedText(e){try{const t=m.gql`
131
168
  mutation EmbedText(
132
169
  $textToEmbed: [String!]!,
133
170
  $modelSize: String!
@@ -142,7 +179,7 @@
142
179
  error
143
180
  }
144
181
  }
145
- `,s={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},a=await this._dataProvider.ExecuteGQL(t,s);if(!a?.EmbedText)throw new Error("Invalid response from server");const o=a.EmbedText;return{embeddings:Array.isArray(e.textToEmbed)?o.embeddings:o.embeddings[0],modelName:o.modelName,vectorDimensions:o.vectorDimensions,error:o.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"}}}};S(X,"GraphQLAIClient");let N=X;const P="default",H=class H{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()):[]}};S(H,"BrowserStorageProviderBase");let b=H;const we="MJ_Metadata",Pe=3,he=["mj:default","mj:Metadata","mj:RunViewCache","mj:RunQueryCache","mj:DatasetCache"],Se="Metadata_KVPairs",Y=class Y extends b{constructor(){super(),this._dbReady=!1,this.dbPromise=De.openDB(we,Pe,{upgrade(e){try{e.objectStoreNames.contains(Se)&&e.deleteObjectStore(Se);for(const t of he)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 he.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,a=this.getStoreName(r),o=this.getStoreKey(e,r),i=s.transaction(a,"readwrite");await i.objectStore(a).put(t,o),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),a=this.getStoreKey(e,t);return await r.transaction(s).objectStore(s).get(a)??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),a=this.getStoreKey(e,t),o=r.transaction(s,"readwrite");await o.objectStore(s).delete(a),await o.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 a=t.transaction(s,"readwrite");await a.objectStore(s).clear(),await a.done}else{const a=`[${r}]:`,o=t.transaction("mj:default","readwrite"),i=o.objectStore("mj:default"),n=await i.getAllKeys();for(const c of n)typeof c=="string"&&c.startsWith(a)&&await i.delete(c);await o.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 n=`[${r}]:`;return i.map(c=>String(c)).filter(c=>c.startsWith(n)).map(c=>c.slice(n.length))}catch(t){return u.LogErrorEx({error:t,message:t?.message}),await super.GetCategoryKeys(e)}}};S(Y,"BrowserIndexedDBStorageProvider");let x=Y;const Z=class Z extends u.ProviderConfigDataBase{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,a,o,i,n){super({Token:e,URL:t,WSURL:r,MJAPIKey:n,RefreshTokenFunction:s},a,o,i)}};S(Z,"GraphQLProviderConfigData");let T=Z;const h=class h extends u.ProviderBase{constructor(){super(),this._refreshPromise=null,this._innerCurrentUserQueryString=`CurrentUser {
182
+ `,s={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},a=await this._dataProvider.ExecuteGQL(t,s);if(!a?.EmbedText)throw new Error("Invalid response from server");const o=a.EmbedText;return{embeddings:Array.isArray(e.textToEmbed)?o.embeddings:o.embeddings[0],modelName:o.modelName,vectorDimensions:o.vectorDimensions,error:o.error}}catch(t){const r=t;return c.LogError(`Error generating embeddings: ${r}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:r.message||"Unknown error occurred"}}}};f(H,"GraphQLAIClient");let N=H;const $="default",X=class X{constructor(){this._storage=new Map}getCategoryMap(e){const t=e||$;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||$).get(e)??null}async SetItem(e,t,r){this.getCategoryMap(r||$).set(e,t)}async Remove(e,t){this.getCategoryMap(t||$).delete(e)}async ClearCategory(e){const t=e||$;this._storage.delete(t)}async GetCategoryKeys(e){const t=this._storage.get(e||$);return t?Array.from(t.keys()):[]}};f(X,"BrowserStorageProviderBase");let b=X;const we="MJ_Metadata",$e=3,he=["mj:default","mj:Metadata","mj:RunViewCache","mj:RunQueryCache","mj:DatasetCache"],fe="Metadata_KVPairs",Y=class Y extends b{constructor(){super(),this._dbReady=!1,this.dbPromise=De.openDB(we,$e,{upgrade(e){try{e.objectStoreNames.contains(fe)&&e.deleteObjectStore(fe);for(const t of he)e.objectStoreNames.contains(t)||e.createObjectStore(t)}catch(t){c.LogErrorEx({error:t,message:t?.message})}}}),this.dbPromise.then(()=>{this._dbReady=!0}).catch(e=>{c.LogErrorEx({error:e,message:"IndexedDB initialization failed: "+e?.message})})}isKnownCategory(e){const t=`mj:${e}`;return he.includes(t)}getStoreName(e){const t=e||$;return this.isKnownCategory(t)?`mj:${t}`:"mj:default"}getStoreKey(e,t){const r=t||$;return this.isKnownCategory(r)?e:`[${r}]:${e}`}async SetItem(e,t,r){try{const s=await this.dbPromise,a=this.getStoreName(r),o=this.getStoreKey(e,r),i=s.transaction(a,"readwrite");await i.objectStore(a).put(t,o),await i.done}catch(s){c.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),a=this.getStoreKey(e,t);return await r.transaction(s).objectStore(s).get(a)??null}catch(r){return c.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),a=this.getStoreKey(e,t),o=r.transaction(s,"readwrite");await o.objectStore(s).delete(a),await o.done}catch(r){c.LogErrorEx({error:r,message:r?.message}),await super.Remove(e,t)}}async ClearCategory(e){try{const t=await this.dbPromise,r=e||$,s=this.getStoreName(e);if(this.isKnownCategory(r)){const a=t.transaction(s,"readwrite");await a.objectStore(s).clear(),await a.done}else{const a=`[${r}]:`,o=t.transaction("mj:default","readwrite"),i=o.objectStore("mj:default"),n=await i.getAllKeys();for(const u of n)typeof u=="string"&&u.startsWith(a)&&await i.delete(u);await o.done}}catch(t){c.LogErrorEx({error:t,message:t?.message}),await super.ClearCategory(e)}}async GetCategoryKeys(e){try{const t=await this.dbPromise,r=e||$,s=this.getStoreName(e),i=await t.transaction(s,"readonly").objectStore(s).getAllKeys();if(this.isKnownCategory(r))return i.map(u=>String(u));const n=`[${r}]:`;return i.map(u=>String(u)).filter(u=>u.startsWith(n)).map(u=>u.slice(n.length))}catch(t){return c.LogErrorEx({error:t,message:t?.message}),await super.GetCategoryKeys(e)}}};f(Y,"BrowserIndexedDBStorageProvider");let x=Y;const Z=class Z extends c.ProviderConfigDataBase{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,a,o,i,n){super({Token:e,URL:t,WSURL:r,MJAPIKey:n,RefreshTokenFunction:s},a,o,i)}};f(Z,"GraphQLProviderConfigData");let T=Z;const h=class h extends c.ProviderBase{constructor(){super(),this._refreshPromise=null,this._innerCurrentUserQueryString=`CurrentUser {
146
183
  ${this.userInfoString()}
147
184
  UserRoles_UserIDArray {
148
185
  ${this.userRoleInfoString()}
@@ -150,7 +187,7 @@
150
187
  }
151
188
  `,this._currentUserQuery=m.gql`query CurrentUserAndRoles {
152
189
  ${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,h._instance||(h._instance=this)}static get Instance(){return h._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 Ee.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),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(a){throw u.LogError(a),a}}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 u.UserInfo(this,{...t,UserRoles:r})}}async RunReport(e,t){const r=m.gql`
190
+ }`,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}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 Ee.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),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(a){throw c.LogError(a),a}}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 c.UserInfo(this,{...t,UserRoles:r})}}async RunReport(e,t){const r=m.gql`
154
191
  query GetReportDataQuery ($ReportID: String!) {
155
192
  GetReportData(ReportID: $ReportID) {
156
193
  Success
@@ -171,13 +208,13 @@
171
208
  ${this.QueryReturnFieldList}
172
209
  }
173
210
  }
174
- `,c={QueryID:e};t!==void 0&&(c.CategoryID=t),r!==void 0&&(c.CategoryPath=r),a!==void 0&&(c.Parameters=a),o!==void 0&&(c.MaxRows=o),i!==void 0&&(c.StartRow=i);const p=await this.ExecuteGQL(n,c);if(p&&p.GetQueryData)return this.TransformQueryPayload(p.GetQueryData)}async RunQueryByName(e,t,r,s,a,o,i){const n=m.gql`
211
+ `,u={QueryID:e};t!==void 0&&(u.CategoryID=t),r!==void 0&&(u.CategoryPath=r),a!==void 0&&(u.Parameters=a),o!==void 0&&(u.MaxRows=o),i!==void 0&&(u.StartRow=i);const p=await this.ExecuteGQL(n,u);if(p&&p.GetQueryData)return this.TransformQueryPayload(p.GetQueryData)}async RunQueryByName(e,t,r,s,a,o,i){const n=m.gql`
175
212
  query GetQueryDataByNameQuery($QueryName: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int) {
176
213
  GetQueryDataByName(QueryName: $QueryName, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {
177
214
  ${this.QueryReturnFieldList}
178
215
  }
179
216
  }
180
- `,c={QueryName:e};t!==void 0&&(c.CategoryID=t),r!==void 0&&(c.CategoryPath=r),a!==void 0&&(c.Parameters=a),o!==void 0&&(c.MaxRows=o),i!==void 0&&(c.StartRow=i);const p=await this.ExecuteGQL(n,c);if(p&&p.GetQueryDataByName)return this.TransformQueryPayload(p.GetQueryDataByName)}get QueryReturnFieldList(){return`
217
+ `,u={QueryName:e};t!==void 0&&(u.CategoryID=t),r!==void 0&&(u.CategoryPath=r),a!==void 0&&(u.Parameters=a),o!==void 0&&(u.MaxRows=o),i!==void 0&&(u.StartRow=i);const p=await this.ExecuteGQL(n,u);if(p&&p.GetQueryDataByName)return this.TransformQueryPayload(p.GetQueryDataByName)}get QueryReturnFieldList(){return`
181
218
  Success
182
219
  QueryID
183
220
  QueryName
@@ -186,7 +223,7 @@
186
223
  TotalRowCount
187
224
  ExecutionTime
188
225
  ErrorMessage
189
- 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 u.LogError(`Error transforming query payload: ${t}`),null}}async RunQueriesWithCacheCheck(e,t){try{const r=e.map(n=>({params:{QueryID:n.params.QueryID||null,QueryName:n.params.QueryName||null,CategoryID:n.params.CategoryID||null,CategoryPath:n.params.CategoryPath||null,Parameters:n.params.Parameters||null,MaxRows:n.params.MaxRows??null,StartRow:n.params.StartRow??null,ForceAuditLog:n.params.ForceAuditLog||!1,AuditLogDescription:n.params.AuditLogDescription||null},cacheStatus:n.cacheStatus?{maxUpdatedAt:n.cacheStatus.maxUpdatedAt,rowCount:n.cacheStatus.rowCount}:null})),s=m.gql`
226
+ 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 c.LogError(`Error transforming query payload: ${t}`),null}}async RunQueriesWithCacheCheck(e,t){try{const r=e.map(n=>({params:{QueryID:n.params.QueryID||null,QueryName:n.params.QueryName||null,CategoryID:n.params.CategoryID||null,CategoryPath:n.params.CategoryPath||null,Parameters:n.params.Parameters||null,MaxRows:n.params.MaxRows??null,StartRow:n.params.StartRow??null,ForceAuditLog:n.params.ForceAuditLog||!1,AuditLogDescription:n.params.AuditLogDescription||null},cacheStatus:n.cacheStatus?{maxUpdatedAt:n.cacheStatus.maxUpdatedAt,rowCount:n.cacheStatus.rowCount}:null})),s=m.gql`
190
227
  query RunQueriesWithCacheCheckQuery($input: [RunQueryWithCacheCheckInput!]!) {
191
228
  RunQueriesWithCacheCheck(input: $input) {
192
229
  success
@@ -202,7 +239,7 @@
202
239
  }
203
240
  }
204
241
  }
205
- `,o=(await this.ExecuteGQL(s,{input:r}))?.RunQueriesWithCacheCheck;if(!o)return{success:!1,results:[],errorMessage:"No response from server"};const i=o.results.map(n=>{if((n.status==="stale"||n.status==="no_validation")&&n.Results){const c=JSON.parse(n.Results);return{queryIndex:n.queryIndex,queryId:n.queryId,status:n.status,results:c,maxUpdatedAt:n.maxUpdatedAt,rowCount:n.rowCount,errorMessage:n.errorMessage}}return{queryIndex:n.queryIndex,queryId:n.queryId,status:n.status,maxUpdatedAt:n.maxUpdatedAt,rowCount:n.rowCount,errorMessage:n.errorMessage}});return{success:o.success,results:i,errorMessage:o.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 a={};let o,i;if(e.ViewEntity)i=e.ViewEntity,o=i.Entity;else{const{entityName:l,v:d}=await this.getEntityNameAndUserView(e,t);i=d,o=l}const n=this.Entities.find(l=>l.Name===o);if(!n)throw new Error(`Entity ${o} not found in metadata`);let c=!1;const p=u.getGraphQLTypeNameBase(n);e.ViewID?(r=`Run${p}ViewByID`,s="RunViewByIDInput",a.ViewID=e.ViewID):e.ViewName?(r=`Run${p}ViewByName`,s="RunViewByNameInput",a.ViewName=e.ViewName):(c=!0,r=`Run${p}DynamicView`,s="RunDynamicViewInput",a.EntityName=e.EntityName),a.ExtraFilter=e.ExtraFilter?e.ExtraFilter:"",a.OrderBy=e.OrderBy?e.OrderBy:"",a.UserSearchString=e.UserSearchString?e.UserSearchString:"",a.Fields=e.Fields,a.IgnoreMaxRows=e.IgnoreMaxRows?e.IgnoreMaxRows:!1,e.MaxRows!==void 0&&(a.MaxRows=e.MaxRows),e.StartRow!==void 0&&(a.StartRow=e.StartRow),a.ForceAuditLog=e.ForceAuditLog?e.ForceAuditLog:!1,a.ResultType=e.ResultType?e.ResultType:"simple",e.AuditLogDescription&&e.AuditLogDescription.length>0&&(a.AuditLogDescription=e.AuditLogDescription),c||(a.ExcludeUserViewRunID=e.ExcludeUserViewRunID?e.ExcludeUserViewRunID:"",a.ExcludeDataFromAllPriorViewRuns=e.ExcludeDataFromAllPriorViewRuns?e.ExcludeDataFromAllPriorViewRuns:!1,a.OverrideExcludeFilter=e.OverrideExcludeFilter?e.OverrideExcludeFilter:"",a.SaveViewResults=e.SaveViewResults?e.SaveViewResults:!1);const g=this.getViewRunTimeFieldList(n,i,e,c),R=m.gql`
242
+ `,o=(await this.ExecuteGQL(s,{input:r}))?.RunQueriesWithCacheCheck;if(!o)return{success:!1,results:[],errorMessage:"No response from server"};const i=o.results.map(n=>{if((n.status==="stale"||n.status==="no_validation")&&n.Results){const u=JSON.parse(n.Results);return{queryIndex:n.queryIndex,queryId:n.queryId,status:n.status,results:u,maxUpdatedAt:n.maxUpdatedAt,rowCount:n.rowCount,errorMessage:n.errorMessage}}return{queryIndex:n.queryIndex,queryId:n.queryId,status:n.status,maxUpdatedAt:n.maxUpdatedAt,rowCount:n.rowCount,errorMessage:n.errorMessage}});return{success:o.success,results:i,errorMessage:o.errorMessage}}catch(r){return c.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 a={};let o,i;if(e.ViewEntity)i=e.ViewEntity,o=i.Entity;else{const{entityName:l,v:d}=await this.getEntityNameAndUserView(e,t);i=d,o=l}const n=this.Entities.find(l=>l.Name===o);if(!n)throw new Error(`Entity ${o} not found in metadata`);let u=!1;const p=c.getGraphQLTypeNameBase(n);e.ViewID?(r=`Run${p}ViewByID`,s="RunViewByIDInput",a.ViewID=e.ViewID):e.ViewName?(r=`Run${p}ViewByName`,s="RunViewByNameInput",a.ViewName=e.ViewName):(u=!0,r=`Run${p}DynamicView`,s="RunDynamicViewInput",a.EntityName=e.EntityName),a.ExtraFilter=e.ExtraFilter?e.ExtraFilter:"",a.OrderBy=e.OrderBy?e.OrderBy:"",a.UserSearchString=e.UserSearchString?e.UserSearchString:"",a.Fields=e.Fields,a.IgnoreMaxRows=e.IgnoreMaxRows?e.IgnoreMaxRows:!1,e.MaxRows!==void 0&&(a.MaxRows=e.MaxRows),e.StartRow!==void 0&&(a.StartRow=e.StartRow),a.ForceAuditLog=e.ForceAuditLog?e.ForceAuditLog:!1,a.ResultType=e.ResultType?e.ResultType:"simple",e.AuditLogDescription&&e.AuditLogDescription.length>0&&(a.AuditLogDescription=e.AuditLogDescription),u||(a.ExcludeUserViewRunID=e.ExcludeUserViewRunID?e.ExcludeUserViewRunID:"",a.ExcludeDataFromAllPriorViewRuns=e.ExcludeDataFromAllPriorViewRuns?e.ExcludeDataFromAllPriorViewRuns:!1,a.OverrideExcludeFilter=e.OverrideExcludeFilter?e.OverrideExcludeFilter:"",a.SaveViewResults=e.SaveViewResults?e.SaveViewResults:!1);const g=this.getViewRunTimeFieldList(n,i,e,u),I=m.gql`
206
243
  query RunViewQuery ($input: ${s}!) {
207
244
  ${r}(input: $input) {
208
245
  Results {
@@ -216,7 +253,7 @@
216
253
  Success
217
254
  ErrorMessage
218
255
  }
219
- }`,y=await this.ExecuteGQL(R,{input:a});if(y&&y[r]){const l=y[r].Results;if(l&&l.length>0){const I=n.Fields.filter(f=>f.CodeName!==f.Name&&f.CodeName!==void 0);l.forEach(f=>{this.ConvertBackToMJFields(f),I.forEach(D=>{f[D.Name]=f[D.CodeName]})})}return y[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=[],a=[];for(const n of e){let c="",p="";const g={};let R=null,y=null;if(n.ViewEntity)y=n.ViewEntity,R=y.Get("Entity");else{const{entityName:f,v:D}=await this.getEntityNameAndUserView(n,t);y=D,R=f}const l=this.Entities.find(f=>f.Name===R);if(!l)throw new Error(`Entity ${R} not found in metadata`);s.push(l);let d=!1;const I=u.getGraphQLTypeNameBase(l);n.ViewID?(c=`Run${I}ViewByID`,p="RunViewByIDInput",g.ViewID=n.ViewID):n.ViewName?(c=`Run${I}ViewByName`,p="RunViewByNameInput",g.ViewName=n.ViewName):(d=!0,c=`Run${I}DynamicView`,p="RunDynamicViewInput",g.EntityName=n.EntityName),g.ExtraFilter=n.ExtraFilter||"",g.OrderBy=n.OrderBy||"",g.UserSearchString=n.UserSearchString||"",g.Fields=n.Fields,g.IgnoreMaxRows=n.IgnoreMaxRows||!1,n.MaxRows!==void 0&&(g.MaxRows=n.MaxRows),n.StartRow!==void 0&&(g.StartRow=n.StartRow),g.ForceAuditLog=n.ForceAuditLog||!1,g.ResultType=n.ResultType||"simple",n.AuditLogDescription&&n.AuditLogDescription.length>0&&(g.AuditLogDescription=n.AuditLogDescription),d||(g.ExcludeUserViewRunID=n.ExcludeUserViewRunID||"",g.ExcludeDataFromAllPriorViewRuns=n.ExcludeDataFromAllPriorViewRuns||!1,g.OverrideExcludeFilter=n.OverrideExcludeFilter||"",g.SaveViewResults=n.SaveViewResults||!1),r.push(g),a.push(...this.getViewRunTimeFieldList(l,y,n,d))}const o=m.gql`
256
+ }`,y=await this.ExecuteGQL(I,{input:a});if(y&&y[r]){const l=y[r].Results;if(l&&l.length>0){const R=n.Fields.filter(S=>S.CodeName!==S.Name&&S.CodeName!==void 0);l.forEach(S=>{this.ConvertBackToMJFields(S),R.forEach(D=>{S[D.Name]=S[D.CodeName]})})}return y[r]}}else throw"No parameters passed to RunView";return null}catch(r){throw c.LogError(r),r}}async InternalRunViews(e,t){try{let r=[],s=[],a=[];for(const n of e){let u="",p="";const g={};let I=null,y=null;if(n.ViewEntity)y=n.ViewEntity,I=y.Get("Entity");else{const{entityName:S,v:D}=await this.getEntityNameAndUserView(n,t);y=D,I=S}const l=this.Entities.find(S=>S.Name===I);if(!l)throw new Error(`Entity ${I} not found in metadata`);s.push(l);let d=!1;const R=c.getGraphQLTypeNameBase(l);n.ViewID?(u=`Run${R}ViewByID`,p="RunViewByIDInput",g.ViewID=n.ViewID):n.ViewName?(u=`Run${R}ViewByName`,p="RunViewByNameInput",g.ViewName=n.ViewName):(d=!0,u=`Run${R}DynamicView`,p="RunDynamicViewInput",g.EntityName=n.EntityName),g.ExtraFilter=n.ExtraFilter||"",g.OrderBy=n.OrderBy||"",g.UserSearchString=n.UserSearchString||"",g.Fields=n.Fields,g.IgnoreMaxRows=n.IgnoreMaxRows||!1,n.MaxRows!==void 0&&(g.MaxRows=n.MaxRows),n.StartRow!==void 0&&(g.StartRow=n.StartRow),g.ForceAuditLog=n.ForceAuditLog||!1,g.ResultType=n.ResultType||"simple",n.AuditLogDescription&&n.AuditLogDescription.length>0&&(g.AuditLogDescription=n.AuditLogDescription),d||(g.ExcludeUserViewRunID=n.ExcludeUserViewRunID||"",g.ExcludeDataFromAllPriorViewRuns=n.ExcludeDataFromAllPriorViewRuns||!1,g.OverrideExcludeFilter=n.OverrideExcludeFilter||"",g.SaveViewResults=n.SaveViewResults||!1),r.push(g),a.push(...this.getViewRunTimeFieldList(l,y,n,d))}const o=m.gql`
220
257
  query RunViewsQuery ($input: [RunViewGenericInput!]!) {
221
258
  RunViews(input: $input) {
222
259
  Results {
@@ -234,7 +271,7 @@
234
271
  Success
235
272
  ErrorMessage
236
273
  }
237
- }`,i=await this.ExecuteGQL(o,{input:r});if(i&&i.RunViews){const n=i.RunViews;for(const[c,p]of n.entries())p.Results=p.Results.map(g=>{let R=JSON.parse(g.Data);return this.ConvertBackToMJFields(R),R});return n}return null}catch(r){throw u.LogError(r),r}}async RunViewsWithCacheCheck(e,t){try{const r=e.map(n=>({params:{EntityName:n.params.EntityName||"",ExtraFilter:n.params.ExtraFilter||"",OrderBy:n.params.OrderBy||"",Fields:n.params.Fields,UserSearchString:n.params.UserSearchString||"",IgnoreMaxRows:n.params.IgnoreMaxRows||!1,MaxRows:n.params.MaxRows,StartRow:n.params.StartRow,ForceAuditLog:n.params.ForceAuditLog||!1,AuditLogDescription:n.params.AuditLogDescription||"",ResultType:n.params.ResultType||"simple"},cacheStatus:n.cacheStatus?{maxUpdatedAt:n.cacheStatus.maxUpdatedAt,rowCount:n.cacheStatus.rowCount}:null})),s=m.gql`
274
+ }`,i=await this.ExecuteGQL(o,{input:r});if(i&&i.RunViews){const n=i.RunViews;for(const[u,p]of n.entries())p.Results=p.Results.map(g=>{let I=JSON.parse(g.Data);return this.ConvertBackToMJFields(I),I});return n}return null}catch(r){throw c.LogError(r),r}}async RunViewsWithCacheCheck(e,t){try{const r=e.map(n=>({params:{EntityName:n.params.EntityName||"",ExtraFilter:n.params.ExtraFilter||"",OrderBy:n.params.OrderBy||"",Fields:n.params.Fields,UserSearchString:n.params.UserSearchString||"",IgnoreMaxRows:n.params.IgnoreMaxRows||!1,MaxRows:n.params.MaxRows,StartRow:n.params.StartRow,ForceAuditLog:n.params.ForceAuditLog||!1,AuditLogDescription:n.params.AuditLogDescription||"",ResultType:n.params.ResultType||"simple"},cacheStatus:n.cacheStatus?{maxUpdatedAt:n.cacheStatus.maxUpdatedAt,rowCount:n.cacheStatus.rowCount}:null})),s=m.gql`
238
275
  query RunViewsWithCacheCheckQuery($input: [RunViewWithCacheCheckInput!]!) {
239
276
  RunViewsWithCacheCheck(input: $input) {
240
277
  success
@@ -256,7 +293,7 @@
256
293
  }
257
294
  }
258
295
  }
259
- `,o=(await this.ExecuteGQL(s,{input:r}))?.RunViewsWithCacheCheck;if(!o)return{success:!1,results:[],errorMessage:"No response from server"};const i=o.results.map((n,c)=>{const p=e[c];if(n.status==="stale"&&n.Results){const g=p.params.EntityName,R=this.Entities.find(l=>l.Name===g),y=n.Results.map(l=>{const d=JSON.parse(l.Data);return this.ConvertBackToMJFields(d),d});return{viewIndex:n.viewIndex,status:n.status,results:y,maxUpdatedAt:n.maxUpdatedAt,rowCount:n.rowCount,errorMessage:n.errorMessage}}return{viewIndex:n.viewIndex,status:n.status,results:void 0,maxUpdatedAt:n.maxUpdatedAt,rowCount:n.rowCount,errorMessage:n.errorMessage}});return{success:o.success,results:i,errorMessage:o.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 pe.ViewInfo.GetViewEntity(e.ViewID,t),r=s.Entity;else if(e.ViewName)s=await pe.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 a=[],o=new C;if(r.Fields){for(const i of e.PrimaryKeys)r.Fields.find(n=>n.trim().toLowerCase()===i.Name.toLowerCase())===void 0&&a.push(i.Name);r.Fields.forEach(i=>{a.push(o.MapFieldName(i))})}else if(s)e.Fields.forEach(i=>{i.IsBinaryFieldType||a.push(o.MapFieldName(i.CodeName))});else{for(const i of e.PrimaryKeys)a.find(n=>n.trim().toLowerCase()===i.Name.toLowerCase())===void 0&&a.push(i.Name);t.Columns.forEach(i=>{i.hidden===!1&&!a.find(n=>n.trim().toLowerCase()===i.EntityField?.Name.trim().toLowerCase())&&i.EntityField&&a.push(o.MapFieldName(i.EntityField.CodeName))})}return a}get ProviderType(){return u.ProviderType.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((a,o)=>a.ChangedAt>o.ChangedAt?-1:1):null}catch(r){throw u.LogError(r),r}}async GetRecordDependencies(e,t){try{const r=m.gql`query GetRecordDependenciesQuery ($entityName: String!, $CompositeKey: CompositeKeyInputType!) {
296
+ `,o=(await this.ExecuteGQL(s,{input:r}))?.RunViewsWithCacheCheck;if(!o)return{success:!1,results:[],errorMessage:"No response from server"};const i=o.results.map((n,u)=>{const p=e[u];if(n.status==="stale"&&n.Results){const g=p.params.EntityName,I=this.Entities.find(l=>l.Name===g),y=n.Results.map(l=>{const d=JSON.parse(l.Data);return this.ConvertBackToMJFields(d),d});return{viewIndex:n.viewIndex,status:n.status,results:y,maxUpdatedAt:n.maxUpdatedAt,rowCount:n.rowCount,errorMessage:n.errorMessage}}return{viewIndex:n.viewIndex,status:n.status,results:void 0,maxUpdatedAt:n.maxUpdatedAt,rowCount:n.rowCount,errorMessage:n.errorMessage}});return{success:o.success,results:i,errorMessage:o.errorMessage}}catch(r){return c.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 pe.ViewInfo.GetViewEntity(e.ViewID,t),r=s.Entity;else if(e.ViewName)s=await pe.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 a=[],o=new P;if(r.Fields){for(const i of e.PrimaryKeys)r.Fields.find(n=>n.trim().toLowerCase()===i.Name.toLowerCase())===void 0&&a.push(i.Name);r.Fields.forEach(i=>{a.push(o.MapFieldName(i))})}else if(s)e.Fields.forEach(i=>{i.IsBinaryFieldType||a.push(o.MapFieldName(i.CodeName))});else{for(const i of e.PrimaryKeys)a.find(n=>n.trim().toLowerCase()===i.Name.toLowerCase())===void 0&&a.push(i.Name);t.Columns.forEach(i=>{i.hidden===!1&&!a.find(n=>n.trim().toLowerCase()===i.EntityField?.Name.trim().toLowerCase())&&i.EntityField&&a.push(o.MapFieldName(i.EntityField.CodeName))})}return a}get ProviderType(){return c.ProviderType.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((a,o)=>a.ChangedAt>o.ChangedAt?-1:1):null}catch(r){throw c.LogError(r),r}}async GetRecordDependencies(e,t){try{const r=m.gql`query GetRecordDependenciesQuery ($entityName: String!, $CompositeKey: CompositeKeyInputType!) {
260
297
  GetRecordDependencies(entityName: $entityName, CompositeKey: $CompositeKey) {
261
298
  EntityName
262
299
  RelatedEntityName
@@ -268,7 +305,7 @@
268
305
  }
269
306
  }
270
307
  }
271
- }`,s={entityName:e,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(t.KeyValuePairs)}};return(await this.ExecuteGQL(r,s))?.GetRecordDependencies}catch(r){throw u.LogError(r),r}}ensureKeyValuePairValueIsString(e){return e.map(t=>({FieldName:t.FieldName,Value:t.Value.toString()}))}async GetRecordDuplicates(e,t){if(!e)return null;const r=m.gql`query GetRecordDuplicatesQuery ($params: PotentialDuplicateRequestType!) {
308
+ }`,s={entityName:e,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(t.KeyValuePairs)}};return(await this.ExecuteGQL(r,s))?.GetRecordDependencies}catch(r){throw c.LogError(r),r}}ensureKeyValuePairValueIsString(e){return e.map(t=>({FieldName:t.FieldName,Value:t.Value.toString()}))}async GetRecordDuplicates(e,t){if(!e)return null;const r=m.gql`query GetRecordDuplicatesQuery ($params: PotentialDuplicateRequestType!) {
272
309
  GetRecordDuplicates(params: $params) {
273
310
  Status
274
311
  ErrorMessage
@@ -307,32 +344,32 @@
307
344
  Message
308
345
  }
309
346
  }
310
- }`,o={EntityName:e.EntityName,SurvivingRecordCompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(e.SurvivingRecordCompositeKey.KeyValuePairs)},FieldMap:e.FieldMap?.map(n=>({FieldName:n.FieldName,Value:n.Value.toString()})),RecordsToMerge:e.RecordsToMerge.map(n=>n.Copy())};return(await this.ExecuteGQL(a,{request:o}))?.MergeRecords}catch(a){return u.LogError(a),{Success:!1,OverallStatus:a&&a.message?a.message:a,RecordStatus:[],RecordMergeLogID:"",Request:e}}}async Save(e,t,r){const s=new u.BaseEntityResult;try{e.RegisterTransactionPreprocessing();const a={input:{}},o=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 i=u.getGraphQLTypeNameBase(e.EntityInfo),n=`${o}${i}`,c=e.Fields.filter(y=>!y.ReadOnly||y.IsPrimaryKey&&e.IsSaved),p=new C,g=` ${n}(input: $input) {
347
+ }`,o={EntityName:e.EntityName,SurvivingRecordCompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(e.SurvivingRecordCompositeKey.KeyValuePairs)},FieldMap:e.FieldMap?.map(n=>({FieldName:n.FieldName,Value:n.Value.toString()})),RecordsToMerge:e.RecordsToMerge.map(n=>n.Copy())};return(await this.ExecuteGQL(a,{request:o}))?.MergeRecords}catch(a){return c.LogError(a),{Success:!1,OverallStatus:a&&a.message?a.message:a,RecordStatus:[],RecordMergeLogID:"",Request:e}}}async Save(e,t,r){const s=new c.BaseEntityResult;try{e.RegisterTransactionPreprocessing();const a={input:{}},o=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 i=c.getGraphQLTypeNameBase(e.EntityInfo),n=`${o}${i}`,u=e.Fields.filter(y=>!y.ReadOnly||y.IsPrimaryKey&&e.IsSaved),p=new P,g=` ${n}(input: $input) {
311
348
  ${e.Fields.map(y=>p.MapFieldName(y.CodeName)).join(`
312
349
  `)}
313
- }`,R=m.gql`mutation ${o}${i} ($input: ${n}Input!) {
350
+ }`,I=m.gql`mutation ${o}${i} ($input: ${n}Input!) {
314
351
  ${g}
315
352
  }
316
- `;for(let y=0;y<c.length;y++){const l=c[y];let d=l.Value;if(d)switch(l.EntityFieldInfo.TSType){case u.EntityFieldTSType.Date:d=d.getTime();break;case u.EntityFieldTSType.Boolean:typeof d!="boolean"&&(d=parseInt(d)!==0);break;case u.EntityFieldTSType.Number:if(typeof d!="number"){const I=Number(d);isNaN(I)||(d=I)}break}d===null&&l.EntityFieldInfo.AllowsNull===!1&&(l.EntityFieldInfo.DefaultValue!==null?d=l.EntityFieldInfo.DefaultValue:l.FieldType===u.EntityFieldTSType.Number||l.FieldType===u.EntityFieldTSType.Boolean?d=0:d=""),a.input[l.CodeName]=d}if(o.trim().toLowerCase()==="update"&&r.SkipOldValuesCheck===!1){const y=[];e.Fields.forEach(l=>{let d=null;l.OldValue!==null&&l.OldValue!==void 0&&(l.EntityFieldInfo.TSType===u.EntityFieldTSType.Date?d=l.OldValue.getTime().toString():l.EntityFieldInfo.TSType===u.EntityFieldTSType.Boolean?d=l.OldValue===!0?"1":"0":typeof l.OldValue!="string"?d=l.OldValue.toString():d=l.OldValue),y.push({Key:l.CodeName,Value:d})}),a.input.OldValues___=y}if(e.TransactionGroup){const y=[{varName:"input",inputType:n+"Input!"}];return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new u.TransactionItem(e,s.Type==="create"?"Create":"Update",g,a,{mutationName:n,mutationInputTypes:y},(l,d)=>{s.EndedAt=new Date,d&&l?(s.Success=!0,s.NewValues=this.ConvertBackToMJFields(l)):(s.Success=!1,s.Message="Transaction failed")})),!0}else{const y=await this.ExecuteGQL(R,a);if(y&&y[n])return s.Success=!0,s.EndedAt=new Date,s.NewValues=this.ConvertBackToMJFields(y[n]),s.NewValues;throw new Error(`Save failed for ${e.EntityInfo.ClassName}`)}}catch(a){return s.Success=!1,s.EndedAt=new Date,s.Message=a.response?.errors?.length>0?a.response.errors[0].message:a.message,u.LogError(a),null}}async Load(e,t,r=null,s){try{const a={};let o="",i="";for(let y=0;y<t.KeyValuePairs.length;y++){const l=e.Fields.find(f=>f.Name.trim().toLowerCase()===t.KeyValuePairs[y].FieldName.trim().toLowerCase()).EntityFieldInfo,d=t.GetValueByIndex(y),I=l.GraphQLType;if(i.length>0&&(i+=", "),i+=`$${l.CodeName}: ${I}!`,o.length>0&&(o+=", "),o+=`${l.CodeName}: $${l.CodeName}`,l.TSType===u.EntityFieldTSType.Number){if(isNaN(t.GetValueByIndex(y)))throw new Error(`Primary Key value ${d} (${l.Name}) is not a valid number`);a[l.CodeName]=parseInt(d)}else a[l.CodeName]=d}const n=r&&r.length>0?this.getRelatedEntityString(e.EntityInfo,r):"",c=u.getGraphQLTypeNameBase(e.EntityInfo),p=new C,g=m.gql`query Single${c}${n.length>0?"Full":""} (${i}) {
317
- ${c}(${o}) {
353
+ `;for(let y=0;y<u.length;y++){const l=u[y];let d=l.Value;if(d)switch(l.EntityFieldInfo.TSType){case c.EntityFieldTSType.Date:d=d.getTime();break;case c.EntityFieldTSType.Boolean:typeof d!="boolean"&&(d=parseInt(d)!==0);break;case c.EntityFieldTSType.Number:if(typeof d!="number"){const R=Number(d);isNaN(R)||(d=R)}break}d===null&&l.EntityFieldInfo.AllowsNull===!1&&(l.EntityFieldInfo.DefaultValue!==null?d=l.EntityFieldInfo.DefaultValue:l.FieldType===c.EntityFieldTSType.Number||l.FieldType===c.EntityFieldTSType.Boolean?d=0:d=""),a.input[l.CodeName]=d}if(o.trim().toLowerCase()==="update"&&r.SkipOldValuesCheck===!1){const y=[];e.Fields.forEach(l=>{let d=null;l.OldValue!==null&&l.OldValue!==void 0&&(l.EntityFieldInfo.TSType===c.EntityFieldTSType.Date?d=l.OldValue.getTime().toString():l.EntityFieldInfo.TSType===c.EntityFieldTSType.Boolean?d=l.OldValue===!0?"1":"0":typeof l.OldValue!="string"?d=l.OldValue.toString():d=l.OldValue),y.push({Key:l.CodeName,Value:d})}),a.input.OldValues___=y}if(e.TransactionGroup){const y=[{varName:"input",inputType:n+"Input!"}];return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new c.TransactionItem(e,s.Type==="create"?"Create":"Update",g,a,{mutationName:n,mutationInputTypes:y},(l,d)=>{s.EndedAt=new Date,d&&l?(s.Success=!0,s.NewValues=this.ConvertBackToMJFields(l)):(s.Success=!1,s.Message="Transaction failed")})),!0}else{const y=await this.ExecuteGQL(I,a);if(y&&y[n])return s.Success=!0,s.EndedAt=new Date,s.NewValues=this.ConvertBackToMJFields(y[n]),s.NewValues;throw new Error(`Save failed for ${e.EntityInfo.ClassName}`)}}catch(a){return s.Success=!1,s.EndedAt=new Date,s.Message=a.response?.errors?.length>0?a.response.errors[0].message:a.message,c.LogError(a),null}}async Load(e,t,r=null,s){try{const a={};let o="",i="";for(let y=0;y<t.KeyValuePairs.length;y++){const l=e.Fields.find(S=>S.Name.trim().toLowerCase()===t.KeyValuePairs[y].FieldName.trim().toLowerCase()).EntityFieldInfo,d=t.GetValueByIndex(y),R=l.GraphQLType;if(i.length>0&&(i+=", "),i+=`$${l.CodeName}: ${R}!`,o.length>0&&(o+=", "),o+=`${l.CodeName}: $${l.CodeName}`,l.TSType===c.EntityFieldTSType.Number){if(isNaN(t.GetValueByIndex(y)))throw new Error(`Primary Key value ${d} (${l.Name}) is not a valid number`);a[l.CodeName]=parseInt(d)}else a[l.CodeName]=d}const n=r&&r.length>0?this.getRelatedEntityString(e.EntityInfo,r):"",u=c.getGraphQLTypeNameBase(e.EntityInfo),p=new P,g=m.gql`query Single${u}${n.length>0?"Full":""} (${i}) {
354
+ ${u}(${o}) {
318
355
  ${e.Fields.filter(y=>!y.EntityFieldInfo.IsBinaryFieldType).map(y=>y.EntityFieldInfo.Name.trim().toLowerCase().startsWith("__mj_")?y.CodeName.replace("__mj_","_mj__"):y.CodeName).join(`
319
356
  `)}
320
357
  ${n}
321
358
  }
322
359
  }
323
- `,R=await this.ExecuteGQL(g,a);return R&&R[c]?this.ConvertBackToMJFields(R[c]):null}catch(a){return u.LogError(a),null}}ConvertBackToMJFields(e){return new C().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 a=e.RelatedEntities[s],o=this.Entities.find(n=>n.ID===a.RelatedEntityID);let i="";a.Type.toLowerCase().trim()==="many to many"?i=`${a.RelatedEntityCodeName}_${a.JoinEntityJoinField.replace(/\s/g,"")}`:i=`${a.RelatedEntityCodeName}_${a.RelatedEntityJoinField.replace(/\s/g,"")}`,r+=`
360
+ `,I=await this.ExecuteGQL(g,a);return I&&I[u]?this.ConvertBackToMJFields(I[u]):null}catch(a){return c.LogError(a),null}}ConvertBackToMJFields(e){return new P().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 a=e.RelatedEntities[s],o=this.Entities.find(n=>n.ID===a.RelatedEntityID);let i="";a.Type.toLowerCase().trim()==="many to many"?i=`${a.RelatedEntityCodeName}_${a.JoinEntityJoinField.replace(/\s/g,"")}`:i=`${a.RelatedEntityCodeName}_${a.RelatedEntityJoinField.replace(/\s/g,"")}`,r+=`
324
361
  ${i} {
325
362
  ${o.Fields.map(n=>n.CodeName).join(`
326
363
  `)}
327
364
  }
328
- `}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(l=>({FieldName:l.CodeName,Value:l.Value})),e.ResultHistory.push(s);const a={},o=[];let i="",n="",c="";for(let l of e.PrimaryKey.KeyValuePairs){const d=e.Fields.find(I=>I.Name.trim().toLowerCase()===l.FieldName.trim().toLowerCase());a[d.CodeName]=d.Value,o.push({varName:d.CodeName,inputType:d.EntityFieldInfo.GraphQLType+"!"}),i.length>0&&(i+=", "),i+=`${d.CodeName}: $${d.CodeName}`,n.length>0&&(n+=", "),n+=`$${d.CodeName}: ${d.EntityFieldInfo.GraphQLType}!`,c.length>0&&(c+=`
329
- `),c+=`${d.CodeName}`}o.push({varName:"options___",inputType:"DeleteOptionsInput!"}),a.options___=t||{SkipEntityAIActions:!1,SkipEntityActions:!1};const g="Delete"+u.getGraphQLTypeNameBase(e.EntityInfo),R=m.gql`${g}(${i}, options___: $options___) {
330
- ${c}
365
+ `}return r}async Delete(e,t,r){const s=new c.BaseEntityResult;try{e.RegisterTransactionPreprocessing(),s.StartedAt=new Date,s.Type="delete",s.OriginalValues=e.Fields.map(l=>({FieldName:l.CodeName,Value:l.Value})),e.ResultHistory.push(s);const a={},o=[];let i="",n="",u="";for(let l of e.PrimaryKey.KeyValuePairs){const d=e.Fields.find(R=>R.Name.trim().toLowerCase()===l.FieldName.trim().toLowerCase());a[d.CodeName]=d.Value,o.push({varName:d.CodeName,inputType:d.EntityFieldInfo.GraphQLType+"!"}),i.length>0&&(i+=", "),i+=`${d.CodeName}: $${d.CodeName}`,n.length>0&&(n+=", "),n+=`$${d.CodeName}: ${d.EntityFieldInfo.GraphQLType}!`,u.length>0&&(u+=`
366
+ `),u+=`${d.CodeName}`}o.push({varName:"options___",inputType:"DeleteOptionsInput!"}),a.options___=t||{SkipEntityAIActions:!1,SkipEntityActions:!1};const g="Delete"+c.getGraphQLTypeNameBase(e.EntityInfo),I=m.gql`${g}(${i}, options___: $options___) {
367
+ ${u}
331
368
  }
332
369
  `,y=m.gql`mutation ${g} (${n}, $options___: DeleteOptionsInput!) {
333
- ${R}
370
+ ${I}
334
371
  }
335
- `;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new u.TransactionItem(e,"Delete",R,a,{mutationName:g,mutationInputTypes:o},(l,d)=>{if(s.EndedAt=new Date,d&&l){let I=!0;for(const f of e.PrimaryKey.KeyValuePairs)f.Value!==l[f.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 l=await this.ExecuteGQL(y,a);if(l&&l[g]){const d=l[g];for(let I of e.PrimaryKey.KeyValuePairs){let f=d[I.FieldName],D=I.Value;if(typeof D=="number"&&(D=D.toString()),typeof f=="number"&&(f=f.toString()),D!==f)throw new Error(`Primary key value mismatch in server Delete response. Field: ${I.FieldName}, Original: ${D}, Returned: ${f}`)}return s.Success=!0,s.EndedAt=new Date,!0}else throw new Error(`Delete failed for ${e.EntityInfo.Name}: ${e.PrimaryKey.ToString()} `)}}catch(a){return s.EndedAt=new Date,s.Success=!1,s.Message=a.response?.errors?.length>0?a.response.errors[0].message:a.message,u.LogError(a),!1}}async GetDatasetByName(e,t){const r=m.gql`query GetDatasetByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
372
+ `;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new c.TransactionItem(e,"Delete",I,a,{mutationName:g,mutationInputTypes:o},(l,d)=>{if(s.EndedAt=new Date,d&&l){let R=!0;for(const S of e.PrimaryKey.KeyValuePairs)S.Value!==l[S.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 l=await this.ExecuteGQL(y,a);if(l&&l[g]){const d=l[g];for(let R of e.PrimaryKey.KeyValuePairs){let S=d[R.FieldName],D=R.Value;if(typeof D=="number"&&(D=D.toString()),typeof S=="number"&&(S=S.toString()),D!==S)throw new Error(`Primary key value mismatch in server Delete response. Field: ${R.FieldName}, Original: ${D}, 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(a){return s.EndedAt=new Date,s.Success=!1,s.Message=a.response?.errors?.length>0?a.response.errors[0].message:a.message,c.LogError(a),!1}}async GetDatasetByName(e,t){const r=m.gql`query GetDatasetByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
336
373
  GetDatasetByName(DatasetName: $DatasetName, ItemFilters: $ItemFilters) {
337
374
  DatasetID
338
375
  DatasetName
@@ -350,12 +387,12 @@
350
387
  LatestUpdateDate
351
388
  EntityUpdateDates
352
389
  }
353
- }`,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 v(this)}async GetRecordFavoriteStatus(e,t,r){if(!r.Validate().IsValid)return!1;const a=this.Entities.find(n=>n.Name===t);if(!a)throw new Error(`Entity ${t} not found in metadata`);const o=m.gql`query GetRecordFavoriteStatus($params: UserFavoriteSearchParams!) {
390
+ }`,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 C(this)}async GetRecordFavoriteStatus(e,t,r){if(!r.Validate().IsValid)return!1;const a=this.Entities.find(n=>n.Name===t);if(!a)throw new Error(`Entity ${t} not found in metadata`);const o=m.gql`query GetRecordFavoriteStatus($params: UserFavoriteSearchParams!) {
354
391
  GetRecordFavoriteStatus(params: $params) {
355
392
  Success
356
393
  IsFavorite
357
394
  }
358
- }`,i=await this.ExecuteGQL(o,{params:{UserID:e,EntityID:a.ID,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(r.KeyValuePairs)}}});if(i&&i.GetRecordFavoriteStatus&&i.GetRecordFavoriteStatus.Success)return i.GetRecordFavoriteStatus.IsFavorite}async SetRecordFavoriteStatus(e,t,r,s,a){const o=this.Entities.find(c=>c.Name===t);if(!o)throw new Error(`Entity ${t} not found in metadata`);const i=m.gql`mutation SetRecordFavoriteStatus($params: UserFavoriteSetParams!) {
395
+ }`,i=await this.ExecuteGQL(o,{params:{UserID:e,EntityID:a.ID,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(r.KeyValuePairs)}}});if(i&&i.GetRecordFavoriteStatus&&i.GetRecordFavoriteStatus.Success)return i.GetRecordFavoriteStatus.IsFavorite}async SetRecordFavoriteStatus(e,t,r,s,a){const o=this.Entities.find(u=>u.Name===t);if(!o)throw new Error(`Entity ${t} not found in metadata`);const i=m.gql`mutation SetRecordFavoriteStatus($params: UserFavoriteSetParams!) {
359
396
  SetRecordFavoriteStatus(params: $params){
360
397
  Success
361
398
  }
@@ -384,29 +421,29 @@
384
421
  ErrorMessages
385
422
  Results
386
423
  }
387
- }`,r=await this.ExecuteGQL(t,{DataContextID:e});if(r&&r.GetDataContextData){if(r.GetDataContextData.Success)return r.GetDataContextData.Results.map(s=>JSON.parse(s));throw new Error(r.GetDataContextData.ErrorMessages.join(", "))}else throw new Error("GraphQL query failed")}catch(t){throw u.LogError(t),t}}async GetDataContextItemData(e){try{const t=m.gql`query GetDataContextItemData ($DataContextItemID: String!) {
424
+ }`,r=await this.ExecuteGQL(t,{DataContextID:e});if(r&&r.GetDataContextData){if(r.GetDataContextData.Success)return r.GetDataContextData.Results.map(s=>JSON.parse(s));throw new Error(r.GetDataContextData.ErrorMessages.join(", "))}else throw new Error("GraphQL query failed")}catch(t){throw c.LogError(t),t}}async GetDataContextItemData(e){try{const t=m.gql`query GetDataContextItemData ($DataContextItemID: String!) {
388
425
  GetDataContextItemData(DataContextItemID: $DataContextItemID) {
389
426
  Success
390
427
  ErrorMessage
391
428
  Result
392
429
  }
393
- }`,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 h.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=h.Instance&&h.Instance._configData===this._configData;if(e&&h.Instance._refreshPromise)return h.Instance._refreshPromise;if(this._refreshPromise)return 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 a={"x-session-id":r};return t&&(a.authorization="Bearer "+t),s&&(a["x-mj-api-key"]=s),new m.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__")+`
430
+ }`,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 c.LogError(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.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 c.LogError("JWT_EXPIRED and refreshTokenIfNeeded is false"),s}else throw s;else throw c.LogError(s),s}}async RefreshToken(){const e=h.Instance&&h.Instance._configData===this._configData;if(e&&h.Instance._refreshPromise)return h.Instance._refreshPromise;if(this._refreshPromise)return 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 a={"x-session-id":r};return t&&(a.authorization="Bearer "+t),s&&(a["x-mj-api-key"]=s),new m.GraphQLClient(e,{headers:a})}userInfoString(){return this.infoString(new c.UserInfo(null,null))}userRoleInfoString(){return this.infoString(new c.UserRoleInfo(null))}infoString(e){let t="";const r=Object.keys(e);for(const s of r)s.startsWith("__mj_")?t+=s.replace("__mj_","_mj__")+`
394
431
  `:s.startsWith("_")||(t+=s+`
395
- `);return t}get LocalStorageProvider(){return this._localStorageProvider||(this._localStorageProvider=new x),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=Ie.createClient({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(([a,o])=>{const i=e-o.lastRequestedAt,n=e-o.lastEmissionAt;o.activeSubscribers===0&&i>=this.SUBSCRIPTION_IDLE_TIMEOUT_MS&&n>=this.SUBSCRIPTION_IDLE_TIMEOUT_MS&&(console.log(`[GraphQLDataProvider] Marking session ${a} for cleanup: activeSubscribers=${o.activeSubscribers}, timeSinceRequested=${Math.round(i/1e3)}s, timeSinceEmission=${Math.round(n/1e3)}s`),s.push(a))}),s.forEach(a=>{const o=this._pushStatusSubjects.get(a);if(o)try{o.subject.complete(),o.subscription.unsubscribe(),this._pushStatusSubjects.delete(a),console.log(`[GraphQLDataProvider] Cleaned up stale subscription for session: ${a}`)}catch(i){console.error(`[GraphQLDataProvider] Error cleaning up subscription for ${a}:`,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 $.Observable(r=>{const s=this.getOrCreateWSClient();this._activeSubscriptionCount++;const a=s.subscribe({query:e,variables:t},{next:o=>{r.next(o.data)},error:async o=>{const i=o;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(o)},complete:()=>{r.complete()}});return()=>{this._activeSubscriptionCount--,a()}})}PushStatusUpdates(e=null){e||(e=this.sessionId);const t=Date.now(),r=this._pushStatusSubjects.get(e);if(r)return r.lastRequestedAt=t,new $.Observable(n=>{r.activeSubscribers++;const c=r.subject.subscribe(n);return()=>{const p=this._pushStatusSubjects.get(e);p&&p.activeSubscribers>0&&p.activeSubscribers--,c.unsubscribe()}});const s=m.gql`subscription StatusUpdates($sessionId: String!) {
432
+ `);return t}get LocalStorageProvider(){return this._localStorageProvider||(this._localStorageProvider=new x),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=Re.createClient({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(([a,o])=>{const i=e-o.lastRequestedAt,n=e-o.lastEmissionAt;o.activeSubscribers===0&&i>=this.SUBSCRIPTION_IDLE_TIMEOUT_MS&&n>=this.SUBSCRIPTION_IDLE_TIMEOUT_MS&&(console.log(`[GraphQLDataProvider] Marking session ${a} for cleanup: activeSubscribers=${o.activeSubscribers}, timeSinceRequested=${Math.round(i/1e3)}s, timeSinceEmission=${Math.round(n/1e3)}s`),s.push(a))}),s.forEach(a=>{const o=this._pushStatusSubjects.get(a);if(o)try{o.subject.complete(),o.subscription.unsubscribe(),this._pushStatusSubjects.delete(a),console.log(`[GraphQLDataProvider] Cleaned up stale subscription for session: ${a}`)}catch(i){console.error(`[GraphQLDataProvider] Error cleaning up subscription for ${a}:`,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 a=s.subscribe({query:e,variables:t},{next:o=>{r.next(o.data)},error:async o=>{const i=o;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(u){console.error("[GraphQLDataProvider] Failed to refresh token for WebSocket:",u),r.error(u)}}else r.error(o)},complete:()=>{r.complete()}});return()=>{this._activeSubscriptionCount--,a()}})}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(n=>{r.activeSubscribers++;const u=r.subject.subscribe(n);return()=>{const p=this._pushStatusSubjects.get(e);p&&p.activeSubscribers>0&&p.activeSubscribers--,u.unsubscribe()}});const s=m.gql`subscription StatusUpdates($sessionId: String!) {
396
433
  statusUpdates(sessionId: $sessionId) {
397
434
  date
398
435
  message
399
436
  sessionId
400
437
  }
401
438
  }
402
- `,a=new $.Subject,o=this.getOrCreateWSClient(),i=new $.Subscription;return i.add(new $.Observable(n=>{const c=o.subscribe({query:s,variables:{sessionId:e}},{next:p=>{const g=this._pushStatusSubjects.get(e);g&&(g.lastEmissionAt=Date.now()),n.next(p.data.statusUpdates.message)},error:async p=>{const g=p;if(g?.extensions?.code==="JWT_EXPIRED"||g?.message?.includes("token has expired")||g?.message?.includes("JWT_EXPIRED")){console.log("[GraphQLDataProvider] PushStatusUpdates JWT token expired, refreshing and reconnecting...");try{await this.RefreshToken(),this.disposeWSClient(),n.complete()}catch(y){console.error("[GraphQLDataProvider] Failed to refresh token for PushStatusUpdates:",y),n.error(y)}}else n.error(p)},complete:()=>{n.complete()}});return this._activeSubscriptionCount++,()=>{this._activeSubscriptionCount--,c()}}).subscribe({next:n=>a.next(n),error:n=>{a.error(n),this._pushStatusSubjects.delete(e)},complete:()=>{a.complete(),this._pushStatusSubjects.delete(e)}})),this._pushStatusSubjects.set(e,{subject:a,subscription:i,createdAt:t,lastRequestedAt:t,lastEmissionAt:t,activeSubscribers:0}),new $.Observable(n=>{const c=this._pushStatusSubjects.get(e);c&&c.activeSubscribers++;const p=a.subscribe(n);return()=>{const g=this._pushStatusSubjects.get(e);g&&g.activeSubscribers>0&&g.activeSubscribers--,p.unsubscribe()}})}disposeWebSocketResources(){this._subscriptionCleanupTimer&&(clearInterval(this._subscriptionCleanupTimer),this._subscriptionCleanupTimer=null),this.completeAllSubjects(),this._activeSubscriptionCount=0,this.disposeWSClient()}};S(h,"GraphQLDataProvider");let L=h;async function Ce(E){const e=new L;return u.SetProvider(e),await e.Config(E),await u.StartupManager.Instance.Startup(),w.MJGlobal.Instance.RaiseEvent({event:w.MJEventType.LoggedIn,eventCode:null,component:this,args:null}),e}S(Ce,"setupGraphQLClient");const ee=class ee{};S(ee,"SyncRolesAndUsersResult");let M=ee;const te=class te{};S(te,"RoleInput");let V=te;const re=class re{};S(re,"UserInput");let A=re;const se=class se{};S(se,"RolesAndUsersInput");let Q=se;var fe=(E=>(E.Create="Create",E.Update="Update",E.CreateOrUpdate="CreateOrUpdate",E.Delete="Delete",E.DeleteWithFilter="DeleteWithFilter",E))(fe||{});const ae=class ae{};S(ae,"ActionItemInput");let G=ae;const ne=class ne{constructor(){this.Results=[]}};S(ne,"SyncDataResult");let F=ne;const oe=class oe{};S(oe,"ActionItemOutput");let U=oe;const ie=class ie{get Client(){return this._client}constructor(e,t,r,s){const a={"x-session-id":r};this._sessionId=r,t&&(a.authorization="Bearer "+t),s&&(a["x-mj-api-key"]=s),this._client=new m.GraphQLClient(e,{headers:a})}async GetData(e,t){try{const s=await this.Client.request(`query GetData($input: GetDataInputType!) {
439
+ `,a=new v.Subject,o=this.getOrCreateWSClient(),i=new v.Subscription;return i.add(new v.Observable(n=>{const u=o.subscribe({query:s,variables:{sessionId:e}},{next:p=>{const g=this._pushStatusSubjects.get(e);g&&(g.lastEmissionAt=Date.now()),n.next(p.data.statusUpdates.message)},error:async p=>{const g=p;if(g?.extensions?.code==="JWT_EXPIRED"||g?.message?.includes("token has expired")||g?.message?.includes("JWT_EXPIRED")){console.log("[GraphQLDataProvider] PushStatusUpdates JWT token expired, refreshing and reconnecting...");try{await this.RefreshToken(),this.disposeWSClient(),n.complete()}catch(y){console.error("[GraphQLDataProvider] Failed to refresh token for PushStatusUpdates:",y),n.error(y)}}else n.error(p)},complete:()=>{n.complete()}});return this._activeSubscriptionCount++,()=>{this._activeSubscriptionCount--,u()}}).subscribe({next:n=>a.next(n),error:n=>{a.error(n),this._pushStatusSubjects.delete(e)},complete:()=>{a.complete(),this._pushStatusSubjects.delete(e)}})),this._pushStatusSubjects.set(e,{subject:a,subscription:i,createdAt:t,lastRequestedAt:t,lastEmissionAt:t,activeSubscribers:0}),new v.Observable(n=>{const u=this._pushStatusSubjects.get(e);u&&u.activeSubscribers++;const p=a.subscribe(n);return()=>{const g=this._pushStatusSubjects.get(e);g&&g.activeSubscribers>0&&g.activeSubscribers--,p.unsubscribe()}})}disposeWebSocketResources(){this._subscriptionCleanupTimer&&(clearInterval(this._subscriptionCleanupTimer),this._subscriptionCleanupTimer=null),this.completeAllSubjects(),this._activeSubscriptionCount=0,this.disposeWSClient()}};f(h,"GraphQLDataProvider");let L=h;async function Pe(E){const e=new L;return c.SetProvider(e),await e.Config(E),await c.StartupManager.Instance.Startup(),w.MJGlobal.Instance.RaiseEvent({event:w.MJEventType.LoggedIn,eventCode:null,component:this,args:null}),e}f(Pe,"setupGraphQLClient");const ee=class ee{};f(ee,"SyncRolesAndUsersResult");let A=ee;const te=class te{};f(te,"RoleInput");let M=te;const re=class re{};f(re,"UserInput");let V=re;const se=class se{};f(se,"RolesAndUsersInput");let Q=se;var Se=(E=>(E.Create="Create",E.Update="Update",E.CreateOrUpdate="CreateOrUpdate",E.Delete="Delete",E.DeleteWithFilter="DeleteWithFilter",E))(Se||{});const ae=class ae{};f(ae,"ActionItemInput");let G=ae;const ne=class ne{constructor(){this.Results=[]}};f(ne,"SyncDataResult");let F=ne;const oe=class oe{};f(oe,"ActionItemOutput");let U=oe;const ie=class ie{get Client(){return this._client}constructor(e,t,r,s){const a={"x-session-id":r};this._sessionId=r,t&&(a.authorization="Bearer "+t),s&&(a["x-mj-api-key"]=s),this._client=new m.GraphQLClient(e,{headers:a})}async GetData(e,t){try{const s=await this.Client.request(`query GetData($input: GetDataInputType!) {
403
440
  GetData(input: $input) {
404
441
  Success
405
442
  ErrorMessages
406
443
  Queries
407
444
  Results
408
445
  }
409
- }`,{input:{Queries:e,Token:t}});return s&&s.GetData?{Success:s.GetData.Success,Results:s.GetData.Results.map(a=>a?w.SafeJSONParse(a):null),ErrorMessages:s.GetData.ErrorMessages,Queries:s.GetData.Queries}:{Success:!1,Results:[],ErrorMessages:s.GetData?.ErrorMessages??["Unknown error"],Queries:s.GetData?.Queries??e}}catch(r){let s=r instanceof Error?r.message:String(r);const a=s.match(/Error: ([^:]+)\./);if(a&&(s=a[1]+"."),u.IsVerboseLoggingEnabled()){const o=`GraphQLSystemUserClient::GetData - Error getting data - ${r}`;u.LogError(o)}return{Success:!1,Results:[],ErrorMessages:[s],Queries:e}}}async GetAllRemoteEntities(){try{const t=await this.Client.request(`query GetAllEntities {
446
+ }`,{input:{Queries:e,Token:t}});return s&&s.GetData?{Success:s.GetData.Success,Results:s.GetData.Results.map(a=>a?w.SafeJSONParse(a):null),ErrorMessages:s.GetData.ErrorMessages,Queries:s.GetData.Queries}:{Success:!1,Results:[],ErrorMessages:s.GetData?.ErrorMessages??["Unknown error"],Queries:s.GetData?.Queries??e}}catch(r){let s=r instanceof Error?r.message:String(r);const a=s.match(/Error: ([^:]+)\./);if(a&&(s=a[1]+"."),c.IsVerboseLoggingEnabled()){const o=`GraphQLSystemUserClient::GetData - Error getting data - ${r}`;c.LogError(o)}return{Success:!1,Results:[],ErrorMessages:[s],Queries:e}}}async GetAllRemoteEntities(){try{const t=await this.Client.request(`query GetAllEntities {
410
447
  GetAllEntities {
411
448
  Success
412
449
  ErrorMessage
@@ -429,7 +466,7 @@
429
466
  }
430
467
  }
431
468
  }
432
- }`);return t&&t.GetAllEntities?t.GetAllEntities:{Success:!1,Results:[],ErrorMessage:t.GetAllEntities?.ErrorMessage??"Unknown error"}}catch(e){return u.LogError(`GraphQLSystemUserClient::GetAllRemoteEntities - Error getting remote entities - ${e}`),{Success:!1,Results:[],ErrorMessage:e}}}async SyncData(e){try{const r=await this.Client.request(`mutation SyncData($items: [ActionItemInputType!]!) {
469
+ }`);return t&&t.GetAllEntities?t.GetAllEntities:{Success:!1,Results:[],ErrorMessage:t.GetAllEntities?.ErrorMessage??"Unknown error"}}catch(e){return c.LogError(`GraphQLSystemUserClient::GetAllRemoteEntities - Error getting remote entities - ${e}`),{Success:!1,Results:[],ErrorMessage:e}}}async SyncData(e){try{const r=await this.Client.request(`mutation SyncData($items: [ActionItemInputType!]!) {
433
470
  SyncData(items: $items) {
434
471
  Success
435
472
  Results {
@@ -453,11 +490,11 @@
453
490
  RecordJSON
454
491
  }
455
492
  }
456
- }`,{items:e});return r&&r.SyncData?r.SyncData:{Success:!1,Results:[]}}catch(t){return u.LogError(`GraphQLSystemUserClient::SyncData - Error syncing data - ${t}`),{Success:!1,Results:[]}}}async SyncRolesAndUsers(e){try{const r=await this.Client.request(`mutation SyncRolesAndUsers($data: RolesAndUsersInputType!) {
493
+ }`,{items:e});return r&&r.SyncData?r.SyncData:{Success:!1,Results:[]}}catch(t){return c.LogError(`GraphQLSystemUserClient::SyncData - Error syncing data - ${t}`),{Success:!1,Results:[]}}}async SyncRolesAndUsers(e){try{const r=await this.Client.request(`mutation SyncRolesAndUsers($data: RolesAndUsersInputType!) {
457
494
  SyncRolesAndUsers(data: $data) {
458
495
  Success
459
496
  }
460
- }`,{data:e});return r&&r.SyncRolesAndUsers?r.SyncRolesAndUsers:{Success:!1}}catch(t){return u.LogError(`GraphQLSystemUserClient::SyncRolesAndUsers - Error syncing roles and users - ${t}`),{Success:!1}}}async RunViewByName(e){try{const r=await this.Client.request(`query RunViewByNameSystemUser($input: RunViewByNameInput!) {
497
+ }`,{data:e});return r&&r.SyncRolesAndUsers?r.SyncRolesAndUsers:{Success:!1}}catch(t){return c.LogError(`GraphQLSystemUserClient::SyncRolesAndUsers - Error syncing roles and users - ${t}`),{Success:!1}}}async RunViewByName(e){try{const r=await this.Client.request(`query RunViewByNameSystemUser($input: RunViewByNameInput!) {
461
498
  RunViewByNameSystemUser(input: $input) {
462
499
  Results {
463
500
  PrimaryKey {
@@ -474,7 +511,7 @@
474
511
  ErrorMessage
475
512
  Success
476
513
  }
477
- }`,{input:e});return r&&r.RunViewByNameSystemUser?r.RunViewByNameSystemUser:{Results:[],Success:!1,ErrorMessage:"Failed to execute view by name"}}catch(t){return u.LogError(`GraphQLSystemUserClient::RunViewByNameSystemUser - Error running view by name - ${t}`),{Results:[],Success:!1,ErrorMessage:t.toString()}}}async RunViewByID(e){try{const r=await this.Client.request(`query RunViewByIDSystemUser($input: RunViewByIDInput!) {
514
+ }`,{input:e});return r&&r.RunViewByNameSystemUser?r.RunViewByNameSystemUser:{Results:[],Success:!1,ErrorMessage:"Failed to execute view by name"}}catch(t){return c.LogError(`GraphQLSystemUserClient::RunViewByNameSystemUser - Error running view by name - ${t}`),{Results:[],Success:!1,ErrorMessage:t.toString()}}}async RunViewByID(e){try{const r=await this.Client.request(`query RunViewByIDSystemUser($input: RunViewByIDInput!) {
478
515
  RunViewByIDSystemUser(input: $input) {
479
516
  Results {
480
517
  PrimaryKey {
@@ -491,7 +528,7 @@
491
528
  ErrorMessage
492
529
  Success
493
530
  }
494
- }`,{input:e});return r&&r.RunViewByIDSystemUser?r.RunViewByIDSystemUser:{Results:[],Success:!1,ErrorMessage:"Failed to execute view by ID"}}catch(t){return u.LogError(`GraphQLSystemUserClient::RunViewByIDSystemUser - Error running view by ID - ${t}`),{Results:[],Success:!1,ErrorMessage:t.toString()}}}async RunDynamicView(e){try{const r=await this.Client.request(`query RunDynamicViewSystemUser($input: RunDynamicViewInput!) {
531
+ }`,{input:e});return r&&r.RunViewByIDSystemUser?r.RunViewByIDSystemUser:{Results:[],Success:!1,ErrorMessage:"Failed to execute view by ID"}}catch(t){return c.LogError(`GraphQLSystemUserClient::RunViewByIDSystemUser - Error running view by ID - ${t}`),{Results:[],Success:!1,ErrorMessage:t.toString()}}}async RunDynamicView(e){try{const r=await this.Client.request(`query RunDynamicViewSystemUser($input: RunDynamicViewInput!) {
495
532
  RunDynamicViewSystemUser(input: $input) {
496
533
  Results {
497
534
  PrimaryKey {
@@ -508,7 +545,7 @@
508
545
  ErrorMessage
509
546
  Success
510
547
  }
511
- }`,{input:e});return r&&r.RunDynamicViewSystemUser?r.RunDynamicViewSystemUser:{Results:[],Success:!1,ErrorMessage:"Failed to execute dynamic view"}}catch(t){return u.LogError(`GraphQLSystemUserClient::RunDynamicViewSystemUser - Error running dynamic view - ${t}`),{Results:[],Success:!1,ErrorMessage:t.toString()}}}async RunViews(e){try{const r=await this.Client.request(`query RunViewsSystemUser($input: [RunViewGenericInput!]!) {
548
+ }`,{input:e});return r&&r.RunDynamicViewSystemUser?r.RunDynamicViewSystemUser:{Results:[],Success:!1,ErrorMessage:"Failed to execute dynamic view"}}catch(t){return c.LogError(`GraphQLSystemUserClient::RunDynamicViewSystemUser - Error running dynamic view - ${t}`),{Results:[],Success:!1,ErrorMessage:t.toString()}}}async RunViews(e){try{const r=await this.Client.request(`query RunViewsSystemUser($input: [RunViewGenericInput!]!) {
512
549
  RunViewsSystemUser(input: $input) {
513
550
  Results {
514
551
  PrimaryKey {
@@ -525,7 +562,7 @@
525
562
  ErrorMessage
526
563
  Success
527
564
  }
528
- }`,{input:e});return r&&r.RunViewsSystemUser?r.RunViewsSystemUser:[]}catch(t){return u.LogError(`GraphQLSystemUserClient::RunViewsSystemUser - Error running views - ${t}`),[]}}async GetQueryData(e){try{if(e.Parameters!==void 0&&Array.isArray(e.Parameters))throw new Error("Parameters must be a JSON object, not an array. Use {} for empty parameters instead of [].");const t=`query GetQueryDataSystemUser($QueryID: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int) {
565
+ }`,{input:e});return r&&r.RunViewsSystemUser?r.RunViewsSystemUser:[]}catch(t){return c.LogError(`GraphQLSystemUserClient::RunViewsSystemUser - Error running views - ${t}`),[]}}async GetQueryData(e){try{if(e.Parameters!==void 0&&Array.isArray(e.Parameters))throw new Error("Parameters must be a JSON object, not an array. Use {} for empty parameters instead of [].");const t=`query GetQueryDataSystemUser($QueryID: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int) {
529
566
  GetQueryDataSystemUser(QueryID: $QueryID, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {
530
567
  QueryID
531
568
  QueryName
@@ -537,7 +574,7 @@
537
574
  ErrorMessage
538
575
  AppliedParameters
539
576
  }
540
- }`,r={QueryID:e.QueryID};e.CategoryID!==void 0&&(r.CategoryID=e.CategoryID),e.CategoryPath!==void 0&&(r.CategoryPath=e.CategoryPath),e.Parameters!==void 0&&(r.Parameters=e.Parameters),e.MaxRows!==void 0&&(r.MaxRows=e.MaxRows),e.StartRow!==void 0&&(r.StartRow=e.StartRow);const s=await this.Client.request(t,r);return s&&s.GetQueryDataSystemUser?{...s.GetQueryDataSystemUser,Results:s.GetQueryDataSystemUser.Results?w.SafeJSONParse(s.GetQueryDataSystemUser.Results):null}:{QueryID:e.QueryID,QueryName:"",Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:"Query execution failed"}}catch(t){return u.LogError(`GraphQLSystemUserClient::GetQueryDataSystemUser - Error executing query - ${t}`),{QueryID:e.QueryID,QueryName:"",Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:t.toString()}}}async GetQueryDataByName(e){try{if(e.Parameters!==void 0&&Array.isArray(e.Parameters))throw new Error("Parameters must be a JSON object, not an array. Use {} for empty parameters instead of [].");const t=`query GetQueryDataByNameSystemUser($QueryName: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int) {
577
+ }`,r={QueryID:e.QueryID};e.CategoryID!==void 0&&(r.CategoryID=e.CategoryID),e.CategoryPath!==void 0&&(r.CategoryPath=e.CategoryPath),e.Parameters!==void 0&&(r.Parameters=e.Parameters),e.MaxRows!==void 0&&(r.MaxRows=e.MaxRows),e.StartRow!==void 0&&(r.StartRow=e.StartRow);const s=await this.Client.request(t,r);return s&&s.GetQueryDataSystemUser?{...s.GetQueryDataSystemUser,Results:s.GetQueryDataSystemUser.Results?w.SafeJSONParse(s.GetQueryDataSystemUser.Results):null}:{QueryID:e.QueryID,QueryName:"",Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:"Query execution failed"}}catch(t){return c.LogError(`GraphQLSystemUserClient::GetQueryDataSystemUser - Error executing query - ${t}`),{QueryID:e.QueryID,QueryName:"",Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:t.toString()}}}async GetQueryDataByName(e){try{if(e.Parameters!==void 0&&Array.isArray(e.Parameters))throw new Error("Parameters must be a JSON object, not an array. Use {} for empty parameters instead of [].");const t=`query GetQueryDataByNameSystemUser($QueryName: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int) {
541
578
  GetQueryDataByNameSystemUser(QueryName: $QueryName, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {
542
579
  QueryID
543
580
  QueryName
@@ -549,7 +586,7 @@
549
586
  ErrorMessage
550
587
  AppliedParameters
551
588
  }
552
- }`,r={QueryName:e.QueryName};e.CategoryID!==void 0&&(r.CategoryID=e.CategoryID),e.CategoryPath!==void 0&&(r.CategoryPath=e.CategoryPath),e.Parameters!==void 0&&(r.Parameters=e.Parameters),e.MaxRows!==void 0&&(r.MaxRows=e.MaxRows),e.StartRow!==void 0&&(r.StartRow=e.StartRow);const s=await this.Client.request(t,r);return s&&s.GetQueryDataByNameSystemUser?{...s.GetQueryDataByNameSystemUser,Results:s.GetQueryDataByNameSystemUser.Results?w.SafeJSONParse(s.GetQueryDataByNameSystemUser.Results):null}:{QueryID:"",QueryName:e.QueryName,Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:"Query execution failed"}}catch(t){return u.LogError(`GraphQLSystemUserClient::GetQueryDataByNameSystemUser - Error executing query - ${t}`),{QueryID:"",QueryName:e.QueryName,Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:t.toString()}}}async CreateQuery(e){try{const r=await this.Client.request(`mutation CreateQuerySystemUser($input: CreateQuerySystemUserInput!) {
589
+ }`,r={QueryName:e.QueryName};e.CategoryID!==void 0&&(r.CategoryID=e.CategoryID),e.CategoryPath!==void 0&&(r.CategoryPath=e.CategoryPath),e.Parameters!==void 0&&(r.Parameters=e.Parameters),e.MaxRows!==void 0&&(r.MaxRows=e.MaxRows),e.StartRow!==void 0&&(r.StartRow=e.StartRow);const s=await this.Client.request(t,r);return s&&s.GetQueryDataByNameSystemUser?{...s.GetQueryDataByNameSystemUser,Results:s.GetQueryDataByNameSystemUser.Results?w.SafeJSONParse(s.GetQueryDataByNameSystemUser.Results):null}:{QueryID:"",QueryName:e.QueryName,Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:"Query execution failed"}}catch(t){return c.LogError(`GraphQLSystemUserClient::GetQueryDataByNameSystemUser - Error executing query - ${t}`),{QueryID:"",QueryName:e.QueryName,Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:t.toString()}}}async CreateQuery(e){try{const r=await this.Client.request(`mutation CreateQuerySystemUser($input: CreateQuerySystemUserInput!) {
553
590
  CreateQuerySystemUser(input: $input) {
554
591
  Success
555
592
  ErrorMessage
@@ -604,7 +641,7 @@
604
641
  Role
605
642
  }
606
643
  }
607
- }`,{input:e});return r&&r.CreateQuerySystemUser?r.CreateQuerySystemUser:{Success:!1,ErrorMessage:"Failed to create query"}}catch(t){return u.LogError(`GraphQLSystemUserClient::CreateQuery - Error creating query - ${t}`),{Success:!1,ErrorMessage:t.toString()}}}async UpdateQuery(e){try{const r=await this.Client.request(`mutation UpdateQuerySystemUser($input: UpdateQuerySystemUserInput!) {
644
+ }`,{input:e});return r&&r.CreateQuerySystemUser?r.CreateQuerySystemUser:{Success:!1,ErrorMessage:"Failed to create query"}}catch(t){return c.LogError(`GraphQLSystemUserClient::CreateQuery - Error creating query - ${t}`),{Success:!1,ErrorMessage:t.toString()}}}async UpdateQuery(e){try{const r=await this.Client.request(`mutation UpdateQuerySystemUser($input: UpdateQuerySystemUserInput!) {
608
645
  UpdateQuerySystemUser(input: $input) {
609
646
  Success
610
647
  ErrorMessage
@@ -659,14 +696,14 @@
659
696
  Role
660
697
  }
661
698
  }
662
- }`,{input:e});return r&&r.UpdateQuerySystemUser?r.UpdateQuerySystemUser:{Success:!1,ErrorMessage:"Failed to update query"}}catch(t){return u.LogError(`GraphQLSystemUserClient::UpdateQuery - Error updating query - ${t}`),{Success:!1,ErrorMessage:t.toString()}}}async DeleteQuery(e,t){try{if(!e||e.trim()==="")return u.LogError("GraphQLSystemUserClient::DeleteQuery - Invalid query ID: ID cannot be null or empty"),{Success:!1,ErrorMessage:"Invalid query ID: ID cannot be null or empty"};const r=`mutation DeleteQuerySystemResolver($ID: String!, $options: DeleteOptionsInput) {
699
+ }`,{input:e});return r&&r.UpdateQuerySystemUser?r.UpdateQuerySystemUser:{Success:!1,ErrorMessage:"Failed to update query"}}catch(t){return c.LogError(`GraphQLSystemUserClient::UpdateQuery - Error updating query - ${t}`),{Success:!1,ErrorMessage:t.toString()}}}async DeleteQuery(e,t){try{if(!e||e.trim()==="")return c.LogError("GraphQLSystemUserClient::DeleteQuery - Invalid query ID: ID cannot be null or empty"),{Success:!1,ErrorMessage:"Invalid query ID: ID cannot be null or empty"};const r=`mutation DeleteQuerySystemResolver($ID: String!, $options: DeleteOptionsInput) {
663
700
  DeleteQuerySystemResolver(ID: $ID, options: $options) {
664
701
  Success
665
702
  ErrorMessage
666
703
  ID
667
704
  Name
668
705
  }
669
- }`,s={ID:e};t!==void 0&&(s.options=t);const a=await this.Client.request(r,s);return a&&a.DeleteQuerySystemResolver?a.DeleteQuerySystemResolver:{Success:!1,ErrorMessage:"Failed to delete query"}}catch(r){return u.LogError(`GraphQLSystemUserClient::DeleteQuery - Error deleting query - ${r}`),{Success:!1,ErrorMessage:r.toString()}}}async RunAIPrompt(e){try{const t=m.gql`
706
+ }`,s={ID:e};t!==void 0&&(s.options=t);const a=await this.Client.request(r,s);return a&&a.DeleteQuerySystemResolver?a.DeleteQuerySystemResolver:{Success:!1,ErrorMessage:"Failed to delete query"}}catch(r){return c.LogError(`GraphQLSystemUserClient::DeleteQuery - Error deleting query - ${r}`),{Success:!1,ErrorMessage:r.toString()}}}async RunAIPrompt(e){try{const t=m.gql`
670
707
  query RunAIPromptSystemUser(
671
708
  $promptId: String!,
672
709
  $data: String,
@@ -725,7 +762,7 @@
725
762
  chatResult
726
763
  }
727
764
  }
728
- `,r=this.preparePromptVariables(e),s=await this.Client.request(t,r);return s&&s.RunAIPromptSystemUser?this.processPromptResult(s.RunAIPromptSystemUser):{success:!1,error:"Failed to execute AI prompt as system user"}}catch(t){return u.LogError(`GraphQLSystemUserClient::RunAIPrompt - Error running AI prompt - ${t}`),{success:!1,error:t.toString()}}}async RunAIAgent(e){try{const t=m.gql`
765
+ `,r=this.preparePromptVariables(e),s=await this.Client.request(t,r);return s&&s.RunAIPromptSystemUser?this.processPromptResult(s.RunAIPromptSystemUser):{success:!1,error:"Failed to execute AI prompt as system user"}}catch(t){return c.LogError(`GraphQLSystemUserClient::RunAIPrompt - Error running AI prompt - ${t}`),{success:!1,error:t.toString()}}}async RunAIAgent(e){try{const t=m.gql`
729
766
  query RunAIAgentSystemUser(
730
767
  $agentId: String!,
731
768
  $messages: String!,
@@ -752,7 +789,7 @@
752
789
  result
753
790
  }
754
791
  }
755
- `,r=this.prepareAgentVariables(e),s=await this.Client.request(t,r);return s&&s.RunAIAgentSystemUser?this.processAgentResult(s.RunAIAgentSystemUser.result):{success:!1,agentRun:void 0}}catch(t){return u.LogError(`GraphQLSystemUserClient::RunAIAgent - Error running AI agent - ${t}`),{success:!1,agentRun:void 0}}}preparePromptVariables(e){const t={promptId:e.promptId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.templateData!==void 0&&(t.templateData=typeof e.templateData=="object"?JSON.stringify(e.templateData):e.templateData),e.messages!==void 0&&(t.messages=JSON.stringify(e.messages)),e.overrideModelId!==void 0&&(t.overrideModelId=e.overrideModelId),e.overrideVendorId!==void 0&&(t.overrideVendorId=e.overrideVendorId),e.configurationId!==void 0&&(t.configurationId=e.configurationId),e.skipValidation!==void 0&&(t.skipValidation=e.skipValidation),e.responseFormat!==void 0&&(t.responseFormat=e.responseFormat),e.temperature!==void 0&&(t.temperature=e.temperature),e.topP!==void 0&&(t.topP=e.topP),e.topK!==void 0&&(t.topK=e.topK),e.minP!==void 0&&(t.minP=e.minP),e.frequencyPenalty!==void 0&&(t.frequencyPenalty=e.frequencyPenalty),e.presencePenalty!==void 0&&(t.presencePenalty=e.presencePenalty),e.seed!==void 0&&(t.seed=e.seed),e.stopSequences!==void 0&&(t.stopSequences=e.stopSequences),e.includeLogProbs!==void 0&&(t.includeLogProbs=e.includeLogProbs),e.topLogProbs!==void 0&&(t.topLogProbs=e.topLogProbs),e.rerunFromPromptRunID!==void 0&&(t.rerunFromPromptRunID=e.rerunFromPromptRunID),e.systemPromptOverride!==void 0&&(t.systemPromptOverride=e.systemPromptOverride),t}prepareAgentVariables(e){const t={agentId:e.agent.ID,messages:JSON.stringify(e.conversationMessages),sessionId:this._sessionId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.lastRunId!==void 0&&(t.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(t.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(t.configurationId=e.configurationId),t}processPromptResult(e){let t,r,s;try{e.parsedResult&&(t=JSON.parse(e.parsedResult))}catch{t=e.parsedResult}try{e.validationResult&&(r=JSON.parse(e.validationResult))}catch{r=e.validationResult}try{e.chatResult&&(s=JSON.parse(e.chatResult))}catch{s=e.chatResult}return{success:e.success,output:e.output,parsedResult:t,error:e.error,executionTimeMs:e.executionTimeMs,tokensUsed:e.tokensUsed,promptRunId:e.promptRunId,rawResult:e.rawResult,validationResult:r,chatResult:s}}processAgentResult(e){return w.SafeJSONParse(e)}async ExecuteSimplePrompt(e){try{const t=m.gql`
792
+ `,r=this.prepareAgentVariables(e),s=await this.Client.request(t,r);return s&&s.RunAIAgentSystemUser?this.processAgentResult(s.RunAIAgentSystemUser.result):{success:!1,agentRun:void 0}}catch(t){return c.LogError(`GraphQLSystemUserClient::RunAIAgent - Error running AI agent - ${t}`),{success:!1,agentRun:void 0}}}preparePromptVariables(e){const t={promptId:e.promptId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.templateData!==void 0&&(t.templateData=typeof e.templateData=="object"?JSON.stringify(e.templateData):e.templateData),e.messages!==void 0&&(t.messages=JSON.stringify(e.messages)),e.overrideModelId!==void 0&&(t.overrideModelId=e.overrideModelId),e.overrideVendorId!==void 0&&(t.overrideVendorId=e.overrideVendorId),e.configurationId!==void 0&&(t.configurationId=e.configurationId),e.skipValidation!==void 0&&(t.skipValidation=e.skipValidation),e.responseFormat!==void 0&&(t.responseFormat=e.responseFormat),e.temperature!==void 0&&(t.temperature=e.temperature),e.topP!==void 0&&(t.topP=e.topP),e.topK!==void 0&&(t.topK=e.topK),e.minP!==void 0&&(t.minP=e.minP),e.frequencyPenalty!==void 0&&(t.frequencyPenalty=e.frequencyPenalty),e.presencePenalty!==void 0&&(t.presencePenalty=e.presencePenalty),e.seed!==void 0&&(t.seed=e.seed),e.stopSequences!==void 0&&(t.stopSequences=e.stopSequences),e.includeLogProbs!==void 0&&(t.includeLogProbs=e.includeLogProbs),e.topLogProbs!==void 0&&(t.topLogProbs=e.topLogProbs),e.rerunFromPromptRunID!==void 0&&(t.rerunFromPromptRunID=e.rerunFromPromptRunID),e.systemPromptOverride!==void 0&&(t.systemPromptOverride=e.systemPromptOverride),t}prepareAgentVariables(e){const t={agentId:e.agent.ID,messages:JSON.stringify(e.conversationMessages),sessionId:this._sessionId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.lastRunId!==void 0&&(t.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(t.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(t.configurationId=e.configurationId),t}processPromptResult(e){let t,r,s;try{e.parsedResult&&(t=JSON.parse(e.parsedResult))}catch{t=e.parsedResult}try{e.validationResult&&(r=JSON.parse(e.validationResult))}catch{r=e.validationResult}try{e.chatResult&&(s=JSON.parse(e.chatResult))}catch{s=e.chatResult}return{success:e.success,output:e.output,parsedResult:t,error:e.error,executionTimeMs:e.executionTimeMs,tokensUsed:e.tokensUsed,promptRunId:e.promptRunId,rawResult:e.rawResult,validationResult:r,chatResult:s}}processAgentResult(e){return w.SafeJSONParse(e)}async ExecuteSimplePrompt(e){try{const t=m.gql`
756
793
  query ExecuteSimplePromptSystemUser(
757
794
  $systemPrompt: String!,
758
795
  $messages: String,
@@ -775,7 +812,7 @@
775
812
  executionTimeMs
776
813
  }
777
814
  }
778
- `,r={systemPrompt:e.systemPrompt};e.messages&&e.messages.length>0&&(r.messages=JSON.stringify(e.messages)),e.preferredModels&&(r.preferredModels=e.preferredModels),e.modelPower&&(r.modelPower=e.modelPower),e.responseFormat&&(r.responseFormat=e.responseFormat);const s=await this.Client.request(t,r);if(!s?.ExecuteSimplePromptSystemUser)return{success:!1,modelName:"Unknown",error:"Failed to execute simple prompt as system user"};const a=s.ExecuteSimplePromptSystemUser;let o;if(a.resultObject)try{o=JSON.parse(a.resultObject)}catch{o=a.resultObject}return{success:a.success,result:a.result,resultObject:o,modelName:a.modelName,error:a.error,executionTimeMs:a.executionTimeMs}}catch(t){return u.LogError(`GraphQLSystemUserClient::ExecuteSimplePrompt - Error executing simple prompt - ${t}`),{success:!1,modelName:"Unknown",error:t.toString()}}}async EmbedText(e){try{const t=m.gql`
815
+ `,r={systemPrompt:e.systemPrompt};e.messages&&e.messages.length>0&&(r.messages=JSON.stringify(e.messages)),e.preferredModels&&(r.preferredModels=e.preferredModels),e.modelPower&&(r.modelPower=e.modelPower),e.responseFormat&&(r.responseFormat=e.responseFormat);const s=await this.Client.request(t,r);if(!s?.ExecuteSimplePromptSystemUser)return{success:!1,modelName:"Unknown",error:"Failed to execute simple prompt as system user"};const a=s.ExecuteSimplePromptSystemUser;let o;if(a.resultObject)try{o=JSON.parse(a.resultObject)}catch{o=a.resultObject}return{success:a.success,result:a.result,resultObject:o,modelName:a.modelName,error:a.error,executionTimeMs:a.executionTimeMs}}catch(t){return c.LogError(`GraphQLSystemUserClient::ExecuteSimplePrompt - Error executing simple prompt - ${t}`),{success:!1,modelName:"Unknown",error:t.toString()}}}async EmbedText(e){try{const t=m.gql`
779
816
  query EmbedTextSystemUser(
780
817
  $textToEmbed: [String!]!,
781
818
  $modelSize: String!
@@ -790,7 +827,7 @@
790
827
  error
791
828
  }
792
829
  }
793
- `,s={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},a=await this.Client.request(t,s);if(!a?.EmbedTextSystemUser)return{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:"Failed to generate embeddings as system user"};const o=a.EmbedTextSystemUser;return{embeddings:Array.isArray(e.textToEmbed)?o.embeddings:o.embeddings[0],modelName:o.modelName,vectorDimensions:o.vectorDimensions,error:o.error}}catch(t){return u.LogError(`GraphQLSystemUserClient::EmbedText - Error generating embeddings - ${t}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:t.toString()}}}};S(ie,"GraphQLSystemUserClient");let q=ie;const ue=class ue{};S(ue,"GetDataOutput");let _=ue;const ce=class ce{};S(ce,"SimpleRemoteEntityOutput");let O=ce;const le=class le{};S(le,"SimpleRemoteEntity");let k=le;const de=class de{};S(de,"SimpleRemoteEntityField");let B=de;const ye=class ye{constructor(e){this._dataProvider=e}async RunAction(e,t,r=!1){try{const s=this.serializeActionParameters(t),a=this.createActionVariables(e,s,r),o=await this.executeActionMutation(a);return this.processActionResult(o,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=m.gql`
830
+ `,s={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},a=await this.Client.request(t,s);if(!a?.EmbedTextSystemUser)return{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:"Failed to generate embeddings as system user"};const o=a.EmbedTextSystemUser;return{embeddings:Array.isArray(e.textToEmbed)?o.embeddings:o.embeddings[0],modelName:o.modelName,vectorDimensions:o.vectorDimensions,error:o.error}}catch(t){return c.LogError(`GraphQLSystemUserClient::EmbedText - Error generating embeddings - ${t}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:t.toString()}}}};f(ie,"GraphQLSystemUserClient");let q=ie;const ue=class ue{};f(ue,"GetDataOutput");let _=ue;const ce=class ce{};f(ce,"SimpleRemoteEntityOutput");let O=ce;const le=class le{};f(le,"SimpleRemoteEntity");let k=le;const de=class de{};f(de,"SimpleRemoteEntityField");let B=de;const ye=class ye{constructor(e){this._dataProvider=e}async RunAction(e,t,r=!1){try{const s=this.serializeActionParameters(t),a=this.createActionVariables(e,s,r),o=await this.executeActionMutation(a);return this.processActionResult(o,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=m.gql`
794
831
  mutation RunAction($input: RunActionInput!) {
795
832
  RunAction(input: $input) {
796
833
  Success
@@ -799,7 +836,7 @@
799
836
  ResultData
800
837
  }
801
838
  }
802
- `;return await this._dataProvider.ExecuteGQL(t,e)}processActionResult(e,t){if(!e?.RunAction)throw new Error("Invalid response from server");let r;try{e.RunAction.ResultData&&(r=JSON.parse(e.RunAction.ResultData))}catch(s){u.LogError(`Failed to parse action result data: ${s}`)}return{Success:e.RunAction.Success,Message:e.RunAction.Message,Result:r,LogEntry:null,Params:t||[],RunParams:null}}handleActionError(e,t){const r=e;return u.LogError(`Error running action: ${r}`),{Success:!1,Message:`Error: ${r.message}`,Result:null,LogEntry:null,Params:t||[],RunParams:null}}async RunEntityAction(e){try{const t=this.createEntityActionInput(e),r=await this.executeEntityActionMutation(t);return this.processEntityActionResult(r)}catch(t){return this.handleEntityActionError(t)}}createEntityActionInput(e){const t={EntityActionID:e.EntityAction.ID,InvocationType:e.InvocationType.Name,ListID:e.ListID,ViewID:e.ViewID};return e.Params&&(t.Params=this.convertActionParams(e.Params)),e.EntityObject&&this.addEntityInformation(t,e.EntityObject),t}convertActionParams(e){return e.map(t=>{let r=t.Value;return r!=null&&typeof r=="object"&&(r=JSON.stringify(r)),{Name:t.Name,Value:r,Type:t.Type}})}addEntityInformation(e,t){e.EntityName=t.EntityInfo?.Name,t.PrimaryKey&&(e.PrimaryKey=this.convertPrimaryKey(t.PrimaryKey))}convertPrimaryKey(e){return{KeyValuePairs:e.KeyValuePairs.map(t=>this.convertKeyValuePair(t))}}convertKeyValuePair(e){return{FieldName:e.FieldName,Value:e.Value!==null&&e.Value!==void 0?typeof e.Value=="object"?JSON.stringify(e.Value):e.Value.toString():null}}async executeEntityActionMutation(e){const t=m.gql`
839
+ `;return await this._dataProvider.ExecuteGQL(t,e)}processActionResult(e,t){if(!e?.RunAction)throw new Error("Invalid response from server");let r;try{e.RunAction.ResultData&&(r=JSON.parse(e.RunAction.ResultData))}catch(s){c.LogError(`Failed to parse action result data: ${s}`)}return{Success:e.RunAction.Success,Message:e.RunAction.Message,Result:r,LogEntry:null,Params:t||[],RunParams:null}}handleActionError(e,t){const r=e;return c.LogError(`Error running action: ${r}`),{Success:!1,Message:`Error: ${r.message}`,Result:null,LogEntry:null,Params:t||[],RunParams:null}}async RunEntityAction(e){try{const t=this.createEntityActionInput(e),r=await this.executeEntityActionMutation(t);return this.processEntityActionResult(r)}catch(t){return this.handleEntityActionError(t)}}createEntityActionInput(e){const t={EntityActionID:e.EntityAction.ID,InvocationType:e.InvocationType.Name,ListID:e.ListID,ViewID:e.ViewID};return e.Params&&(t.Params=this.convertActionParams(e.Params)),e.EntityObject&&this.addEntityInformation(t,e.EntityObject),t}convertActionParams(e){return e.map(t=>{let r=t.Value;return r!=null&&typeof r=="object"&&(r=JSON.stringify(r)),{Name:t.Name,Value:r,Type:t.Type}})}addEntityInformation(e,t){e.EntityName=t.EntityInfo?.Name,t.PrimaryKey&&(e.PrimaryKey=this.convertPrimaryKey(t.PrimaryKey))}convertPrimaryKey(e){return{KeyValuePairs:e.KeyValuePairs.map(t=>this.convertKeyValuePair(t))}}convertKeyValuePair(e){return{FieldName:e.FieldName,Value:e.Value!==null&&e.Value!==void 0?typeof e.Value=="object"?JSON.stringify(e.Value):e.Value.toString():null}}async executeEntityActionMutation(e){const t=m.gql`
803
840
  mutation RunEntityAction($input: EntityActionInput!) {
804
841
  RunEntityAction(input: $input) {
805
842
  Success
@@ -807,16 +844,18 @@
807
844
  ResultData
808
845
  }
809
846
  }
810
- `;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}}};S(ye,"GraphQLActionClient");let K=ye;const me=class me{constructor(e){this._dataProvider=e}async RunTest(e){let t;try{e.onProgress&&(t=this._dataProvider.PushStatusUpdates(this._dataProvider.sessionId).subscribe(o=>{try{const i=JSON.parse(o);i.resolver==="RunTestResolver"&&i.type==="TestExecutionProgress"&&i.status==="ok"&&i.data?.progress&&e.onProgress(i.data.progress)}catch(i){console.error("[GraphQLTestingClient] Failed to parse progress message:",i)}}));const r=m.gql`
847
+ `;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){c.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 c.LogError(`Error running entity action: ${t}`),{Success:!1,Message:`Error: ${t.message}`,RunParams:null,LogEntry:null}}};f(ye,"GraphQLActionClient");let K=ye;const me=class me{constructor(e){this._dataProvider=e}async RunTest(e){let t;try{e.onProgress&&(t=this._dataProvider.PushStatusUpdates(this._dataProvider.sessionId).subscribe(i=>{try{const n=JSON.parse(i);n.resolver==="RunTestResolver"&&n.type==="TestExecutionProgress"&&n.status==="ok"&&n.data?.progress&&e.onProgress(n.data.progress)}catch(n){console.error("[GraphQLTestingClient] Failed to parse progress message:",n)}}));const r=m.gql`
811
848
  mutation RunTest(
812
849
  $testId: String!,
813
850
  $verbose: Boolean,
814
- $environment: String
851
+ $environment: String,
852
+ $tags: String
815
853
  ) {
816
854
  RunTest(
817
855
  testId: $testId,
818
856
  verbose: $verbose,
819
- environment: $environment
857
+ environment: $environment,
858
+ tags: $tags
820
859
  ) {
821
860
  success
822
861
  errorMessage
@@ -824,18 +863,26 @@
824
863
  result
825
864
  }
826
865
  }
827
- `,s={testId:e.testId,verbose:e.verbose,environment:e.environment},a=await this._dataProvider.ExecuteGQL(r,s);return this.processTestResult(a.RunTest)}catch(r){return this.handleError(r,"RunTest")}finally{t&&t.unsubscribe()}}async RunTestSuite(e){let t;try{e.onProgress&&(t=this._dataProvider.PushStatusUpdates(this._dataProvider.sessionId).subscribe(o=>{try{const i=JSON.parse(o);i.resolver==="RunTestResolver"&&i.type==="TestExecutionProgress"&&i.status==="ok"&&i.data?.progress&&e.onProgress(i.data.progress)}catch(i){console.error("[GraphQLTestingClient] Failed to parse progress message:",i)}}));const r=m.gql`
866
+ `,s=e.tags&&e.tags.length>0?JSON.stringify(e.tags):void 0,a={testId:e.testId,verbose:e.verbose,environment:e.environment,tags:s},o=await this._dataProvider.ExecuteGQL(r,a);return this.processTestResult(o.RunTest)}catch(r){return this.handleError(r,"RunTest")}finally{t&&t.unsubscribe()}}async RunTestSuite(e){let t;try{e.onProgress&&(t=this._dataProvider.PushStatusUpdates(this._dataProvider.sessionId).subscribe(n=>{try{const u=JSON.parse(n);u.resolver==="RunTestResolver"&&u.type==="TestExecutionProgress"&&u.status==="ok"&&u.data?.progress&&e.onProgress(u.data.progress)}catch(u){console.error("[GraphQLTestingClient] Failed to parse progress message:",u)}}));const r=m.gql`
828
867
  mutation RunTestSuite(
829
868
  $suiteId: String!,
830
869
  $verbose: Boolean,
831
870
  $environment: String,
832
- $parallel: Boolean
871
+ $parallel: Boolean,
872
+ $tags: String,
873
+ $selectedTestIds: String,
874
+ $sequenceStart: Int,
875
+ $sequenceEnd: Int
833
876
  ) {
834
877
  RunTestSuite(
835
878
  suiteId: $suiteId,
836
879
  verbose: $verbose,
837
880
  environment: $environment,
838
- parallel: $parallel
881
+ parallel: $parallel,
882
+ tags: $tags,
883
+ selectedTestIds: $selectedTestIds,
884
+ sequenceStart: $sequenceStart,
885
+ sequenceEnd: $sequenceEnd
839
886
  ) {
840
887
  success
841
888
  errorMessage
@@ -843,11 +890,11 @@
843
890
  result
844
891
  }
845
892
  }
846
- `,s={suiteId:e.suiteId,verbose:e.verbose,environment:e.environment,parallel:e.parallel},a=await this._dataProvider.ExecuteGQL(r,s);return this.processSuiteResult(a.RunTestSuite)}catch(r){return this.handleError(r,"RunTestSuite")}finally{t&&t.unsubscribe()}}async IsTestRunning(e){try{const t=m.gql`
893
+ `,s=e.tags&&e.tags.length>0?JSON.stringify(e.tags):void 0,a=e.selectedTestIds&&e.selectedTestIds.length>0?JSON.stringify(e.selectedTestIds):void 0,o={suiteId:e.suiteId,verbose:e.verbose,environment:e.environment,parallel:e.parallel,tags:s,selectedTestIds:a,sequenceStart:e.sequenceStart,sequenceEnd:e.sequenceEnd},i=await this._dataProvider.ExecuteGQL(r,o);return this.processSuiteResult(i.RunTestSuite)}catch(r){return this.handleError(r,"RunTestSuite")}finally{t&&t.unsubscribe()}}async IsTestRunning(e){try{const t=m.gql`
847
894
  query IsTestRunning($testId: String!) {
848
895
  IsTestRunning(testId: $testId)
849
896
  }
850
- `;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=w.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=w.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}}};S(me,"GraphQLTestingClient");let J=me;const ge=class ge{constructor(e){this._dataProvider=e}async GetRegistryComponent(e){try{const t=m.gql`
897
+ `;return(await this._dataProvider.ExecuteGQL(t,{testId:e})).IsTestRunning}catch(t){return c.LogError(`Error checking test running status: ${t.message}`),!1}}processTestResult(e){if(!e)throw new Error("Invalid response from server");let t;try{t=w.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=w.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 c.LogError(`${t} failed: ${r}`),{success:!1,errorMessage:r,result:null}}};f(me,"GraphQLTestingClient");let J=me;const ge=class ge{constructor(e){this._dataProvider=e}async GetRegistryComponent(e){try{const t=m.gql`
851
898
  query GetRegistryComponent(
852
899
  $registryName: String!,
853
900
  $namespace: String!,
@@ -868,7 +915,7 @@
868
915
  specification
869
916
  }
870
917
  }
871
- `,r={registryName:e.registryName,namespace:e.namespace,name:e.name};e.version!==void 0&&(r.version=e.version),e.hash!==void 0&&(r.hash=e.hash);const s=await this._dataProvider.ExecuteGQL(t,r);if(s&&s.GetRegistryComponent){const a=s.GetRegistryComponent;if(a.notModified&&!a.specification)return null;if(a.specification){if(typeof a.specification=="object")return a.specification;try{return JSON.parse(a.specification)}catch(o){return u.LogError(`Failed to parse component specification: ${o}`),null}}return null}return null}catch(t){throw u.LogError(t),new Error(`Failed to get registry component: ${t instanceof Error?t.message:"Unknown error"}`)}}async GetRegistryComponentWithHash(e){try{const t=m.gql`
918
+ `,r={registryName:e.registryName,namespace:e.namespace,name:e.name};e.version!==void 0&&(r.version=e.version),e.hash!==void 0&&(r.hash=e.hash);const s=await this._dataProvider.ExecuteGQL(t,r);if(s&&s.GetRegistryComponent){const a=s.GetRegistryComponent;if(a.notModified&&!a.specification)return null;if(a.specification){if(typeof a.specification=="object")return a.specification;try{return JSON.parse(a.specification)}catch(o){return c.LogError(`Failed to parse component specification: ${o}`),null}}return null}return null}catch(t){throw c.LogError(t),new Error(`Failed to get registry component: ${t instanceof Error?t.message:"Unknown error"}`)}}async GetRegistryComponentWithHash(e){try{const t=m.gql`
872
919
  query GetRegistryComponent(
873
920
  $registryName: String!,
874
921
  $namespace: String!,
@@ -889,7 +936,7 @@
889
936
  specification
890
937
  }
891
938
  }
892
- `,r={registryName:e.registryName,namespace:e.namespace,name:e.name};e.version!==void 0&&(r.version=e.version),e.hash!==void 0&&(r.hash=e.hash);const s=await this._dataProvider.ExecuteGQL(t,r);if(s&&s.GetRegistryComponent){const a=s.GetRegistryComponent;let o;if(a.specification)try{o=JSON.parse(a.specification)}catch(i){u.LogError(`Failed to parse component specification in GetRegistryComponentWithHash: ${i}`),o=void 0}return{specification:o,hash:a.hash,notModified:a.notModified,message:a.message}}return{specification:void 0,hash:"",notModified:!1,message:"Component not found"}}catch(t){throw u.LogError(t),new Error(`Failed to get registry component with hash: ${t instanceof Error?t.message:"Unknown error"}`)}}async SearchRegistryComponents(e){try{const t=m.gql`
939
+ `,r={registryName:e.registryName,namespace:e.namespace,name:e.name};e.version!==void 0&&(r.version=e.version),e.hash!==void 0&&(r.hash=e.hash);const s=await this._dataProvider.ExecuteGQL(t,r);if(s&&s.GetRegistryComponent){const a=s.GetRegistryComponent;let o;if(a.specification)try{o=JSON.parse(a.specification)}catch(i){c.LogError(`Failed to parse component specification in GetRegistryComponentWithHash: ${i}`),o=void 0}return{specification:o,hash:a.hash,notModified:a.notModified,message:a.message}}return{specification:void 0,hash:"",notModified:!1,message:"Component not found"}}catch(t){throw c.LogError(t),new Error(`Failed to get registry component with hash: ${t instanceof Error?t.message:"Unknown error"}`)}}async SearchRegistryComponents(e){try{const t=m.gql`
893
940
  query SearchRegistryComponents($params: SearchRegistryComponentsInput!) {
894
941
  SearchRegistryComponents(params: $params) {
895
942
  components
@@ -898,7 +945,7 @@
898
945
  limit
899
946
  }
900
947
  }
901
- `,r=await this._dataProvider.ExecuteGQL(t,{params:e});if(r&&r.SearchRegistryComponents){const s=r.SearchRegistryComponents;return{components:s.components.map(a=>JSON.parse(a)),total:s.total,offset:s.offset,limit:s.limit}}return{components:[],total:0,offset:0,limit:e.limit||10}}catch(t){throw u.LogError(t),new Error(`Failed to search registry components: ${t instanceof Error?t.message:"Unknown error"}`)}}async ResolveComponentDependencies(e,t){try{const r=m.gql`
948
+ `,r=await this._dataProvider.ExecuteGQL(t,{params:e});if(r&&r.SearchRegistryComponents){const s=r.SearchRegistryComponents;return{components:s.components.map(a=>JSON.parse(a)),total:s.total,offset:s.offset,limit:s.limit}}return{components:[],total:0,offset:0,limit:e.limit||10}}catch(t){throw c.LogError(t),new Error(`Failed to search registry components: ${t instanceof Error?t.message:"Unknown error"}`)}}async ResolveComponentDependencies(e,t){try{const r=m.gql`
902
949
  query ResolveComponentDependencies(
903
950
  $registryId: String!,
904
951
  $componentId: String!
@@ -923,7 +970,7 @@
923
970
  }
924
971
  }
925
972
  }
926
- `,s=await this._dataProvider.ExecuteGQL(r,{registryId:e,componentId:t});return s&&s.ResolveComponentDependencies?s.ResolveComponentDependencies:null}catch(r){throw u.LogError(r),new Error(`Failed to resolve component dependencies: ${r instanceof Error?r.message:"Unknown error"}`)}}async ComponentExists(e){try{return await this.GetRegistryComponent(e)!==null}catch{return!1}}async GetLatestVersion(e,t,r){try{return(await this.GetRegistryComponent({registryName:e,namespace:t,name:r,version:"latest"}))?.version||null}catch(s){return u.LogError(s),null}}async SendComponentFeedback(e){try{const t=m.gql`
973
+ `,s=await this._dataProvider.ExecuteGQL(r,{registryId:e,componentId:t});return s&&s.ResolveComponentDependencies?s.ResolveComponentDependencies:null}catch(r){throw c.LogError(r),new Error(`Failed to resolve component dependencies: ${r instanceof Error?r.message:"Unknown error"}`)}}async ComponentExists(e){try{return await this.GetRegistryComponent(e)!==null}catch{return!1}}async GetLatestVersion(e,t,r){try{return(await this.GetRegistryComponent({registryName:e,namespace:t,name:r,version:"latest"}))?.version||null}catch(s){return c.LogError(s),null}}async SendComponentFeedback(e){try{const t=m.gql`
927
974
  mutation SendComponentFeedback($feedback: ComponentFeedbackInput!) {
928
975
  SendComponentFeedback(feedback: $feedback) {
929
976
  success
@@ -931,5 +978,5 @@
931
978
  error
932
979
  }
933
980
  }
934
- `,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"}}}};S(ge,"GraphQLComponentRegistryClient");let j=ge;Object.defineProperty(exports,"gql",{enumerable:!0,get:function(){return m.gql}}),exports.ActionItemInput=G,exports.ActionItemOutput=U,exports.BrowserIndexedDBStorageProvider=x,exports.BrowserStorageProviderBase=b,exports.FieldMapper=C,exports.GetDataOutput=_,exports.GraphQLAIClient=N,exports.GraphQLActionClient=K,exports.GraphQLComponentRegistryClient=j,exports.GraphQLDataProvider=L,exports.GraphQLProviderConfigData=T,exports.GraphQLSystemUserClient=q,exports.GraphQLTestingClient=J,exports.GraphQLTransactionGroup=v,exports.RoleInput=V,exports.RolesAndUsersInput=Q,exports.SimpleRemoteEntity=k,exports.SimpleRemoteEntityField=B,exports.SimpleRemoteEntityOutput=O,exports.SyncDataAction=fe,exports.SyncDataResult=F,exports.SyncRolesAndUsersResult=M,exports.UserInput=A,exports.setupGraphQLClient=Ce;
981
+ `,r=await this._dataProvider.ExecuteGQL(t,{feedback:e});return r&&r.SendComponentFeedback?r.SendComponentFeedback:{success:!1,error:"No response from server"}}catch(t){return c.LogError(t),{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}};f(ge,"GraphQLComponentRegistryClient");let j=ge;Object.defineProperty(exports,"gql",{enumerable:!0,get:function(){return m.gql}}),exports.ActionItemInput=G,exports.ActionItemOutput=U,exports.BrowserIndexedDBStorageProvider=x,exports.BrowserStorageProviderBase=b,exports.FieldMapper=P,exports.GetDataOutput=_,exports.GraphQLAIClient=N,exports.GraphQLActionClient=K,exports.GraphQLComponentRegistryClient=j,exports.GraphQLDataProvider=L,exports.GraphQLProviderConfigData=T,exports.GraphQLSystemUserClient=q,exports.GraphQLTestingClient=J,exports.GraphQLTransactionGroup=C,exports.RoleInput=M,exports.RolesAndUsersInput=Q,exports.SimpleRemoteEntity=k,exports.SimpleRemoteEntityField=B,exports.SimpleRemoteEntityOutput=O,exports.SyncDataAction=Se,exports.SyncDataResult=F,exports.SyncRolesAndUsersResult=A,exports.UserInput=V,exports.setupGraphQLClient=Pe;
935
982
  //# sourceMappingURL=index.cjs.map