@memberjunction/graphql-dataprovider 2.103.0 → 2.105.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 pe=Object.defineProperty;var f=(D,e)=>pe(D,"name",{value:e,configurable:!0});var y=require("graphql-request"),u=require("@memberjunction/core"),de=require("@memberjunction/core-entities"),fe=require("@tempfix/idb"),ye=require("rxjs"),me=require("graphql-ws"),Se=require("uuid"),P=require("@memberjunction/global");const K=class K{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(K,"FieldMapper");let w=K;const J=class J extends u.TransactionGroupBase{constructor(e){super(),this._provider=e}async HandleSubmit(){const e=y.gql`
1
+ "use strict";var Se=Object.defineProperty;var f=(I,e)=>Se(I,"name",{value:e,configurable:!0});var h,y=require("graphql-request"),u=require("@memberjunction/core"),de=require("@memberjunction/core-entities"),Re=require("@tempfix/idb"),ye=require("rxjs"),me=require("graphql-ws"),he=require("uuid"),E=require("@memberjunction/global");const K=class K{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(K,"FieldMapper");let $=K;const J=class J extends u.TransactionGroupBase{constructor(e){super(),this._provider=e}async HandleSubmit(){const e=y.gql`
2
2
  mutation ExecuteTransactionGroup($group: TransactionInputType!) {
3
3
  ExecuteTransactionGroup(group: $group) {
4
4
  Success
@@ -6,7 +6,7 @@
6
6
  ResultsJSON
7
7
  }
8
8
  }
9
- `,t=[];for(const 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,n=[];for(let i=0;i<this.PendingTransactions.length;i++){const o=a.ResultsJSON[i],m=P.SafeJSONParse(o),p=this.PendingTransactions[i];n.push(new u.TransactionResult(p,m,m!==null))}return n}else throw new Error("Failed to execute transaction group")}};f(J,"GraphQLTransactionGroup");let $=J;const j=class j{constructor(e){this._dataProvider=e}async RunAIPrompt(e){try{const t=y.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,n=[];for(let o=0;o<this.PendingTransactions.length;o++){const i=a.ResultsJSON[o],m=E.SafeJSONParse(i),p=this.PendingTransactions[o];n.push(new u.TransactionResult(p,m,m!==null))}return n}else throw new Error("Failed to execute transaction group")}};f(J,"GraphQLTransactionGroup");let N=J;const j=class j{constructor(e){this._dataProvider=e}async RunAIPrompt(e){try{const t=y.gql`
10
10
  mutation RunAIPrompt(
11
11
  $promptId: String!,
12
12
  $data: String,
@@ -65,34 +65,38 @@
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){try{const t=y.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 u.LogError(`Error running AI prompt: ${t}`),{success:!1,error:t.message||"Unknown error occurred"}}async RunAIAgent(e){let t;try{e.onProgress&&(t=this._dataProvider.PushStatusUpdates(this._dataProvider.sessionId).subscribe(n=>{try{console.log("[GraphQLAIClient] Received statusUpdate message:",n);const o=JSON.parse(n);if(console.log("[GraphQLAIClient] Parsed message:",o),o.resolver==="RunAIAgentResolver"&&o.type==="ExecutionProgress"&&o.status==="ok"&&o.data?.progress){console.log("[GraphQLAIClient] Forwarding progress to callback:",o.data.progress);const i={...o.data.progress,metadata:{...o.data.progress.metadata||{},agentRunId:o.data.agentRunId}};e.onProgress(i)}else console.log("[GraphQLAIClient] Message does not match filter criteria:",{resolver:o.resolver,type:o.type,status:o.status,hasProgress:!!o.data?.progress})}catch(o){console.error("[GraphQLAIClient] Failed to parse progress message:",o,"Raw message:",n)}}));const r=y.gql`
69
69
  mutation RunAIAgent(
70
70
  $agentId: String!,
71
71
  $messages: String!,
72
72
  $sessionId: String!,
73
73
  $data: String,
74
+ $payload: String,
74
75
  $templateData: String,
75
76
  $lastRunId: String,
76
77
  $autoPopulateLastRunPayload: Boolean,
77
- $configurationId: String
78
+ $configurationId: String,
79
+ $conversationDetailId: String
78
80
  ) {
79
81
  RunAIAgent(
80
82
  agentId: $agentId,
81
83
  messages: $messages,
82
84
  sessionId: $sessionId,
83
85
  data: $data,
86
+ payload: $payload,
84
87
  templateData: $templateData,
85
88
  lastRunId: $lastRunId,
86
89
  autoPopulateLastRunPayload: $autoPopulateLastRunPayload,
87
- configurationId: $configurationId
90
+ configurationId: $configurationId,
91
+ conversationDetailId: $conversationDetailId
88
92
  ) {
89
93
  success
90
94
  errorMessage
91
95
  executionTimeMs
92
- payload
96
+ result
93
97
  }
94
98
  }
95
- `,r=this.prepareAgentVariables(e),s=await this._dataProvider.ExecuteGQL(t,r);return this.processAgentResult(s)}catch(t){return this.handleAgentError(t)}}prepareAgentVariables(e){const t={agentId:e.agentId,messages:JSON.stringify(e.messages),sessionId:e.sessionId};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.lastRunId!==void 0&&(t.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(t.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(t.configurationId=e.configurationId),t}processAgentResult(e){if(!e?.RunAIAgent)throw new Error("Invalid response from server");const t=e.RunAIAgent;let r;try{t.payload&&(r=JSON.parse(t.payload))}catch{r=t.payload}return{success:t.success,errorMessage:t.errorMessage,executionTimeMs:t.executionTimeMs,payload:r}}handleAgentError(e){const t=e;return u.LogError(`Error running AI agent: ${t}`),{success:!1,errorMessage:t.message||"Unknown error occurred"}}async ExecuteSimplePrompt(e){try{const t=y.gql`
99
+ `,s=this.prepareAgentVariables(e),a=await this._dataProvider.ExecuteGQL(r,s);return this.processAgentResult(a.RunAIAgent?.result)}catch(r){return this.handleAgentError(r)}finally{t&&t.unsubscribe()}}prepareAgentVariables(e){const t={agentId:e.agent.ID,messages:JSON.stringify(e.conversationMessages),sessionId:this._dataProvider.sessionId};return e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.payload!==void 0&&(t.payload=typeof e.payload=="object"?JSON.stringify(e.payload):e.payload),e.lastRunId!==void 0&&(t.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(t.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(t.configurationId=e.configurationId),e.conversationDetailId!==void 0&&(t.conversationDetailId=e.conversationDetailId),t}processAgentResult(e){return E.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=y.gql`
96
100
  mutation ExecuteSimplePrompt(
97
101
  $systemPrompt: String!,
98
102
  $messages: String,
@@ -130,7 +134,7 @@
130
134
  error
131
135
  }
132
136
  }
133
- `,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 n=a.EmbedText;return{embeddings:Array.isArray(e.textToEmbed)?n.embeddings:n.embeddings[0],modelName:n.modelName,vectorDimensions:n.vectorDimensions,error:n.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"}}}};f(j,"GraphQLAIClient");let N=j;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,n,i,o){super({Token:e,URL:t,WSURL:r,MJAPIKey:o,RefreshTokenFunction:s},a,n,i)}};f(z,"GraphQLProviderConfigData");let C=z;const h=class h extends u.ProviderBase{constructor(){super(),this._innerCurrentUserQueryString=`CurrentUser {
137
+ `,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 n=a.EmbedText;return{embeddings:Array.isArray(e.textToEmbed)?n.embeddings:n.embeddings[0],modelName:n.modelName,vectorDimensions:n.vectorDimensions,error:n.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"}}}};f(j,"GraphQLAIClient");let v=j;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,n,o,i){super({Token:e,URL:t,WSURL:r,MJAPIKey:i,RefreshTokenFunction:s},a,n,o)}};f(z,"GraphQLProviderConfigData");let C=z;const ge=(h=class extends u.ProviderBase{constructor(){super(),this._innerCurrentUserQueryString=`CurrentUser {
134
138
  ${this.userInfoString()}
135
139
  UserRoles_UserIDArray {
136
140
  ${this.userRoleInfoString()}
@@ -138,7 +142,7 @@
138
142
  }
139
143
  `,this._currentUserQuery=y.gql`query CurrentUserAndRoles {
140
144
  ${this._innerCurrentUserQueryString}
141
- }`,this._wsClient=null,this._pushStatusRequests=[],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 Se.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 r?(this._configData=e,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)),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=y.gql`
145
+ }`,this._wsClient=null,this._pushStatusRequests=[],h._instance||(h._instance=this)}static get Instance(){return h._instance}get ConfigData(){return this._configData}sanitizeGraphQLName(e){if(!e||e.length===0)return"";let t=e.replace(/[^A-Za-z0-9_]/g,"");return t.startsWith("__")&&(t=t.substring(2)),t=t.replace(/_/g,""),t.length===0||/^[0-9]/.test(t)?"_"+t:t}getGraphQLTypeNameBase(e){const t=e.SchemaName.trim().toLowerCase()===h.MJ_CORE_SCHEMA.trim().toLowerCase()?"MJ":this.sanitizeGraphQLName(e.SchemaName),r=this.sanitizeGraphQLName(e.BaseTable);return`${t}${r}`}get AI(){return this._aiClient||(this._aiClient=new v(this)),this._aiClient}get DatabaseConnection(){throw new Error("DatabaseConnection not implemented for the GraphQLDataProvider")}get InstanceConnectionString(){return this._configData.URL}GenerateUUID(){return he.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 r?(this._configData=e,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)),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=y.gql`
142
146
  query GetReportDataQuery ($ReportID: String!) {
143
147
  GetReportData(ReportID: $ReportID) {
144
148
  Success
@@ -147,19 +151,19 @@
147
151
  ExecutionTime
148
152
  ErrorMessage
149
153
  }
150
- }`,s=await this.ExecuteGQL(r,{ReportID:e.ReportID});if(s&&s.GetReportData)return{ReportID:e.ReportID,Success:s.GetReportData.Success,Results:JSON.parse(s.GetReportData.Results),RowCount:s.GetReportData.RowCount,ExecutionTime:s.GetReportData.ExecutionTime,ErrorMessage:s.GetReportData.ErrorMessage}}async RunQuery(e,t){if(e.QueryID)return this.RunQueryByID(e.QueryID,e.CategoryID,e.CategoryPath,t,e.Parameters,e.MaxRows,e.StartRow);if(e.QueryName)return this.RunQueryByName(e.QueryName,e.CategoryID,e.CategoryPath,t,e.Parameters,e.MaxRows,e.StartRow);throw new Error("No QueryID or QueryName provided to RunQuery")}async RunQueryByID(e,t,r,s,a,n,i){const o=y.gql`
154
+ }`,s=await this.ExecuteGQL(r,{ReportID:e.ReportID});if(s&&s.GetReportData)return{ReportID:e.ReportID,Success:s.GetReportData.Success,Results:JSON.parse(s.GetReportData.Results),RowCount:s.GetReportData.RowCount,ExecutionTime:s.GetReportData.ExecutionTime,ErrorMessage:s.GetReportData.ErrorMessage}}async RunQuery(e,t){if(e.QueryID)return this.RunQueryByID(e.QueryID,e.CategoryID,e.CategoryPath,t,e.Parameters,e.MaxRows,e.StartRow);if(e.QueryName)return this.RunQueryByName(e.QueryName,e.CategoryID,e.CategoryPath,t,e.Parameters,e.MaxRows,e.StartRow);throw new Error("No QueryID or QueryName provided to RunQuery")}async RunQueryByID(e,t,r,s,a,n,o){const i=y.gql`
151
155
  query GetQueryDataQuery($QueryID: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int) {
152
156
  GetQueryData(QueryID: $QueryID, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {
153
157
  ${this.QueryReturnFieldList}
154
158
  }
155
159
  }
156
- `,m={QueryID:e};t!==void 0&&(m.CategoryID=t),r!==void 0&&(m.CategoryPath=r),a!==void 0&&(m.Parameters=a),n!==void 0&&(m.MaxRows=n),i!==void 0&&(m.StartRow=i);const p=await this.ExecuteGQL(o,m);if(p&&p.GetQueryData)return this.TransformQueryPayload(p.GetQueryData)}async RunQueryByName(e,t,r,s,a,n,i){const o=y.gql`
160
+ `,m={QueryID:e};t!==void 0&&(m.CategoryID=t),r!==void 0&&(m.CategoryPath=r),a!==void 0&&(m.Parameters=a),n!==void 0&&(m.MaxRows=n),o!==void 0&&(m.StartRow=o);const p=await this.ExecuteGQL(i,m);if(p&&p.GetQueryData)return this.TransformQueryPayload(p.GetQueryData)}async RunQueryByName(e,t,r,s,a,n,o){const i=y.gql`
157
161
  query GetQueryDataByNameQuery($QueryName: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int) {
158
162
  GetQueryDataByName(QueryName: $QueryName, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {
159
163
  ${this.QueryReturnFieldList}
160
164
  }
161
165
  }
162
- `,m={QueryName:e};t!==void 0&&(m.CategoryID=t),r!==void 0&&(m.CategoryPath=r),a!==void 0&&(m.Parameters=a),n!==void 0&&(m.MaxRows=n),i!==void 0&&(m.StartRow=i);const p=await this.ExecuteGQL(o,m);if(p&&p.GetQueryDataByName)return this.TransformQueryPayload(p.GetQueryDataByName)}get QueryReturnFieldList(){return`
166
+ `,m={QueryName:e};t!==void 0&&(m.CategoryID=t),r!==void 0&&(m.CategoryPath=r),a!==void 0&&(m.Parameters=a),n!==void 0&&(m.MaxRows=n),o!==void 0&&(m.StartRow=o);const p=await this.ExecuteGQL(i,m);if(p&&p.GetQueryDataByName)return this.TransformQueryPayload(p.GetQueryDataByName)}get QueryReturnFieldList(){return`
163
167
  Success
164
168
  QueryID
165
169
  QueryName
@@ -168,11 +172,11 @@
168
172
  TotalRowCount
169
173
  ExecutionTime
170
174
  ErrorMessage
171
- 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 RunView(e,t){await this.PreProcessRunView(e,t);try{let r="",s="";if(e){const a={};let n,i;if(e.ViewEntity)i=e.ViewEntity,n=i.Entity;else{const{entityName:l,v:c}=await this.getEntityNameAndUserView(e,t);i=c,n=l}const o=this.Entities.find(l=>l.Name===n);if(!o)throw new Error(`Entity ${n} not found in metadata`);let m=!1;e.ViewID?(r=`Run${o.ClassName}ViewByID`,s="RunViewByIDInput",a.ViewID=e.ViewID):e.ViewName?(r=`Run${o.ClassName}ViewByName`,s="RunViewByNameInput",a.ViewName=e.ViewName):(m=!0,r=`Run${o.ClassName}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),m||(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 p=this.getViewRunTimeFieldList(o,i,e,m),g=y.gql`
175
+ 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 RunView(e,t){await this.PreProcessRunView(e,t);try{let r="",s="";if(e){const a={};let n,o;if(e.ViewEntity)o=e.ViewEntity,n=o.Entity;else{const{entityName:l,v:c}=await this.getEntityNameAndUserView(e,t);o=c,n=l}const i=this.Entities.find(l=>l.Name===n);if(!i)throw new Error(`Entity ${n} not found in metadata`);let m=!1;const p=this.getGraphQLTypeNameBase(i);e.ViewID?(r=`Run${p}ViewByID`,s="RunViewByIDInput",a.ViewID=e.ViewID):e.ViewName?(r=`Run${p}ViewByName`,s="RunViewByNameInput",a.ViewName=e.ViewName):(m=!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),m||(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(i,o,e,m),D=y.gql`
172
176
  query RunViewQuery ($input: ${s}!) {
173
177
  ${r}(input: $input) {
174
178
  Results {
175
- ${p.join(`
179
+ ${g.join(`
176
180
  `)}
177
181
  }
178
182
  UserViewRunID
@@ -182,7 +186,7 @@
182
186
  Success
183
187
  ErrorMessage
184
188
  }
185
- }`,d=await this.ExecuteGQL(g,{input:a});if(d&&d[r]){const l=d[r].Results;if(l&&l.length>0){const R=o.Fields.filter(S=>S.CodeName!==S.Name&&S.CodeName!==void 0);l.forEach(S=>{this.ConvertBackToMJFields(S),R.forEach(I=>{S[I.Name]=S[I.CodeName]})})}const c=d[r];return await this.PostProcessRunView(c,e,t),c}}else throw"No parameters passed to RunView";return null}catch(r){throw u.LogError(r),r}}async RunViews(e,t){await this.PreProcessRunViews(e,t);try{let r=[],s=[],a=[];for(const o of e){let m="",p="";const g={};let d=null,l=null;if(o.ViewEntity)l=o.ViewEntity,d=l.Get("Entity");else{const{entityName:S,v:I}=await this.getEntityNameAndUserView(o,t);l=I,d=S}const c=this.Entities.find(S=>S.Name===d);if(!c)throw new Error(`Entity ${d} not found in metadata`);s.push(c);let R=!1;o.ViewID?(m=`Run${c.ClassName}ViewByID`,p="RunViewByIDInput",g.ViewID=o.ViewID):o.ViewName?(m=`Run${c.ClassName}ViewByName`,p="RunViewByNameInput",g.ViewName=o.ViewName):(R=!0,m=`Run${c.ClassName}DynamicView`,p="RunDynamicViewInput",g.EntityName=o.EntityName),g.ExtraFilter=o.ExtraFilter||"",g.OrderBy=o.OrderBy||"",g.UserSearchString=o.UserSearchString||"",g.Fields=o.Fields,g.IgnoreMaxRows=o.IgnoreMaxRows||!1,o.MaxRows!==void 0&&(g.MaxRows=o.MaxRows),o.StartRow!==void 0&&(g.StartRow=o.StartRow),g.ForceAuditLog=o.ForceAuditLog||!1,g.ResultType=o.ResultType||"simple",o.AuditLogDescription&&o.AuditLogDescription.length>0&&(g.AuditLogDescription=o.AuditLogDescription),R||(g.ExcludeUserViewRunID=o.ExcludeUserViewRunID||"",g.ExcludeDataFromAllPriorViewRuns=o.ExcludeDataFromAllPriorViewRuns||!1,g.OverrideExcludeFilter=o.OverrideExcludeFilter||"",g.SaveViewResults=o.SaveViewResults||!1),r.push(g),a.push(...this.getViewRunTimeFieldList(c,l,o,R))}const n=y.gql`
189
+ }`,d=await this.ExecuteGQL(D,{input:a});if(d&&d[r]){const l=d[r].Results;if(l&&l.length>0){const R=i.Fields.filter(S=>S.CodeName!==S.Name&&S.CodeName!==void 0);l.forEach(S=>{this.ConvertBackToMJFields(S),R.forEach(w=>{S[w.Name]=S[w.CodeName]})})}const c=d[r];return await this.PostProcessRunView(c,e,t),c}}else throw"No parameters passed to RunView";return null}catch(r){throw u.LogError(r),r}}async RunViews(e,t){await this.PreProcessRunViews(e,t);try{let r=[],s=[],a=[];for(const i of e){let m="",p="";const g={};let D=null,d=null;if(i.ViewEntity)d=i.ViewEntity,D=d.Get("Entity");else{const{entityName:S,v:w}=await this.getEntityNameAndUserView(i,t);d=w,D=S}const l=this.Entities.find(S=>S.Name===D);if(!l)throw new Error(`Entity ${D} not found in metadata`);s.push(l);let c=!1;const R=this.getGraphQLTypeNameBase(l);i.ViewID?(m=`Run${R}ViewByID`,p="RunViewByIDInput",g.ViewID=i.ViewID):i.ViewName?(m=`Run${R}ViewByName`,p="RunViewByNameInput",g.ViewName=i.ViewName):(c=!0,m=`Run${R}DynamicView`,p="RunDynamicViewInput",g.EntityName=i.EntityName),g.ExtraFilter=i.ExtraFilter||"",g.OrderBy=i.OrderBy||"",g.UserSearchString=i.UserSearchString||"",g.Fields=i.Fields,g.IgnoreMaxRows=i.IgnoreMaxRows||!1,i.MaxRows!==void 0&&(g.MaxRows=i.MaxRows),i.StartRow!==void 0&&(g.StartRow=i.StartRow),g.ForceAuditLog=i.ForceAuditLog||!1,g.ResultType=i.ResultType||"simple",i.AuditLogDescription&&i.AuditLogDescription.length>0&&(g.AuditLogDescription=i.AuditLogDescription),c||(g.ExcludeUserViewRunID=i.ExcludeUserViewRunID||"",g.ExcludeDataFromAllPriorViewRuns=i.ExcludeDataFromAllPriorViewRuns||!1,g.OverrideExcludeFilter=i.OverrideExcludeFilter||"",g.SaveViewResults=i.SaveViewResults||!1),r.push(g),a.push(...this.getViewRunTimeFieldList(l,d,i,c))}const n=y.gql`
186
190
  query RunViewsQuery ($input: [RunViewGenericInput!]!) {
187
191
  RunViews(input: $input) {
188
192
  Results {
@@ -200,7 +204,7 @@
200
204
  Success
201
205
  ErrorMessage
202
206
  }
203
- }`,i=await this.ExecuteGQL(n,{input:r});if(i&&i.RunViews){const o=i.RunViews;for(const[m,p]of o.entries())p.Results=p.Results.map(g=>{let d=JSON.parse(g.Data);return this.ConvertBackToMJFields(d),d});return await this.PostProcessRunViews(o,e,t),o}return null}catch(r){throw u.LogError(r),r}}async getEntityNameAndUserView(e,t){let r,s;if(e.EntityName)r=e.EntityName;else if(e.ViewID)s=await de.ViewInfo.GetViewEntity(e.ViewID,t),r=s.Entity;else if(e.ViewName)s=await de.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=[],n=new w;if(r.Fields){for(const i of e.PrimaryKeys)r.Fields.find(o=>o.trim().toLowerCase()===i.Name.toLowerCase())===void 0&&a.push(i.Name);r.Fields.forEach(i=>{a.push(n.MapFieldName(i))})}else if(s)e.Fields.forEach(i=>{i.IsBinaryFieldType||a.push(n.MapFieldName(i.CodeName))});else{for(const i of e.PrimaryKeys)a.find(o=>o.trim().toLowerCase()===i.Name.toLowerCase())===void 0&&a.push(i.Name);t.Columns.forEach(i=>{i.hidden===!1&&!a.find(o=>o.trim().toLowerCase()===i.EntityField?.Name.trim().toLowerCase())&&i.EntityField&&a.push(n.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,n)=>a.ChangedAt>n.ChangedAt?-1:1):null}catch(r){throw u.LogError(r),r}}async GetRecordDependencies(e,t){try{const r=y.gql`query GetRecordDependenciesQuery ($entityName: String!, $CompositeKey: CompositeKeyInputType!) {
207
+ }`,o=await this.ExecuteGQL(n,{input:r});if(o&&o.RunViews){const i=o.RunViews;for(const[m,p]of i.entries())p.Results=p.Results.map(g=>{let D=JSON.parse(g.Data);return this.ConvertBackToMJFields(D),D});return await this.PostProcessRunViews(i,e,t),i}return null}catch(r){throw u.LogError(r),r}}async getEntityNameAndUserView(e,t){let r,s;if(e.EntityName)r=e.EntityName;else if(e.ViewID)s=await de.ViewInfo.GetViewEntity(e.ViewID,t),r=s.Entity;else if(e.ViewName)s=await de.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=[],n=new $;if(r.Fields){for(const o of e.PrimaryKeys)r.Fields.find(i=>i.trim().toLowerCase()===o.Name.toLowerCase())===void 0&&a.push(o.Name);r.Fields.forEach(o=>{a.push(n.MapFieldName(o))})}else if(s)e.Fields.forEach(o=>{o.IsBinaryFieldType||a.push(n.MapFieldName(o.CodeName))});else{for(const o of e.PrimaryKeys)a.find(i=>i.trim().toLowerCase()===o.Name.toLowerCase())===void 0&&a.push(o.Name);t.Columns.forEach(o=>{o.hidden===!1&&!a.find(i=>i.trim().toLowerCase()===o.EntityField?.Name.trim().toLowerCase())&&o.EntityField&&a.push(n.MapFieldName(o.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,n)=>a.ChangedAt>n.ChangedAt?-1:1):null}catch(r){throw u.LogError(r),r}}async GetRecordDependencies(e,t){try{const r=y.gql`query GetRecordDependenciesQuery ($entityName: String!, $CompositeKey: CompositeKeyInputType!) {
204
208
  GetRecordDependencies(entityName: $entityName, CompositeKey: $CompositeKey) {
205
209
  EntityName
206
210
  RelatedEntityName
@@ -251,32 +255,32 @@
251
255
  Message
252
256
  }
253
257
  }
254
- }`,n={EntityName:e.EntityName,SurvivingRecordCompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(e.SurvivingRecordCompositeKey.KeyValuePairs)},FieldMap:e.FieldMap?.map(o=>({FieldName:o.FieldName,Value:o.Value.toString()})),RecordsToMerge:e.RecordsToMerge.map(o=>o.Copy())};return(await this.ExecuteGQL(a,{request:n}))?.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:{}},n=e.IsSaved?"Update":"Create";s.StartedAt=new Date,s.Type=e.IsSaved?"update":"create",s.OriginalValues=e.Fields.map(d=>({FieldName:d.CodeName,Value:d.Value})),e.ResultHistory.push(s);const i=`${n}${e.EntityInfo.ClassName}`,o=e.Fields.filter(d=>!d.ReadOnly||d.IsPrimaryKey&&e.IsSaved),m=new w,p=` ${i}(input: $input) {
255
- ${e.Fields.map(d=>m.MapFieldName(d.CodeName)).join(`
258
+ }`,n={EntityName:e.EntityName,SurvivingRecordCompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(e.SurvivingRecordCompositeKey.KeyValuePairs)},FieldMap:e.FieldMap?.map(i=>({FieldName:i.FieldName,Value:i.Value.toString()})),RecordsToMerge:e.RecordsToMerge.map(i=>i.Copy())};return(await this.ExecuteGQL(a,{request:n}))?.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:{}},n=e.IsSaved?"Update":"Create";s.StartedAt=new Date,s.Type=e.IsSaved?"update":"create",s.OriginalValues=e.Fields.map(d=>({FieldName:d.CodeName,Value:d.Value})),e.ResultHistory.push(s);const o=this.getGraphQLTypeNameBase(e.EntityInfo),i=`${n}${o}`,m=e.Fields.filter(d=>!d.ReadOnly||d.IsPrimaryKey&&e.IsSaved),p=new $,g=` ${i}(input: $input) {
259
+ ${e.Fields.map(d=>p.MapFieldName(d.CodeName)).join(`
256
260
  `)}
257
- }`,g=y.gql`mutation ${n}${e.EntityInfo.ClassName} ($input: ${i}Input!) {
258
- ${p}
261
+ }`,D=y.gql`mutation ${n}${o} ($input: ${i}Input!) {
262
+ ${g}
259
263
  }
260
- `;for(let d=0;d<o.length;d++){const l=o[d];let c=l.Value;if(c)switch(l.EntityFieldInfo.TSType){case u.EntityFieldTSType.Date:c=c.getTime();break;case u.EntityFieldTSType.Boolean:typeof c!="boolean"&&(c=parseInt(c)!==0);break;case u.EntityFieldTSType.Number:if(typeof c!="number"){const R=Number(c);isNaN(R)||(c=R)}break}c===null&&l.EntityFieldInfo.AllowsNull===!1&&(l.EntityFieldInfo.DefaultValue!==null?c=l.EntityFieldInfo.DefaultValue:l.FieldType===u.EntityFieldTSType.Number||l.FieldType===u.EntityFieldTSType.Boolean?c=0:c=""),a.input[l.CodeName]=c}if(n.trim().toLowerCase()==="update"&&r.SkipOldValuesCheck===!1){const d=[];e.Fields.forEach(l=>{let c=null;l.OldValue!==null&&l.OldValue!==void 0&&(l.EntityFieldInfo.TSType===u.EntityFieldTSType.Date?c=l.OldValue.getTime().toString():l.EntityFieldInfo.TSType===u.EntityFieldTSType.Boolean?c=l.OldValue===!0?"1":"0":typeof l.OldValue!="string"?c=l.OldValue.toString():c=l.OldValue),d.push({Key:l.CodeName,Value:c})}),a.input.OldValues___=d}if(e.TransactionGroup){const d=[{varName:"input",inputType:i+"Input!"}];return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new u.TransactionItem(e,s.Type==="create"?"Create":"Update",p,a,{mutationName:i,mutationInputTypes:d},(l,c)=>{s.EndedAt=new Date,c&&l?(s.Success=!0,s.NewValues=this.ConvertBackToMJFields(l)):(s.Success=!1,s.Message="Transaction failed")})),!0}else{const d=await this.ExecuteGQL(g,a);if(d&&d[n+e.EntityInfo.ClassName])return s.Success=!0,s.EndedAt=new Date,s.NewValues=this.ConvertBackToMJFields(d[n+e.EntityInfo.ClassName]),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 n="",i="";for(let d=0;d<t.KeyValuePairs.length;d++){const l=e.Fields.find(S=>S.Name.trim().toLowerCase()===t.KeyValuePairs[d].FieldName.trim().toLowerCase()).EntityFieldInfo,c=t.GetValueByIndex(d),R=l.GraphQLType;if(i.length>0&&(i+=", "),i+=`$${l.CodeName}: ${R}!`,n.length>0&&(n+=", "),n+=`${l.CodeName}: $${l.CodeName}`,l.TSType===u.EntityFieldTSType.Number){if(isNaN(t.GetValueByIndex(d)))throw new Error(`Primary Key value ${c} (${l.Name}) is not a valid number`);a[l.CodeName]=parseInt(c)}else a[l.CodeName]=c}const o=r&&r.length>0?this.getRelatedEntityString(e.EntityInfo,r):"",m=new w,p=y.gql`query Single${e.EntityInfo.ClassName}${o.length>0?"Full":""} (${i}) {
261
- ${e.EntityInfo.ClassName}(${n}) {
264
+ `;for(let d=0;d<m.length;d++){const l=m[d];let c=l.Value;if(c)switch(l.EntityFieldInfo.TSType){case u.EntityFieldTSType.Date:c=c.getTime();break;case u.EntityFieldTSType.Boolean:typeof c!="boolean"&&(c=parseInt(c)!==0);break;case u.EntityFieldTSType.Number:if(typeof c!="number"){const R=Number(c);isNaN(R)||(c=R)}break}c===null&&l.EntityFieldInfo.AllowsNull===!1&&(l.EntityFieldInfo.DefaultValue!==null?c=l.EntityFieldInfo.DefaultValue:l.FieldType===u.EntityFieldTSType.Number||l.FieldType===u.EntityFieldTSType.Boolean?c=0:c=""),a.input[l.CodeName]=c}if(n.trim().toLowerCase()==="update"&&r.SkipOldValuesCheck===!1){const d=[];e.Fields.forEach(l=>{let c=null;l.OldValue!==null&&l.OldValue!==void 0&&(l.EntityFieldInfo.TSType===u.EntityFieldTSType.Date?c=l.OldValue.getTime().toString():l.EntityFieldInfo.TSType===u.EntityFieldTSType.Boolean?c=l.OldValue===!0?"1":"0":typeof l.OldValue!="string"?c=l.OldValue.toString():c=l.OldValue),d.push({Key:l.CodeName,Value:c})}),a.input.OldValues___=d}if(e.TransactionGroup){const d=[{varName:"input",inputType:i+"Input!"}];return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new u.TransactionItem(e,s.Type==="create"?"Create":"Update",g,a,{mutationName:i,mutationInputTypes:d},(l,c)=>{s.EndedAt=new Date,c&&l?(s.Success=!0,s.NewValues=this.ConvertBackToMJFields(l)):(s.Success=!1,s.Message="Transaction failed")})),!0}else{const d=await this.ExecuteGQL(D,a);if(d&&d[i])return s.Success=!0,s.EndedAt=new Date,s.NewValues=this.ConvertBackToMJFields(d[i]),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 n="",o="";for(let d=0;d<t.KeyValuePairs.length;d++){const l=e.Fields.find(S=>S.Name.trim().toLowerCase()===t.KeyValuePairs[d].FieldName.trim().toLowerCase()).EntityFieldInfo,c=t.GetValueByIndex(d),R=l.GraphQLType;if(o.length>0&&(o+=", "),o+=`$${l.CodeName}: ${R}!`,n.length>0&&(n+=", "),n+=`${l.CodeName}: $${l.CodeName}`,l.TSType===u.EntityFieldTSType.Number){if(isNaN(t.GetValueByIndex(d)))throw new Error(`Primary Key value ${c} (${l.Name}) is not a valid number`);a[l.CodeName]=parseInt(c)}else a[l.CodeName]=c}const i=r&&r.length>0?this.getRelatedEntityString(e.EntityInfo,r):"",m=this.getGraphQLTypeNameBase(e.EntityInfo),p=new $,g=y.gql`query Single${m}${i.length>0?"Full":""} (${o}) {
265
+ ${m}(${n}) {
262
266
  ${e.Fields.filter(d=>!d.EntityFieldInfo.IsBinaryFieldType).map(d=>d.EntityFieldInfo.Name.trim().toLowerCase().startsWith("__mj_")?d.CodeName.replace("__mj_","_mj__"):d.CodeName).join(`
263
267
  `)}
264
- ${o}
268
+ ${i}
265
269
  }
266
270
  }
267
- `,g=await this.ExecuteGQL(p,a);return g&&g[e.EntityInfo.ClassName]?this.ConvertBackToMJFields(g[e.EntityInfo.ClassName]):null}catch(a){return u.LogError(a),null}}ConvertBackToMJFields(e){return new w().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],n=this.Entities.find(o=>o.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+=`
268
- ${i} {
269
- ${n.Fields.map(o=>o.CodeName).join(`
271
+ `,D=await this.ExecuteGQL(g,a);return D&&D[m]?this.ConvertBackToMJFields(D[m]):null}catch(a){return u.LogError(a),null}}ConvertBackToMJFields(e){return new $().ReverseMapFields(e),e}getRelatedEntityString(e,t){let r="";for(let s=0;s<e.RelatedEntities.length;s++)if(t.indexOf(e.RelatedEntities[s].RelatedEntity)>=0){const a=e.RelatedEntities[s],n=this.Entities.find(i=>i.ID===a.RelatedEntityID);let o="";a.Type.toLowerCase().trim()==="many to many"?o=`${a.RelatedEntityCodeName}_${a.JoinEntityJoinField.replace(/\s/g,"")}`:o=`${a.RelatedEntityCodeName}_${a.RelatedEntityJoinField.replace(/\s/g,"")}`,r+=`
272
+ ${o} {
273
+ ${n.Fields.map(i=>i.CodeName).join(`
270
274
  `)}
271
275
  }
272
- `}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={},n=[];let i="",o="",m="";for(let l of e.PrimaryKey.KeyValuePairs){const c=e.Fields.find(R=>R.Name.trim().toLowerCase()===l.FieldName.trim().toLowerCase());a[c.CodeName]=c.Value,n.push({varName:c.CodeName,inputType:c.EntityFieldInfo.GraphQLType+"!"}),i.length>0&&(i+=", "),i+=`${c.CodeName}: $${c.CodeName}`,o.length>0&&(o+=", "),o+=`$${c.CodeName}: ${c.EntityFieldInfo.GraphQLType}!`,m.length>0&&(m+=`
273
- `),m+=`${c.CodeName}`}n.push({varName:"options___",inputType:"DeleteOptionsInput!"}),a.options___=t||{SkipEntityAIActions:!1,SkipEntityActions:!1};const p="Delete"+e.EntityInfo.ClassName,g=y.gql`${p}(${i}, options___: $options___) {
276
+ `}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={},n=[];let o="",i="",m="";for(let l of e.PrimaryKey.KeyValuePairs){const c=e.Fields.find(R=>R.Name.trim().toLowerCase()===l.FieldName.trim().toLowerCase());a[c.CodeName]=c.Value,n.push({varName:c.CodeName,inputType:c.EntityFieldInfo.GraphQLType+"!"}),o.length>0&&(o+=", "),o+=`${c.CodeName}: $${c.CodeName}`,i.length>0&&(i+=", "),i+=`$${c.CodeName}: ${c.EntityFieldInfo.GraphQLType}!`,m.length>0&&(m+=`
277
+ `),m+=`${c.CodeName}`}n.push({varName:"options___",inputType:"DeleteOptionsInput!"}),a.options___=t||{SkipEntityAIActions:!1,SkipEntityActions:!1};const g="Delete"+this.getGraphQLTypeNameBase(e.EntityInfo),D=y.gql`${g}(${o}, options___: $options___) {
274
278
  ${m}
275
279
  }
276
- `,d=y.gql`mutation ${p} (${o}, $options___: DeleteOptionsInput!) {
277
- ${g}
280
+ `,d=y.gql`mutation ${g} (${i}, $options___: DeleteOptionsInput!) {
281
+ ${D}
278
282
  }
279
- `;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new u.TransactionItem(e,"Delete",g,a,{mutationName:p,mutationInputTypes:n},(l,c)=>{if(s.EndedAt=new Date,c&&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(d,a);if(l&&l[p]){const c=l[p];for(let R of e.PrimaryKey.KeyValuePairs){let S=c[R.FieldName],I=R.Value;if(typeof I=="number"&&(I=I.toString()),typeof S=="number"&&(S=S.toString()),I!==S)throw new Error(`Primary key value mismatch in server Delete response. Field: ${R.FieldName}, Original: ${I}, 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,u.LogError(a),!1}}async GetDatasetByName(e,t){const r=y.gql`query GetDatasetByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
283
+ `;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new u.TransactionItem(e,"Delete",D,a,{mutationName:g,mutationInputTypes:n},(l,c)=>{if(s.EndedAt=new Date,c&&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(d,a);if(l&&l[g]){const c=l[g];for(let R of e.PrimaryKey.KeyValuePairs){let S=c[R.FieldName],w=R.Value;if(typeof w=="number"&&(w=w.toString()),typeof S=="number"&&(S=S.toString()),w!==S)throw new Error(`Primary key value mismatch in server Delete response. Field: ${R.FieldName}, Original: ${w}, Returned: ${S}`)}return s.Success=!0,s.EndedAt=new Date,!0}else throw new Error(`Delete failed for ${e.EntityInfo.Name}: ${e.PrimaryKey.ToString()} `)}}catch(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=y.gql`query GetDatasetByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
280
284
  GetDatasetByName(DatasetName: $DatasetName, ItemFilters: $ItemFilters) {
281
285
  DatasetID
282
286
  DatasetName
@@ -294,16 +298,16 @@
294
298
  LatestUpdateDate
295
299
  EntityUpdateDates
296
300
  }
297
- }`,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 $(this)}async GetRecordFavoriteStatus(e,t,r){if(!r.Validate().IsValid)return!1;const a=this.Entities.find(o=>o.Name===t);if(!a)throw new Error(`Entity ${t} not found in metadata`);const n=y.gql`query GetRecordFavoriteStatus($params: UserFavoriteSearchParams!) {
301
+ }`,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 N(this)}async GetRecordFavoriteStatus(e,t,r){if(!r.Validate().IsValid)return!1;const a=this.Entities.find(i=>i.Name===t);if(!a)throw new Error(`Entity ${t} not found in metadata`);const n=y.gql`query GetRecordFavoriteStatus($params: UserFavoriteSearchParams!) {
298
302
  GetRecordFavoriteStatus(params: $params) {
299
303
  Success
300
304
  IsFavorite
301
305
  }
302
- }`,i=await this.ExecuteGQL(n,{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 n=this.Entities.find(m=>m.Name===t);if(!n)throw new Error(`Entity ${t} not found in metadata`);const i=y.gql`mutation SetRecordFavoriteStatus($params: UserFavoriteSetParams!) {
306
+ }`,o=await this.ExecuteGQL(n,{params:{UserID:e,EntityID:a.ID,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(r.KeyValuePairs)}}});if(o&&o.GetRecordFavoriteStatus&&o.GetRecordFavoriteStatus.Success)return o.GetRecordFavoriteStatus.IsFavorite}async SetRecordFavoriteStatus(e,t,r,s,a){const n=this.Entities.find(m=>m.Name===t);if(!n)throw new Error(`Entity ${t} not found in metadata`);const o=y.gql`mutation SetRecordFavoriteStatus($params: UserFavoriteSetParams!) {
303
307
  SetRecordFavoriteStatus(params: $params){
304
308
  Success
305
309
  }
306
- }`,o=await this.ExecuteGQL(i,{params:{UserID:e,EntityID:n.ID,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(r.KeyValuePairs)},IsFavorite:s}});if(o&&o.SetRecordFavoriteStatus!==null)return o.SetRecordFavoriteStatus.Success}async GetEntityRecordName(e,t){if(!e||!t||t.KeyValuePairs?.length===0)return null;const r=y.gql`query GetEntityRecordNameQuery ($EntityName: String!, $CompositeKey: CompositeKeyInputType!) {
310
+ }`,i=await this.ExecuteGQL(o,{params:{UserID:e,EntityID:n.ID,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(r.KeyValuePairs)},IsFavorite:s}});if(i&&i.SetRecordFavoriteStatus!==null)return i.SetRecordFavoriteStatus.Success}async GetEntityRecordName(e,t){if(!e||!t||t.KeyValuePairs?.length===0)return null;const r=y.gql`query GetEntityRecordNameQuery ($EntityName: String!, $CompositeKey: CompositeKeyInputType!) {
307
311
  GetEntityRecordName(EntityName: $EntityName, CompositeKey: $CompositeKey) {
308
312
  Success
309
313
  Status
@@ -336,21 +340,21 @@
336
340
  }
337
341
  }`,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(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(){if(this._configData.Data.RefreshTokenFunction){const e=await this._configData.Data.RefreshTokenFunction();if(e)this._configData.Token=e,this._client=this.CreateNewGraphQLClient(this._configData.URL,this._configData.Token,this._sessionId,this._configData.MJAPIKey);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 y.GraphQLClient(e,{headers:a})}userInfoString(){return this.infoString(new u.UserInfo(null,null))}userRoleInfoString(){return this.infoString(new u.UserRoleInfo(null))}infoString(e){let t="";const r=Object.keys(e);for(const s of r)s.startsWith("__mj_")?t+=s.replace("__mj_","_mj__")+`
338
342
  `:s.startsWith("_")||(t+=s+`
339
- `);return t}get LocalStorageProvider(){return this._localStorageProvider||(this._localStorageProvider=new x),this._localStorageProvider}get Metadata(){return this}subscribe(e,t){return this._wsClient||(this._wsClient=me.createClient({url:this.ConfigData.WSURL,connectionParams:{Authorization:"Bearer "+this.ConfigData.Token}})),new ye.Observable(r=>{const s=this._wsClient.subscribe({query:e,variables:t},{next:a=>{r.next(a.data)},error:a=>{r.error(a)},complete:()=>{r.complete()}});return()=>{s()}})}PushStatusUpdates(e=null){e||(e=this.sessionId),this._wsClient||(this._wsClient=me.createClient({url:this.ConfigData.WSURL,connectionParams:{Authorization:"Bearer "+this.ConfigData.Token}}));const t=this._pushStatusRequests.find(a=>a.sessionId===e);if(t)return t.observable;const r=y.gql`subscription StatusUpdates($sessionId: String!) {
343
+ `);return t}get LocalStorageProvider(){return this._localStorageProvider||(this._localStorageProvider=new V),this._localStorageProvider}get Metadata(){return this}subscribe(e,t){return this._wsClient||(this._wsClient=me.createClient({url:this.ConfigData.WSURL,connectionParams:{Authorization:"Bearer "+this.ConfigData.Token}})),new ye.Observable(r=>{const s=this._wsClient.subscribe({query:e,variables:t},{next:a=>{r.next(a.data)},error:a=>{r.error(a)},complete:()=>{r.complete()}});return()=>{s()}})}PushStatusUpdates(e=null){e||(e=this.sessionId),this._wsClient||(this._wsClient=me.createClient({url:this.ConfigData.WSURL,connectionParams:{Authorization:"Bearer "+this.ConfigData.Token}}));const t=this._pushStatusRequests.find(a=>a.sessionId===e);if(t)return t.observable;const r=y.gql`subscription StatusUpdates($sessionId: String!) {
340
344
  statusUpdates(sessionId: $sessionId) {
341
345
  date
342
346
  message
343
347
  sessionId
344
348
  }
345
349
  }
346
- `,s=new ye.Observable(a=>(this._wsClient.subscribe({query:r,variables:{sessionId:e}},{next:n=>a.next(n.data.statusUpdates),error:n=>a.error(n),complete:()=>a.complete()}),()=>{console.log("would unsub here")}));return this._pushStatusRequests.push({sessionId:e,observable:s}),s}};f(h,"GraphQLDataProvider");let v=h;const W=class W{constructor(){this._localStorage={}}async GetItem(e){return new Promise(t=>{this._localStorage.hasOwnProperty(e)?t(this._localStorage[e]):t(null)})}async SetItem(e,t){return new Promise(r=>{this._localStorage[e]=t,r()})}async Remove(e){return new Promise(t=>{this._localStorage.hasOwnProperty(e)&&delete this._localStorage[e],t()})}};f(W,"BrowserStorageProviderBase");let V=W;const Re="MJ_Metadata",E="Metadata_KVPairs",H=class H extends V{constructor(){super(),this.dbPromise=fe.openDB(Re,1,{upgrade(e){e.objectStoreNames.contains(E)||e.createObjectStore(E)}})}async setItem(e,t){const s=(await this.dbPromise).transaction(E,"readwrite");await s.objectStore(E).put(t,e),await s.done}async getItem(e){return await(await this.dbPromise).transaction(E).objectStore(E).get(e)}async remove(e){const r=(await this.dbPromise).transaction(E,"readwrite");await r.objectStore(E).delete(e),await r.done}};f(H,"BrowserIndexedDBStorageProvider");let x=H;async function he(D){const e=new v;return u.SetProvider(e),await e.Config(D),P.MJGlobal.Instance.RaiseEvent({event:P.MJEventType.LoggedIn,eventCode:null,component:this,args:null}),e}f(he,"setupGraphQLClient");const X=class X{};f(X,"SyncRolesAndUsersResult");let T=X;const Z=class Z{};f(Z,"RoleInput");let L=Z;const Y=class Y{};f(Y,"UserInput");let F=Y;const ee=class ee{};f(ee,"RolesAndUsersInput");let U=ee;var ge=(D=>(D.Create="Create",D.Update="Update",D.CreateOrUpdate="CreateOrUpdate",D.Delete="Delete",D.DeleteWithFilter="DeleteWithFilter",D))(ge||{});const te=class te{};f(te,"ActionItemInput");let G=te;const re=class re{constructor(){this.Results=[]}};f(re,"SyncDataResult");let Q=re;const se=class se{};f(se,"ActionItemOutput");let M=se;const ae=class ae{get Client(){return this._client}constructor(e,t,r,s){const a={"x-session-id":r};t&&(a.authorization="Bearer "+t),s&&(a["x-mj-api-key"]=s),this._client=new y.GraphQLClient(e,{headers:a})}async GetData(e,t){try{const s=await this.Client.request(`query GetData($input: GetDataInputType!) {
350
+ `,s=new ye.Observable(a=>(this._wsClient.subscribe({query:r,variables:{sessionId:e}},{next:n=>a.next(n.data.statusUpdates.message),error:n=>a.error(n),complete:()=>a.complete()}),()=>{console.log("would unsub here")}));return this._pushStatusRequests.push({sessionId:e,observable:s}),s}},f(h,"_GraphQLDataProvider"),h);ge.MJ_CORE_SCHEMA="__mj";let pe=ge;const W=class W{constructor(){this._localStorage={}}async GetItem(e){return new Promise(t=>{this._localStorage.hasOwnProperty(e)?t(this._localStorage[e]):t(null)})}async SetItem(e,t){return new Promise(r=>{this._localStorage[e]=t,r()})}async Remove(e){return new Promise(t=>{this._localStorage.hasOwnProperty(e)&&delete this._localStorage[e],t()})}};f(W,"BrowserStorageProviderBase");let L=W;const De="MJ_Metadata",P="Metadata_KVPairs",H=class H extends L{constructor(){super(),this.dbPromise=Re.openDB(De,1,{upgrade(e){e.objectStoreNames.contains(P)||e.createObjectStore(P)}})}async setItem(e,t){const s=(await this.dbPromise).transaction(P,"readwrite");await s.objectStore(P).put(t,e),await s.done}async getItem(e){return await(await this.dbPromise).transaction(P).objectStore(P).get(e)}async remove(e){const r=(await this.dbPromise).transaction(P,"readwrite");await r.objectStore(P).delete(e),await r.done}};f(H,"BrowserIndexedDBStorageProvider");let V=H;async function Ie(I){const e=new pe;return u.SetProvider(e),await e.Config(I),E.MJGlobal.Instance.RaiseEvent({event:E.MJEventType.LoggedIn,eventCode:null,component:this,args:null}),e}f(Ie,"setupGraphQLClient");const X=class X{};f(X,"SyncRolesAndUsersResult");let Q=X;const Z=class Z{};f(Z,"RoleInput");let T=Z;const Y=class Y{};f(Y,"UserInput");let G=Y;const ee=class ee{};f(ee,"RolesAndUsersInput");let F=ee;var fe=(I=>(I.Create="Create",I.Update="Update",I.CreateOrUpdate="CreateOrUpdate",I.Delete="Delete",I.DeleteWithFilter="DeleteWithFilter",I))(fe||{});const te=class te{};f(te,"ActionItemInput");let x=te;const re=class re{constructor(){this.Results=[]}};f(re,"SyncDataResult");let U=re;const se=class se{};f(se,"ActionItemOutput");let b=se;const ae=class ae{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 y.GraphQLClient(e,{headers:a})}async GetData(e,t){try{const s=await this.Client.request(`query GetData($input: GetDataInputType!) {
347
351
  GetData(input: $input) {
348
352
  Success
349
353
  ErrorMessages
350
354
  Queries
351
355
  Results
352
356
  }
353
- }`,{input:{Queries:e,Token:t}});return s&&s.GetData?{Success:s.GetData.Success,Results:s.GetData.Results.map(a=>a?P.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){const s=`GraphQLSystemUserClient::GetData - Error getting data - ${r}`;return u.LogError(s),{Success:!1,Results:[],ErrorMessages:[s],Queries:e}}}async GetAllRemoteEntities(){try{const t=await this.Client.request(`query GetAllEntities {
357
+ }`,{input:{Queries:e,Token:t}});return s&&s.GetData?{Success:s.GetData.Success,Results:s.GetData.Results.map(a=>a?E.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){const s=`GraphQLSystemUserClient::GetData - Error getting data - ${r}`;return u.LogError(s),{Success:!1,Results:[],ErrorMessages:[s],Queries:e}}}async GetAllRemoteEntities(){try{const t=await this.Client.request(`query GetAllEntities {
354
358
  GetAllEntities {
355
359
  Success
356
360
  ErrorMessage
@@ -481,7 +485,7 @@
481
485
  ErrorMessage
482
486
  AppliedParameters
483
487
  }
484
- }`,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?P.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) {
488
+ }`,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?E.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) {
485
489
  GetQueryDataByNameSystemUser(QueryName: $QueryName, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {
486
490
  QueryID
487
491
  QueryName
@@ -493,7 +497,7 @@
493
497
  ErrorMessage
494
498
  AppliedParameters
495
499
  }
496
- }`,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?P.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!) {
500
+ }`,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?E.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!) {
497
501
  CreateQuerySystemUser(input: $input) {
498
502
  Success
499
503
  ErrorMessage
@@ -661,10 +665,10 @@
661
665
  success
662
666
  errorMessage
663
667
  executionTimeMs
664
- payload
668
+ result
665
669
  }
666
670
  }
667
- `,r=this.prepareAgentVariables(e),s=await this.Client.request(t,r);return s&&s.RunAIAgentSystemUser?this.processAgentResult(s.RunAIAgentSystemUser):{success:!1,errorMessage:"Failed to execute AI agent as system user"}}catch(t){return u.LogError(`GraphQLSystemUserClient::RunAIAgent - Error running AI agent - ${t}`),{success:!1,errorMessage:t.toString()}}}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.agentId,messages:JSON.stringify(e.messages),sessionId:e.sessionId};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.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){let t;try{e.payload&&(t=JSON.parse(e.payload))}catch{t=e.payload}return{success:e.success,errorMessage:e.errorMessage,executionTimeMs:e.executionTimeMs,payload:t}}async ExecuteSimplePrompt(e){try{const t=y.gql`
671
+ `,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 E.SafeJSONParse(e)}async ExecuteSimplePrompt(e){try{const t=y.gql`
668
672
  query ExecuteSimplePromptSystemUser(
669
673
  $systemPrompt: String!,
670
674
  $messages: String,
@@ -702,7 +706,7 @@
702
706
  error
703
707
  }
704
708
  }
705
- `,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 n=a.EmbedTextSystemUser;return{embeddings:Array.isArray(e.textToEmbed)?n.embeddings:n.embeddings[0],modelName:n.modelName,vectorDimensions:n.vectorDimensions,error:n.error}}catch(t){return u.LogError(`GraphQLSystemUserClient::EmbedText - Error generating embeddings - ${t}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:t.toString()}}}};f(ae,"GraphQLSystemUserClient");let b=ae;const ne=class ne{};f(ne,"GetDataOutput");let q=ne;const oe=class oe{};f(oe,"SimpleRemoteEntityOutput");let A=oe;const ie=class ie{};f(ie,"SimpleRemoteEntity");let O=ie;const ue=class ue{};f(ue,"SimpleRemoteEntityField");let _=ue;const le=class le{constructor(e){this._dataProvider=e}async RunAction(e,t,r=!1){try{const s=this.serializeActionParameters(t),a=this.createActionVariables(e,s,r),n=await this.executeActionMutation(a);return this.processActionResult(n,t)}catch(s){return this.handleActionError(s,t)}}serializeActionParameters(e){if(e)return e.map(t=>{let r=t.Value;return r!=null&&typeof r=="object"&&(r=JSON.stringify(r)),{...t,Value:r}})}createActionVariables(e,t,r=!1){return{input:{ActionID:e,Params:t,SkipActionLog:r}}}async executeActionMutation(e){const t=y.gql`
709
+ `,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 n=a.EmbedTextSystemUser;return{embeddings:Array.isArray(e.textToEmbed)?n.embeddings:n.embeddings[0],modelName:n.modelName,vectorDimensions:n.vectorDimensions,error:n.error}}catch(t){return u.LogError(`GraphQLSystemUserClient::EmbedText - Error generating embeddings - ${t}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:t.toString()}}}};f(ae,"GraphQLSystemUserClient");let M=ae;const ne=class ne{};f(ne,"GetDataOutput");let q=ne;const oe=class oe{};f(oe,"SimpleRemoteEntityOutput");let A=oe;const ie=class ie{};f(ie,"SimpleRemoteEntity");let O=ie;const ue=class ue{};f(ue,"SimpleRemoteEntityField");let _=ue;const le=class le{constructor(e){this._dataProvider=e}async RunAction(e,t,r=!1){try{const s=this.serializeActionParameters(t),a=this.createActionVariables(e,s,r),n=await this.executeActionMutation(a);return this.processActionResult(n,t)}catch(s){return this.handleActionError(s,t)}}serializeActionParameters(e){if(e)return e.map(t=>{let r=t.Value;return r!=null&&typeof r=="object"&&(r=JSON.stringify(r)),{...t,Value:r}})}createActionVariables(e,t,r=!1){return{input:{ActionID:e,Params:t,SkipActionLog:r}}}async executeActionMutation(e){const t=y.gql`
706
710
  mutation RunAction($input: RunActionInput!) {
707
711
  RunAction(input: $input) {
708
712
  Success
@@ -761,7 +765,7 @@
761
765
  specification
762
766
  }
763
767
  }
764
- `,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 n;if(a.specification)try{n=JSON.parse(a.specification)}catch(i){u.LogError(`Failed to parse component specification in GetRegistryComponentWithHash: ${i}`),n=void 0}return{specification:n,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=y.gql`
768
+ `,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 n;if(a.specification)try{n=JSON.parse(a.specification)}catch(o){u.LogError(`Failed to parse component specification in GetRegistryComponentWithHash: ${o}`),n=void 0}return{specification:n,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=y.gql`
765
769
  query SearchRegistryComponents($params: SearchRegistryComponentsInput!) {
766
770
  SearchRegistryComponents(params: $params) {
767
771
  components
@@ -795,5 +799,13 @@
795
799
  }
796
800
  }
797
801
  }
798
- `,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}}};f(ce,"GraphQLComponentRegistryClient");let k=ce;Object.defineProperty(exports,"gql",{enumerable:!0,get:function(){return y.gql}}),exports.ActionItemInput=G,exports.ActionItemOutput=M,exports.FieldMapper=w,exports.GetDataOutput=q,exports.GraphQLAIClient=N,exports.GraphQLActionClient=B,exports.GraphQLComponentRegistryClient=k,exports.GraphQLDataProvider=v,exports.GraphQLProviderConfigData=C,exports.GraphQLSystemUserClient=b,exports.GraphQLTransactionGroup=$,exports.RoleInput=L,exports.RolesAndUsersInput=U,exports.SimpleRemoteEntity=O,exports.SimpleRemoteEntityField=_,exports.SimpleRemoteEntityOutput=A,exports.SyncDataAction=ge,exports.SyncDataResult=Q,exports.SyncRolesAndUsersResult=T,exports.UserInput=F,exports.setupGraphQLClient=he;
802
+ `,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=y.gql`
803
+ mutation SendComponentFeedback($feedback: ComponentFeedbackInput!) {
804
+ SendComponentFeedback(feedback: $feedback) {
805
+ success
806
+ feedbackID
807
+ error
808
+ }
809
+ }
810
+ `,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"}}}};f(ce,"GraphQLComponentRegistryClient");let k=ce;Object.defineProperty(exports,"gql",{enumerable:!0,get:function(){return y.gql}}),exports.ActionItemInput=x,exports.ActionItemOutput=b,exports.FieldMapper=$,exports.GetDataOutput=q,exports.GraphQLAIClient=v,exports.GraphQLActionClient=B,exports.GraphQLComponentRegistryClient=k,exports.GraphQLDataProvider=pe,exports.GraphQLProviderConfigData=C,exports.GraphQLSystemUserClient=M,exports.GraphQLTransactionGroup=N,exports.RoleInput=T,exports.RolesAndUsersInput=F,exports.SimpleRemoteEntity=O,exports.SimpleRemoteEntityField=_,exports.SimpleRemoteEntityOutput=A,exports.SyncDataAction=fe,exports.SyncDataResult=U,exports.SyncRolesAndUsersResult=Q,exports.UserInput=G,exports.setupGraphQLClient=Ie;
799
811
  //# sourceMappingURL=index.cjs.map