@memberjunction/graphql-dataprovider 6.2.0-edge.0 → 6.2.0-edge.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +46 -44
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +30 -7
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +30 -7
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +59 -57
- package/dist/index.mjs.map +1 -1
- package/package.json +8 -8
package/dist/index.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var Y=Object.defineProperty;var l=(g,e)=>Y(g,"name",{value:e,configurable:!0});var u=require("graphql-request"),c=require("@memberjunction/core"),v=require("@memberjunction/global"),_=require("@memberjunction/core-entities"),$=require("rxjs"),Z=require("graphql-ws"),ee=require("uuid"),te=require("@tempfix/idb");class L{static{l(this,"FieldMapper")}static{this.DB_PREFIX="__mj_"}static{this.GQL_PREFIX="_mj__"}constructor(){}MapFields(e){if(e)for(const t in e){const r=this.MapFieldName(t);r!==t&&(e[r]=e[t],delete e[t])}return e}MapFieldName(e){return e.startsWith(L.DB_PREFIX)?L.GQL_PREFIX+e.substring(L.DB_PREFIX.length):e}ReverseMapFieldName(e){return e.startsWith(L.GQL_PREFIX)?L.DB_PREFIX+e.substring(L.GQL_PREFIX.length):e}ReverseMapFields(e){for(const t in e){const r=this.ReverseMapFieldName(t);r!==t&&(e[r]=e[t],delete e[t])}return e}}class V extends c.TransactionGroupBase{static{l(this,"GraphQLTransactionGroup")}constructor(e){super(),this._provider=e}async HandleSubmit(){const e=u.gql`
|
|
2
2
|
mutation ExecuteTransactionGroup($group: TransactionInputType!) {
|
|
3
3
|
ExecuteTransactionGroup(group: $group) {
|
|
4
4
|
Success
|
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
ResultsJSON
|
|
7
7
|
}
|
|
8
8
|
}
|
|
9
|
-
`,t=[];for(const n of this.PendingTransactions)t.push({EntityName:n.BaseEntity.EntityInfo.Name,EntityObjectJSON:await n.BaseEntity.GetDataObjectJSON(),OperationType:n.OperationType});const r={group:{Items:t,Variables:this.Variables.map(n=>({Name:n.Name,ItemIndex:this.MapVariableEntityObjectToPosition(n),FieldName:n.FieldName,Type:n.Type}))}},s=await this._provider.ExecuteGQL(e,r);if(s&&s.ExecuteTransactionGroup){const n=s.ExecuteTransactionGroup,a=n.Success===!0,i=[];for(let o=0;o<this.PendingTransactions.length;o++){const y=n.ResultsJSON[o],d=v.SafeJSONParse(y),m=this.PendingTransactions[o];a||this.recordServerFailure(m.BaseEntity,n.ErrorMessages?.[o]),i.push(new c.TransactionResult(m,d,a&&d!==null))}return i}else throw new Error("Failed to execute transaction group")}recordServerFailure(e,t){const r=v.SafeJSONParse(t??"");if(!r||r.Success!==!1)return;const s=r.Message?.trim();if(!s&&(r.Errors?.length??0)===0)return;const n=new c.BaseEntityResult;n.Success=!1,n.Type=r.Type??(e.IsSaved?"update":"create"),n.Message=s??null,n.Errors=r.Errors??[],n.StartedAt=new Date,n.EndedAt=new Date,e.RegisterResultHistoryEntry(n)}}const
|
|
9
|
+
`,t=[];for(const n of this.PendingTransactions)t.push({EntityName:n.BaseEntity.EntityInfo.Name,EntityObjectJSON:await n.BaseEntity.GetDataObjectJSON(),OperationType:n.OperationType});const r={group:{Items:t,Variables:this.Variables.map(n=>({Name:n.Name,ItemIndex:this.MapVariableEntityObjectToPosition(n),FieldName:n.FieldName,Type:n.Type}))}},s=await this._provider.ExecuteGQL(e,r);if(s&&s.ExecuteTransactionGroup){const n=s.ExecuteTransactionGroup,a=n.Success===!0,i=[];for(let o=0;o<this.PendingTransactions.length;o++){const y=n.ResultsJSON[o],d=v.SafeJSONParse(y),m=this.PendingTransactions[o];a||this.recordServerFailure(m.BaseEntity,n.ErrorMessages?.[o]),i.push(new c.TransactionResult(m,d,a&&d!==null))}return i}else throw new Error("Failed to execute transaction group")}recordServerFailure(e,t){const r=v.SafeJSONParse(t??"");if(!r||r.Success!==!1)return;const s=r.Message?.trim();if(!s&&(r.Errors?.length??0)===0)return;const n=new c.BaseEntityResult;n.Success=!1,n.Type=r.Type??(e.IsSaved?"update":"create"),n.Message=s??null,n.Errors=r.Errors??[],n.StartedAt=new Date,n.EndedAt=new Date,e.RegisterResultHistoryEntry(n)}}const re=720*1e3,se=6;class w{static{l(this,"FireAndForgetHelper")}static async Execute(e){const t=e.operationLabel??e.mutationFieldName;if(!(typeof e.dataProvider.PushStatusUpdates=="function"))return w.executeSynchronously(e);const s=e.timeoutMs??re,n=e.maxStallReconciles??se;let a,i=!1,o=0;const{promise:y,resolve:d,reject:m}=w.createCompletionPromise(),f=l(p=>{i||(i=!0,h.clear(),p())},"finish"),S=l(p=>f(()=>d(p)),"settleResolve"),E=l(p=>f(()=>m(p)),"settleReject"),D=l(async()=>{if(i)return;if(!e.onStall){E(new Error(w.timeoutMessage(e.timeoutErrorMessage,s)));return}let p;try{c.LogStatus(`[FireAndForget:${t}] Idle window elapsed, reconciling against server run record`),p=await e.onStall()}catch(R){E(R);return}i||(p==="continue"?++o>n?E(new Error(`The operation is still reported as running but no signal has arrived after ${o} checks. Please refresh the page to check the latest status.`)):h.reset():"resolve"in p?(c.LogStatus(`[FireAndForget:${t}] Reconciliation recovered a completed run`),S(p.resolve)):E(p.reject))},"onStall"),h=w.createIdleTimer(s,()=>{D()});try{h.reset(),a=w.subscribeToPubSub(e,{onActivity:l(()=>{o=0,h.reset()},"onActivity"),onCompletion:l(R=>S(R),"onCompletion"),onStreamEnd:l(()=>{D()},"onStreamEnd")});const p=await w.executeMutation(e);if(!e.validateAck(p)){h.clear();const R=p?.errorMessage??"Server rejected the request";return c.LogError(`[FireAndForget:${t}] Server rejected: ${R}`),e.createErrorResult(R)}return c.LogStatus(`[FireAndForget:${t}] Server accepted, waiting for completion via WebSocket`),await y}catch(p){const R=p;throw c.LogError(`[FireAndForget:${t}] Error: ${R.message}`),p}finally{h.clear(),a&&a.unsubscribe()}}static createCompletionPromise(){let e,t;return{promise:new Promise((s,n)=>{e=s,t=n}),resolve:e,reject:t}}static createIdleTimer(e,t){let r;return{reset:l(()=>{r&&clearTimeout(r),r=setTimeout(t,e)},"reset"),clear:l(()=>{r&&clearTimeout(r),r=void 0},"clear")}}static timeoutMessage(e,t){const r=Math.round(t/6e4);return e??`The operation may still be running on the server but the client received no updates for ${r} minutes. Please refresh the page to check the latest status.`}static subscribeToPubSub(e,t){const r=e.dataProvider.sessionId,s=e.operationLabel??e.mutationFieldName;return e.dataProvider.PushStatusUpdates(r).subscribe({next:l(n=>{t.onActivity();try{const a=JSON.parse(n);e.onMessage&&e.onMessage(a),e.isCompletionEvent(a)&&(c.LogStatus(`[FireAndForget:${s}] Completion event received`),t.onCompletion(e.extractResult(a)))}catch(a){console.error(`[FireAndForget:${s}] Failed to parse PubSub message:`,a)}},"next"),error:l(()=>t.onStreamEnd(),"error"),complete:l(()=>t.onStreamEnd(),"complete")})}static async executeMutation(e){return(await e.dataProvider.ExecuteGQL(e.mutation,e.variables))[e.mutationFieldName]}static async executeSynchronously(e){const t=e.operationLabel??e.mutationFieldName;c.LogStatus(`[FireAndForget:${t}] Provider has no PushStatusUpdates channel \u2014 running synchronously (fireAndForget disabled)`);const r={...e.variables,fireAndForget:!1},n=(await e.dataProvider.ExecuteGQL(e.mutation,r))?.[e.mutationFieldName];return n?e.extractSyncResult?(c.LogStatus(`[FireAndForget:${t}] Synchronous execution completed`),e.extractSyncResult(n)):e.createErrorResult(`${t} cannot run on this data provider: it has no PushStatusUpdates channel and no synchronous result extractor is configured for this operation.`):(c.LogError(`[FireAndForget:${t}] Synchronous execution returned no '${e.mutationFieldName}' payload`),e.createErrorResult(`Server returned no '${e.mutationFieldName}' result for ${t}`))}}class O{static{l(this,"GraphQLAIClient")}constructor(e){this._dataProvider=e}async RunAIPrompt(e){try{const t=u.gql`
|
|
10
10
|
mutation RunAIPrompt(
|
|
11
11
|
$promptId: String!,
|
|
12
12
|
$data: String,
|
|
@@ -112,7 +112,9 @@
|
|
|
112
112
|
result
|
|
113
113
|
}
|
|
114
114
|
}
|
|
115
|
-
`}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),e.planMode!==void 0&&(s.planMode=e.planMode),e.requestedSkillIDs!==void 0&&(s.requestedSkillIDs=e.requestedSkillIDs),e.taskGraphDebug!==void 0&&(s.taskGraphDebug=JSON.stringify(e.taskGraphDebug)),s}processAgentResult(e){return v.SafeJSONParse(e)}handleAgentError(e,t=!1){const s=e?.message||String(e);c.LogError(`Error running AI agent: ${s}`);const n=s.includes("Failed to fetch")||s.includes("NetworkError"),a=s.includes("timed out")||s.includes("timeout");let i;return n&&t?i="Lost connection to the server. The agent may still be running. Please refresh to check the latest status.":n?i="Could not reach the server. The request may not have started. Please try again.":i=s,{success:!1,agentRun:void 0,errorMessage:i,requestAcknowledged:t}}async RunAIAgentFromConversationDetail(e){let t=!1;try{const r=this.buildConversationDetailMutation(),s=this.prepareConversationDetailVariables(e);return await w.Execute({dataProvider:this._dataProvider,mutation:r,variables:s,mutationFieldName:"RunAIAgentFromConversationDetail",operationLabel:"RunAIAgentFromConversationDetail",validateAck:l(n=>{const a=n?.success===!0;return a&&(t=!0),a},"validateAck"),isCompletionEvent:l(n=>this.isConversationDetailCompletionEvent(n,e.conversationDetailId),"isCompletionEvent"),extractResult:l(n=>this.extractAgentResult(n),"extractResult"),extractSyncResult:l(n=>this.extractAgentResultFromAck(n),"extractSyncResult"),onMessage:e.onProgress?n=>this.forwardConversationDetailProgress(n,e.onProgress):void 0,onStall:l(()=>this.reconcileAgentRun(`ConversationDetailID='${e.conversationDetailId}'`),"onStall"),createErrorResult:l(n=>this.createAgentErrorResult(n,t),"createErrorResult")})}catch(r){return this.handleAgentError(r,t)}}buildConversationDetailMutation(){
|
|
115
|
+
`}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),e.planMode!==void 0&&(s.planMode=e.planMode),e.requestedSkillIDs!==void 0&&(s.requestedSkillIDs=e.requestedSkillIDs),e.taskGraphDebug!==void 0&&(s.taskGraphDebug=JSON.stringify(e.taskGraphDebug)),s}processAgentResult(e){return v.SafeJSONParse(e)}handleAgentError(e,t=!1){const s=e?.message||String(e);c.LogError(`Error running AI agent: ${s}`);const n=s.includes("Failed to fetch")||s.includes("NetworkError"),a=s.includes("timed out")||s.includes("timeout");let i;return n&&t?i="Lost connection to the server. The agent may still be running. Please refresh to check the latest status.":n?i="Could not reach the server. The request may not have started. Please try again.":i=s,{success:!1,agentRun:void 0,errorMessage:i,requestAcknowledged:t}}async RunAIAgentFromConversationDetail(e){let t=!1;try{const r=this.buildConversationDetailMutation(e.agentHistoryFrom!=null),s=this.prepareConversationDetailVariables(e);return await w.Execute({dataProvider:this._dataProvider,mutation:r,variables:s,mutationFieldName:"RunAIAgentFromConversationDetail",operationLabel:"RunAIAgentFromConversationDetail",validateAck:l(n=>{const a=n?.success===!0;return a&&(t=!0),a},"validateAck"),isCompletionEvent:l(n=>this.isConversationDetailCompletionEvent(n,e.conversationDetailId),"isCompletionEvent"),extractResult:l(n=>this.extractAgentResult(n),"extractResult"),extractSyncResult:l(n=>this.extractAgentResultFromAck(n),"extractSyncResult"),onMessage:e.onProgress?n=>this.forwardConversationDetailProgress(n,e.onProgress):void 0,onStall:l(()=>this.reconcileAgentRun(`ConversationDetailID='${e.conversationDetailId}'`),"onStall"),createErrorResult:l(n=>this.createAgentErrorResult(n,t),"createErrorResult")})}catch(r){return this.handleAgentError(r,t)}}buildConversationDetailMutation(e){const t=e?`,
|
|
116
|
+
$agentHistoryFrom: String`:"",r=e?`,
|
|
117
|
+
agentHistoryFrom: $agentHistoryFrom`:"";return u.gql`
|
|
116
118
|
mutation RunAIAgentFromConversationDetail(
|
|
117
119
|
$conversationDetailId: String!,
|
|
118
120
|
$agentId: String!,
|
|
@@ -129,7 +131,7 @@
|
|
|
129
131
|
$createNotification: Boolean,
|
|
130
132
|
$sourceArtifactId: String,
|
|
131
133
|
$sourceArtifactVersionId: String,
|
|
132
|
-
$fireAndForget: Boolean
|
|
134
|
+
$fireAndForget: Boolean${t}
|
|
133
135
|
) {
|
|
134
136
|
RunAIAgentFromConversationDetail(
|
|
135
137
|
conversationDetailId: $conversationDetailId,
|
|
@@ -147,7 +149,7 @@
|
|
|
147
149
|
createNotification: $createNotification,
|
|
148
150
|
sourceArtifactId: $sourceArtifactId,
|
|
149
151
|
sourceArtifactVersionId: $sourceArtifactVersionId,
|
|
150
|
-
fireAndForget: $fireAndForget
|
|
152
|
+
fireAndForget: $fireAndForget${r}
|
|
151
153
|
) {
|
|
152
154
|
success
|
|
153
155
|
errorMessage
|
|
@@ -155,7 +157,7 @@
|
|
|
155
157
|
result
|
|
156
158
|
}
|
|
157
159
|
}
|
|
158
|
-
`}prepareConversationDetailVariables(e){const t={conversationDetailId:e.conversationDetailId,agentId:e.agentId,sessionId:this._dataProvider.sessionId,fireAndForget:!0};return e.maxHistoryMessages!==void 0&&(t.maxHistoryMessages=e.maxHistoryMessages),e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.payload!==void 0&&(t.payload=typeof e.payload=="object"?JSON.stringify(e.payload):e.payload),e.lastRunId!==void 0&&(t.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(t.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(t.configurationId=e.configurationId),e.planMode!==void 0&&(t.planMode=e.planMode),e.requestedSkillIDs!==void 0&&(t.requestedSkillIDs=e.requestedSkillIDs),e.createArtifacts!==void 0&&(t.createArtifacts=e.createArtifacts),e.createNotification!==void 0&&(t.createNotification=e.createNotification),e.sourceArtifactId!==void 0&&(t.sourceArtifactId=e.sourceArtifactId),e.sourceArtifactVersionId!==void 0&&(t.sourceArtifactVersionId=e.sourceArtifactVersionId),t}isAgentCompletionEvent(e){const t=e.data;return e.resolver==="RunAIAgentResolver"&&e.type==="StreamingContent"&&t?.type==="complete"}isConversationDetailCompletionEvent(e,t){const r=e.data;return e.resolver==="RunAIAgentResolver"&&e.type==="StreamingContent"&&r?.type==="complete"&&r?.conversationDetailId===t}captureAgentRunId(e,t){const r=e.data,s=r?.agentRunId??r?.runId;s&&s!=="unknown"&&(t.id=s)}async reconcileAgentRun(e){if(!e)return"continue";const t=await this._dataProvider.RunView({EntityName:"MJ: AI Agent Runs",ExtraFilter:e,OrderBy:"__mj_CreatedAt DESC",ResultType:"entity_object",BypassCache:!0}),r=t.Success?t.Results?.[0]:void 0;return!r||r.Status==="Running"?"continue":{resolve:{success:r.Status==="Completed"||r.Status==="Paused"||r.Status==="AwaitingFeedback",agentRun:r,payload:r.Result?v.SafeJSONParse(r.Result)??void 0:void 0,errorMessage:r.ErrorMessage??void 0}}}extractAgentResult(e){const t=e.data,r=t.result;if(r){const a=v.SafeJSONParse(r);if(a)return!a.errorMessage&&typeof t.errorMessage=="string"&&(a.errorMessage=t.errorMessage),a}const s=!!t.success,n=typeof t.errorMessage=="string"&&t.errorMessage?t.errorMessage:void 0;return{success:s,agentRun:void 0,errorMessage:n??(s?void 0:"Agent execution ended without a result payload")}}extractAgentResultFromAck(e){const t=e.result;if(t){const r=v.SafeJSONParse(t);if(r)return r}return{success:e.success,agentRun:void 0,errorMessage:e.errorMessage}}forwardAgentProgress(e,t){if(e.resolver!=="RunAIAgentResolver"||e.type!=="ExecutionProgress"||e.status!=="ok")return;const s=e.data?.progress;s&&t({step:s.currentStep,percentage:s.percentage,message:s.message,metadata:s})}forwardConversationDetailProgress(e,t){if(e.resolver!=="RunAIAgentResolver"||e.type!=="ExecutionProgress"||e.status!=="ok")return;const r=e.data,s=r?.progress;s&&t({currentStep:s.currentStep,percentage:s.percentage,message:s.message,metadata:{...s,agentRun:r?.agentRun,agentRunId:r?.agentRunId}})}createAgentErrorResult(e,t=!1){return{success:!1,agentRun:void 0,errorMessage:e,requestAcknowledged:t}}async ExecuteSimplePrompt(e){try{const t=u.gql`
|
|
160
|
+
`}prepareConversationDetailVariables(e){const t={conversationDetailId:e.conversationDetailId,agentId:e.agentId,sessionId:this._dataProvider.sessionId,fireAndForget:!0};return e.maxHistoryMessages!==void 0&&(t.maxHistoryMessages=e.maxHistoryMessages),e.data!==void 0&&(t.data=typeof e.data=="object"?JSON.stringify(e.data):e.data),e.payload!==void 0&&(t.payload=typeof e.payload=="object"?JSON.stringify(e.payload):e.payload),e.lastRunId!==void 0&&(t.lastRunId=e.lastRunId),e.autoPopulateLastRunPayload!==void 0&&(t.autoPopulateLastRunPayload=e.autoPopulateLastRunPayload),e.configurationId!==void 0&&(t.configurationId=e.configurationId),e.planMode!==void 0&&(t.planMode=e.planMode),e.requestedSkillIDs!==void 0&&(t.requestedSkillIDs=e.requestedSkillIDs),e.createArtifacts!==void 0&&(t.createArtifacts=e.createArtifacts),e.createNotification!==void 0&&(t.createNotification=e.createNotification),e.sourceArtifactId!==void 0&&(t.sourceArtifactId=e.sourceArtifactId),e.sourceArtifactVersionId!==void 0&&(t.sourceArtifactVersionId=e.sourceArtifactVersionId),e.agentHistoryFrom!=null&&(t.agentHistoryFrom=e.agentHistoryFrom.toISOString()),t}isAgentCompletionEvent(e){const t=e.data;return e.resolver==="RunAIAgentResolver"&&e.type==="StreamingContent"&&t?.type==="complete"}isConversationDetailCompletionEvent(e,t){const r=e.data;return e.resolver==="RunAIAgentResolver"&&e.type==="StreamingContent"&&r?.type==="complete"&&r?.conversationDetailId===t}captureAgentRunId(e,t){const r=e.data,s=r?.agentRunId??r?.runId;s&&s!=="unknown"&&(t.id=s)}async reconcileAgentRun(e){if(!e)return"continue";const t=await this._dataProvider.RunView({EntityName:"MJ: AI Agent Runs",ExtraFilter:e,OrderBy:"__mj_CreatedAt DESC",ResultType:"entity_object",BypassCache:!0}),r=t.Success?t.Results?.[0]:void 0;return!r||r.Status==="Running"?"continue":{resolve:{success:r.Status==="Completed"||r.Status==="Paused"||r.Status==="AwaitingFeedback",agentRun:r,payload:r.Result?v.SafeJSONParse(r.Result)??void 0:void 0,errorMessage:r.ErrorMessage??void 0}}}extractAgentResult(e){const t=e.data,r=t.result;if(r){const a=v.SafeJSONParse(r);if(a)return!a.errorMessage&&typeof t.errorMessage=="string"&&(a.errorMessage=t.errorMessage),a}const s=!!t.success,n=typeof t.errorMessage=="string"&&t.errorMessage?t.errorMessage:void 0;return{success:s,agentRun:void 0,errorMessage:n??(s?void 0:"Agent execution ended without a result payload")}}extractAgentResultFromAck(e){const t=e.result;if(t){const r=v.SafeJSONParse(t);if(r)return r}return{success:e.success,agentRun:void 0,errorMessage:e.errorMessage}}forwardAgentProgress(e,t){if(e.resolver!=="RunAIAgentResolver"||e.type!=="ExecutionProgress"||e.status!=="ok")return;const s=e.data?.progress;s&&t({step:s.currentStep,percentage:s.percentage,message:s.message,metadata:s})}forwardConversationDetailProgress(e,t){if(e.resolver!=="RunAIAgentResolver"||e.type!=="ExecutionProgress"||e.status!=="ok")return;const r=e.data,s=r?.progress;s&&t({currentStep:s.currentStep,percentage:s.percentage,message:s.message,metadata:{...s,agentRun:r?.agentRun,agentRunId:r?.agentRunId}})}createAgentErrorResult(e,t=!1){return{success:!1,agentRun:void 0,errorMessage:e,requestAcknowledged:t}}async ExecuteSimplePrompt(e){try{const t=u.gql`
|
|
159
161
|
mutation ExecuteSimplePrompt(
|
|
160
162
|
$systemPrompt: String!,
|
|
161
163
|
$messages: String,
|
|
@@ -307,14 +309,14 @@
|
|
|
307
309
|
}
|
|
308
310
|
}
|
|
309
311
|
}
|
|
310
|
-
`,r={entityDocumentID:e.entityDocumentID};e.maxRecords!==void 0&&(r.maxRecords=e.maxRecords),e.filter!==void 0&&(r.filter=e.filter);const s=await this._dataProvider.ExecuteGQL(t,r);if(!s?.FetchEntityVectors)throw new Error("Invalid response from server");return s.FetchEntityVectors}catch(t){const r=t;return c.LogError("GraphQLAIClient.FetchEntityVectors failed",void 0,r),{Success:!1,Results:[],TotalCount:0,ElapsedMs:0,ErrorMessage:r.message||"Unknown error"}}}}const M="6.2.0-edge.
|
|
311
|
-
${e.stackFrames}`:this.stack}}function j(g){return g instanceof x?g:new x(G(g))}l(j,"ToSafeGraphQLError");const
|
|
312
|
-
at `);return e===-1?"":g.slice(e+1)}l(
|
|
312
|
+
`,r={entityDocumentID:e.entityDocumentID};e.maxRecords!==void 0&&(r.maxRecords=e.maxRecords),e.filter!==void 0&&(r.filter=e.filter);const s=await this._dataProvider.ExecuteGQL(t,r);if(!s?.FetchEntityVectors)throw new Error("Invalid response from server");return s.FetchEntityVectors}catch(t){const r=t;return c.LogError("GraphQLAIClient.FetchEntityVectors failed",void 0,r),{Success:!1,Results:[],TotalCount:0,ElapsedMs:0,ErrorMessage:r.message||"Unknown error"}}}}const M="6.2.0-edge.1",P="default";class k{static{l(this,"BrowserStorageProviderBase")}constructor(){this._storage=new Map}get SharesReferences(){return!0}getCategoryMap(e){const t=e||P;let r=this._storage.get(t);return r||(r=new Map,this._storage.set(t,r)),r}async GetItem(e,t){const s=this.getCategoryMap(t||P).get(e);return s===void 0?null:s}async GetItems(e,t){const r=new Map;if(e.length===0)return r;const s=this.getCategoryMap(t||P);for(const n of new Set(e)){const a=s.get(n);r.set(n,a===void 0?null:a)}return r}async SetItem(e,t,r){this.getCategoryMap(r||P).set(e,t)}async Remove(e,t){this.getCategoryMap(t||P).delete(e)}async ClearCategory(e){const t=e||P;this._storage.delete(t)}async GetCategoryKeys(e){const t=this._storage.get(e||P);return t?Array.from(t.keys()):[]}}const ne="MJ_Metadata",ae=0;function oe(){try{const g=M.split("."),e=parseInt(g[0],10),t=parseInt(g[1],10);if(!Number.isFinite(e)||!Number.isFinite(t))throw new Error(`Could not parse major.minor from version "${M}"`);return e*1e3+t+ae}catch(g){return c.LogErrorEx({error:g,message:"Failed to derive IDB version from PACKAGE_VERSION; using fallback 99999"}),99999}}l(oe,"computeIdbVersion");const ie=oe(),K=["mj:default","mj:Metadata","mj:RunViewCache","mj:RunQueryCache","mj:DatasetCache"];class B extends k{static{l(this,"BrowserIndexedDBStorageProvider")}constructor(){super(),this._dbReady=!1,this.dbPromise=te.openDB(ne,ie,{upgrade:l((e,t,r)=>{try{c.LogStatus(`[IDBCache] Upgrading IndexedDB schema v${t} \u2192 v${r} (package ${M}). Dropping all stores; caches will repopulate on first use.`);for(const s of Array.from(e.objectStoreNames))e.deleteObjectStore(s);for(const s of K)e.objectStoreNames.contains(s)||e.createObjectStore(s)}catch(s){c.LogErrorEx({error:s,message:s?.message})}},"upgrade"),blocked:l((e,t)=>{c.LogStatus(`[IDBCache] Upgrade from v${e} to v${t} blocked by another tab. Close other tabs to allow the upgrade to proceed.`)},"blocked")}),this.dbPromise.then(e=>{this._dbReady=!0,e.onversionchange=()=>{c.LogStatus("[IDBCache] DB schema upgraded in another tab \u2014 closing local connection."),e.close(),this._dbReady=!1}}).catch(e=>{c.LogErrorEx({error:e,message:"IndexedDB initialization failed: "+e?.message})})}get SharesReferences(){return!1}get IsReady(){return this._dbReady}isKnownCategory(e){const t=`mj:${e}`;return K.includes(t)}getStoreName(e){const t=e||P;return this.isKnownCategory(t)?`mj:${t}`:"mj:default"}getStoreKey(e,t){const r=t||P;return this.isKnownCategory(r)?e:`[${r}]:${e}`}async SetItem(e,t,r){try{const s=await this.dbPromise,n=this.getStoreName(r),a=this.getStoreKey(e,r),i=s.transaction(n,"readwrite");await i.objectStore(n).put(t,a),await i.done}catch(s){c.LogErrorEx({error:s,message:s?.message})}}async GetItem(e,t){try{const r=await this.dbPromise,s=this.getStoreName(t),n=this.getStoreKey(e,t),a=await r.transaction(s).objectStore(s).get(n);return a===void 0?null:a}catch(r){return c.LogErrorEx({error:r,message:r?.message}),null}}async GetItems(e,t){const r=new Map;if(e.length===0)return r;try{const s=await this.dbPromise,n=this.getStoreName(t),a=Array.from(new Set(e)),i=a.map(f=>this.getStoreKey(f,t)),o=s.transaction(n,"readonly"),y=o.objectStore(n),d=i.map(f=>y.get(f)),m=await Promise.all(d);await o.done;for(let f=0;f<a.length;f++){const S=m[f];r.set(a[f],S===void 0?null:S)}return r}catch(s){c.LogErrorEx({error:s,message:s?.message});for(const n of new Set(e))r.set(n,null);return r}}async Remove(e,t){try{const r=await this.dbPromise,s=this.getStoreName(t),n=this.getStoreKey(e,t),a=r.transaction(s,"readwrite");await a.objectStore(s).delete(n),await a.done}catch(r){c.LogErrorEx({error:r,message:r?.message})}}async ClearCategory(e){try{const t=await this.dbPromise,r=e||P,s=this.getStoreName(e);if(this.isKnownCategory(r)){const n=t.transaction(s,"readwrite");await n.objectStore(s).clear(),await n.done}else{const n=`[${r}]:`,a=t.transaction("mj:default","readwrite"),i=a.objectStore("mj:default"),o=await i.getAllKeys();for(const y of o)typeof y=="string"&&y.startsWith(n)&&await i.delete(y);await a.done}}catch(t){c.LogErrorEx({error:t,message:t?.message})}}async GetCategoryKeys(e){try{const t=await this.dbPromise,r=e||P,s=this.getStoreName(e),i=await t.transaction(s,"readonly").objectStore(s).getAllKeys();if(this.isKnownCategory(r))return i.map(y=>String(y));const o=`[${r}]:`;return i.map(y=>String(y)).filter(y=>y.startsWith(o)).map(y=>y.slice(o.length))}catch(t){return c.LogErrorEx({error:t,message:t?.message}),[]}}}class x extends Error{static{l(this,"SafeGraphQLError")}constructor(e){super(e.message),this.name=e.name,this.response={status:e.status,errors:e.errors},this.request={query:e.query},this.Code=e.code,this.VariableShape=e.variableShape,this.stack=e.stackFrames?`${e.name}: ${e.message}
|
|
313
|
+
${e.stackFrames}`:this.stack}}function j(g){return g instanceof x?g:new x(G(g))}l(j,"ToSafeGraphQLError");const ce=3,ue=25;function F(g,e=0){if(g===null)return"null";if(g===void 0)return"undefined";if(Array.isArray(g))return g.length===0?"array(empty)":`array(${g.length} \xD7 ${le(F(g[0],e+1))})`;if(typeof g=="object"){if(e>=ce)return"object(\u2026)";const t=Object.keys(g);if(t.length>ue)return`object(${t.length} keys)`;const r={};for(const s of t)r[s]=F(g[s],e+1);return r}return typeof g=="string"?g.length===0?"string(empty)":"string":typeof g}l(F,"describeShape");function le(g){return typeof g=="string"?g:"object"}l(le,"typeOf");function de(g){const e=g.indexOf(`
|
|
314
|
+
at `);return e===-1?"":g.slice(e+1)}l(de,"stripStackHeader");function ge(g,e){const t=g?.[0]?.message;return typeof t=="string"&&t.length>0?t:`GraphQL Error (Code: ${String(e??"unknown")})`}l(ge,"deriveMessage");function ye(g){if(Array.isArray(g))return g.map(e=>{const t=e??{};return{message:typeof t.message=="string"?t.message:void 0,path:Array.isArray(t.path)?t.path:void 0,extensions:t.extensions&&typeof t.extensions=="object"?t.extensions:void 0}})}l(ye,"extractErrors");function G(g,e=!1){if(!g||typeof g!="object")return{name:typeof g,message:"Non-object value thrown; contents withheld",variables:"[REDACTED]"};const t=g,r=typeof t.response?.status=="number"?t.response.status:void 0,s=ye(t.response?.errors),n=s?.[0]?.extensions?.code;return{name:typeof t.name=="string"?t.name:"Error",message:ge(s,r),status:r,errors:s,code:typeof n=="string"?n:void 0,query:typeof t.request?.query=="string"?t.request.query:void 0,stackFrames:typeof t.stack=="string"?de(t.stack):void 0,variables:e?t.request?.variables:"[REDACTED]",variableShape:t.request?.variables===void 0?void 0:F(t.request.variables)}}l(G,"SanitizeGraphQLError");const b=new L,me=u.gql`subscription RemoteOperationProgress($channelId: ID!) {
|
|
313
315
|
RemoteOperationProgress(channelId: $channelId) {
|
|
314
316
|
ChannelId
|
|
315
317
|
ProgressJSON
|
|
316
318
|
}
|
|
317
|
-
}`;class
|
|
319
|
+
}`;class Se extends c.ProviderConfigDataBase{static{l(this,"GraphQLProviderConfigData")}get Token(){return this.Data.Token}set Token(e){this.Data.Token=e}get MJAPIKey(){return this.Data.MJAPIKey}set MJAPIKey(e){this.Data.MJAPIKey=e}get UserAPIKey(){return this.Data.UserAPIKey}set UserAPIKey(e){this.Data.UserAPIKey=e}get URL(){return this.Data.URL}get WSURL(){return this.Data.WSURL}get LogVariableValues(){return this.Data.LogVariableValues===!0}set LogVariableValues(e){this.Data.LogVariableValues=e}get RefreshTokenFunction(){return this.Data.RefreshFunction}get OnAuthenticationError(){return this.Data.OnAuthenticationError}set OnAuthenticationError(e){this.Data.OnAuthenticationError=e}constructor(e,t,r,s,n,a,i,o,y,d){super({Token:e,URL:t,WSURL:r,MJAPIKey:o,UserAPIKey:y,RefreshTokenFunction:s,OnAuthenticationError:d},n,a,i)}}class I extends c.ProviderBase{static{l(this,"GraphQLDataProvider")}constructor(){super(),this._refreshPromise=null,this._dynamicHeaders=new Map,this._innerCurrentUserQueryString=`CurrentUser {
|
|
318
320
|
${this.userInfoString()}
|
|
319
321
|
Roles {
|
|
320
322
|
${this.userRoleInfoString()}
|
|
@@ -323,7 +325,7 @@ ${e.stackFrames}`:this.stack}}function j(g){return g instanceof x?g:new x(G(g))}
|
|
|
323
325
|
`,this._currentUserQuery=u.gql`query CurrentUserAndRoles {
|
|
324
326
|
${this._innerCurrentUserQueryString}
|
|
325
327
|
CurrentUserTenantContext
|
|
326
|
-
}`,this._wsClient=null,this._wsClientCreatedAt=null,this._socketStateSubject=new $.BehaviorSubject("unknown"),this._isDisposingSocketIntentionally=!1,this._pushStatusSubjects=new Map,this._activeSubscriptionCount=0,this.WS_CLIENT_MAX_AGE_MS=1800*1e3,this.SUBSCRIPTION_CLEANUP_INTERVAL_MS=300*1e3,this.SUBSCRIPTION_IDLE_TIMEOUT_MS=600*1e3,this._subscriptionCleanupTimer=null,this._isCleaningUp=!1,this._taskGraphFrameStreams=new Map,this._cacheInvalidationSubscription=null;const e=v.GetGlobalObjectStore();if(e&&e[I._globalStoreKey])return e[I._globalStoreKey];e&&(e[I._globalStoreKey]=this)}static{this.VerboseCacheInvalidationLogging=!1}static{this._globalStoreKey="___SINGLETON__GraphQLDataProvider"}static get Instance(){const e=v.GetGlobalObjectStore();return e?e[I._globalStoreKey]:void 0}get ConfigData(){return this._configData}get AI(){return this._aiClient||(this._aiClient=new O(this)),this._aiClient}get DatabaseConnection(){throw new Error("DatabaseConnection not implemented for the GraphQLDataProvider")}async InternalExecuteQueryFromSpec(e,t){throw new Error("ExecuteQueryFromSpec is not supported by this provider.")}get InstanceConnectionString(){return this._configData.URL}GenerateUUID(){return
|
|
328
|
+
}`,this._wsClient=null,this._wsClientCreatedAt=null,this._socketStateSubject=new $.BehaviorSubject("unknown"),this._isDisposingSocketIntentionally=!1,this._pushStatusSubjects=new Map,this._activeSubscriptionCount=0,this.WS_CLIENT_MAX_AGE_MS=1800*1e3,this.SUBSCRIPTION_CLEANUP_INTERVAL_MS=300*1e3,this.SUBSCRIPTION_IDLE_TIMEOUT_MS=600*1e3,this._subscriptionCleanupTimer=null,this._isCleaningUp=!1,this._taskGraphFrameStreams=new Map,this._cacheInvalidationSubscription=null;const e=v.GetGlobalObjectStore();if(e&&e[I._globalStoreKey])return e[I._globalStoreKey];e&&(e[I._globalStoreKey]=this)}static{this.VerboseCacheInvalidationLogging=!1}static{this._globalStoreKey="___SINGLETON__GraphQLDataProvider"}static get Instance(){const e=v.GetGlobalObjectStore();return e?e[I._globalStoreKey]:void 0}get ConfigData(){return this._configData}get AI(){return this._aiClient||(this._aiClient=new O(this)),this._aiClient}get DatabaseConnection(){throw new Error("DatabaseConnection not implemented for the GraphQLDataProvider")}async InternalExecuteQueryFromSpec(e,t){throw new Error("ExecuteQueryFromSpec is not supported by this provider.")}get InstanceConnectionString(){return this._configData.URL}GenerateUUID(){return ee.v4()}get LocalStoragePrefix(){if(this._configData===void 0||this._configData.URL===void 0)throw new Error("GraphQLDataProvider: ConfigData is not set. Please call Config() first.");return this._configData.URL.replace(/[^a-zA-Z0-9]/g,"_")+"."}async GetStoredSessionID(){try{const e=this.LocalStorageProvider;if(e){const t=this.LocalStoragePrefix+"sessionId";return await e.GetItem(t)}return null}catch(e){return console.error("Error retrieving session ID from local storage:",e),null}}async saveStoredSessionID(e){try{const t=this.LocalStorageProvider;if(t){const r=this.LocalStoragePrefix+"sessionId";await t.SetItem(r,e)}}catch{}}async GetPreferredUUID(e){const t=await this.GetStoredSessionID();return e||!t?this.GenerateUUID():t}async Config(e,t,r,s){try{return this._configData=e,r?(this._sessionId=await this.GetPreferredUUID(s),this._client=this.CreateNewGraphQLClient(e.URL,e.Token,this._sessionId,e.MJAPIKey,e.UserAPIKey),await this.saveStoredSessionID(this._sessionId)):(I.Instance._configData=e,I.Instance._sessionId===void 0&&(I.Instance._sessionId=await this.GetPreferredUUID(s)),I.Instance._client||(I.Instance._client=this.CreateNewGraphQLClient(e.URL,e.Token,I.Instance._sessionId,e.MJAPIKey,e.UserAPIKey)),await I.Instance.saveStoredSessionID(I.Instance._sessionId),this._sessionId=I.Instance._sessionId,this._client=I.Instance._client),super.Config(e)}catch(n){throw c.LogError(n),n}}get sessionId(){return this._sessionId}get AllowRefresh(){return!0}SetDynamicHeader(e,t){this._dynamicHeaders.set(e,t),this._client&&this._client.setHeader(e,t),I.Instance&&I.Instance!==this&&I.Instance._configData===this._configData&&(I.Instance._dynamicHeaders.set(e,t),I.Instance._client&&I.Instance._client.setHeader(e,t))}RemoveDynamicHeader(e){this._dynamicHeaders.delete(e),this._client&&this._client.setHeader(e,""),I.Instance&&I.Instance!==this&&I.Instance._configData===this._configData&&(I.Instance._dynamicHeaders.delete(e),I.Instance._client&&I.Instance._client.setHeader(e,""))}GetDynamicHeaders(){return this._dynamicHeaders}async GetCurrentUser(){const e=await this.ExecuteGQL(this._currentUserQuery,null);if(e){const t=this.ConvertBackToMJFields(e.CurrentUser),{Roles:r,...s}=t,n=(r??[]).map(i=>this.ConvertBackToMJFields(i)),a=new c.UserInfo(this,{...s,UserRoles:n});return e.CurrentUserTenantContext&&typeof e.CurrentUserTenantContext=="object"&&(a.TenantContext=e.CurrentUserTenantContext),a}}async InternalRunQuery(e,t){if(e.SQL)return this.RunAdhocQuery(e.SQL,e.MaxRows,void 0,e.StartRow);if(e.QueryID)return this.RunQueryByID(e.QueryID,e.CategoryID,e.CategoryPath,t,e.Parameters,e.MaxRows,e.StartRow,e.Enrichment,e.DataSource);if(e.QueryName)return this.RunQueryByName(e.QueryName,e.CategoryID,e.CategoryPath,t,e.Parameters,e.MaxRows,e.StartRow,e.Enrichment,e.DataSource);throw new Error("No SQL, QueryID, or QueryName provided to RunQuery")}async RunAdhocQuery(e,t,r,s){const n=u.gql`
|
|
327
329
|
query ExecuteAdhocQuery($input: AdhocQueryInput!) {
|
|
328
330
|
ExecuteAdhocQuery(input: $input) {
|
|
329
331
|
${this.QueryReturnFieldList}
|
|
@@ -515,7 +517,7 @@ ${e.stackFrames}`:this.stack}}function j(g){return g instanceof x?g:new x(G(g))}
|
|
|
515
517
|
handle
|
|
516
518
|
errorMessage
|
|
517
519
|
}
|
|
518
|
-
}`;let n,a;r.onProgress&&(n=this.GenerateUUID(),a=this.
|
|
520
|
+
}`;let n,a;r.onProgress&&(n=this.GenerateUUID(),a=this.Subscribe(me,{channelId:n}).subscribe({next:l(i=>{const o=i?.RemoteOperationProgress?.ProgressJSON;if(o)try{r.onProgress(JSON.parse(o))}catch{}},"next"),error:l(()=>{},"error")}),await new Promise(i=>setTimeout(i,400)));try{const o=(await this.ExecuteGQL(s,{operationKey:e,inputJSON:JSON.stringify(t??null),invokeMode:r.mode??"attached",progressChannelId:n??null}))?.ExecuteRemoteOperation;return o?{Success:!!o.success,ResultCode:o.resultCode??void 0,Output:o.outputJSON!=null?JSON.parse(o.outputJSON):void 0,Handle:o.handle??void 0,ErrorMessage:o.errorMessage??void 0}:{Success:!1,ResultCode:"NO_RESPONSE",ErrorMessage:"No response from ExecuteRemoteOperation"}}catch(i){return{Success:!1,ResultCode:"TRANSPORT_ERROR",ErrorMessage:i instanceof Error?i.message:String(i)}}finally{a?.unsubscribe()}}async MergeRecords(e,t,r){const s=this.Entities.find(n=>n.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 n=u.gql`mutation MergeRecordsMutation ($request: RecordMergeRequest!) {
|
|
519
521
|
MergeRecords(request: $request) {
|
|
520
522
|
Success
|
|
521
523
|
OverallStatus
|
|
@@ -532,18 +534,18 @@ ${e.stackFrames}`:this.stack}}function j(g){return g instanceof x?g:new x(G(g))}
|
|
|
532
534
|
Message
|
|
533
535
|
}
|
|
534
536
|
}
|
|
535
|
-
}`,a={EntityName:e.EntityName,SurvivingRecordCompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(e.SurvivingRecordCompositeKey.KeyValuePairs)},FieldMap:e.FieldMap?.map(o=>({FieldName:o.FieldName,Value:o.Value.toString()})),RecordsToMerge:e.RecordsToMerge.map(o=>o.Copy())};return(await this.ExecuteGQL(n,{request:a}))?.MergeRecords}catch(n){return c.LogError(n),{Success:!1,OverallStatus:n&&n.message?n.message:n,RecordStatus:[],RecordMergeLogID:"",Request:e}}}
|
|
537
|
+
}`,a={EntityName:e.EntityName,SurvivingRecordCompositeKey:{KeyValuePairs:this.ensureKeyValuePairValueIsString(e.SurvivingRecordCompositeKey.KeyValuePairs)},FieldMap:e.FieldMap?.map(o=>({FieldName:o.FieldName,Value:o.Value.toString()})),RecordsToMerge:e.RecordsToMerge.map(o=>o.Copy())};return(await this.ExecuteGQL(n,{request:a}))?.MergeRecords}catch(n){return c.LogError(n),{Success:!1,OverallStatus:n&&n.message?n.message:n,RecordStatus:[],RecordMergeLogID:"",Request:e}}}getDeniedReadFieldNamesForCurrentUser(e){return!e?.EnableFieldLevelSecurity||!this.CurrentUser?new Set:e.GetDeniedReadFields(this.CurrentUser)}fieldSecurityTransportSelection(e){return e?.EnableFieldLevelSecurity?c.ReadableFieldsTransportKey:""}ApplyServerFieldAccess(e,t){if(!t||typeof t!="object")return t;const r=t,s=r[c.ReadableFieldsTransportKey];if(delete r[c.ReadableFieldsTransportKey],Array.isArray(s)){const a=new Set(s.map(i=>String(i).trim().toLowerCase()));for(const i of e.Fields)a.has(i.Name.trim().toLowerCase())||(delete r[i.Name],delete r[i.CodeName]);return t}const n=this.getDeniedReadFieldNamesForCurrentUser(e);if(n.size===0)return t;for(const a of e.Fields)n.has(a.Name.trim().toLowerCase())&&(r[a.Name]===null&&delete r[a.Name],r[a.CodeName]===null&&delete r[a.CodeName]);return t}async Save(e,t,r){if(r?.IsParentEntitySave){const n=new c.BaseEntityResult;return n.StartedAt=new Date,n.EndedAt=new Date,n.Type=e.IsSaved?"update":"create",n.Success=!0,n.NewValues=e.GetAll(),e.RegisterResultHistoryEntry(n),n.NewValues}const s=new c.BaseEntityResult;try{e.RegisterTransactionPreprocessing();const n={input:{}},a=e.IsSaved?"Update":"Create";s.StartedAt=new Date,s.Type=e.IsSaved?"update":"create",s.OriginalValues=e.Fields.map(h=>({FieldName:h.CodeName,Value:h.Value})),e.RegisterResultHistoryEntry(s);const i=c.getGraphQLTypeNameBase(e.EntityInfo),o=`${a}${i}`,y=!e.IsSaved&&e.EntityInfo.IsChildType&&e.ISAParent?.IsSaved===!0,d=this.getDeniedReadFieldNamesForCurrentUser(e.EntityInfo),m=l(h=>d.has(h.trim().toLowerCase()),"isDeniedRead"),f=e.Fields.filter(h=>(!h.ReadOnly||h.IsPrimaryKey&&(e.IsSaved||y))&&(h.IsPrimaryKey||!h.NotLoaded&&!m(h.Name))),S=` ${o}(input: $input) {
|
|
536
538
|
${e.Fields.filter(h=>!m(h.Name)).map(h=>b.MapFieldName(h.CodeName)).join(`
|
|
537
539
|
`)}
|
|
538
|
-
${this.
|
|
540
|
+
${this.fieldSecurityTransportSelection(e.EntityInfo)}
|
|
539
541
|
}`,E=u.gql`mutation ${a}${i} ($input: ${o}Input!) {
|
|
540
542
|
${S}
|
|
541
543
|
}
|
|
542
|
-
`;for(let h=0;h<f.length;h++){const p=f[h];let R=e.Get(p.Name);if(R)switch(p.EntityFieldInfo.TSType){case c.EntityFieldTSType.Date:R=R.getTime();break;case c.EntityFieldTSType.Boolean:typeof R!="boolean"&&(R=parseInt(R)!==0);break;case c.EntityFieldTSType.Number:if(typeof R!="number"){const C=Number(R);isNaN(C)||(R=C)}break}R===null&&p.EntityFieldInfo.AllowsNull===!1&&(p.EntityFieldInfo.DefaultValue!==null?R=p.EntityFieldInfo.DefaultValue:p.FieldType===c.EntityFieldTSType.Number||p.FieldType===c.EntityFieldTSType.Boolean?R=0:R=""),n.input[b.MapFieldName(p.CodeName)]=R}const D=e.RestoreContext;if(D&&(n.input.RestoreContext___={SourceChangeID:D.SourceChangeID,Reason:D.Reason}),a.trim().toLowerCase()==="update"&&r.SkipOldValuesCheck===!1){const h=[];e.Fields.forEach(p=>{if(p.NotLoaded&&!p.IsPrimaryKey)return;let R=null;p.OldValue!==null&&p.OldValue!==void 0&&(p.EntityFieldInfo.TSType===c.EntityFieldTSType.Date?R=p.OldValue.getTime().toString():p.EntityFieldInfo.TSType===c.EntityFieldTSType.Boolean?R=p.OldValue===!0?"1":"0":typeof p.OldValue!="string"?R=p.OldValue.toString():R=p.OldValue),h.push({Key:b.MapFieldName(p.CodeName),Value:R})}),n.input.OldValues___=h}if(e.TransactionGroup){const h=[{varName:"input",inputType:o+"Input!"}];return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new c.TransactionItem(e,s.Type==="create"?"Create":"Update",S,n,{mutationName:o,mutationInputTypes:h},(p,R)=>{s.EndedAt=new Date,R&&p?(s.Success=!0,s.NewValues=this.ApplyServerFieldAccess(e.EntityInfo,this.ConvertBackToMJFields(p))):(s.Success=!1,s.Message="Transaction failed")})),!0}else{const h=await this.ExecuteGQL(E,n);if(h&&h[o])return s.Success=!0,s.EndedAt=new Date,s.NewValues=this.ApplyServerFieldAccess(e.EntityInfo,this.ConvertBackToMJFields(h[o])),s.NewValues;throw new Error(`Save failed for ${e.EntityInfo.ClassName}`)}}catch(n){s.Success=!1,s.EndedAt=new Date,s.Message=n.response?.errors?.length>0?n.response.errors[0].message:n.message;const a=n.response?.errors?.[0]?.extensions;return s.Errors=v.DeserializeValidationErrors(a?.validationErrors),s.MessageIncludesErrors=s.Errors.length>0&&a?.messageIncludesValidationErrors===!0,c.LogError(n),null}}async Load(e,t,r=null,s){try{const n={};let a="",i="";for(let S=0;S<t.KeyValuePairs.length;S++){const E=e.Fields.find(R=>R.Name.trim().toLowerCase()===t.KeyValuePairs[S].FieldName.trim().toLowerCase()).EntityFieldInfo,D=t.GetValueByIndex(S),h=E.GraphQLType;i.length>0&&(i+=", "),i+=`$${E.CodeName}: ${h}!`,a.length>0&&(a+=", ");const p=E.CodeName.startsWith("__mj_")?E.CodeName.replace("__mj_","_mj__"):E.CodeName;if(a+=`${p}: $${E.CodeName}`,E.TSType===c.EntityFieldTSType.Number){if(isNaN(t.GetValueByIndex(S)))throw new Error(`Primary Key value ${D} (${E.Name}) is not a valid number`);n[E.CodeName]=parseInt(D)}else n[E.CodeName]=D}const o=r&&r.length>0?this.getRelatedEntityString(e.EntityInfo,r):"",y=c.getGraphQLTypeNameBase(e.EntityInfo),d=this.
|
|
544
|
+
`;for(let h=0;h<f.length;h++){const p=f[h];let R=e.Get(p.Name);if(R)switch(p.EntityFieldInfo.TSType){case c.EntityFieldTSType.Date:R=R.getTime();break;case c.EntityFieldTSType.Boolean:typeof R!="boolean"&&(R=parseInt(R)!==0);break;case c.EntityFieldTSType.Number:if(typeof R!="number"){const C=Number(R);isNaN(C)||(R=C)}break}R===null&&p.EntityFieldInfo.AllowsNull===!1&&(p.EntityFieldInfo.DefaultValue!==null?R=p.EntityFieldInfo.DefaultValue:p.FieldType===c.EntityFieldTSType.Number||p.FieldType===c.EntityFieldTSType.Boolean?R=0:R=""),n.input[b.MapFieldName(p.CodeName)]=R}const D=e.RestoreContext;if(D&&(n.input.RestoreContext___={SourceChangeID:D.SourceChangeID,Reason:D.Reason}),a.trim().toLowerCase()==="update"&&r.SkipOldValuesCheck===!1){const h=[];e.Fields.forEach(p=>{if(p.NotLoaded&&!p.IsPrimaryKey)return;let R=null;p.OldValue!==null&&p.OldValue!==void 0&&(p.EntityFieldInfo.TSType===c.EntityFieldTSType.Date?R=p.OldValue.getTime().toString():p.EntityFieldInfo.TSType===c.EntityFieldTSType.Boolean?R=p.OldValue===!0?"1":"0":typeof p.OldValue!="string"?R=p.OldValue.toString():R=p.OldValue),h.push({Key:b.MapFieldName(p.CodeName),Value:R})}),n.input.OldValues___=h}if(e.TransactionGroup){const h=[{varName:"input",inputType:o+"Input!"}];return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new c.TransactionItem(e,s.Type==="create"?"Create":"Update",S,n,{mutationName:o,mutationInputTypes:h},(p,R)=>{s.EndedAt=new Date,R&&p?(s.Success=!0,s.NewValues=this.ApplyServerFieldAccess(e.EntityInfo,this.ConvertBackToMJFields(p))):(s.Success=!1,s.Message="Transaction failed")})),!0}else{const h=await this.ExecuteGQL(E,n);if(h&&h[o])return s.Success=!0,s.EndedAt=new Date,s.NewValues=this.ApplyServerFieldAccess(e.EntityInfo,this.ConvertBackToMJFields(h[o])),s.NewValues;throw new Error(`Save failed for ${e.EntityInfo.ClassName}`)}}catch(n){s.Success=!1,s.EndedAt=new Date,s.Message=n.response?.errors?.length>0?n.response.errors[0].message:n.message;const a=n.response?.errors?.[0]?.extensions;return s.Errors=v.DeserializeValidationErrors(a?.validationErrors),s.MessageIncludesErrors=s.Errors.length>0&&a?.messageIncludesValidationErrors===!0,c.LogError(n),null}}async Load(e,t,r=null,s){try{const n={};let a="",i="";for(let S=0;S<t.KeyValuePairs.length;S++){const E=e.Fields.find(R=>R.Name.trim().toLowerCase()===t.KeyValuePairs[S].FieldName.trim().toLowerCase()).EntityFieldInfo,D=t.GetValueByIndex(S),h=E.GraphQLType;i.length>0&&(i+=", "),i+=`$${E.CodeName}: ${h}!`,a.length>0&&(a+=", ");const p=E.CodeName.startsWith("__mj_")?E.CodeName.replace("__mj_","_mj__"):E.CodeName;if(a+=`${p}: $${E.CodeName}`,E.TSType===c.EntityFieldTSType.Number){if(isNaN(t.GetValueByIndex(S)))throw new Error(`Primary Key value ${D} (${E.Name}) is not a valid number`);n[E.CodeName]=parseInt(D)}else n[E.CodeName]=D}const o=r&&r.length>0?this.getRelatedEntityString(e.EntityInfo,r):"",y=c.getGraphQLTypeNameBase(e.EntityInfo),d=this.getDeniedReadFieldNamesForCurrentUser(e.EntityInfo),m=u.gql`query Single${y}${o.length>0?"Full":""} (${i}) {
|
|
543
545
|
${y}(${a}) {
|
|
544
546
|
${e.Fields.filter(S=>!S.EntityFieldInfo.IsBinaryFieldType&&!d.has(S.Name.trim().toLowerCase())).map(S=>S.EntityFieldInfo.Name.trim().toLowerCase().startsWith("__mj_")?S.CodeName.replace("__mj_","_mj__"):S.CodeName).join(`
|
|
545
547
|
`)}
|
|
546
|
-
${this.
|
|
548
|
+
${this.fieldSecurityTransportSelection(e.EntityInfo)}
|
|
547
549
|
${o}
|
|
548
550
|
}
|
|
549
551
|
}
|
|
@@ -626,9 +628,9 @@ ${e.stackFrames}`:this.stack}}function j(g){return g instanceof x?g:new x(G(g))}
|
|
|
626
628
|
ErrorMessage
|
|
627
629
|
Result
|
|
628
630
|
}
|
|
629
|
-
}`,r=await this.ExecuteGQL(t,{DataContextItemID:e});if(r&&r.GetDataContextItemData){if(r.GetDataContextItemData.Success)return JSON.parse(r.GetDataContextItemData.Result);throw new Error(r.GetDataContextItemData.ErrorMessage)}else throw new Error("GraphQL query failed")}catch(t){throw c.LogError(t),t}}static async ExecuteGQL(e,t,r=!0){return I.Instance.ExecuteGQL(e,t,r)}static async ExecuteGQLWithProgress(e,t,r,s=!0){return I.Instance.ExecuteGQLWithProgress(e,t,r,s)}async ExecuteGQLWithProgress(e,t,r,s=!0){if(!this._configData?.URL)throw new Error("GraphQLDataProvider is not configured with a URL.");const n=this._configData.URL,a=JSON.stringify({query:e,variables:t});return new Promise((i,o)=>{const y=new XMLHttpRequest;y.open("POST",n),y.setRequestHeader("Content-Type","application/json"),this._sessionId&&y.setRequestHeader("x-session-id",this._sessionId),this._configData?.Token&&y.setRequestHeader("authorization","Bearer "+this._configData.Token),this._configData?.MJAPIKey&&y.setRequestHeader("x-mj-api-key",this._configData.MJAPIKey),this._configData?.UserAPIKey&&y.setRequestHeader("x-api-key",this._configData.UserAPIKey);for(const[d,m]of this._dynamicHeaders)y.setRequestHeader(d,m);y.upload&&r&&(y.upload.onprogress=d=>{if(d.lengthComputable&&d.total>0){const m=Math.min(100,Math.round(d.loaded/d.total*100));r({loaded:d.loaded,total:d.total,percent:m})}}),y.onload=async()=>{if(y.status>=200&&y.status<300)try{const d=JSON.parse(y.responseText);if(d.errors&&d.errors.length>0){const m=d.errors[0];if(m?.extensions?.code?.toUpperCase()?.trim()==="JWT_EXPIRED"&&s){await this.RefreshToken(),i(await this.ExecuteGQLWithProgress(e,t,r,!1));return}o(new Error(m.message||"GraphQL Error"))}else i(d.data)}catch(d){o(d)}else o(new Error(`HTTP error ${y.status}: ${y.statusText}`))},y.onerror=()=>o(new Error("Network error during request")),y.onabort=()=>o(new Error("Request aborted")),y.send(a)})}async ExecuteGQL(e,t,r=!0){try{return await this._client.request(e,t)}catch(s){const n=G(s,this._configData?.LogVariableValues===!0);console.error("[GraphQL] ExecuteGQL error caught:",n);const a=j(s);if(s&&s.response&&s.response.errors?.length>0)if(s.response.errors[0]?.extensions?.code?.toUpperCase().trim()==="JWT_EXPIRED"){if(r)return await this.RefreshToken(),await this.ExecuteGQL(e,t,!1);throw c.LogError("JWT_EXPIRED and refreshTokenIfNeeded is false"),a}else throw a;else throw c.LogError(JSON.stringify(n)),a}}async RefreshToken(){const e=I.Instance&&I.Instance._configData===this._configData;if(e&&I.Instance._refreshPromise)return I.Instance._refreshPromise;if(this._refreshPromise)return this._refreshPromise;console.log("[GraphQL] Starting token refresh..."),this._refreshPromise=this.performTokenRefresh(),e&&(I.Instance._refreshPromise=this._refreshPromise);try{await this._refreshPromise,console.log("[GraphQL] Token refresh completed successfully")}finally{this._refreshPromise=null,e&&I.Instance&&(I.Instance._refreshPromise=null)}}async performTokenRefresh(){if(this._configData.Data.RefreshTokenFunction)try{const e=await this._configData.Data.RefreshTokenFunction();if(e){this._configData.Token=e;const t=this.CreateNewGraphQLClient(this._configData.URL,this._configData.Token,this._sessionId,this._configData.MJAPIKey,this._configData.UserAPIKey);this._client=t,I.Instance&&I.Instance._configData===this._configData&&(I.Instance._client=t)}else{const t=new Error("Refresh token function returned null or undefined token");throw this.notifyAuthenticationError(t),t}}catch(e){const t=e instanceof Error?e:new Error(String(e));throw this.notifyAuthenticationError(t),e}else{const e=new Error("No refresh token function provided");throw this.notifyAuthenticationError(e),e}}notifyAuthenticationError(e){try{const t=this._configData?.OnAuthenticationError;t&&t(e)}catch(t){console.error("[GraphQLDataProvider] Error in OnAuthenticationError callback:",t)}}static async RefreshToken(){return I.Instance.RefreshToken()}static async
|
|
631
|
+
}`,r=await this.ExecuteGQL(t,{DataContextItemID:e});if(r&&r.GetDataContextItemData){if(r.GetDataContextItemData.Success)return JSON.parse(r.GetDataContextItemData.Result);throw new Error(r.GetDataContextItemData.ErrorMessage)}else throw new Error("GraphQL query failed")}catch(t){throw c.LogError(t),t}}static async ExecuteGQL(e,t,r=!0){return I.Instance.ExecuteGQL(e,t,r)}static async ExecuteGQLWithProgress(e,t,r,s=!0){return I.Instance.ExecuteGQLWithProgress(e,t,r,s)}async ExecuteGQLWithProgress(e,t,r,s=!0){if(!this._configData?.URL)throw new Error("GraphQLDataProvider is not configured with a URL.");const n=this._configData.URL,a=JSON.stringify({query:e,variables:t});return new Promise((i,o)=>{const y=new XMLHttpRequest;y.open("POST",n),y.setRequestHeader("Content-Type","application/json"),this._sessionId&&y.setRequestHeader("x-session-id",this._sessionId),this._configData?.Token&&y.setRequestHeader("authorization","Bearer "+this._configData.Token),this._configData?.MJAPIKey&&y.setRequestHeader("x-mj-api-key",this._configData.MJAPIKey),this._configData?.UserAPIKey&&y.setRequestHeader("x-api-key",this._configData.UserAPIKey);for(const[d,m]of this._dynamicHeaders)y.setRequestHeader(d,m);y.upload&&r&&(y.upload.onprogress=d=>{if(d.lengthComputable&&d.total>0){const m=Math.min(100,Math.round(d.loaded/d.total*100));r({loaded:d.loaded,total:d.total,percent:m})}}),y.onload=async()=>{if(y.status>=200&&y.status<300)try{const d=JSON.parse(y.responseText);if(d.errors&&d.errors.length>0){const m=d.errors[0];if(m?.extensions?.code?.toUpperCase()?.trim()==="JWT_EXPIRED"&&s){await this.RefreshToken(),i(await this.ExecuteGQLWithProgress(e,t,r,!1));return}o(new Error(m.message||"GraphQL Error"))}else i(d.data)}catch(d){o(d)}else o(new Error(`HTTP error ${y.status}: ${y.statusText}`))},y.onerror=()=>o(new Error("Network error during request")),y.onabort=()=>o(new Error("Request aborted")),y.send(a)})}async ExecuteGQL(e,t,r=!0){try{return await this._client.request(e,t)}catch(s){const n=G(s,this._configData?.LogVariableValues===!0);console.error("[GraphQL] ExecuteGQL error caught:",n);const a=j(s);if(s&&s.response&&s.response.errors?.length>0)if(s.response.errors[0]?.extensions?.code?.toUpperCase().trim()==="JWT_EXPIRED"){if(r)return await this.RefreshToken(),await this.ExecuteGQL(e,t,!1);throw c.LogError("JWT_EXPIRED and refreshTokenIfNeeded is false"),a}else throw a;else throw c.LogError(JSON.stringify(n)),a}}async RefreshToken(){const e=I.Instance&&I.Instance._configData===this._configData;if(e&&I.Instance._refreshPromise)return I.Instance._refreshPromise;if(this._refreshPromise)return this._refreshPromise;console.log("[GraphQL] Starting token refresh..."),this._refreshPromise=this.performTokenRefresh(),e&&(I.Instance._refreshPromise=this._refreshPromise);try{await this._refreshPromise,console.log("[GraphQL] Token refresh completed successfully")}finally{this._refreshPromise=null,e&&I.Instance&&(I.Instance._refreshPromise=null)}}async performTokenRefresh(){if(this._configData.Data.RefreshTokenFunction)try{const e=await this._configData.Data.RefreshTokenFunction();if(e){this._configData.Token=e;const t=this.CreateNewGraphQLClient(this._configData.URL,this._configData.Token,this._sessionId,this._configData.MJAPIKey,this._configData.UserAPIKey);this._client=t,I.Instance&&I.Instance._configData===this._configData&&(I.Instance._client=t)}else{const t=new Error("Refresh token function returned null or undefined token");throw this.notifyAuthenticationError(t),t}}catch(e){const t=e instanceof Error?e:new Error(String(e));throw this.notifyAuthenticationError(t),e}else{const e=new Error("No refresh token function provided");throw this.notifyAuthenticationError(e),e}}notifyAuthenticationError(e){try{const t=this._configData?.OnAuthenticationError;t&&t(e)}catch(t){console.error("[GraphQLDataProvider] Error in OnAuthenticationError callback:",t)}}static async RefreshToken(){return I.Instance.RefreshToken()}static async ClearClientCache(e=new Set){const t=[];for(let r=0;r<localStorage.length;r++){const s=localStorage.key(r);s&&!e.has(s)&&t.push(s)}t.forEach(r=>localStorage.removeItem(r)),await new Promise(r=>{const s=indexedDB.deleteDatabase("MJ_Metadata");s.onsuccess=()=>r(),s.onerror=()=>r(),s.onblocked=()=>r()})}static async clearClientCache(e=new Set){return this.ClearClientCache(e)}CreateNewGraphQLClient(e,t,r,s,n){const a={"x-session-id":r};t&&(a.authorization="Bearer "+t),s&&(a["x-mj-api-key"]=s),n&&(a["x-api-key"]=n);const i=new u.GraphQLClient(e,{headers:a});for(const[o,y]of this._dynamicHeaders)i.setHeader(o,y);return i}userInfoString(){return this.infoString(new c.UserInfo(null,null))}userRoleInfoString(){return this.infoString(new c.UserRoleInfo(null))}infoString(e){let t="";const r=Object.keys(e);for(const s of r)s.startsWith("__mj_")?t+=s.replace("__mj_","_mj__")+`
|
|
630
632
|
`:s.startsWith("_")||(t+=s+`
|
|
631
|
-
`);return t}get LocalStorageProvider(){return this._localStorageProvider||(typeof indexedDB<"u"?this._localStorageProvider=new B:this._localStorageProvider=new c.InMemoryLocalStorageProvider),this._localStorageProvider}get Metadata(){return this}get SocketConnectivity$(){return this._socketStateSubject.asObservable()}get SocketConnectionState(){return this._socketStateSubject.value}ForceSocketReconnect(){this.disposeWSClient()}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._isDisposingSocketIntentionally=!1,this._wsClient=
|
|
633
|
+
`);return t}get LocalStorageProvider(){return this._localStorageProvider||(typeof indexedDB<"u"?this._localStorageProvider=new B:this._localStorageProvider=new c.InMemoryLocalStorageProvider),this._localStorageProvider}get Metadata(){return this}get SocketConnectivity$(){return this._socketStateSubject.asObservable()}get SocketConnectionState(){return this._socketStateSubject.value}ForceSocketReconnect(){this.disposeWSClient()}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._isDisposingSocketIntentionally=!1,this._wsClient=Z.createClient({url:this.ConfigData.WSURL,connectionParams:l(()=>({Authorization:"Bearer "+this.ConfigData.Token,...this.ConfigData.MJAPIKey?{"x-mj-api-key":this.ConfigData.MJAPIKey}:{},...this.ConfigData.UserAPIKey?{"x-mj-user-api-key":this.ConfigData.UserAPIKey}:{}}),"connectionParams"),keepAlive:3e4,retryAttempts:3,shouldRetry:l(()=>!0,"shouldRetry")}),this._wsClientCreatedAt=e,this._wsClient.on("connected",()=>{this._socketStateSubject.next("connected")}),this._wsClient.on("closed",t=>{if(this._isDisposingSocketIntentionally)return;this._socketStateSubject.next("disconnected"),t?.code===4403&&this._configData.Data.RefreshTokenFunction&&this.RefreshToken().catch(()=>{})}),this._subscriptionCleanupTimer||(this._subscriptionCleanupTimer=setInterval(()=>{this.cleanupStaleSubscriptions()},this.SUBSCRIPTION_CLEANUP_INTERVAL_MS))),this._wsClient}disposeWSClient(){if(this._wsClient){this._isDisposingSocketIntentionally=!0;try{this._wsClient.dispose()}catch(e){console.error("[GraphQLDataProvider] Error disposing WebSocket client:",e)}this._wsClient=null,this._wsClientCreatedAt=null,this._socketStateSubject.next("unknown")}}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(),this._taskGraphFrameStreams.forEach((e,t)=>{try{e.subject.complete(),e.subscription.unsubscribe()}catch(r){console.error(`[GraphQLDataProvider] Error cleaning up frame stream for ${t}:`,r)}}),this._taskGraphFrameStreams.clear()}cleanupStaleSubscriptions(){if(!this._isCleaningUp){this._isCleaningUp=!0;try{const e=Date.now(),t=this._pushStatusSubjects.size,r=Array.from(this._pushStatusSubjects.entries()),s=[];r.forEach(([n,a])=>{const i=e-a.lastRequestedAt,o=e-a.lastEmissionAt;a.activeSubscribers===0&&i>=this.SUBSCRIPTION_IDLE_TIMEOUT_MS&&o>=this.SUBSCRIPTION_IDLE_TIMEOUT_MS&&(console.log(`[GraphQLDataProvider] Marking session ${n} for cleanup: activeSubscribers=${a.activeSubscribers}, timeSinceRequested=${Math.round(i/1e3)}s, timeSinceEmission=${Math.round(o/1e3)}s`),s.push(n))}),s.forEach(n=>{const a=this._pushStatusSubjects.get(n);if(a)try{a.subject.complete(),a.subscription.unsubscribe(),this._pushStatusSubjects.delete(n),console.log(`[GraphQLDataProvider] Cleaned up stale subscription for session: ${n}`)}catch(i){console.error(`[GraphQLDataProvider] Error cleaning up subscription for ${n}:`,i)}}),s.length>0&&console.log(`[GraphQLDataProvider] Cleaned up ${s.length} stale subscription(s)`),this._pushStatusSubjects.size===0&&this._wsClient&&this._wsClientCreatedAt&&e-this._wsClientCreatedAt>this.WS_CLIENT_MAX_AGE_MS&&(console.log("[GraphQLDataProvider] Disposing of idle WebSocket client"),this.disposeWSClient())}finally{this._isCleaningUp=!1}}}Subscribe(e,t){return new $.Observable(r=>{const s=this.getOrCreateWSClient();this._activeSubscriptionCount++;const n=s.subscribe({query:e,variables:t},{next:l(a=>{r.next(a.data)},"next"),error:l(async a=>{const i=a;if(i?.extensions?.code==="JWT_EXPIRED"||i?.message?.includes("token has expired")||i?.message?.includes("JWT_EXPIRED")){console.log("[GraphQLDataProvider] WebSocket JWT token expired, refreshing and reconnecting...");try{await this.RefreshToken(),this.disposeWSClient(),r.complete()}catch(y){console.error("[GraphQLDataProvider] Failed to refresh token for WebSocket:",y),r.error(y)}}else r.error(a)},"error"),complete:l(()=>{r.complete()},"complete")});return()=>{this._activeSubscriptionCount--,n()}})}subscribe(e,t){return this.Subscribe(e,t)}PushStatusUpdates(e=null){e||(e=this.sessionId);const t=Date.now(),r=this._pushStatusSubjects.get(e);if(r)return r.lastRequestedAt=t,new $.Observable(o=>{r.activeSubscribers++;const y=r.subject.subscribe(o);return()=>{const d=this._pushStatusSubjects.get(e);d&&d.activeSubscribers>0&&d.activeSubscribers--,y.unsubscribe()}});const s=u.gql`subscription StatusUpdates($sessionId: String!) {
|
|
632
634
|
statusUpdates(sessionId: $sessionId) {
|
|
633
635
|
date
|
|
634
636
|
message
|
|
@@ -663,7 +665,7 @@ ${e.stackFrames}`:this.stack}}function j(g){return g instanceof x?g:new x(G(g))}
|
|
|
663
665
|
progressPercent
|
|
664
666
|
date
|
|
665
667
|
}
|
|
666
|
-
}`,n=new $.Subject,a=new $.Subscription;a.add(this.
|
|
668
|
+
}`,n=new $.Subject,a=new $.Subscription;a.add(this.Subscribe(s,{parentTaskId:e}).subscribe({next:l(o=>{o?.taskGraphFrames&&n.next(o.taskGraphFrames)},"next"),error:l(o=>{n.error(o),this._taskGraphFrameStreams.delete(e)},"error"),complete:l(()=>{n.complete(),this._taskGraphFrameStreams.delete(e)},"complete")}));const i={subject:n,subscription:a,activeSubscribers:0};return this._taskGraphFrameStreams.set(e,i),t(i)}DisposeWebSocketResources(){this._subscriptionCleanupTimer&&(clearInterval(this._subscriptionCleanupTimer),this._subscriptionCleanupTimer=null),this.UnsubscribeFromCacheInvalidation(),this.completeAllSubjects(),this._activeSubscriptionCount=0,this.disposeWSClient()}disposeWebSocketResources(){return this.DisposeWebSocketResources()}ClientToolRequests(e){return this.Subscribe(`
|
|
667
669
|
subscription ClientToolRequest($sessionID: String!) {
|
|
668
670
|
ClientToolRequest(sessionID: $sessionID) {
|
|
669
671
|
AgentRunID
|
|
@@ -685,7 +687,7 @@ ${e.stackFrames}`:this.stack}}function j(g){return g instanceof x?g:new x(G(g))}
|
|
|
685
687
|
OriginSessionID
|
|
686
688
|
RecordData
|
|
687
689
|
}
|
|
688
|
-
}`,t=this.
|
|
690
|
+
}`,t=this.Subscribe(e);this._cacheInvalidationSubscription=t.subscribe({next:l(r=>{const s=r?.cacheInvalidation;if(!s)return;if(s.OriginSessionID&&s.OriginSessionID===this.sessionId){I.VerboseCacheInvalidationLogging&&console.debug(`[GraphQLDataProvider] Skipping self-originated cache invalidation for "${s.EntityName}" (action: ${s.Action})`);return}I.VerboseCacheInvalidationLogging&&console.debug(`[GraphQLDataProvider] Cache invalidation received: ${s.Action} for "${s.EntityName}" from server ${s.SourceServerID?.substring(0,8)||"unknown"}`);const n={type:"remote-invalidate",entityName:s.EntityName,baseEntity:null,provider:this,payload:{primaryKeyValues:s.PrimaryKeyValues,action:s.Action,sourceServerId:s.SourceServerID,timestamp:s.Timestamp,recordData:s.RecordData}};v.MJGlobal.Instance.RaiseEvent({event:v.MJEventType.ComponentEvent,eventCode:c.BaseEntity.BaseEventCode,args:n,component:this})},"next"),error:l(r=>{console.error("[GraphQLDataProvider] Cache invalidation subscription error:",r),this._cacheInvalidationSubscription=null},"error"),complete:l(()=>{console.log("[GraphQLDataProvider] Cache invalidation subscription completed, will re-establish on next WebSocket creation"),this._cacheInvalidationSubscription=null},"complete")})}static{this.ClientMemberRefreshWindowMinMs=15e3}static{this.ClientMemberRefreshWindowJitterMs=3e4}get MetadataMemberRefreshDelayMs(){return I.ClientMemberRefreshWindowMinMs+Math.random()*I.ClientMemberRefreshWindowJitterMs}get MetadataMemberRefreshRearmsOnNewEvents(){return!1}async RefreshAfterMetadataMemberChange(){return this.RefreshIfNeeded(void 0,!0)}UnsubscribeFromCacheInvalidation(){this.CancelPendingMetadataMemberRefresh(),this._cacheInvalidationSubscription&&(this._cacheInvalidationSubscription.unsubscribe(),this._cacheInvalidationSubscription=null)}async FindISAChildEntity(e,t,r){if(!e.IsParentType)return null;const s=`query FindISAChildEntity($EntityName: String!, $RecordID: String!) {
|
|
689
691
|
FindISAChildEntity(EntityName: $EntityName, RecordID: $RecordID) {
|
|
690
692
|
Success
|
|
691
693
|
ChildEntityName
|
|
@@ -697,7 +699,7 @@ ${e.stackFrames}`:this.stack}}function j(g){return g instanceof x?g:new x(G(g))}
|
|
|
697
699
|
ChildEntityNames
|
|
698
700
|
ErrorMessage
|
|
699
701
|
}
|
|
700
|
-
}`;try{const n=await this.ExecuteGQL(s,{EntityName:e.Name,RecordID:t});return n?.FindISAChildEntities?.Success&&n.FindISAChildEntities.ChildEntityNames?n.FindISAChildEntities.ChildEntityNames.map(a=>({ChildEntityName:a})):[]}catch(n){return c.LogError(`FindISAChildEntities failed for ${e.Name}: ${n}`),[]}}}async function
|
|
702
|
+
}`;try{const n=await this.ExecuteGQL(s,{EntityName:e.Name,RecordID:t});return n?.FindISAChildEntities?.Success&&n.FindISAChildEntities.ChildEntityNames?n.FindISAChildEntities.ChildEntityNames.map(a=>({ChildEntityName:a})):[]}catch(n){return c.LogError(`FindISAChildEntities failed for ${e.Name}: ${n}`),[]}}}async function J(g){const e=new I;return c.SetProvider(e),await e.Config(g),await e.preValidateAndRefresh(),v.MJGlobal.Instance.RaiseEvent({event:v.MJEventType.LoggedIn,eventCode:null,component:this,args:null}),await c.StartupManager.Instance.Startup(),e}l(J,"SetupGraphQLClient");async function pe(g){return J(g)}l(pe,"setupGraphQLClient");class he{static{l(this,"SyncRolesAndUsersResult")}}class Ie{static{l(this,"RoleInput")}}class fe{static{l(this,"UserInput")}}class Ee{static{l(this,"RolesAndUsersInput")}}var W=(g=>(g.Create="Create",g.Update="Update",g.CreateOrUpdate="CreateOrUpdate",g.Delete="Delete",g.DeleteWithFilter="DeleteWithFilter",g))(W||{});class Re{static{l(this,"ActionItemInput")}}class De{static{l(this,"SyncDataResult")}constructor(){this.Results=[]}}class ve{static{l(this,"ActionItemOutput")}}const H=`Success
|
|
701
703
|
ErrorMessage
|
|
702
704
|
Query {
|
|
703
705
|
ID
|
|
@@ -752,7 +754,7 @@ ${e.stackFrames}`:this.stack}}function j(g){return g instanceof x?g:new x(G(g))}
|
|
|
752
754
|
QueryID
|
|
753
755
|
RoleID
|
|
754
756
|
Role
|
|
755
|
-
}`;class
|
|
757
|
+
}`;class Ce{static{l(this,"GraphQLSystemUserClient")}get Client(){return this._client}constructor(e,t,r,s){const n={"x-session-id":r};this._sessionId=r,t&&(n.authorization="Bearer "+t),s&&(n["x-mj-api-key"]=s),this._client=new u.GraphQLClient(e,{headers:n})}resolvePlatformSQL(e){if(e!=null)return c.IsPlatformSQL(e)?e.default:e}async GetData(e,t){try{const s=await this.Client.request(`query GetData($input: GetDataInputType!) {
|
|
756
758
|
GetData(input: $input) {
|
|
757
759
|
Success
|
|
758
760
|
ErrorMessages
|
|
@@ -904,11 +906,11 @@ ${e.stackFrames}`:this.stack}}function j(g){return g instanceof x?g:new x(G(g))}
|
|
|
904
906
|
}
|
|
905
907
|
}`,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),e.Enrichment!==void 0&&(r.Enrichment=e.Enrichment);const s=await this.Client.request(t,r);return s&&s.GetQueryDataByNameSystemUser?{...s.GetQueryDataByNameSystemUser,Results:s.GetQueryDataByNameSystemUser.Results?v.SafeJSONParse(s.GetQueryDataByNameSystemUser.Results):null}:{QueryID:"",QueryName:e.QueryName,Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:"Query execution failed"}}catch(t){return c.LogError(`GraphQLSystemUserClient::GetQueryDataByNameSystemUser - Error executing query - ${t}`),{QueryID:"",QueryName:e.QueryName,Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:t.toString()}}}async CreateQuery(e){try{const t=`mutation CreateQueryExtended($input: CreateQuerySystemUserInput!) {
|
|
906
908
|
CreateQueryExtended(input: $input) {
|
|
907
|
-
${
|
|
909
|
+
${H}
|
|
908
910
|
}
|
|
909
911
|
}`,r=await this.Client.request(t,{input:e});return r&&r.CreateQueryExtended?r.CreateQueryExtended:{Success:!1,ErrorMessage:"Failed to create query"}}catch(t){return c.LogError(`GraphQLSystemUserClient::CreateQuery - Error creating query - ${t}`),{Success:!1,ErrorMessage:t.toString()}}}async UpdateQuery(e){try{const t=`mutation UpdateQueryExtended($input: UpdateQuerySystemUserInput!) {
|
|
910
912
|
UpdateQueryExtended(input: $input) {
|
|
911
|
-
${
|
|
913
|
+
${H}
|
|
912
914
|
}
|
|
913
915
|
}`,r=await this.Client.request(t,{input:e});return r&&r.UpdateQueryExtended?r.UpdateQueryExtended:{Success:!1,ErrorMessage:"Failed to update query"}}catch(t){return c.LogError(`GraphQLSystemUserClient::UpdateQuery - Error updating query - ${t}`),{Success:!1,ErrorMessage:t.toString()}}}async DeleteQuery(e,t){try{if(!e||e.trim()==="")return c.LogError("GraphQLSystemUserClient::DeleteQuery - Invalid query ID: ID cannot be null or empty"),{Success:!1,ErrorMessage:"Invalid query ID: ID cannot be null or empty"};const r=`mutation DeleteQueryExtended($ID: String!, $options: DeleteOptionsInput) {
|
|
914
916
|
DeleteQueryExtended(ID: $ID, options: $options) {
|
|
@@ -1155,7 +1157,7 @@ ${e.stackFrames}`:this.stack}}function j(g){return g instanceof x?g:new x(G(g))}
|
|
|
1155
1157
|
ErrorMessage
|
|
1156
1158
|
}
|
|
1157
1159
|
}
|
|
1158
|
-
`,s={EntityNames:e,UserEmail:t},n=await this.Client.request(r,s);if(n?.CheckEntityPermissionsSystemUser){const a=n.CheckEntityPermissionsSystemUser;return{Success:a.Success,Results:(a.Results||[]).map(i=>({EntityName:i.EntityName,CanRead:i.CanRead})),ErrorMessage:a.ErrorMessage}}return{Success:!1,Results:[],ErrorMessage:"Invalid response from server"}}catch(r){return c.LogError(`GraphQLSystemUserClient::CheckEntityPermissionsSystemUser - Error checking entity permissions - ${r}`),{Success:!1,Results:[],ErrorMessage:r instanceof Error?r.message:String(r)}}}}class
|
|
1160
|
+
`,s={EntityNames:e,UserEmail:t},n=await this.Client.request(r,s);if(n?.CheckEntityPermissionsSystemUser){const a=n.CheckEntityPermissionsSystemUser;return{Success:a.Success,Results:(a.Results||[]).map(i=>({EntityName:i.EntityName,CanRead:i.CanRead})),ErrorMessage:a.ErrorMessage}}return{Success:!1,Results:[],ErrorMessage:"Invalid response from server"}}catch(r){return c.LogError(`GraphQLSystemUserClient::CheckEntityPermissionsSystemUser - Error checking entity permissions - ${r}`),{Success:!1,Results:[],ErrorMessage:r instanceof Error?r.message:String(r)}}}}class we{static{l(this,"GetDataOutput")}}class $e{static{l(this,"SimpleRemoteEntityOutput")}}class Pe{static{l(this,"SimpleRemoteEntity")}}class be{static{l(this,"SimpleRemoteEntityField")}}class Le{static{l(this,"GraphQLActionClient")}constructor(e){this._dataProvider=e}async RunAction(e,t,r=!1){try{const s=this.serializeActionParameters(t),n=this.createActionVariables(e,s,r),a=await this.executeActionMutation(n);return this.processActionResult(a,t)}catch(s){return this.handleActionError(s,t)}}serializeActionParameters(e){if(e)return e.map(t=>{let r=t.Value;return r!=null&&typeof r=="object"&&(r=JSON.stringify(r)),{...t,Value:r}})}createActionVariables(e,t,r=!1){return{input:{ActionID:e,Params:t,SkipActionLog:r}}}async executeActionMutation(e){const t=u.gql`
|
|
1159
1161
|
mutation RunAction($input: RunActionInput!) {
|
|
1160
1162
|
RunAction(input: $input) {
|
|
1161
1163
|
Success
|
|
@@ -1172,14 +1174,14 @@ ${e.stackFrames}`:this.stack}}function j(g){return g instanceof x?g:new x(G(g))}
|
|
|
1172
1174
|
ResultData
|
|
1173
1175
|
}
|
|
1174
1176
|
}
|
|
1175
|
-
`;return await this._dataProvider.ExecuteGQL(t,{input:e})}processEntityActionResult(e){if(!e?.RunEntityAction)throw new Error("Invalid response from server");let t={};try{e.RunEntityAction.ResultData&&(t=JSON.parse(e.RunEntityAction.ResultData))}catch(r){c.LogError(`Failed to parse entity action result data: ${r}`)}return{Success:e.RunEntityAction.Success,Message:e.RunEntityAction.Message,RunParams:null,LogEntry:null,...t}}handleEntityActionError(e){const t=e;return c.LogError(`Error running entity action: ${t}`),{Success:!1,Message:`Error: ${t.message}`,RunParams:null,LogEntry:null}}}class
|
|
1177
|
+
`;return await this._dataProvider.ExecuteGQL(t,{input:e})}processEntityActionResult(e){if(!e?.RunEntityAction)throw new Error("Invalid response from server");let t={};try{e.RunEntityAction.ResultData&&(t=JSON.parse(e.RunEntityAction.ResultData))}catch(r){c.LogError(`Failed to parse entity action result data: ${r}`)}return{Success:e.RunEntityAction.Success,Message:e.RunEntityAction.Message,RunParams:null,LogEntry:null,...t}}handleEntityActionError(e){const t=e;return c.LogError(`Error running entity action: ${t}`),{Success:!1,Message:`Error: ${t.message}`,RunParams:null,LogEntry:null}}}class Ne{static{l(this,"GraphQLListsClient")}constructor(e){this.dataProvider=e}async PreviewListDelta(e){const t=u.gql`
|
|
1176
1178
|
query PreviewListDelta($input: ComputeDeltaInput!) {
|
|
1177
1179
|
PreviewListDelta(input: $input) {
|
|
1178
1180
|
...ListDeltaFields
|
|
1179
1181
|
}
|
|
1180
1182
|
}
|
|
1181
|
-
${
|
|
1182
|
-
`,r=await this.dataProvider.ExecuteGQL(t,{input:{Target:e.Target,Source:U(e.Source),Mode:e.Mode}});return
|
|
1183
|
+
${z}
|
|
1184
|
+
`,r=await this.dataProvider.ExecuteGQL(t,{input:{Target:e.Target,Source:U(e.Source),Mode:e.Mode}});return X(r?.PreviewListDelta)}async ApplyListDelta(e){const t=u.gql`
|
|
1183
1185
|
mutation ApplyListDelta($input: ApplyDeltaInput!) {
|
|
1184
1186
|
ApplyListDelta(input: $input) {
|
|
1185
1187
|
...ApplyResultFields
|
|
@@ -1213,15 +1215,15 @@ ${e.stackFrames}`:this.stack}}function j(g){return g instanceof x?g:new x(G(g))}
|
|
|
1213
1215
|
...ListDeltaFields
|
|
1214
1216
|
}
|
|
1215
1217
|
}
|
|
1216
|
-
${
|
|
1217
|
-
`,r=await this.dataProvider.ExecuteGQL(t,{input:{Op:e.Op,Inputs:e.Inputs.map(U),Target:e.Target?U(e.Target):null}});return
|
|
1218
|
+
${z}
|
|
1219
|
+
`,r=await this.dataProvider.ExecuteGQL(t,{input:{Op:e.Op,Inputs:e.Inputs.map(U),Target:e.Target?U(e.Target):null}});return X(r?.ComposeLists)}async Share(e){const t=u.gql`
|
|
1218
1220
|
mutation ShareList($input: ShareListInput!) {
|
|
1219
1221
|
ShareList(input: $input) {
|
|
1220
1222
|
...ShareResultFields
|
|
1221
1223
|
}
|
|
1222
1224
|
}
|
|
1223
1225
|
${q}
|
|
1224
|
-
`,r=await this.dataProvider.ExecuteGQL(t,{input:{ListID:e.ListID,Target:
|
|
1226
|
+
`,r=await this.dataProvider.ExecuteGQL(t,{input:{ListID:e.ListID,Target:Me(e.Target),PermissionLevel:e.PermissionLevel}});return Q(r?.ShareList)}async Unshare(e){const t=u.gql`
|
|
1225
1227
|
mutation UnshareList($permissionId: String!) {
|
|
1226
1228
|
UnshareList(permissionId: $permissionId) {
|
|
1227
1229
|
...ShareResultFields
|
|
@@ -1272,7 +1274,7 @@ ${e.stackFrames}`:this.stack}}function j(g){return g instanceof x?g:new x(G(g))}
|
|
|
1272
1274
|
CreatedAt
|
|
1273
1275
|
}
|
|
1274
1276
|
}
|
|
1275
|
-
`;return((await this.dataProvider.ExecuteGQL(t,{listId:e}))?.ListSharesForList??[]).map(
|
|
1277
|
+
`;return((await this.dataProvider.ExecuteGQL(t,{listId:e}))?.ListSharesForList??[]).map(Ae)}async ListsSharedWithMe(){const e=u.gql`
|
|
1276
1278
|
query ListsSharedWithMe {
|
|
1277
1279
|
ListsSharedWithMe {
|
|
1278
1280
|
ListID
|
|
@@ -1282,7 +1284,7 @@ ${e.stackFrames}`:this.stack}}function j(g){return g instanceof x?g:new x(G(g))}
|
|
|
1282
1284
|
SharedAt
|
|
1283
1285
|
}
|
|
1284
1286
|
}
|
|
1285
|
-
`;return((await this.dataProvider.ExecuteGQL(e,{}))?.ListsSharedWithMe??[]).map(s=>({ListID:s.ListID,ListName:s.ListName,PermissionLevel:s.PermissionLevel,SharedByUserID:s.SharedByUserID??null,SharedAt:new Date(s.SharedAt)}))}}const
|
|
1287
|
+
`;return((await this.dataProvider.ExecuteGQL(e,{}))?.ListsSharedWithMe??[]).map(s=>({ListID:s.ListID,ListName:s.ListName,PermissionLevel:s.PermissionLevel,SharedByUserID:s.SharedByUserID??null,SharedAt:new Date(s.SharedAt)}))}}const z=u.gql`
|
|
1286
1288
|
fragment ListDeltaFields on ListDeltaType {
|
|
1287
1289
|
TargetListId
|
|
1288
1290
|
EntityName
|
|
@@ -1322,7 +1324,7 @@ ${e.stackFrames}`:this.stack}}function j(g){return g instanceof x?g:new x(G(g))}
|
|
|
1322
1324
|
Message
|
|
1323
1325
|
PermissionID
|
|
1324
1326
|
}
|
|
1325
|
-
`;function
|
|
1327
|
+
`;function Me(g){return g.kind==="user"?{Kind:"user",UserID:g.userId}:{Kind:"role",RoleID:g.roleId}}l(Me,"serializeShareTarget");function Q(g){if(!g||typeof g!="object")throw new Error("GraphQLListsClient: empty/invalid ShareResult response");const e=g;return{Success:e.Success,ResultCode:e.ResultCode,Message:e.Message,PermissionID:e.PermissionID??void 0}}l(Q,"parseShareResult");function Ae(g){const e=g,t=e.Target.Kind==="user"?{kind:"user",userId:e.Target.UserID}:{kind:"role",roleId:e.Target.RoleID};return{PermissionID:e.PermissionID,ListID:e.ListID,Target:t,PermissionLevel:e.PermissionLevel,Status:e.Status,SharedByUserID:e.SharedByUserID??null,CreatedAt:new Date(e.CreatedAt)}}l(Ae,"parseShareSummary");function U(g){switch(g.kind){case"list":return{Kind:"list",ListID:g.listId};case"view":return{Kind:"view",ViewID:g.viewId};case"adhoc":return{Kind:"adhoc",EntityName:g.entityName,ExtraFilter:g.extraFilter}}}l(U,"serializeListSource");function X(g){if(!g||typeof g!="object")throw new Error("GraphQLListsClient: empty/invalid ListDelta response from server");const e=g;return{TargetListId:e.TargetListId,EntityName:e.EntityName,ToAdd:e.ToAdd,ToRemove:e.ToRemove,Unchanged:e.Unchanged,Counts:e.Counts,Warnings:e.Warnings.map(Te),DeltaToken:e.DeltaToken}}l(X,"parseListDelta");function Te(g){let e;if(g.DetailsJSON)try{e=JSON.parse(g.DetailsJSON)}catch(t){c.LogError(`GraphQLListsClient: failed to parse warning details JSON: ${t}`)}return{Code:g.Code,Message:g.Message,Details:e}}l(Te,"parseWarning");function T(g){if(!g||typeof g!="object")throw new Error("GraphQLListsClient: empty/invalid ApplyResult response from server");const e=g;return{Success:e.Success,ResultCode:e.ResultCode,Message:e.Message,CreatedListId:e.CreatedListId??void 0,TargetListId:e.TargetListId??void 0,Counts:e.AddedCount!=null||e.RemovedCount!=null||e.FailedCount!=null?{Added:e.AddedCount??0,Removed:e.RemovedCount??0,Failed:e.FailedCount??0}:void 0,Errors:e.Errors??void 0}}l(T,"parseApplyResult");class xe{static{l(this,"GraphQLEncryptionClient")}constructor(e){this._dataProvider=e}async CreateAPIKey(e){try{const t=this.createAPIKeyVariables(e),r=await this.executeCreateAPIKeyMutation(t);return this.processCreateAPIKeyResult(r)}catch(t){return this.handleCreateAPIKeyError(t)}}createAPIKeyVariables(e){return{input:{Label:e.Label,Description:e.Description,ExpiresAt:e.ExpiresAt?.toISOString(),ScopeIDs:e.ScopeIDs}}}async executeCreateAPIKeyMutation(e){const t=u.gql`
|
|
1326
1328
|
mutation CreateAPIKey($input: CreateAPIKeyInput!) {
|
|
1327
1329
|
CreateAPIKey(input: $input) {
|
|
1328
1330
|
Success
|
|
@@ -1338,7 +1340,7 @@ ${e.stackFrames}`:this.stack}}function j(g){return g instanceof x?g:new x(G(g))}
|
|
|
1338
1340
|
Error
|
|
1339
1341
|
}
|
|
1340
1342
|
}
|
|
1341
|
-
`,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 c.LogError(`Error revoking API key: ${r.message}`),{Success:!1,Error:`Error: ${r.message}`}}}}class
|
|
1343
|
+
`,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 c.LogError(`Error revoking API key: ${r.message}`),{Success:!1,Error:`Error: ${r.message}`}}}}class Fe{static{l(this,"GraphQLClusterClient")}constructor(e){this._dataProvider=e}async RunClusterAnalysis(e){try{const t=u.gql`
|
|
1342
1344
|
mutation RunClusterAnalysis($input: RunClusterAnalysisInput!) {
|
|
1343
1345
|
RunClusterAnalysis(input: $input) {
|
|
1344
1346
|
Success
|
|
@@ -1354,7 +1356,7 @@ ${e.stackFrames}`:this.stack}}function j(g){return g instanceof x?g:new x(G(g))}
|
|
|
1354
1356
|
AnalysisID
|
|
1355
1357
|
}
|
|
1356
1358
|
}
|
|
1357
|
-
`,s=(await this._dataProvider.ExecuteGQL(t,{input:e}))?.RunClusterAnalysis;if(!s)throw new Error("Invalid response from server");return this.parseResult(s)}catch(t){const r=t;return c.LogError("GraphQLClusterClient.RunClusterAnalysis failed",void 0,r),this.errorResult(r.message||"Unknown error occurred")}}parseResult(e){const t=this.parseMetrics(e),r=v.SafeJSONParse(e.ClustersJSON)??[],s=v.SafeJSONParse(e.PointsJSON)??[];return{Success:e.Success,ErrorMessage:e.ErrorMessage,Metrics:t,Clusters:r,Points:s,AnalysisID:e.AnalysisID}}parseMetrics(e){const t=v.SafeJSONParse(e.MetricsJSON);return t||{SilhouetteScore:e.SilhouetteScore,ClusterCount:e.ClusterCount,ComputationTimeMs:e.ComputationTimeMs,RecordCount:e.RecordCount,OutlierCount:e.OutlierCount}}errorResult(e){return{Success:!1,ErrorMessage:e,Metrics:{SilhouetteScore:0,ClusterCount:0,ComputationTimeMs:0,RecordCount:0,OutlierCount:0},Clusters:[],Points:[]}}}class
|
|
1359
|
+
`,s=(await this._dataProvider.ExecuteGQL(t,{input:e}))?.RunClusterAnalysis;if(!s)throw new Error("Invalid response from server");return this.parseResult(s)}catch(t){const r=t;return c.LogError("GraphQLClusterClient.RunClusterAnalysis failed",void 0,r),this.errorResult(r.message||"Unknown error occurred")}}parseResult(e){const t=this.parseMetrics(e),r=v.SafeJSONParse(e.ClustersJSON)??[],s=v.SafeJSONParse(e.PointsJSON)??[];return{Success:e.Success,ErrorMessage:e.ErrorMessage,Metrics:t,Clusters:r,Points:s,AnalysisID:e.AnalysisID}}parseMetrics(e){const t=v.SafeJSONParse(e.MetricsJSON);return t||{SilhouetteScore:e.SilhouetteScore,ClusterCount:e.ClusterCount,ComputationTimeMs:e.ComputationTimeMs,RecordCount:e.RecordCount,OutlierCount:e.OutlierCount}}errorResult(e){return{Success:!1,ErrorMessage:e,Metrics:{SilhouetteScore:0,ClusterCount:0,ComputationTimeMs:0,RecordCount:0,OutlierCount:0},Clusters:[],Points:[]}}}class Ge{static{l(this,"GraphQLLiveKitClient")}constructor(e){this._dataProvider=e}async MintClientToken(e){try{const t=u.gql`
|
|
1358
1360
|
mutation MintLiveKitClientToken($input: MintLiveKitClientTokenInput!) {
|
|
1359
1361
|
MintLiveKitClientToken(input: $input) {
|
|
1360
1362
|
Success
|
|
@@ -1419,7 +1421,7 @@ ${e.stackFrames}`:this.stack}}function j(g){return g instanceof x?g:new x(G(g))}
|
|
|
1419
1421
|
RecordingFileID
|
|
1420
1422
|
}
|
|
1421
1423
|
}
|
|
1422
|
-
`,{egressID:e},"StopLiveKitRecording",e)}async runRecordingMutation(e,t,r,s){try{const a=(await this._dataProvider.ExecuteGQL(e,t))?.[r];if(!a)throw new Error("Invalid response from server");return a}catch(n){const a=n;return c.LogError(`GraphQLLiveKitClient.${r} failed`,void 0,a),{Success:!1,ErrorMessage:a.message||"Unknown error",EgressID:s,Status:""}}}}class
|
|
1424
|
+
`,{egressID:e},"StopLiveKitRecording",e)}async runRecordingMutation(e,t,r,s){try{const a=(await this._dataProvider.ExecuteGQL(e,t))?.[r];if(!a)throw new Error("Invalid response from server");return a}catch(n){const a=n;return c.LogError(`GraphQLLiveKitClient.${r} failed`,void 0,a),{Success:!1,ErrorMessage:a.message||"Unknown error",EgressID:s,Status:""}}}}class qe{static{l(this,"GraphQLClassifyClient")}constructor(e){this._dataProvider=e}async GenerateSeedTaxonomy(e){try{const t=u.gql`
|
|
1423
1425
|
mutation GenerateSeedTaxonomy($sourceID: String!, $sampleSize: Int!) {
|
|
1424
1426
|
GenerateSeedTaxonomy(sourceID: $sourceID, sampleSize: $sampleSize) {
|
|
1425
1427
|
Success
|
|
@@ -1429,7 +1431,7 @@ ${e.stackFrames}`:this.stack}}function j(g){return g instanceof x?g:new x(G(g))}
|
|
|
1429
1431
|
NodesJSON
|
|
1430
1432
|
}
|
|
1431
1433
|
}
|
|
1432
|
-
`,s=(await this._dataProvider.ExecuteGQL(t,{sourceID:e.SourceID,sampleSize:e.SampleSize}))?.GenerateSeedTaxonomy;if(!s)throw new Error("Invalid response from server");return this.parseResult(s)}catch(t){const r=t;return c.LogError("GraphQLClassifyClient.GenerateSeedTaxonomy failed",void 0,r),this.errorResult(r.message||"Unknown error occurred")}}parseResult(e){const t=v.SafeJSONParse(e.NodesJSON)??[];return{Success:e.Success,ErrorMessage:e.ErrorMessage,Method:e.Method,SampleSize:e.SampleSize,Nodes:t}}errorResult(e){return{Success:!1,ErrorMessage:e,SampleSize:0,Nodes:[]}}}class
|
|
1434
|
+
`,s=(await this._dataProvider.ExecuteGQL(t,{sourceID:e.SourceID,sampleSize:e.SampleSize}))?.GenerateSeedTaxonomy;if(!s)throw new Error("Invalid response from server");return this.parseResult(s)}catch(t){const r=t;return c.LogError("GraphQLClassifyClient.GenerateSeedTaxonomy failed",void 0,r),this.errorResult(r.message||"Unknown error occurred")}}parseResult(e){const t=v.SafeJSONParse(e.NodesJSON)??[];return{Success:e.Success,ErrorMessage:e.ErrorMessage,Method:e.Method,SampleSize:e.SampleSize,Nodes:t}}errorResult(e){return{Success:!1,ErrorMessage:e,SampleSize:0,Nodes:[]}}}class Qe{static{l(this,"GraphQLTestingClient")}constructor(e){this._dataProvider=e}async RunTest(e){try{const t=this.buildRunTestMutation(),r=this.buildRunTestVariables(e),s={};return await w.Execute({dataProvider:this._dataProvider,mutation:t,variables:r,mutationFieldName:"RunTest",operationLabel:"RunTest",validateAck:l(n=>n?.success===!0,"validateAck"),isCompletionEvent:l(n=>this.isTestCompletionEvent(n,e.testId),"isCompletionEvent"),extractResult:l(n=>this.extractTestResult(n),"extractResult"),onMessage:l(n=>{this.captureTestRunId(n,s),e.onProgress&&this.forwardTestProgress(n,e.onProgress)},"onMessage"),onStall:l(()=>this.reconcileTestRun(s),"onStall"),createErrorResult:l(n=>({success:!1,errorMessage:n,result:null}),"createErrorResult")})}catch(t){return this.handleError(t,"RunTest")}}async RunTestSuite(e){try{const t=this.buildRunTestSuiteMutation(),r=this.buildRunTestSuiteVariables(e);return await w.Execute({dataProvider:this._dataProvider,mutation:t,variables:r,mutationFieldName:"RunTestSuite",operationLabel:"RunTestSuite",validateAck:l(s=>s?.success===!0,"validateAck"),isCompletionEvent:l(s=>this.isSuiteCompletionEvent(s,e.suiteId),"isCompletionEvent"),extractResult:l(s=>this.extractSuiteResult(s),"extractResult"),onMessage:e.onProgress?s=>this.forwardTestProgress(s,e.onProgress):void 0,createErrorResult:l(s=>({success:!1,errorMessage:s,result:null}),"createErrorResult")})}catch(t){return this.handleError(t,"RunTestSuite")}}async IsTestRunning(e){try{const t=u.gql`
|
|
1433
1435
|
query IsTestRunning($testId: String!) {
|
|
1434
1436
|
IsTestRunning(testId: $testId)
|
|
1435
1437
|
}
|
|
@@ -1487,7 +1489,7 @@ ${e.stackFrames}`:this.stack}}function j(g){return g instanceof x?g:new x(G(g))}
|
|
|
1487
1489
|
result
|
|
1488
1490
|
}
|
|
1489
1491
|
}
|
|
1490
|
-
`}buildRunTestVariables(e){const t=e.tags&&e.tags.length>0?JSON.stringify(e.tags):void 0,r=e.variables?JSON.stringify(e.variables):void 0;return{testId:e.testId,verbose:e.verbose,environment:e.environment,tags:t,variables:r,fireAndForget:!0}}buildRunTestSuiteVariables(e){const t=e.tags&&e.tags.length>0?JSON.stringify(e.tags):void 0,r=e.variables?JSON.stringify(e.variables):void 0,s=e.selectedTestIds&&e.selectedTestIds.length>0?JSON.stringify(e.selectedTestIds):void 0;return{suiteId:e.suiteId,verbose:e.verbose,environment:e.environment,parallel:e.parallel,tags:t,variables:r,selectedTestIds:s,sequenceStart:e.sequenceStart,sequenceEnd:e.sequenceEnd,fireAndForget:!0}}isTestCompletionEvent(e,t){const r=e.data;return e.resolver==="RunTestResolver"&&e.type==="FireAndForgetComplete"&&r?.type==="complete"&&r?.testId===t}isSuiteCompletionEvent(e,t){const r=e.data;return e.resolver==="RunTestResolver"&&e.type==="FireAndForgetSuiteComplete"&&r?.type==="complete"&&r?.suiteId===t}captureTestRunId(e,t){if(e.resolver!=="RunTestResolver")return;const s=e.data?.testRunId;s&&(t.id=s)}async reconcileTestRun(e){if(!e.id)return"continue";const t=await this._dataProvider.RunView({EntityName:"MJ: Test Runs",ExtraFilter:`ID='${e.id}'`,ResultType:"entity_object",BypassCache:!0}),r=t.Success?t.Results?.[0]:void 0;if(!r||r.Status==="Pending"||r.Status==="Running")return"continue";const s=r.Status==="Passed";return{resolve:{success:s,errorMessage:s?void 0:`Test run ${r.Status}`,result:null}}}extractTestResult(e){const t=e.data;return{success:t.success,errorMessage:t.errorMessage,executionTimeMs:t.executionTimeMs,result:t.result?v.SafeJSONParse(t.result):null}}extractSuiteResult(e){const t=e.data;return{success:t.success,errorMessage:t.errorMessage,executionTimeMs:t.executionTimeMs,result:t.result?v.SafeJSONParse(t.result):null}}forwardTestProgress(e,t){if(e.resolver==="RunTestResolver"&&e.type==="TestExecutionProgress"&&e.status==="ok"){const s=e.data?.progress;s&&t(s)}}handleError(e,t){const r=e.message;return c.LogError(`${t} failed: ${r}`),{success:!1,errorMessage:r.includes("Failed to fetch")||r.includes("NetworkError")?"Lost connection to the server. The test may still be running. Please refresh to check the latest status.":r,result:null}}}class
|
|
1492
|
+
`}buildRunTestVariables(e){const t=e.tags&&e.tags.length>0?JSON.stringify(e.tags):void 0,r=e.variables?JSON.stringify(e.variables):void 0;return{testId:e.testId,verbose:e.verbose,environment:e.environment,tags:t,variables:r,fireAndForget:!0}}buildRunTestSuiteVariables(e){const t=e.tags&&e.tags.length>0?JSON.stringify(e.tags):void 0,r=e.variables?JSON.stringify(e.variables):void 0,s=e.selectedTestIds&&e.selectedTestIds.length>0?JSON.stringify(e.selectedTestIds):void 0;return{suiteId:e.suiteId,verbose:e.verbose,environment:e.environment,parallel:e.parallel,tags:t,variables:r,selectedTestIds:s,sequenceStart:e.sequenceStart,sequenceEnd:e.sequenceEnd,fireAndForget:!0}}isTestCompletionEvent(e,t){const r=e.data;return e.resolver==="RunTestResolver"&&e.type==="FireAndForgetComplete"&&r?.type==="complete"&&r?.testId===t}isSuiteCompletionEvent(e,t){const r=e.data;return e.resolver==="RunTestResolver"&&e.type==="FireAndForgetSuiteComplete"&&r?.type==="complete"&&r?.suiteId===t}captureTestRunId(e,t){if(e.resolver!=="RunTestResolver")return;const s=e.data?.testRunId;s&&(t.id=s)}async reconcileTestRun(e){if(!e.id)return"continue";const t=await this._dataProvider.RunView({EntityName:"MJ: Test Runs",ExtraFilter:`ID='${e.id}'`,ResultType:"entity_object",BypassCache:!0}),r=t.Success?t.Results?.[0]:void 0;if(!r||r.Status==="Pending"||r.Status==="Running")return"continue";const s=r.Status==="Passed";return{resolve:{success:s,errorMessage:s?void 0:`Test run ${r.Status}`,result:null}}}extractTestResult(e){const t=e.data;return{success:t.success,errorMessage:t.errorMessage,executionTimeMs:t.executionTimeMs,result:t.result?v.SafeJSONParse(t.result):null}}extractSuiteResult(e){const t=e.data;return{success:t.success,errorMessage:t.errorMessage,executionTimeMs:t.executionTimeMs,result:t.result?v.SafeJSONParse(t.result):null}}forwardTestProgress(e,t){if(e.resolver==="RunTestResolver"&&e.type==="TestExecutionProgress"&&e.status==="ok"){const s=e.data?.progress;s&&t(s)}}handleError(e,t){const r=e.message;return c.LogError(`${t} failed: ${r}`),{success:!1,errorMessage:r.includes("Failed to fetch")||r.includes("NetworkError")?"Lost connection to the server. The test may still be running. Please refresh to check the latest status.":r,result:null}}}class Ue{static{l(this,"GraphQLComponentRegistryClient")}constructor(e){this._dataProvider=e}async GetRegistryComponent(e){try{const t=u.gql`
|
|
1491
1493
|
query GetRegistryComponent(
|
|
1492
1494
|
$registryName: String!,
|
|
1493
1495
|
$namespace: String!,
|
|
@@ -1571,7 +1573,7 @@ ${e.stackFrames}`:this.stack}}function j(g){return g instanceof x?g:new x(G(g))}
|
|
|
1571
1573
|
error
|
|
1572
1574
|
}
|
|
1573
1575
|
}
|
|
1574
|
-
`,r=await this._dataProvider.ExecuteGQL(t,{feedback:e});return r&&r.SendComponentFeedback?r.SendComponentFeedback:{success:!1,error:"No response from server"}}catch(t){return c.LogError(t),{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}}class
|
|
1576
|
+
`,r=await this._dataProvider.ExecuteGQL(t,{feedback:e});return r&&r.SendComponentFeedback?r.SendComponentFeedback:{success:!1,error:"No response from server"}}catch(t){return c.LogError(t),{success:!1,error:t instanceof Error?t.message:"Unknown error"}}}}class _e{static{l(this,"GraphQLVersionHistoryClient")}constructor(e){this._dataProvider=e}async CreateLabel(e){let t;try{e.OnProgress&&(t=this._dataProvider.PushStatusUpdates(this._dataProvider.sessionId).subscribe(a=>{try{const i=JSON.parse(a);i.resolver==="VersionHistoryResolver"&&i.type==="CreateLabelProgress"&&i.status==="ok"&&i.data&&e.OnProgress(i.data)}catch{}}));const r=u.gql`
|
|
1575
1577
|
mutation CreateVersionLabel($input: CreateVersionLabelInput!, $sessionId: String) {
|
|
1576
1578
|
CreateVersionLabel(input: $input, sessionId: $sessionId) {
|
|
1577
1579
|
Success
|
|
@@ -1587,7 +1589,7 @@ ${e.stackFrames}`:this.stack}}function j(g){return g instanceof x?g:new x(G(g))}
|
|
|
1587
1589
|
}
|
|
1588
1590
|
}
|
|
1589
1591
|
}
|
|
1590
|
-
`,s={input:this.buildInput(e),sessionId:this._dataProvider.sessionId},n=await this._dataProvider.ExecuteGQL(r,s);return this.processResult(n)}catch(r){const s=r instanceof Error?r.message:String(r);return c.LogError(`GraphQLVersionHistoryClient.CreateLabel error: ${s}`),{Success:!1,Error:s}}finally{t&&t.unsubscribe()}}buildInput(e){const t={Name:e.Name};return e.Description!=null&&(t.Description=e.Description),e.Scope!=null&&(t.Scope=e.Scope),e.EntityName!=null&&(t.EntityName=e.EntityName),e.ParentID!=null&&(t.ParentID=e.ParentID),e.ExternalSystemID!=null&&(t.ExternalSystemID=e.ExternalSystemID),e.IncludeDependencies!=null&&(t.IncludeDependencies=e.IncludeDependencies),e.MaxDepth!=null&&(t.MaxDepth=e.MaxDepth),e.ExcludeEntities!=null&&(t.ExcludeEntities=e.ExcludeEntities),e.RecordKeys&&e.RecordKeys.length>0&&(t.RecordKeys=e.RecordKeys.map(r=>({Key:r.Key,Value:r.Value}))),t}processResult(e){const t=e?.CreateVersionLabel;if(!t)return{Success:!1,Error:"Invalid response from server."};const r=Array.isArray(t.CaptureErrors)?t.CaptureErrors.map(s=>({EntityName:s.EntityName??"",RecordID:s.RecordID??"",ErrorMessage:s.ErrorMessage??""})):void 0;return{Success:t.Success,LabelID:t.LabelID,LabelName:t.LabelName,ItemsCaptured:t.ItemsCaptured,SyntheticSnapshotsCreated:t.SyntheticSnapshotsCreated,Error:t.Error,CaptureErrors:r}}}class
|
|
1592
|
+
`,s={input:this.buildInput(e),sessionId:this._dataProvider.sessionId},n=await this._dataProvider.ExecuteGQL(r,s);return this.processResult(n)}catch(r){const s=r instanceof Error?r.message:String(r);return c.LogError(`GraphQLVersionHistoryClient.CreateLabel error: ${s}`),{Success:!1,Error:s}}finally{t&&t.unsubscribe()}}buildInput(e){const t={Name:e.Name};return e.Description!=null&&(t.Description=e.Description),e.Scope!=null&&(t.Scope=e.Scope),e.EntityName!=null&&(t.EntityName=e.EntityName),e.ParentID!=null&&(t.ParentID=e.ParentID),e.ExternalSystemID!=null&&(t.ExternalSystemID=e.ExternalSystemID),e.IncludeDependencies!=null&&(t.IncludeDependencies=e.IncludeDependencies),e.MaxDepth!=null&&(t.MaxDepth=e.MaxDepth),e.ExcludeEntities!=null&&(t.ExcludeEntities=e.ExcludeEntities),e.RecordKeys&&e.RecordKeys.length>0&&(t.RecordKeys=e.RecordKeys.map(r=>({Key:r.Key,Value:r.Value}))),t}processResult(e){const t=e?.CreateVersionLabel;if(!t)return{Success:!1,Error:"Invalid response from server."};const r=Array.isArray(t.CaptureErrors)?t.CaptureErrors.map(s=>({EntityName:s.EntityName??"",RecordID:s.RecordID??"",ErrorMessage:s.ErrorMessage??""})):void 0;return{Success:t.Success,LabelID:t.LabelID,LabelName:t.LabelName,ItemsCaptured:t.ItemsCaptured,SyntheticSnapshotsCreated:t.SyntheticSnapshotsCreated,Error:t.Error,CaptureErrors:r}}}class Ve{static{l(this,"GraphQLFileStorageClient")}constructor(e){this._dataProvider=e}async ListObjects(e,t="",r){try{const s=u.gql`
|
|
1591
1593
|
query ListStorageObjects($input: ListStorageObjectsInput!) {
|
|
1592
1594
|
ListStorageObjects(input: $input) {
|
|
1593
1595
|
objects {
|
|
@@ -1688,7 +1690,7 @@ ${e.stackFrames}`:this.stack}}function j(g){return g instanceof x?g:new x(G(g))}
|
|
|
1688
1690
|
failedAccounts
|
|
1689
1691
|
}
|
|
1690
1692
|
}
|
|
1691
|
-
`,n={input:{AccountIDs:e,Query:t,MaxResultsPerAccount:r?.maxResultsPerAccount,FileTypes:r?.fileTypes,SearchContent:r?.searchContent}},a=await this._dataProvider.ExecuteGQL(s,n);if(!a?.SearchAcrossAccounts)throw new Error("Invalid response from server");const i=a.SearchAcrossAccounts;return{accountResults:i.accountResults.map(o=>({accountId:o.accountID,accountName:o.accountName,success:o.success,errorMessage:o.errorMessage,results:o.results.map(y=>({path:y.path,name:y.name,size:y.size,contentType:y.contentType,lastModified:new Date(y.lastModified),relevance:y.relevance,excerpt:y.excerpt,matchInFilename:y.matchInFilename,objectId:y.objectId})),totalMatches:o.totalMatches,hasMore:o.hasMore,nextPageToken:o.nextPageToken})),totalResultsReturned:i.totalResultsReturned,successfulAccounts:i.successfulAccounts,failedAccounts:i.failedAccounts}}catch(s){const n=s;return c.LogError(`Error searching across accounts: ${n}`),{accountResults:[],totalResultsReturned:0,successfulAccounts:0,failedAccounts:e.length}}}}class
|
|
1693
|
+
`,n={input:{AccountIDs:e,Query:t,MaxResultsPerAccount:r?.maxResultsPerAccount,FileTypes:r?.fileTypes,SearchContent:r?.searchContent}},a=await this._dataProvider.ExecuteGQL(s,n);if(!a?.SearchAcrossAccounts)throw new Error("Invalid response from server");const i=a.SearchAcrossAccounts;return{accountResults:i.accountResults.map(o=>({accountId:o.accountID,accountName:o.accountName,success:o.success,errorMessage:o.errorMessage,results:o.results.map(y=>({path:y.path,name:y.name,size:y.size,contentType:y.contentType,lastModified:new Date(y.lastModified),relevance:y.relevance,excerpt:y.excerpt,matchInFilename:y.matchInFilename,objectId:y.objectId})),totalMatches:o.totalMatches,hasMore:o.hasMore,nextPageToken:o.nextPageToken})),totalResultsReturned:i.totalResultsReturned,successfulAccounts:i.successfulAccounts,failedAccounts:i.failedAccounts}}catch(s){const n=s;return c.LogError(`Error searching across accounts: ${n}`),{accountResults:[],totalResultsReturned:0,successfulAccounts:0,failedAccounts:e.length}}}}class Oe{static{l(this,"GraphQLSearchClient")}constructor(e){this._dataProvider=e}async ExecuteSearch(e){try{const t=this.buildSearchKnowledgeMutation(),r=this.prepareSearchVariables(e),s=await this._dataProvider.ExecuteGQL(t,r);return this.processSearchKnowledgeResult(s)}catch(t){return this.handleSearchError(t)}}async PreviewSearch(e,t){try{const r=this.buildPreviewSearchMutation(),s=this.preparePreviewVariables(e,t),n=await this._dataProvider.ExecuteGQL(r,s);return this.processPreviewSearchResult(n)}catch(r){return this.handleSearchError(r)}}buildSearchKnowledgeMutation(){return u.gql`
|
|
1692
1694
|
mutation SearchKnowledge($query: String!, $maxResults: Float, $filters: SearchFiltersInput, $minScore: Float, $scopeIDs: [ID!], $searchContext: SearchContextInput) {
|
|
1693
1695
|
SearchKnowledge(query: $query, maxResults: $maxResults, filters: $filters, minScore: $minScore, scopeIDs: $scopeIDs, searchContext: $searchContext) {
|
|
1694
1696
|
Success
|
|
@@ -1829,7 +1831,7 @@ ${e.stackFrames}`:this.stack}}function j(g){return g instanceof x?g:new x(G(g))}
|
|
|
1829
1831
|
ElapsedMs
|
|
1830
1832
|
ErrorMessage
|
|
1831
1833
|
}
|
|
1832
|
-
}`;n=this._dataProvider.subscribe(o,{streamID:i.StreamID}).subscribe({next:l(y=>{const d=y?.SearchStreamEvents;d&&(t.next(d),d.Phase==="final"?(t.complete(),n?.unsubscribe()):d.Phase==="error"&&(t.error(new Error(d.ErrorMessage??"Stream error")),n?.unsubscribe()))},"next"),error:l(y=>t.error(y),"error")})}catch(a){t.error(a)}})(),()=>{n?.unsubscribe()}})}prepareFilters(e){const t={};return e.EntityNames!==void 0&&e.EntityNames.length>0&&(t.EntityNames=e.EntityNames),e.SourceTypes!==void 0&&e.SourceTypes.length>0&&(t.SourceTypes=e.SourceTypes),e.Tags!==void 0&&e.Tags.length>0&&(t.Tags=e.Tags),t}preparePreviewVariables(e,t){const r={query:e};return t!==void 0&&(r.maxResults=t),r}processSearchKnowledgeResult(e){if(!e?.SearchKnowledge)throw new Error("Invalid response from server");const t=e.SearchKnowledge;return this.mapSearchResponse(t)}processPreviewSearchResult(e){if(!e?.PreviewSearch)throw new Error("Invalid response from server");const t=e.PreviewSearch;return this.mapSearchResponse(t)}mapSearchResponse(e){return{Success:e.Success,Results:(e.Results||[]).map(t=>this.mapResultItem(t)),TotalCount:e.TotalCount,ElapsedMs:e.ElapsedMs,SourceCounts:this.mapSourceCounts(e.SourceCounts),Providers:(e.Providers||[]).map(t=>({ID:t.ID,Name:t.Name,DisplayName:t.DisplayName,Icon:t.Icon,SourceType:t.SourceType,Priority:t.Priority})),ErrorMessage:e.ErrorMessage}}mapResultItem(e){return{ID:e.ID,EntityName:e.EntityName,EntityDisplayName:e.EntityDisplayName,RecordID:e.RecordID,SourceType:e.SourceType,ResultType:e.ResultType,Title:e.Title,Snippet:e.Snippet,Score:e.Score,ScoreBreakdown:this.mapScoreBreakdown(e.ScoreBreakdown),Tags:e.Tags||[],EntityIcon:e.EntityIcon,RecordName:e.RecordName,MatchedAt:e.MatchedAt,RawMetadata:e.RawMetadata,ProviderId:e.ProviderId,ProviderLabel:e.ProviderLabel,ProviderIcon:e.ProviderIcon}}mapScoreBreakdown(e){if(!e)return{};const t={};return e.Vector!==void 0&&(t.Vector=e.Vector),e.FullText!==void 0&&(t.FullText=e.FullText),e.Entity!==void 0&&(t.Entity=e.Entity),e.Storage!==void 0&&(t.Storage=e.Storage),t}mapSourceCounts(e){return e?{Vector:e.Vector??0,FullText:e.FullText??0,Entity:e.Entity??0,Storage:e.Storage??0}:{Vector:0,FullText:0,Entity:0,Storage:0}}handleSearchError(e){const t=e;return c.LogError(`Error executing search: ${t}`),{Success:!1,Results:[],TotalCount:0,ElapsedMs:0,SourceCounts:{Vector:0,FullText:0,Entity:0,Storage:0},Providers:[],ErrorMessage:`Error: ${t.message}`}}}class
|
|
1834
|
+
}`;n=this._dataProvider.subscribe(o,{streamID:i.StreamID}).subscribe({next:l(y=>{const d=y?.SearchStreamEvents;d&&(t.next(d),d.Phase==="final"?(t.complete(),n?.unsubscribe()):d.Phase==="error"&&(t.error(new Error(d.ErrorMessage??"Stream error")),n?.unsubscribe()))},"next"),error:l(y=>t.error(y),"error")})}catch(a){t.error(a)}})(),()=>{n?.unsubscribe()}})}prepareFilters(e){const t={};return e.EntityNames!==void 0&&e.EntityNames.length>0&&(t.EntityNames=e.EntityNames),e.SourceTypes!==void 0&&e.SourceTypes.length>0&&(t.SourceTypes=e.SourceTypes),e.Tags!==void 0&&e.Tags.length>0&&(t.Tags=e.Tags),t}preparePreviewVariables(e,t){const r={query:e};return t!==void 0&&(r.maxResults=t),r}processSearchKnowledgeResult(e){if(!e?.SearchKnowledge)throw new Error("Invalid response from server");const t=e.SearchKnowledge;return this.mapSearchResponse(t)}processPreviewSearchResult(e){if(!e?.PreviewSearch)throw new Error("Invalid response from server");const t=e.PreviewSearch;return this.mapSearchResponse(t)}mapSearchResponse(e){return{Success:e.Success,Results:(e.Results||[]).map(t=>this.mapResultItem(t)),TotalCount:e.TotalCount,ElapsedMs:e.ElapsedMs,SourceCounts:this.mapSourceCounts(e.SourceCounts),Providers:(e.Providers||[]).map(t=>({ID:t.ID,Name:t.Name,DisplayName:t.DisplayName,Icon:t.Icon,SourceType:t.SourceType,Priority:t.Priority})),ErrorMessage:e.ErrorMessage}}mapResultItem(e){return{ID:e.ID,EntityName:e.EntityName,EntityDisplayName:e.EntityDisplayName,RecordID:e.RecordID,SourceType:e.SourceType,ResultType:e.ResultType,Title:e.Title,Snippet:e.Snippet,Score:e.Score,ScoreBreakdown:this.mapScoreBreakdown(e.ScoreBreakdown),Tags:e.Tags||[],EntityIcon:e.EntityIcon,RecordName:e.RecordName,MatchedAt:e.MatchedAt,RawMetadata:e.RawMetadata,ProviderId:e.ProviderId,ProviderLabel:e.ProviderLabel,ProviderIcon:e.ProviderIcon}}mapScoreBreakdown(e){if(!e)return{};const t={};return e.Vector!==void 0&&(t.Vector=e.Vector),e.FullText!==void 0&&(t.FullText=e.FullText),e.Entity!==void 0&&(t.Entity=e.Entity),e.Storage!==void 0&&(t.Storage=e.Storage),t}mapSourceCounts(e){return e?{Vector:e.Vector??0,FullText:e.FullText??0,Entity:e.Entity??0,Storage:e.Storage??0}:{Vector:0,FullText:0,Entity:0,Storage:0}}handleSearchError(e){const t=e;return c.LogError(`Error executing search: ${t}`),{Success:!1,Results:[],TotalCount:0,ElapsedMs:0,SourceCounts:{Vector:0,FullText:0,Entity:0,Storage:0},Providers:[],ErrorMessage:`Error: ${t.message}`}}}class ke{static{l(this,"GraphQLIntegrationClient")}constructor(e){this._dataProvider=e}async DiscoverObjects(e){try{const t=u.gql`
|
|
1833
1835
|
query IntegrationDiscoverObjects($companyIntegrationID: String!) {
|
|
1834
1836
|
IntegrationDiscoverObjects(companyIntegrationID: $companyIntegrationID) {
|
|
1835
1837
|
Success
|
|
@@ -2022,5 +2024,5 @@ ${e.stackFrames}`:this.stack}}function j(g){return g instanceof x?g:new x(G(g))}
|
|
|
2022
2024
|
IntegrationGetConnectorCapabilities(companyIntegrationID: $companyIntegrationID) {
|
|
2023
2025
|
Success Message SupportsGet SupportsCreate SupportsUpdate SupportsDelete SupportsSearch
|
|
2024
2026
|
}
|
|
2025
|
-
}`;return(await this._dataProvider.ExecuteGQL(t,{companyIntegrationID:e}))?.IntegrationGetConnectorCapabilities??{Success:!1,Message:"No response"}}catch(t){return{Success:!1,Message:t.message}}}handleError(e,t){const r=e;return c.LogError(`Error in integration discovery: ${r}`),{Success:!1,Message:`Error: ${r.message}`,Data:t}}}Object.defineProperty(exports,"gql",{enumerable:!0,get:l(function(){return u.gql},"get")}),exports.ActionItemInput=
|
|
2027
|
+
}`;return(await this._dataProvider.ExecuteGQL(t,{companyIntegrationID:e}))?.IntegrationGetConnectorCapabilities??{Success:!1,Message:"No response"}}catch(t){return{Success:!1,Message:t.message}}}handleError(e,t){const r=e;return c.LogError(`Error in integration discovery: ${r}`),{Success:!1,Message:`Error: ${r.message}`,Data:t}}}Object.defineProperty(exports,"gql",{enumerable:!0,get:l(function(){return u.gql},"get")}),exports.ActionItemInput=Re,exports.ActionItemOutput=ve,exports.BrowserIndexedDBStorageProvider=B,exports.BrowserStorageProviderBase=k,exports.FieldMapper=L,exports.FireAndForgetHelper=w,exports.GetDataOutput=we,exports.GraphQLAIClient=O,exports.GraphQLActionClient=Le,exports.GraphQLClassifyClient=qe,exports.GraphQLClusterClient=Fe,exports.GraphQLComponentRegistryClient=Ue,exports.GraphQLDataProvider=I,exports.GraphQLEncryptionClient=xe,exports.GraphQLFileStorageClient=Ve,exports.GraphQLIntegrationClient=ke,exports.GraphQLListsClient=Ne,exports.GraphQLLiveKitClient=Ge,exports.GraphQLProviderConfigData=Se,exports.GraphQLSearchClient=Oe,exports.GraphQLSystemUserClient=Ce,exports.GraphQLTestingClient=Qe,exports.GraphQLTransactionGroup=V,exports.GraphQLVersionHistoryClient=_e,exports.PACKAGE_VERSION=M,exports.RoleInput=Ie,exports.RolesAndUsersInput=Ee,exports.SafeGraphQLError=x,exports.SanitizeGraphQLError=G,exports.SetupGraphQLClient=J,exports.SimpleRemoteEntity=Pe,exports.SimpleRemoteEntityField=be,exports.SimpleRemoteEntityOutput=$e,exports.SyncDataAction=W,exports.SyncDataResult=De,exports.SyncRolesAndUsersResult=he,exports.ToSafeGraphQLError=j,exports.UserInput=fe,exports.setupGraphQLClient=pe;
|
|
2026
2028
|
//# sourceMappingURL=index.cjs.map
|