@memberjunction/graphql-dataprovider 3.2.0 → 3.4.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 +115 -85
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +164 -3
- package/dist/index.d.mts +164 -3
- package/dist/index.mjs +114 -84
- package/dist/index.mjs.map +1 -1
- package/package.json +7 -7
package/dist/index.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var ve=Object.defineProperty;var f=(w,e)=>ve(w,"name",{value:e,configurable:!0});var y=require("graphql-request"),u=require("@memberjunction/core"),Ee=require("@memberjunction/core-entities"),C=require("rxjs"),$e=require("graphql-ws"),Ce=require("uuid"),P=require("@memberjunction/global"),Ne=require("@tempfix/idb");const Y=class Y{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(Y,"FieldMapper");let $=Y;const Z=class Z 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,
|
|
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=P.SafeJSONParse(n),l=this.PendingTransactions[i];o.push(new u.TransactionResult(l,c,c!==null))}return o}else throw new Error("Failed to execute transaction group")}};f(Z,"GraphQLTransactionGroup");let b=Z;const ee=class ee{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,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
|
|
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 l={...c.data.progress,metadata:{...c.data.progress.metadata||{},agentRunId:c.data.agentRunId}};e.onProgress(l)}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=y.gql`
|
|
69
69
|
mutation RunAIAgent(
|
|
70
70
|
$agentId: String!,
|
|
71
71
|
$messages: String!,
|
|
@@ -104,7 +104,7 @@
|
|
|
104
104
|
result
|
|
105
105
|
}
|
|
106
106
|
}
|
|
107
|
-
`,
|
|
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 P.SafeJSONParse(e)}handleAgentError(e){const t=e;return u.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=y.gql`
|
|
108
108
|
mutation RunAIAgentFromConversationDetail(
|
|
109
109
|
$conversationDetailId: String!,
|
|
110
110
|
$agentId: String!,
|
|
@@ -141,7 +141,7 @@
|
|
|
141
141
|
result
|
|
142
142
|
}
|
|
143
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=
|
|
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=y.gql`
|
|
145
145
|
mutation ExecuteSimplePrompt(
|
|
146
146
|
$systemPrompt: String!,
|
|
147
147
|
$messages: String,
|
|
@@ -164,7 +164,7 @@
|
|
|
164
164
|
executionTimeMs
|
|
165
165
|
}
|
|
166
166
|
}
|
|
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
|
|
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 u.LogError(`Error executing simple prompt: ${r}`),{success:!1,modelName:"Unknown",error:r.message||"Unknown error occurred"}}}async EmbedText(e){try{const t=y.gql`
|
|
168
168
|
mutation EmbedText(
|
|
169
169
|
$textToEmbed: [String!]!,
|
|
170
170
|
$modelSize: String!
|
|
@@ -179,15 +179,15 @@
|
|
|
179
179
|
error
|
|
180
180
|
}
|
|
181
181
|
}
|
|
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
|
|
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 u.LogError(`Error generating embeddings: ${r}`),{embeddings:Array.isArray(e.textToEmbed)?[]:[],modelName:"Unknown",vectorDimensions:0,error:r.message||"Unknown error occurred"}}}};f(ee,"GraphQLAIClient");let A=ee;const v="default",te=class te{constructor(){this._storage=new Map}getCategoryMap(e){const t=e||v;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||v).get(e)??null}async SetItem(e,t,r){this.getCategoryMap(r||v).set(e,t)}async Remove(e,t){this.getCategoryMap(t||v).delete(e)}async ClearCategory(e){const t=e||v;this._storage.delete(t)}async GetCategoryKeys(e){const t=this._storage.get(e||v);return t?Array.from(t.keys()):[]}};f(te,"BrowserStorageProviderBase");let x=te;const be="MJ_Metadata",Ae=3,De=["mj:default","mj:Metadata","mj:RunViewCache","mj:RunQueryCache","mj:DatasetCache"],we="Metadata_KVPairs",re=class re extends x{constructor(){super(),this._dbReady=!1,this.dbPromise=Ne.openDB(be,Ae,{upgrade(e){try{e.objectStoreNames.contains(we)&&e.deleteObjectStore(we);for(const t of De)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 De.includes(t)}getStoreName(e){const t=e||v;return this.isKnownCategory(t)?`mj:${t}`:"mj:default"}getStoreKey(e,t){const r=t||v;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||v,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||v,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)}}};f(re,"BrowserIndexedDBStorageProvider");let L=re;const se=class se 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 UserAPIKey(){return this.Data.UserAPIKey}set UserAPIKey(e){this.Data.UserAPIKey=e}get URL(){return this.Data.URL}get WSURL(){return this.Data.WSURL}get RefreshTokenFunction(){return this.Data.RefreshFunction}constructor(e,t,r,s,a,o,i,n,c){super({Token:e,URL:t,WSURL:r,MJAPIKey:n,UserAPIKey:c,RefreshTokenFunction:s},a,o,i)}};f(se,"GraphQLProviderConfigData");let M=se;const h=class h extends u.ProviderBase{constructor(){super(),this._refreshPromise=null,this._innerCurrentUserQueryString=`CurrentUser {
|
|
183
183
|
${this.userInfoString()}
|
|
184
184
|
UserRoles_UserIDArray {
|
|
185
185
|
${this.userRoleInfoString()}
|
|
186
186
|
}
|
|
187
187
|
}
|
|
188
|
-
`,this._currentUserQuery=
|
|
188
|
+
`,this._currentUserQuery=y.gql`query CurrentUserAndRoles {
|
|
189
189
|
${this._innerCurrentUserQueryString}
|
|
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
|
|
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 A(this)),this._aiClient}get DatabaseConnection(){throw new Error("DatabaseConnection not implemented for the GraphQLDataProvider")}get InstanceConnectionString(){return this._configData.URL}GenerateUUID(){return Ce.v4()}get LocalStoragePrefix(){if(this._configData===void 0||this._configData.URL===void 0)throw new Error("GraphQLDataProvider: ConfigData is not set. Please call Config() first.");return this._configData.URL.replace(/[^a-zA-Z0-9]/g,"_")+"."}async GetStoredSessionID(){try{const e=this.LocalStorageProvider;if(e){const t=this.LocalStoragePrefix+"sessionId";return await e.GetItem(t)}return null}catch(e){return console.error("Error retrieving session ID from local storage:",e),null}}async SaveStoredSessionID(e){try{const t=this.LocalStorageProvider;if(t){const r=this.LocalStoragePrefix+"sessionId";await t.SetItem(r,e)}}catch{}}async GetPreferredUUID(e){const t=await this.GetStoredSessionID();return e||!t?this.GenerateUUID():t}async Config(e,t,r,s){try{return this._configData=e,r?(this._sessionId=await this.GetPreferredUUID(s),this._client=this.CreateNewGraphQLClient(e.URL,e.Token,this._sessionId,e.MJAPIKey,e.UserAPIKey),await this.SaveStoredSessionID(this._sessionId)):(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,e.UserAPIKey)),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=y.gql`
|
|
191
191
|
query GetReportDataQuery ($ReportID: String!) {
|
|
192
192
|
GetReportData(ReportID: $ReportID) {
|
|
193
193
|
Success
|
|
@@ -196,25 +196,25 @@
|
|
|
196
196
|
ExecutionTime
|
|
197
197
|
ErrorMessage
|
|
198
198
|
}
|
|
199
|
-
}`,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 InternalRunQuery(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 InternalRunQueries(e,t){const r=
|
|
199
|
+
}`,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 InternalRunQuery(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 InternalRunQueries(e,t){const r=y.gql`
|
|
200
200
|
query RunQueriesBatch($input: [RunQueryInput!]!) {
|
|
201
201
|
RunQueries(input: $input) {
|
|
202
202
|
${this.QueryReturnFieldList}
|
|
203
203
|
}
|
|
204
204
|
}
|
|
205
|
-
`,s=e.map(
|
|
205
|
+
`,s=e.map(o=>({QueryID:o.QueryID,QueryName:o.QueryName,CategoryID:o.CategoryID,CategoryPath:o.CategoryPath,Parameters:o.Parameters,MaxRows:o.MaxRows,StartRow:o.StartRow,ForceAuditLog:o.ForceAuditLog,AuditLogDescription:o.AuditLogDescription})),a=await this.ExecuteGQL(r,{input:s});return a&&a.RunQueries?a.RunQueries.map(o=>this.TransformQueryPayload(o)):[]}async RunQueryByID(e,t,r,s,a,o,i){const n=y.gql`
|
|
206
206
|
query GetQueryDataQuery($QueryID: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int) {
|
|
207
207
|
GetQueryData(QueryID: $QueryID, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {
|
|
208
208
|
${this.QueryReturnFieldList}
|
|
209
209
|
}
|
|
210
210
|
}
|
|
211
|
-
`,
|
|
211
|
+
`,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 l=await this.ExecuteGQL(n,c);if(l&&l.GetQueryData)return this.TransformQueryPayload(l.GetQueryData)}async RunQueryByName(e,t,r,s,a,o,i){const n=y.gql`
|
|
212
212
|
query GetQueryDataByNameQuery($QueryName: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int) {
|
|
213
213
|
GetQueryDataByName(QueryName: $QueryName, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {
|
|
214
214
|
${this.QueryReturnFieldList}
|
|
215
215
|
}
|
|
216
216
|
}
|
|
217
|
-
`,
|
|
217
|
+
`,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 l=await this.ExecuteGQL(n,c);if(l&&l.GetQueryDataByName)return this.TransformQueryPayload(l.GetQueryDataByName)}get QueryReturnFieldList(){return`
|
|
218
218
|
Success
|
|
219
219
|
QueryID
|
|
220
220
|
QueryName
|
|
@@ -223,7 +223,7 @@
|
|
|
223
223
|
TotalRowCount
|
|
224
224
|
ExecutionTime
|
|
225
225
|
ErrorMessage
|
|
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
|
|
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 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=y.gql`
|
|
227
227
|
query RunQueriesWithCacheCheckQuery($input: [RunQueryWithCacheCheckInput!]!) {
|
|
228
228
|
RunQueriesWithCacheCheck(input: $input) {
|
|
229
229
|
success
|
|
@@ -239,11 +239,18 @@
|
|
|
239
239
|
}
|
|
240
240
|
}
|
|
241
241
|
}
|
|
242
|
-
`,
|
|
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 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:m,v:S}=await this.getEntityNameAndUserView(e,t);i=S,o=m}const n=this.Entities.find(m=>m.Name===o);if(!n)throw new Error(`Entity ${o} not found in metadata`);let c=!1;const l=u.getGraphQLTypeNameBase(n);e.ViewID?(r=`Run${l}ViewByID`,s="RunViewByIDInput",a.ViewID=e.ViewID):e.ViewName?(r=`Run${l}ViewByName`,s="RunViewByNameInput",a.ViewName=e.ViewName):(c=!0,r=`Run${l}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),e.Aggregates&&e.Aggregates.length>0&&(a.Aggregates=e.Aggregates.map(m=>({expression:m.expression,alias:m.alias})));const p=this.getViewRunTimeFieldList(n,i,e,c),I=e.Aggregates&&e.Aggregates.length>0?`
|
|
243
|
+
AggregateResults {
|
|
244
|
+
alias
|
|
245
|
+
expression
|
|
246
|
+
value
|
|
247
|
+
error
|
|
248
|
+
}
|
|
249
|
+
AggregateExecutionTime`:"",d=y.gql`
|
|
243
250
|
query RunViewQuery ($input: ${s}!) {
|
|
244
251
|
${r}(input: $input) {
|
|
245
252
|
Results {
|
|
246
|
-
${
|
|
253
|
+
${p.join(`
|
|
247
254
|
`)}
|
|
248
255
|
}
|
|
249
256
|
UserViewRunID
|
|
@@ -251,9 +258,16 @@
|
|
|
251
258
|
TotalRowCount
|
|
252
259
|
ExecutionTime
|
|
253
260
|
Success
|
|
254
|
-
ErrorMessage
|
|
261
|
+
ErrorMessage${I}
|
|
262
|
+
}
|
|
263
|
+
}`;a.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Sending RunView with aggregates:",{entityName:o,queryName:r,aggregateCount:a.Aggregates.length,aggregates:a.Aggregates});const g=await this.ExecuteGQL(d,{input:a});if(g&&g[r]){const m=g[r].AggregateResults;a.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Received aggregate results:",{entityName:o,aggregateResultCount:m?.length||0,aggregateResults:m,aggregateExecutionTime:g[r].AggregateExecutionTime});const S=g[r].Results;if(S&&S.length>0){const D=n.Fields.filter(E=>E.CodeName!==E.Name&&E.CodeName!==void 0);S.forEach(E=>{this.ConvertBackToMJFields(E),D.forEach(N=>{E[N.Name]=E[N.CodeName]})})}return g[r]}}else throw"No parameters passed to RunView";return null}catch(r){throw u.LogError(r),r}}async InternalRunViews(e,t){try{let r=[],s=[],a=[];for(const l of e){let p="",I="";const d={};let g=null,m=null;if(l.ViewEntity)m=l.ViewEntity,g=m.Get("Entity");else{const{entityName:E,v:N}=await this.getEntityNameAndUserView(l,t);m=N,g=E}const S=this.Entities.find(E=>E.Name===g);if(!S)throw new Error(`Entity ${g} not found in metadata`);s.push(S);let R=!1;const D=u.getGraphQLTypeNameBase(S);l.ViewID?(p=`Run${D}ViewByID`,I="RunViewByIDInput",d.ViewID=l.ViewID):l.ViewName?(p=`Run${D}ViewByName`,I="RunViewByNameInput",d.ViewName=l.ViewName):(R=!0,p=`Run${D}DynamicView`,I="RunDynamicViewInput",d.EntityName=l.EntityName),d.ExtraFilter=l.ExtraFilter||"",d.OrderBy=l.OrderBy||"",d.UserSearchString=l.UserSearchString||"",d.Fields=l.Fields,d.IgnoreMaxRows=l.IgnoreMaxRows||!1,l.MaxRows!==void 0&&(d.MaxRows=l.MaxRows),l.StartRow!==void 0&&(d.StartRow=l.StartRow),d.ForceAuditLog=l.ForceAuditLog||!1,d.ResultType=l.ResultType||"simple",l.AuditLogDescription&&l.AuditLogDescription.length>0&&(d.AuditLogDescription=l.AuditLogDescription),R||(d.ExcludeUserViewRunID=l.ExcludeUserViewRunID||"",d.ExcludeDataFromAllPriorViewRuns=l.ExcludeDataFromAllPriorViewRuns||!1,d.OverrideExcludeFilter=l.OverrideExcludeFilter||"",d.SaveViewResults=l.SaveViewResults||!1),l.Aggregates&&l.Aggregates.length>0&&(d.Aggregates=l.Aggregates.map(E=>({expression:E.expression,alias:E.alias}))),r.push(d),a.push(...this.getViewRunTimeFieldList(S,m,l,R))}const i=e.some(l=>l.Aggregates&&l.Aggregates.length>0)?`
|
|
264
|
+
AggregateResults {
|
|
265
|
+
alias
|
|
266
|
+
expression
|
|
267
|
+
value
|
|
268
|
+
error
|
|
255
269
|
}
|
|
256
|
-
|
|
270
|
+
AggregateExecutionTime`:"",n=y.gql`
|
|
257
271
|
query RunViewsQuery ($input: [RunViewGenericInput!]!) {
|
|
258
272
|
RunViews(input: $input) {
|
|
259
273
|
Results {
|
|
@@ -269,9 +283,9 @@
|
|
|
269
283
|
TotalRowCount
|
|
270
284
|
ExecutionTime
|
|
271
285
|
Success
|
|
272
|
-
ErrorMessage
|
|
286
|
+
ErrorMessage${i}
|
|
273
287
|
}
|
|
274
|
-
}`,
|
|
288
|
+
}`,c=await this.ExecuteGQL(n,{input:r});if(c&&c.RunViews){const l=c.RunViews;for(const[p,I]of l.entries())I.Results=I.Results.map(d=>{let g=JSON.parse(d.Data);return this.ConvertBackToMJFields(g),g});return l}return null}catch(r){throw u.LogError(r),r}}async RunViewsWithCacheCheck(e,t){try{const r=e.map(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=y.gql`
|
|
275
289
|
query RunViewsWithCacheCheckQuery($input: [RunViewWithCacheCheckInput!]!) {
|
|
276
290
|
RunViewsWithCacheCheck(input: $input) {
|
|
277
291
|
success
|
|
@@ -304,7 +318,7 @@
|
|
|
304
318
|
}
|
|
305
319
|
}
|
|
306
320
|
}
|
|
307
|
-
`,
|
|
321
|
+
`,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 l=e[c];if(n.status==="differential"&&n.differentialData){const p=n.differentialData.updatedRows.map(I=>{const d=JSON.parse(I.Data);return this.ConvertBackToMJFields(d),d});return{viewIndex:n.viewIndex,status:n.status,results:void 0,differentialData:{updatedRows:p,deletedRecordIDs:n.differentialData.deletedRecordIDs},maxUpdatedAt:n.maxUpdatedAt,rowCount:n.rowCount,errorMessage:n.errorMessage}}if(n.status==="stale"&&n.Results){const p=n.Results.map(I=>{const d=JSON.parse(I.Data);return this.ConvertBackToMJFields(d),d});return{viewIndex:n.viewIndex,status:n.status,results:p,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 Ee.ViewInfo.GetViewEntity(e.ViewID,t),r=s.Entity;else if(e.ViewName)s=await Ee.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 $;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=y.gql`query GetRecordDependenciesQuery ($entityName: String!, $CompositeKey: CompositeKeyInputType!) {
|
|
308
322
|
GetRecordDependencies(entityName: $entityName, CompositeKey: $CompositeKey) {
|
|
309
323
|
EntityName
|
|
310
324
|
RelatedEntityName
|
|
@@ -316,7 +330,7 @@
|
|
|
316
330
|
}
|
|
317
331
|
}
|
|
318
332
|
}
|
|
319
|
-
}`,s={entityName:e,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(t.KeyValuePairs)}};return(await this.ExecuteGQL(r,s))?.GetRecordDependencies}catch(r){throw
|
|
333
|
+
}`,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=y.gql`query GetRecordDuplicatesQuery ($params: PotentialDuplicateRequestType!) {
|
|
320
334
|
GetRecordDuplicates(params: $params) {
|
|
321
335
|
Status
|
|
322
336
|
ErrorMessage
|
|
@@ -338,7 +352,7 @@
|
|
|
338
352
|
}
|
|
339
353
|
}
|
|
340
354
|
}
|
|
341
|
-
}`;let s={EntityID:e.EntityID,EntityDocumentID:e.EntityDocumentID,ListID:e.ListID,ProbabilityScore:e.ProbabilityScore,Options:e.Options,RecordIDs:e.RecordIDs.map(
|
|
355
|
+
}`;let s={EntityID:e.EntityID,EntityDocumentID:e.EntityDocumentID,ListID:e.ListID,ProbabilityScore:e.ProbabilityScore,Options:e.Options,RecordIDs:e.RecordIDs.map(o=>o.Copy())};const a=await this.ExecuteGQL(r,{params:s});if(a&&a.GetRecordDuplicates)return a.GetRecordDuplicates}async MergeRecords(e,t,r){const s=this.Entities.find(a=>a.Name.trim().toLowerCase()===e.EntityName.trim().toLowerCase());if(!s||!s.AllowRecordMerge)throw new Error(`Entity ${e.EntityName} does not allow record merging, check the AllowRecordMerge property in the entity metadata`);try{const a=y.gql`mutation MergeRecordsMutation ($request: RecordMergeRequest!) {
|
|
342
356
|
MergeRecords(request: $request) {
|
|
343
357
|
Success
|
|
344
358
|
OverallStatus
|
|
@@ -355,32 +369,32 @@
|
|
|
355
369
|
Message
|
|
356
370
|
}
|
|
357
371
|
}
|
|
358
|
-
}`,
|
|
359
|
-
${e.Fields.map(
|
|
372
|
+
}`,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(d=>({FieldName:d.CodeName,Value:d.Value})),e.ResultHistory.push(s);const i=u.getGraphQLTypeNameBase(e.EntityInfo),n=`${o}${i}`,c=e.Fields.filter(d=>!d.ReadOnly||d.IsPrimaryKey&&e.IsSaved),l=new $,p=` ${n}(input: $input) {
|
|
373
|
+
${e.Fields.map(d=>l.MapFieldName(d.CodeName)).join(`
|
|
360
374
|
`)}
|
|
361
|
-
}`,
|
|
362
|
-
${
|
|
375
|
+
}`,I=y.gql`mutation ${o}${i} ($input: ${n}Input!) {
|
|
376
|
+
${p}
|
|
363
377
|
}
|
|
364
|
-
`;for(let
|
|
365
|
-
${
|
|
366
|
-
${e.Fields.filter(
|
|
378
|
+
`;for(let d=0;d<c.length;d++){const g=c[d];let m=g.Value;if(m)switch(g.EntityFieldInfo.TSType){case u.EntityFieldTSType.Date:m=m.getTime();break;case u.EntityFieldTSType.Boolean:typeof m!="boolean"&&(m=parseInt(m)!==0);break;case u.EntityFieldTSType.Number:if(typeof m!="number"){const S=Number(m);isNaN(S)||(m=S)}break}m===null&&g.EntityFieldInfo.AllowsNull===!1&&(g.EntityFieldInfo.DefaultValue!==null?m=g.EntityFieldInfo.DefaultValue:g.FieldType===u.EntityFieldTSType.Number||g.FieldType===u.EntityFieldTSType.Boolean?m=0:m=""),a.input[g.CodeName]=m}if(o.trim().toLowerCase()==="update"&&r.SkipOldValuesCheck===!1){const d=[];e.Fields.forEach(g=>{let m=null;g.OldValue!==null&&g.OldValue!==void 0&&(g.EntityFieldInfo.TSType===u.EntityFieldTSType.Date?m=g.OldValue.getTime().toString():g.EntityFieldInfo.TSType===u.EntityFieldTSType.Boolean?m=g.OldValue===!0?"1":"0":typeof g.OldValue!="string"?m=g.OldValue.toString():m=g.OldValue),d.push({Key:g.CodeName,Value:m})}),a.input.OldValues___=d}if(e.TransactionGroup){const d=[{varName:"input",inputType:n+"Input!"}];return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new u.TransactionItem(e,s.Type==="create"?"Create":"Update",p,a,{mutationName:n,mutationInputTypes:d},(g,m)=>{s.EndedAt=new Date,m&&g?(s.Success=!0,s.NewValues=this.ConvertBackToMJFields(g)):(s.Success=!1,s.Message="Transaction failed")})),!0}else{const d=await this.ExecuteGQL(I,a);if(d&&d[n])return s.Success=!0,s.EndedAt=new Date,s.NewValues=this.ConvertBackToMJFields(d[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 d=0;d<t.KeyValuePairs.length;d++){const g=e.Fields.find(R=>R.Name.trim().toLowerCase()===t.KeyValuePairs[d].FieldName.trim().toLowerCase()).EntityFieldInfo,m=t.GetValueByIndex(d),S=g.GraphQLType;if(i.length>0&&(i+=", "),i+=`$${g.CodeName}: ${S}!`,o.length>0&&(o+=", "),o+=`${g.CodeName}: $${g.CodeName}`,g.TSType===u.EntityFieldTSType.Number){if(isNaN(t.GetValueByIndex(d)))throw new Error(`Primary Key value ${m} (${g.Name}) is not a valid number`);a[g.CodeName]=parseInt(m)}else a[g.CodeName]=m}const n=r&&r.length>0?this.getRelatedEntityString(e.EntityInfo,r):"",c=u.getGraphQLTypeNameBase(e.EntityInfo),l=new $,p=y.gql`query Single${c}${n.length>0?"Full":""} (${i}) {
|
|
379
|
+
${c}(${o}) {
|
|
380
|
+
${e.Fields.filter(d=>!d.EntityFieldInfo.IsBinaryFieldType).map(d=>d.EntityFieldInfo.Name.trim().toLowerCase().startsWith("__mj_")?d.CodeName.replace("__mj_","_mj__"):d.CodeName).join(`
|
|
367
381
|
`)}
|
|
368
|
-
${
|
|
382
|
+
${n}
|
|
369
383
|
}
|
|
370
384
|
}
|
|
371
|
-
`,
|
|
385
|
+
`,I=await this.ExecuteGQL(p,a);return I&&I[c]?this.ConvertBackToMJFields(I[c]):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],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+=`
|
|
372
386
|
${i} {
|
|
373
|
-
${
|
|
387
|
+
${o.Fields.map(n=>n.CodeName).join(`
|
|
374
388
|
`)}
|
|
375
389
|
}
|
|
376
|
-
`}return r}async Delete(e,t,r){const s=new
|
|
377
|
-
`),
|
|
378
|
-
${
|
|
390
|
+
`}return r}async Delete(e,t,r){const s=new u.BaseEntityResult;try{e.RegisterTransactionPreprocessing(),s.StartedAt=new Date,s.Type="delete",s.OriginalValues=e.Fields.map(g=>({FieldName:g.CodeName,Value:g.Value})),e.ResultHistory.push(s);const a={},o=[];let i="",n="",c="";for(let g of e.PrimaryKey.KeyValuePairs){const m=e.Fields.find(S=>S.Name.trim().toLowerCase()===g.FieldName.trim().toLowerCase());a[m.CodeName]=m.Value,o.push({varName:m.CodeName,inputType:m.EntityFieldInfo.GraphQLType+"!"}),i.length>0&&(i+=", "),i+=`${m.CodeName}: $${m.CodeName}`,n.length>0&&(n+=", "),n+=`$${m.CodeName}: ${m.EntityFieldInfo.GraphQLType}!`,c.length>0&&(c+=`
|
|
391
|
+
`),c+=`${m.CodeName}`}o.push({varName:"options___",inputType:"DeleteOptionsInput!"}),a.options___=t||{SkipEntityAIActions:!1,SkipEntityActions:!1};const p="Delete"+u.getGraphQLTypeNameBase(e.EntityInfo),I=y.gql`${p}(${i}, options___: $options___) {
|
|
392
|
+
${c}
|
|
379
393
|
}
|
|
380
|
-
`,y
|
|
381
|
-
${
|
|
394
|
+
`,d=y.gql`mutation ${p} (${n}, $options___: DeleteOptionsInput!) {
|
|
395
|
+
${I}
|
|
382
396
|
}
|
|
383
|
-
`;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new
|
|
397
|
+
`;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new u.TransactionItem(e,"Delete",I,a,{mutationName:p,mutationInputTypes:o},(g,m)=>{if(s.EndedAt=new Date,m&&g){let S=!0;for(const R of e.PrimaryKey.KeyValuePairs)R.Value!==g[R.FieldName]&&(S=!1);S?s.Success=!0:(s.Success=!1,s.Message="Transaction failed to commit")}else s.Success=!1,s.Message="Transaction failed to commit"})),!0;{const g=await this.ExecuteGQL(d,a);if(g&&g[p]){const m=g[p];for(let S of e.PrimaryKey.KeyValuePairs){let R=m[S.FieldName],D=S.Value;if(typeof D=="number"&&(D=D.toString()),typeof R=="number"&&(R=R.toString()),D!==R)throw new Error(`Primary key value mismatch in server Delete response. Field: ${S.FieldName}, Original: ${D}, Returned: ${R}`)}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!]) {
|
|
384
398
|
GetDatasetByName(DatasetName: $DatasetName, ItemFilters: $ItemFilters) {
|
|
385
399
|
DatasetID
|
|
386
400
|
DatasetName
|
|
@@ -389,7 +403,7 @@
|
|
|
389
403
|
LatestUpdateDate
|
|
390
404
|
Results
|
|
391
405
|
}
|
|
392
|
-
}`,s=await this.ExecuteGQL(r,{DatasetName:e,ItemFilters:t});return s&&s.GetDatasetByName&&s.GetDatasetByName.Success?{DatasetID:s.GetDatasetByName.DatasetID,DatasetName:s.GetDatasetByName.DatasetName,Success:s.GetDatasetByName.Success,Status:s.GetDatasetByName.Status,LatestUpdateDate:new Date(s.GetDatasetByName.LatestUpdateDate),Results:JSON.parse(s.GetDatasetByName.Results)}:{DatasetID:"",DatasetName:e,Success:!1,Status:"Unknown",LatestUpdateDate:null,Results:null}}async GetDatasetStatusByName(e,t){const r=
|
|
406
|
+
}`,s=await this.ExecuteGQL(r,{DatasetName:e,ItemFilters:t});return s&&s.GetDatasetByName&&s.GetDatasetByName.Success?{DatasetID:s.GetDatasetByName.DatasetID,DatasetName:s.GetDatasetByName.DatasetName,Success:s.GetDatasetByName.Success,Status:s.GetDatasetByName.Status,LatestUpdateDate:new Date(s.GetDatasetByName.LatestUpdateDate),Results:JSON.parse(s.GetDatasetByName.Results)}:{DatasetID:"",DatasetName:e,Success:!1,Status:"Unknown",LatestUpdateDate:null,Results:null}}async GetDatasetStatusByName(e,t){const r=y.gql`query GetDatasetStatusByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
|
|
393
407
|
GetDatasetStatusByName(DatasetName: $DatasetName, ItemFilters: $ItemFilters) {
|
|
394
408
|
DatasetID
|
|
395
409
|
DatasetName
|
|
@@ -398,22 +412,22 @@
|
|
|
398
412
|
LatestUpdateDate
|
|
399
413
|
EntityUpdateDates
|
|
400
414
|
}
|
|
401
|
-
}`,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
|
|
415
|
+
}`,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 b(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=y.gql`query GetRecordFavoriteStatus($params: UserFavoriteSearchParams!) {
|
|
402
416
|
GetRecordFavoriteStatus(params: $params) {
|
|
403
417
|
Success
|
|
404
418
|
IsFavorite
|
|
405
419
|
}
|
|
406
|
-
}`,i=await this.ExecuteGQL(
|
|
420
|
+
}`,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=y.gql`mutation SetRecordFavoriteStatus($params: UserFavoriteSetParams!) {
|
|
407
421
|
SetRecordFavoriteStatus(params: $params){
|
|
408
422
|
Success
|
|
409
423
|
}
|
|
410
|
-
}`,
|
|
424
|
+
}`,n=await this.ExecuteGQL(i,{params:{UserID:e,EntityID:o.ID,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(r.KeyValuePairs)},IsFavorite:s}});if(n&&n.SetRecordFavoriteStatus!==null)return n.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!) {
|
|
411
425
|
GetEntityRecordName(EntityName: $EntityName, CompositeKey: $CompositeKey) {
|
|
412
426
|
Success
|
|
413
427
|
Status
|
|
414
428
|
RecordName
|
|
415
429
|
}
|
|
416
|
-
}`,s=await this.ExecuteGQL(r,{EntityName:e,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(t.KeyValuePairs)}});if(s&&s.GetEntityRecordName&&s.GetEntityRecordName.Success)return s.GetEntityRecordName.RecordName}async GetEntityRecordNames(e){if(!e)return null;const t=
|
|
430
|
+
}`,s=await this.ExecuteGQL(r,{EntityName:e,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(t.KeyValuePairs)}});if(s&&s.GetEntityRecordName&&s.GetEntityRecordName.Success)return s.GetEntityRecordName.RecordName}async GetEntityRecordNames(e){if(!e)return null;const t=y.gql`query GetEntityRecordNamesQuery ($info: [EntityRecordNameInput!]!) {
|
|
417
431
|
GetEntityRecordNames(info: $info) {
|
|
418
432
|
Success
|
|
419
433
|
Status
|
|
@@ -426,35 +440,35 @@
|
|
|
426
440
|
EntityName
|
|
427
441
|
RecordName
|
|
428
442
|
}
|
|
429
|
-
}`,r=await this.ExecuteGQL(t,{info:e.map(s=>({EntityName:s.EntityName,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(s.CompositeKey.KeyValuePairs)}}))});if(r&&r.GetEntityRecordNames)return r.GetEntityRecordNames}async GetDataContextData(e){try{const t=
|
|
443
|
+
}`,r=await this.ExecuteGQL(t,{info:e.map(s=>({EntityName:s.EntityName,CompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(s.CompositeKey.KeyValuePairs)}}))});if(r&&r.GetEntityRecordNames)return r.GetEntityRecordNames}async GetDataContextData(e){try{const t=y.gql`query GetDataContextData ($DataContextID: String!) {
|
|
430
444
|
GetDataContextData(DataContextID: $DataContextID) {
|
|
431
445
|
Success
|
|
432
446
|
ErrorMessages
|
|
433
447
|
Results
|
|
434
448
|
}
|
|
435
|
-
}`,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
|
|
449
|
+
}`,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=y.gql`query GetDataContextItemData ($DataContextItemID: String!) {
|
|
436
450
|
GetDataContextItemData(DataContextItemID: $DataContextItemID) {
|
|
437
451
|
Success
|
|
438
452
|
ErrorMessage
|
|
439
453
|
Result
|
|
440
454
|
}
|
|
441
|
-
}`,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
|
|
455
|
+
}`,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._configData.UserAPIKey);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,a){const o={"x-session-id":r};return t&&(o.authorization="Bearer "+t),s&&(o["x-mj-api-key"]=s),a&&(o["x-api-key"]=a),new y.GraphQLClient(e,{headers:o})}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__")+`
|
|
442
456
|
`:s.startsWith("_")||(t+=s+`
|
|
443
|
-
`);return t}get LocalStorageProvider(){return this._localStorageProvider||(this._localStorageProvider=new
|
|
457
|
+
`);return t}get LocalStorageProvider(){return this._localStorageProvider||(typeof indexedDB<"u"?this._localStorageProvider=new L:this._localStorageProvider=new u.InMemoryLocalStorageProvider),this._localStorageProvider}get Metadata(){return this}getOrCreateWSClient(){const e=Date.now();return this._wsClient&&this._wsClientCreatedAt&&e-this._wsClientCreatedAt>this.WS_CLIENT_MAX_AGE_MS&&this._activeSubscriptionCount===0&&this.disposeWSClient(),this._wsClient||(this._wsClient=$e.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 C.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 C.Observable(n=>{r.activeSubscribers++;const c=r.subject.subscribe(n);return()=>{const l=this._pushStatusSubjects.get(e);l&&l.activeSubscribers>0&&l.activeSubscribers--,c.unsubscribe()}});const s=y.gql`subscription StatusUpdates($sessionId: String!) {
|
|
444
458
|
statusUpdates(sessionId: $sessionId) {
|
|
445
459
|
date
|
|
446
460
|
message
|
|
447
461
|
sessionId
|
|
448
462
|
}
|
|
449
463
|
}
|
|
450
|
-
`,a=new
|
|
464
|
+
`,a=new C.Subject,o=this.getOrCreateWSClient(),i=new C.Subscription;return i.add(new C.Observable(n=>{const c=o.subscribe({query:s,variables:{sessionId:e}},{next:l=>{const p=this._pushStatusSubjects.get(e);p&&(p.lastEmissionAt=Date.now()),n.next(l.data.statusUpdates.message)},error:async l=>{const p=l;if(p?.extensions?.code==="JWT_EXPIRED"||p?.message?.includes("token has expired")||p?.message?.includes("JWT_EXPIRED")){console.log("[GraphQLDataProvider] PushStatusUpdates JWT token expired, refreshing and reconnecting...");try{await this.RefreshToken(),this.disposeWSClient(),n.complete()}catch(d){console.error("[GraphQLDataProvider] Failed to refresh token for PushStatusUpdates:",d),n.error(d)}}else n.error(l)},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 C.Observable(n=>{const c=this._pushStatusSubjects.get(e);c&&c.activeSubscribers++;const l=a.subscribe(n);return()=>{const p=this._pushStatusSubjects.get(e);p&&p.activeSubscribers>0&&p.activeSubscribers--,l.unsubscribe()}})}disposeWebSocketResources(){this._subscriptionCleanupTimer&&(clearInterval(this._subscriptionCleanupTimer),this._subscriptionCleanupTimer=null),this.completeAllSubjects(),this._activeSubscriptionCount=0,this.disposeWSClient()}};f(h,"GraphQLDataProvider");let T=h;async function xe(w){const e=new T;return u.SetProvider(e),await e.Config(w),await u.StartupManager.Instance.Startup(),P.MJGlobal.Instance.RaiseEvent({event:P.MJEventType.LoggedIn,eventCode:null,component:this,args:null}),e}f(xe,"setupGraphQLClient");const ae=class ae{};f(ae,"SyncRolesAndUsersResult");let U=ae;const oe=class oe{};f(oe,"RoleInput");let V=oe;const ne=class ne{};f(ne,"UserInput");let Q=ne;const ie=class ie{};f(ie,"RolesAndUsersInput");let G=ie;var Pe=(w=>(w.Create="Create",w.Update="Update",w.CreateOrUpdate="CreateOrUpdate",w.Delete="Delete",w.DeleteWithFilter="DeleteWithFilter",w))(Pe||{});const ue=class ue{};f(ue,"ActionItemInput");let F=ue;const ce=class ce{constructor(){this.Results=[]}};f(ce,"SyncDataResult");let q=ce;const le=class le{};f(le,"ActionItemOutput");let _=le;const de=class de{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!) {
|
|
451
465
|
GetData(input: $input) {
|
|
452
466
|
Success
|
|
453
467
|
ErrorMessages
|
|
454
468
|
Queries
|
|
455
469
|
Results
|
|
456
470
|
}
|
|
457
|
-
}`,{input:{Queries:e,Token:t}});return s&&s.GetData?{Success:s.GetData.Success,Results:s.GetData.Results.map(a=>a?
|
|
471
|
+
}`,{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){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 {
|
|
458
472
|
GetAllEntities {
|
|
459
473
|
Success
|
|
460
474
|
ErrorMessage
|
|
@@ -477,7 +491,7 @@
|
|
|
477
491
|
}
|
|
478
492
|
}
|
|
479
493
|
}
|
|
480
|
-
}`);return t&&t.GetAllEntities?t.GetAllEntities:{Success:!1,Results:[],ErrorMessage:t.GetAllEntities?.ErrorMessage??"Unknown error"}}catch(e){return
|
|
494
|
+
}`);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!]!) {
|
|
481
495
|
SyncData(items: $items) {
|
|
482
496
|
Success
|
|
483
497
|
Results {
|
|
@@ -501,11 +515,11 @@
|
|
|
501
515
|
RecordJSON
|
|
502
516
|
}
|
|
503
517
|
}
|
|
504
|
-
}`,{items:e});return r&&r.SyncData?r.SyncData:{Success:!1,Results:[]}}catch(t){return
|
|
518
|
+
}`,{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!) {
|
|
505
519
|
SyncRolesAndUsers(data: $data) {
|
|
506
520
|
Success
|
|
507
521
|
}
|
|
508
|
-
}`,{data:e});return r&&r.SyncRolesAndUsers?r.SyncRolesAndUsers:{Success:!1}}catch(t){return
|
|
522
|
+
}`,{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!) {
|
|
509
523
|
RunViewByNameSystemUser(input: $input) {
|
|
510
524
|
Results {
|
|
511
525
|
PrimaryKey {
|
|
@@ -522,7 +536,7 @@
|
|
|
522
536
|
ErrorMessage
|
|
523
537
|
Success
|
|
524
538
|
}
|
|
525
|
-
}`,{input:e});return r&&r.RunViewByNameSystemUser?r.RunViewByNameSystemUser:{Results:[],Success:!1,ErrorMessage:"Failed to execute view by name"}}catch(t){return
|
|
539
|
+
}`,{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!) {
|
|
526
540
|
RunViewByIDSystemUser(input: $input) {
|
|
527
541
|
Results {
|
|
528
542
|
PrimaryKey {
|
|
@@ -539,7 +553,7 @@
|
|
|
539
553
|
ErrorMessage
|
|
540
554
|
Success
|
|
541
555
|
}
|
|
542
|
-
}`,{input:e});return r&&r.RunViewByIDSystemUser?r.RunViewByIDSystemUser:{Results:[],Success:!1,ErrorMessage:"Failed to execute view by ID"}}catch(t){return
|
|
556
|
+
}`,{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!) {
|
|
543
557
|
RunDynamicViewSystemUser(input: $input) {
|
|
544
558
|
Results {
|
|
545
559
|
PrimaryKey {
|
|
@@ -556,7 +570,7 @@
|
|
|
556
570
|
ErrorMessage
|
|
557
571
|
Success
|
|
558
572
|
}
|
|
559
|
-
}`,{input:e});return r&&r.RunDynamicViewSystemUser?r.RunDynamicViewSystemUser:{Results:[],Success:!1,ErrorMessage:"Failed to execute dynamic view"}}catch(t){return
|
|
573
|
+
}`,{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!]!) {
|
|
560
574
|
RunViewsSystemUser(input: $input) {
|
|
561
575
|
Results {
|
|
562
576
|
PrimaryKey {
|
|
@@ -573,7 +587,7 @@
|
|
|
573
587
|
ErrorMessage
|
|
574
588
|
Success
|
|
575
589
|
}
|
|
576
|
-
}`,{input:e});return r&&r.RunViewsSystemUser?r.RunViewsSystemUser:[]}catch(t){return
|
|
590
|
+
}`,{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) {
|
|
577
591
|
GetQueryDataSystemUser(QueryID: $QueryID, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {
|
|
578
592
|
QueryID
|
|
579
593
|
QueryName
|
|
@@ -585,7 +599,7 @@
|
|
|
585
599
|
ErrorMessage
|
|
586
600
|
AppliedParameters
|
|
587
601
|
}
|
|
588
|
-
}`,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?
|
|
602
|
+
}`,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) {
|
|
589
603
|
GetQueryDataByNameSystemUser(QueryName: $QueryName, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {
|
|
590
604
|
QueryID
|
|
591
605
|
QueryName
|
|
@@ -597,7 +611,7 @@
|
|
|
597
611
|
ErrorMessage
|
|
598
612
|
AppliedParameters
|
|
599
613
|
}
|
|
600
|
-
}`,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?
|
|
614
|
+
}`,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!) {
|
|
601
615
|
CreateQuerySystemUser(input: $input) {
|
|
602
616
|
Success
|
|
603
617
|
ErrorMessage
|
|
@@ -652,7 +666,7 @@
|
|
|
652
666
|
Role
|
|
653
667
|
}
|
|
654
668
|
}
|
|
655
|
-
}`,{input:e});return r&&r.CreateQuerySystemUser?r.CreateQuerySystemUser:{Success:!1,ErrorMessage:"Failed to create query"}}catch(t){return
|
|
669
|
+
}`,{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!) {
|
|
656
670
|
UpdateQuerySystemUser(input: $input) {
|
|
657
671
|
Success
|
|
658
672
|
ErrorMessage
|
|
@@ -707,14 +721,14 @@
|
|
|
707
721
|
Role
|
|
708
722
|
}
|
|
709
723
|
}
|
|
710
|
-
}`,{input:e});return r&&r.UpdateQuerySystemUser?r.UpdateQuerySystemUser:{Success:!1,ErrorMessage:"Failed to update query"}}catch(t){return
|
|
724
|
+
}`,{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) {
|
|
711
725
|
DeleteQuerySystemResolver(ID: $ID, options: $options) {
|
|
712
726
|
Success
|
|
713
727
|
ErrorMessage
|
|
714
728
|
ID
|
|
715
729
|
Name
|
|
716
730
|
}
|
|
717
|
-
}`,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
|
|
731
|
+
}`,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=y.gql`
|
|
718
732
|
query RunAIPromptSystemUser(
|
|
719
733
|
$promptId: String!,
|
|
720
734
|
$data: String,
|
|
@@ -773,7 +787,7 @@
|
|
|
773
787
|
chatResult
|
|
774
788
|
}
|
|
775
789
|
}
|
|
776
|
-
`,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
|
|
790
|
+
`,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=y.gql`
|
|
777
791
|
query RunAIAgentSystemUser(
|
|
778
792
|
$agentId: String!,
|
|
779
793
|
$messages: String!,
|
|
@@ -800,7 +814,7 @@
|
|
|
800
814
|
result
|
|
801
815
|
}
|
|
802
816
|
}
|
|
803
|
-
`,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
|
|
817
|
+
`,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 P.SafeJSONParse(e)}async ExecuteSimplePrompt(e){try{const t=y.gql`
|
|
804
818
|
query ExecuteSimplePromptSystemUser(
|
|
805
819
|
$systemPrompt: String!,
|
|
806
820
|
$messages: String,
|
|
@@ -823,7 +837,7 @@
|
|
|
823
837
|
executionTimeMs
|
|
824
838
|
}
|
|
825
839
|
}
|
|
826
|
-
`,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
|
|
840
|
+
`,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=y.gql`
|
|
827
841
|
query EmbedTextSystemUser(
|
|
828
842
|
$textToEmbed: [String!]!,
|
|
829
843
|
$modelSize: String!
|
|
@@ -838,7 +852,7 @@
|
|
|
838
852
|
error
|
|
839
853
|
}
|
|
840
854
|
}
|
|
841
|
-
`,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
|
|
855
|
+
`,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()}}}};f(de,"GraphQLSystemUserClient");let O=de;const ye=class ye{};f(ye,"GetDataOutput");let k=ye;const ge=class ge{};f(ge,"SimpleRemoteEntityOutput");let K=ge;const me=class me{};f(me,"SimpleRemoteEntity");let B=me;const pe=class pe{};f(pe,"SimpleRemoteEntityField");let j=pe;const he=class he{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=y.gql`
|
|
842
856
|
mutation RunAction($input: RunActionInput!) {
|
|
843
857
|
RunAction(input: $input) {
|
|
844
858
|
Success
|
|
@@ -847,7 +861,7 @@
|
|
|
847
861
|
ResultData
|
|
848
862
|
}
|
|
849
863
|
}
|
|
850
|
-
`;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){
|
|
864
|
+
`;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=y.gql`
|
|
851
865
|
mutation RunEntityAction($input: EntityActionInput!) {
|
|
852
866
|
RunEntityAction(input: $input) {
|
|
853
867
|
Success
|
|
@@ -855,7 +869,23 @@
|
|
|
855
869
|
ResultData
|
|
856
870
|
}
|
|
857
871
|
}
|
|
858
|
-
`;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){
|
|
872
|
+
`;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}}};f(he,"GraphQLActionClient");let J=he;const fe=class fe{constructor(e){this._dataProvider=e}async CreateAPIKey(e){try{const t=this.createAPIKeyVariables(e),r=await this.executeCreateAPIKeyMutation(t);return this.processCreateAPIKeyResult(r)}catch(t){return this.handleCreateAPIKeyError(t)}}createAPIKeyVariables(e){return{input:{Label:e.Label,Description:e.Description,ExpiresAt:e.ExpiresAt?.toISOString(),ScopeIDs:e.ScopeIDs}}}async executeCreateAPIKeyMutation(e){const t=y.gql`
|
|
873
|
+
mutation CreateAPIKey($input: CreateAPIKeyInput!) {
|
|
874
|
+
CreateAPIKey(input: $input) {
|
|
875
|
+
Success
|
|
876
|
+
RawKey
|
|
877
|
+
APIKeyID
|
|
878
|
+
Error
|
|
879
|
+
}
|
|
880
|
+
}
|
|
881
|
+
`;return await this._dataProvider.ExecuteGQL(t,e)}processCreateAPIKeyResult(e){const t=e;return t?.CreateAPIKey?{Success:t.CreateAPIKey.Success,RawKey:t.CreateAPIKey.RawKey,APIKeyID:t.CreateAPIKey.APIKeyID,Error:t.CreateAPIKey.Error}:{Success:!1,Error:"Invalid response from server"}}handleCreateAPIKeyError(e){const t=e;return u.LogError(`Error creating API key: ${t.message}`),{Success:!1,Error:`Error: ${t.message}`}}async RevokeAPIKey(e){try{const t=y.gql`
|
|
882
|
+
mutation RevokeAPIKey($apiKeyId: String!) {
|
|
883
|
+
RevokeAPIKey(apiKeyId: $apiKeyId) {
|
|
884
|
+
Success
|
|
885
|
+
Error
|
|
886
|
+
}
|
|
887
|
+
}
|
|
888
|
+
`,s=await this._dataProvider.ExecuteGQL(t,{apiKeyId:e});return s?.RevokeAPIKey?{Success:s.RevokeAPIKey.Success,Error:s.RevokeAPIKey.Error}:{Success:!1,Error:"Invalid response from server"}}catch(t){const r=t;return u.LogError(`Error revoking API key: ${r.message}`),{Success:!1,Error:`Error: ${r.message}`}}}};f(fe,"GraphQLEncryptionClient");let W=fe;const Se=class Se{constructor(e){this._dataProvider=e}async RunTest(e){let t;try{e.onProgress&&(t=this._dataProvider.PushStatusUpdates(this._dataProvider.sessionId).subscribe(n=>{try{const c=JSON.parse(n);c.resolver==="RunTestResolver"&&c.type==="TestExecutionProgress"&&c.status==="ok"&&c.data?.progress&&e.onProgress(c.data.progress)}catch(c){console.error("[GraphQLTestingClient] Failed to parse progress message:",c)}}));const r=y.gql`
|
|
859
889
|
mutation RunTest(
|
|
860
890
|
$testId: String!,
|
|
861
891
|
$verbose: Boolean,
|
|
@@ -876,7 +906,7 @@
|
|
|
876
906
|
result
|
|
877
907
|
}
|
|
878
908
|
}
|
|
879
|
-
`,s=e.tags&&e.tags.length>0?JSON.stringify(e.tags):void 0,a=e.variables?JSON.stringify(e.variables):void 0,
|
|
909
|
+
`,s=e.tags&&e.tags.length>0?JSON.stringify(e.tags):void 0,a=e.variables?JSON.stringify(e.variables):void 0,o={testId:e.testId,verbose:e.verbose,environment:e.environment,tags:s,variables:a},i=await this._dataProvider.ExecuteGQL(r,o);return this.processTestResult(i.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(c=>{try{const l=JSON.parse(c);l.resolver==="RunTestResolver"&&l.type==="TestExecutionProgress"&&l.status==="ok"&&l.data?.progress&&e.onProgress(l.data.progress)}catch(l){console.error("[GraphQLTestingClient] Failed to parse progress message:",l)}}));const r=y.gql`
|
|
880
910
|
mutation RunTestSuite(
|
|
881
911
|
$suiteId: String!,
|
|
882
912
|
$verbose: Boolean,
|
|
@@ -905,11 +935,11 @@
|
|
|
905
935
|
result
|
|
906
936
|
}
|
|
907
937
|
}
|
|
908
|
-
`,s=e.tags&&e.tags.length>0?JSON.stringify(e.tags):void 0,a=e.variables?JSON.stringify(e.variables):void 0,
|
|
938
|
+
`,s=e.tags&&e.tags.length>0?JSON.stringify(e.tags):void 0,a=e.variables?JSON.stringify(e.variables):void 0,o=e.selectedTestIds&&e.selectedTestIds.length>0?JSON.stringify(e.selectedTestIds):void 0,i={suiteId:e.suiteId,verbose:e.verbose,environment:e.environment,parallel:e.parallel,tags:s,variables:a,selectedTestIds:o,sequenceStart:e.sequenceStart,sequenceEnd:e.sequenceEnd},n=await this._dataProvider.ExecuteGQL(r,i);return this.processSuiteResult(n.RunTestSuite)}catch(r){return this.handleError(r,"RunTestSuite")}finally{t&&t.unsubscribe()}}async IsTestRunning(e){try{const t=y.gql`
|
|
909
939
|
query IsTestRunning($testId: String!) {
|
|
910
940
|
IsTestRunning(testId: $testId)
|
|
911
941
|
}
|
|
912
|
-
`;return(await this._dataProvider.ExecuteGQL(t,{testId:e})).IsTestRunning}catch(t){return
|
|
942
|
+
`;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=P.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=P.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}}};f(Se,"GraphQLTestingClient");let z=Se;const Ie=class Ie{constructor(e){this._dataProvider=e}async GetRegistryComponent(e){try{const t=y.gql`
|
|
913
943
|
query GetRegistryComponent(
|
|
914
944
|
$registryName: String!,
|
|
915
945
|
$namespace: String!,
|
|
@@ -930,7 +960,7 @@
|
|
|
930
960
|
specification
|
|
931
961
|
}
|
|
932
962
|
}
|
|
933
|
-
`,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(
|
|
963
|
+
`,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=y.gql`
|
|
934
964
|
query GetRegistryComponent(
|
|
935
965
|
$registryName: String!,
|
|
936
966
|
$namespace: String!,
|
|
@@ -951,7 +981,7 @@
|
|
|
951
981
|
specification
|
|
952
982
|
}
|
|
953
983
|
}
|
|
954
|
-
`,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
|
|
984
|
+
`,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=y.gql`
|
|
955
985
|
query SearchRegistryComponents($params: SearchRegistryComponentsInput!) {
|
|
956
986
|
SearchRegistryComponents(params: $params) {
|
|
957
987
|
components
|
|
@@ -960,7 +990,7 @@
|
|
|
960
990
|
limit
|
|
961
991
|
}
|
|
962
992
|
}
|
|
963
|
-
`,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
|
|
993
|
+
`,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=y.gql`
|
|
964
994
|
query ResolveComponentDependencies(
|
|
965
995
|
$registryId: String!,
|
|
966
996
|
$componentId: String!
|
|
@@ -985,7 +1015,7 @@
|
|
|
985
1015
|
}
|
|
986
1016
|
}
|
|
987
1017
|
}
|
|
988
|
-
`,s=await this._dataProvider.ExecuteGQL(r,{registryId:e,componentId:t});return s&&s.ResolveComponentDependencies?s.ResolveComponentDependencies:null}catch(r){throw
|
|
1018
|
+
`,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`
|
|
989
1019
|
mutation SendComponentFeedback($feedback: ComponentFeedbackInput!) {
|
|
990
1020
|
SendComponentFeedback(feedback: $feedback) {
|
|
991
1021
|
success
|
|
@@ -993,7 +1023,7 @@
|
|
|
993
1023
|
error
|
|
994
1024
|
}
|
|
995
1025
|
}
|
|
996
|
-
`,r=await this._dataProvider.ExecuteGQL(t,{feedback:e});return r&&r.SendComponentFeedback?r.SendComponentFeedback:{success:!1,error:"No response from server"}}catch(t){return
|
|
1026
|
+
`,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(Ie,"GraphQLComponentRegistryClient");let H=Ie;const Re=class Re{constructor(e){this._dataProvider=e}async ListObjects(e,t="",r){try{const s=y.gql`
|
|
997
1027
|
query ListStorageObjects($input: ListStorageObjectsInput!) {
|
|
998
1028
|
ListStorageObjects(input: $input) {
|
|
999
1029
|
objects {
|
|
@@ -1010,34 +1040,34 @@
|
|
|
1010
1040
|
prefixes
|
|
1011
1041
|
}
|
|
1012
1042
|
}
|
|
1013
|
-
`,a={input:{AccountID:e,Prefix:t,Delimiter:r||"/"}},
|
|
1043
|
+
`,a={input:{AccountID:e,Prefix:t,Delimiter:r||"/"}},o=await this._dataProvider.ExecuteGQL(s,a);if(!o?.ListStorageObjects)throw new Error("Invalid response from server");return{objects:o.ListStorageObjects.objects.map(i=>({...i,lastModified:new Date(i.lastModified)})),prefixes:o.ListStorageObjects.prefixes}}catch(s){const a=s;throw u.LogError(`Error listing storage objects: ${a}`),a}}async DirectoryExists(e,t){try{const r=await this.ListObjects(e,t.endsWith("/")?t:`${t}/`,"/");return r.objects.length>0||r.prefixes.length>0}catch(r){const s=r;return u.LogError(`Error checking directory existence: ${s}`),!1}}async CreateDirectory(e,t){try{const r=y.gql`
|
|
1014
1044
|
mutation CreateDirectory($input: CreateDirectoryInput!) {
|
|
1015
1045
|
CreateDirectory(input: $input)
|
|
1016
1046
|
}
|
|
1017
|
-
`,s={input:{AccountID:e,Path:t}};return(await this._dataProvider.ExecuteGQL(r,s))?.CreateDirectory??!1}catch(r){const s=r;return
|
|
1047
|
+
`,s={input:{AccountID:e,Path:t}};return(await this._dataProvider.ExecuteGQL(r,s))?.CreateDirectory??!1}catch(r){const s=r;return u.LogError(`Error creating directory: ${s}`),!1}}async ObjectExists(e,t){try{const r=t.substring(0,t.lastIndexOf("/")+1),s=t.substring(t.lastIndexOf("/")+1);return(await this.ListObjects(e,r,"/")).objects.some(o=>o.name===s||o.fullPath===t)}catch(r){const s=r;return u.LogError(`Error checking object existence: ${s}`),!1}}async CreatePreAuthUploadUrl(e,t,r){try{const s=y.gql`
|
|
1018
1048
|
mutation CreatePreAuthUploadUrl($input: CreatePreAuthUploadUrlInput!) {
|
|
1019
1049
|
CreatePreAuthUploadUrl(input: $input) {
|
|
1020
1050
|
UploadUrl
|
|
1021
1051
|
ProviderKey
|
|
1022
1052
|
}
|
|
1023
1053
|
}
|
|
1024
|
-
`,a={input:{AccountID:e,ObjectName:t,ContentType:r}},
|
|
1054
|
+
`,a={input:{AccountID:e,ObjectName:t,ContentType:r}},o=await this._dataProvider.ExecuteGQL(s,a);if(!o?.CreatePreAuthUploadUrl)throw new Error("Invalid response from server");return{uploadUrl:o.CreatePreAuthUploadUrl.UploadUrl,providerKey:o.CreatePreAuthUploadUrl.ProviderKey}}catch(s){const a=s;throw u.LogError(`Error creating pre-auth upload URL: ${a}`),a}}async CreatePreAuthDownloadUrl(e,t){try{const r=y.gql`
|
|
1025
1055
|
query CreatePreAuthDownloadUrl($input: CreatePreAuthDownloadUrlInput!) {
|
|
1026
1056
|
CreatePreAuthDownloadUrl(input: $input)
|
|
1027
1057
|
}
|
|
1028
|
-
`,s={input:{AccountID:e,ObjectName:t}},a=await this._dataProvider.ExecuteGQL(r,s);if(a?.CreatePreAuthDownloadUrl===void 0)throw new Error("Invalid response from server");return a.CreatePreAuthDownloadUrl}catch(r){const s=r;throw
|
|
1058
|
+
`,s={input:{AccountID:e,ObjectName:t}},a=await this._dataProvider.ExecuteGQL(r,s);if(a?.CreatePreAuthDownloadUrl===void 0)throw new Error("Invalid response from server");return a.CreatePreAuthDownloadUrl}catch(r){const s=r;throw u.LogError(`Error creating pre-auth download URL: ${s}`),s}}async DeleteObject(e,t){try{const r=y.gql`
|
|
1029
1059
|
mutation DeleteStorageObject($input: DeleteStorageObjectInput!) {
|
|
1030
1060
|
DeleteStorageObject(input: $input)
|
|
1031
1061
|
}
|
|
1032
|
-
`,s={input:{AccountID:e,ObjectName:t}};return(await this._dataProvider.ExecuteGQL(r,s))?.DeleteStorageObject??!1}catch(r){const s=r;return
|
|
1062
|
+
`,s={input:{AccountID:e,ObjectName:t}};return(await this._dataProvider.ExecuteGQL(r,s))?.DeleteStorageObject??!1}catch(r){const s=r;return u.LogError(`Error deleting storage object: ${s}`),!1}}async MoveObject(e,t,r){try{const s=y.gql`
|
|
1033
1063
|
mutation MoveStorageObject($input: MoveStorageObjectInput!) {
|
|
1034
1064
|
MoveStorageObject(input: $input)
|
|
1035
1065
|
}
|
|
1036
|
-
`,a={input:{AccountID:e,OldName:t,NewName:r}};return(await this._dataProvider.ExecuteGQL(s,a))?.MoveStorageObject??!1}catch(s){const a=s;return
|
|
1066
|
+
`,a={input:{AccountID:e,OldName:t,NewName:r}};return(await this._dataProvider.ExecuteGQL(s,a))?.MoveStorageObject??!1}catch(s){const a=s;return u.LogError(`Error moving storage object: ${a}`),!1}}async CopyObject(e,t,r){try{const s=y.gql`
|
|
1037
1067
|
mutation CopyStorageObject($input: CopyStorageObjectInput!) {
|
|
1038
1068
|
CopyStorageObject(input: $input)
|
|
1039
1069
|
}
|
|
1040
|
-
`,a={input:{AccountID:e,SourceName:t,DestinationName:r}};return(await this._dataProvider.ExecuteGQL(s,a))?.CopyStorageObject??!1}catch(s){const a=s;return
|
|
1070
|
+
`,a={input:{AccountID:e,SourceName:t,DestinationName:r}};return(await this._dataProvider.ExecuteGQL(s,a))?.CopyStorageObject??!1}catch(s){const a=s;return u.LogError(`Error copying storage object: ${a}`),!1}}async CopyObjectBetweenAccounts(e,t,r,s){try{const a=y.gql`
|
|
1041
1071
|
mutation CopyObjectBetweenAccounts($input: CopyObjectBetweenAccountsInput!) {
|
|
1042
1072
|
CopyObjectBetweenAccounts(input: $input) {
|
|
1043
1073
|
success
|
|
@@ -1049,7 +1079,7 @@
|
|
|
1049
1079
|
destinationPath
|
|
1050
1080
|
}
|
|
1051
1081
|
}
|
|
1052
|
-
`,
|
|
1082
|
+
`,o={input:{SourceAccountID:e,DestinationAccountID:t,SourcePath:r,DestinationPath:s}},i=await this._dataProvider.ExecuteGQL(a,o);if(!i?.CopyObjectBetweenAccounts)throw new Error("Invalid response from server");return{success:i.CopyObjectBetweenAccounts.success,message:i.CopyObjectBetweenAccounts.message,bytesTransferred:i.CopyObjectBetweenAccounts.bytesTransferred,sourceAccount:i.CopyObjectBetweenAccounts.sourceAccount,destinationAccount:i.CopyObjectBetweenAccounts.destinationAccount,sourcePath:i.CopyObjectBetweenAccounts.sourcePath,destinationPath:i.CopyObjectBetweenAccounts.destinationPath}}catch(a){const o=a;return u.LogError(`Error copying object between accounts: ${o}`),{success:!1,message:o.message,sourceAccount:"",destinationAccount:"",sourcePath:r,destinationPath:s}}}async SearchFiles(e,t,r){try{const s=y.gql`
|
|
1053
1083
|
query SearchAcrossAccounts($input: SearchAcrossAccountsInput!) {
|
|
1054
1084
|
SearchAcrossAccounts(input: $input) {
|
|
1055
1085
|
accountResults {
|
|
@@ -1077,5 +1107,5 @@
|
|
|
1077
1107
|
failedAccounts
|
|
1078
1108
|
}
|
|
1079
1109
|
}
|
|
1080
|
-
`,a={input:{AccountIDs:e,Query:t,MaxResultsPerAccount:r?.maxResultsPerAccount,FileTypes:r?.fileTypes,SearchContent:r?.searchContent}},
|
|
1110
|
+
`,a={input:{AccountIDs:e,Query:t,MaxResultsPerAccount:r?.maxResultsPerAccount,FileTypes:r?.fileTypes,SearchContent:r?.searchContent}},o=await this._dataProvider.ExecuteGQL(s,a);if(!o?.SearchAcrossAccounts)throw new Error("Invalid response from server");const i=o.SearchAcrossAccounts;return{accountResults:i.accountResults.map(n=>({accountId:n.accountID,accountName:n.accountName,success:n.success,errorMessage:n.errorMessage,results:n.results.map(c=>({path:c.path,name:c.name,size:c.size,contentType:c.contentType,lastModified:new Date(c.lastModified),relevance:c.relevance,excerpt:c.excerpt,matchInFilename:c.matchInFilename,objectId:c.objectId})),totalMatches:n.totalMatches,hasMore:n.hasMore,nextPageToken:n.nextPageToken})),totalResultsReturned:i.totalResultsReturned,successfulAccounts:i.successfulAccounts,failedAccounts:i.failedAccounts}}catch(s){const a=s;return u.LogError(`Error searching across accounts: ${a}`),{accountResults:[],totalResultsReturned:0,successfulAccounts:0,failedAccounts:e.length}}}};f(Re,"GraphQLFileStorageClient");let X=Re;Object.defineProperty(exports,"gql",{enumerable:!0,get:function(){return y.gql}}),exports.ActionItemInput=F,exports.ActionItemOutput=_,exports.BrowserIndexedDBStorageProvider=L,exports.BrowserStorageProviderBase=x,exports.FieldMapper=$,exports.GetDataOutput=k,exports.GraphQLAIClient=A,exports.GraphQLActionClient=J,exports.GraphQLComponentRegistryClient=H,exports.GraphQLDataProvider=T,exports.GraphQLEncryptionClient=W,exports.GraphQLFileStorageClient=X,exports.GraphQLProviderConfigData=M,exports.GraphQLSystemUserClient=O,exports.GraphQLTestingClient=z,exports.GraphQLTransactionGroup=b,exports.RoleInput=V,exports.RolesAndUsersInput=G,exports.SimpleRemoteEntity=B,exports.SimpleRemoteEntityField=j,exports.SimpleRemoteEntityOutput=K,exports.SyncDataAction=Pe,exports.SyncDataResult=q,exports.SyncRolesAndUsersResult=U,exports.UserInput=Q,exports.setupGraphQLClient=xe;
|
|
1081
1111
|
//# sourceMappingURL=index.cjs.map
|