@memberjunction/graphql-dataprovider 6.1.0-edge.6 → 6.1.0-edge.7
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 +36 -34
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +56 -1
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +56 -1
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +70 -68
- package/dist/index.mjs.map +1 -1
- package/package.json +8 -8
package/dist/index.cjs
CHANGED
|
@@ -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],l=D.SafeJSONParse(y),
|
|
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],l=D.SafeJSONParse(y),m=this.PendingTransactions[o];i.push(new c.TransactionResult(m,l,a&&l!==null))}return i}else throw new Error("Failed to execute transaction group")}}const te=720*1e3,re=6;class w{static{d(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??te,n=e.maxStallReconciles??re;let a,i=!1,o=0;const{promise:y,resolve:l,reject:m}=w.createCompletionPromise(),R=d(h=>{i||(i=!0,I.clear(),h())},"finish"),S=d(h=>R(()=>l(h)),"settleResolve"),E=d(h=>R(()=>m(h)),"settleReject"),p=d(async()=>{if(i)return;if(!e.onStall){E(new Error(w.timeoutMessage(e.timeoutErrorMessage,s)));return}let h;try{c.LogStatus(`[FireAndForget:${t}] Idle window elapsed, reconciling against server run record`),h=await e.onStall()}catch(v){E(v);return}i||(h==="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.`)):I.reset():"resolve"in h?(c.LogStatus(`[FireAndForget:${t}] Reconciliation recovered a completed run`),S(h.resolve)):E(h.reject))},"onStall"),I=w.createIdleTimer(s,()=>{p()});try{I.reset(),a=w.subscribeToPubSub(e,{onActivity:d(()=>{o=0,I.reset()},"onActivity"),onCompletion:d(v=>S(v),"onCompletion"),onStreamEnd:d(()=>{p()},"onStreamEnd")});const h=await w.executeMutation(e);if(!e.validateAck(h)){I.clear();const v=h?.errorMessage??"Server rejected the request";return c.LogError(`[FireAndForget:${t}] Server rejected: ${v}`),e.createErrorResult(v)}return c.LogStatus(`[FireAndForget:${t}] Server accepted, waiting for completion via WebSocket`),await y}catch(h){const v=h;throw c.LogError(`[FireAndForget:${t}] Error: ${v.message}`),h}finally{I.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:d(()=>{r&&clearTimeout(r),r=setTimeout(t,e)},"reset"),clear:d(()=>{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:d(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:d(()=>t.onStreamEnd(),"error"),complete:d(()=>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{d(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,
|
|
@@ -307,7 +307,7 @@
|
|
|
307
307
|
}
|
|
308
308
|
}
|
|
309
309
|
}
|
|
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
|
|
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.1.0-edge.7",P="default";class k{static{d(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 se="MJ_Metadata",ne=0;function ae(){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+ne}catch(g){return c.LogErrorEx({error:g,message:"Failed to derive IDB version from PACKAGE_VERSION; using fallback 99999"}),99999}}d(ae,"computeIdbVersion");const oe=ae(),K=["mj:default","mj:Metadata","mj:RunViewCache","mj:RunQueryCache","mj:DatasetCache"];class B extends k{static{d(this,"BrowserIndexedDBStorageProvider")}constructor(){super(),this._dbReady=!1,this.dbPromise=ee.openDB(se,oe,{upgrade:d((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:d((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(R=>this.getStoreKey(R,t)),o=s.transaction(n,"readonly"),y=o.objectStore(n),l=i.map(R=>y.get(R)),m=await Promise.all(l);await o.done;for(let R=0;R<a.length;R++){const S=m[R];r.set(a[R],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{d(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}
|
|
311
311
|
${e.stackFrames}`:this.stack}}function j(g){return g instanceof x?g:new x(G(g))}d(j,"ToSafeGraphQLError");const ie=3,ce=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 ${ue(F(g[0],e+1))})`;if(typeof g=="object"){if(e>=ie)return"object(\u2026)";const t=Object.keys(g);if(t.length>ce)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}d(F,"describeShape");function ue(g){return typeof g=="string"?g:"object"}d(ue,"typeOf");function le(g){const e=g.indexOf(`
|
|
312
312
|
at `);return e===-1?"":g.slice(e+1)}d(le,"stripStackHeader");function de(g,e){const t=g?.[0]?.message;return typeof t=="string"&&t.length>0?t:`GraphQL Error (Code: ${String(e??"unknown")})`}d(de,"deriveMessage");function ge(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}})}d(ge,"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=ge(t.response?.errors),n=s?.[0]?.extensions?.code;return{name:typeof t.name=="string"?t.name:"Error",message:de(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"?le(t.stack):void 0,variables:e?t.request?.variables:"[REDACTED]",variableShape:t.request?.variables===void 0?void 0:F(t.request.variables)}}d(G,"SanitizeGraphQLError");const b=new L,ye=u.gql`subscription RemoteOperationProgress($channelId: ID!) {
|
|
313
313
|
RemoteOperationProgress(channelId: $channelId) {
|
|
@@ -341,13 +341,13 @@ ${e.stackFrames}`:this.stack}}function j(g){return g instanceof x?g:new x(G(g))}
|
|
|
341
341
|
${this.QueryReturnFieldList}
|
|
342
342
|
}
|
|
343
343
|
}
|
|
344
|
-
`,
|
|
344
|
+
`,m={QueryID:e};t!==void 0&&(m.CategoryID=t),r!==void 0&&(m.CategoryPath=r),n!==void 0&&(m.Parameters=n),a!==void 0&&(m.MaxRows=a),i!==void 0&&(m.StartRow=i),o!==void 0&&(m.Enrichment=o),y!==void 0&&(m.DataSource=y);const R=await this.ExecuteGQL(l,m);if(R&&R.GetQueryData)return this.TransformQueryPayload(R.GetQueryData)}async RunQueryByName(e,t,r,s,n,a,i,o,y){const l=u.gql`
|
|
345
345
|
query GetQueryDataByNameQuery($QueryName: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int, $Enrichment: JSONObject, $DataSource: String) {
|
|
346
346
|
GetQueryDataByName(QueryName: $QueryName, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow, Enrichment: $Enrichment, DataSource: $DataSource) {
|
|
347
347
|
${this.QueryReturnFieldList}
|
|
348
348
|
}
|
|
349
349
|
}
|
|
350
|
-
`,
|
|
350
|
+
`,m={QueryName:e};t!==void 0&&(m.CategoryID=t),r!==void 0&&(m.CategoryPath=r),n!==void 0&&(m.Parameters=n),a!==void 0&&(m.MaxRows=a),i!==void 0&&(m.StartRow=i),o!==void 0&&(m.Enrichment=o),y!==void 0&&(m.DataSource=y);const R=await this.ExecuteGQL(l,m);if(R&&R.GetQueryDataByName)return this.TransformQueryPayload(R.GetQueryDataByName)}get QueryReturnFieldList(){return`
|
|
351
351
|
Success
|
|
352
352
|
QueryID
|
|
353
353
|
QueryName
|
|
@@ -372,18 +372,18 @@ ${e.stackFrames}`:this.stack}}function j(g){return g instanceof x?g:new x(G(g))}
|
|
|
372
372
|
}
|
|
373
373
|
}
|
|
374
374
|
}
|
|
375
|
-
`,a=(await this.ExecuteGQL(s,{input:r}))?.RunQueriesWithCacheCheck;if(!a)return{success:!1,results:[],errorMessage:"No response from server"};const i=a.results.map(o=>{if((o.status==="stale"||o.status==="no_validation")&&o.Results){const y=JSON.parse(o.Results);return{queryIndex:o.queryIndex,queryId:o.queryId,status:o.status,results:y,maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}}return{queryIndex:o.queryIndex,queryId:o.queryId,status:o.status,maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}});return{success:a.success,results:i,errorMessage:a.errorMessage}}catch(r){return c.LogError(`Error in RunQueriesWithCacheCheck: ${r}`),{success:!1,results:[],errorMessage:r instanceof Error?r.message:String(r)}}}async InternalRunView(e,t){try{let r="",s="";if(e){const n={};let a,i;if(e.ViewEntity)i=e.ViewEntity,a=i.Entity;else{const{entityName:
|
|
375
|
+
`,a=(await this.ExecuteGQL(s,{input:r}))?.RunQueriesWithCacheCheck;if(!a)return{success:!1,results:[],errorMessage:"No response from server"};const i=a.results.map(o=>{if((o.status==="stale"||o.status==="no_validation")&&o.Results){const y=JSON.parse(o.Results);return{queryIndex:o.queryIndex,queryId:o.queryId,status:o.status,results:y,maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}}return{queryIndex:o.queryIndex,queryId:o.queryId,status:o.status,maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}});return{success:a.success,results:i,errorMessage:a.errorMessage}}catch(r){return c.LogError(`Error in RunQueriesWithCacheCheck: ${r}`),{success:!1,results:[],errorMessage:r instanceof Error?r.message:String(r)}}}async InternalRunView(e,t){try{let r="",s="";if(e){const n={};let a,i;if(e.ViewEntity)i=e.ViewEntity,a=i.Entity;else{const{entityName:p,v:I}=await this.getEntityNameAndUserView(e,t);i=I,a=p}const o=this.EntityByName(a);if(!o)throw new Error(`Entity ${a} not found in metadata`);let y=!1;const l=c.getGraphQLTypeNameBase(o);e.ViewID?(r=`Run${l}ViewByID`,s="RunViewByIDInput",n.ViewID=e.ViewID):e.ViewName?(r=`Run${l}ViewByName`,s="RunViewByNameInput",n.ViewName=e.ViewName):(y=!0,r=`Run${l}DynamicView`,s="RunDynamicViewInput",n.EntityName=e.EntityName),n.ExtraFilter=e.ExtraFilter?e.ExtraFilter:"",n.OrderBy=e.OrderBy?e.OrderBy:"",n.UserSearchString=e.UserSearchString?e.UserSearchString:"",n.Fields=e.Fields,n.IgnoreMaxRows=e.IgnoreMaxRows?e.IgnoreMaxRows:!1,e.MaxRows!==void 0&&(n.MaxRows=e.MaxRows),e.StartRow!==void 0&&(n.StartRow=e.StartRow),n.ForceAuditLog=e.ForceAuditLog?e.ForceAuditLog:!1,n.ResultType=e.ResultType?e.ResultType:"simple",e.AuditLogDescription&&e.AuditLogDescription.length>0&&(n.AuditLogDescription=e.AuditLogDescription),e.BypassCache!==void 0&&(n.BypassCache=e.BypassCache),e.DataSource!==void 0&&(n.DataSource=e.DataSource),y||(n.ExcludeUserViewRunID=e.ExcludeUserViewRunID?e.ExcludeUserViewRunID:"",n.ExcludeDataFromAllPriorViewRuns=e.ExcludeDataFromAllPriorViewRuns?e.ExcludeDataFromAllPriorViewRuns:!1,n.OverrideExcludeFilter=e.OverrideExcludeFilter?e.OverrideExcludeFilter:"",n.SaveViewResults=e.SaveViewResults?e.SaveViewResults:!1),e.Aggregates&&e.Aggregates.length>0&&(n.Aggregates=e.Aggregates.map(p=>({expression:p.expression,alias:p.alias})));const m=this.getViewRunTimeFieldList(o,i,e,y),R=e.Aggregates&&e.Aggregates.length>0?`
|
|
376
376
|
AggregateResults {
|
|
377
377
|
alias
|
|
378
378
|
expression
|
|
379
379
|
value
|
|
380
380
|
error
|
|
381
381
|
}
|
|
382
|
-
AggregateExecutionTime`:"",
|
|
382
|
+
AggregateExecutionTime`:"",S=u.gql`
|
|
383
383
|
query RunViewQuery ($input: ${s}!) {
|
|
384
384
|
${r}(input: $input) {
|
|
385
385
|
Results {
|
|
386
|
-
${
|
|
386
|
+
${m.join(`
|
|
387
387
|
`)}
|
|
388
388
|
}
|
|
389
389
|
UserViewRunID
|
|
@@ -391,9 +391,9 @@ ${e.stackFrames}`:this.stack}}function j(g){return g instanceof x?g:new x(G(g))}
|
|
|
391
391
|
TotalRowCount
|
|
392
392
|
ExecutionTime
|
|
393
393
|
Success
|
|
394
|
-
ErrorMessage${
|
|
394
|
+
ErrorMessage${R}
|
|
395
395
|
}
|
|
396
|
-
}`;n.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Sending RunView with aggregates:",{entityName:a,queryName:r,aggregateCount:n.Aggregates.length,aggregates:n.Aggregates});const
|
|
396
|
+
}`;n.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Sending RunView with aggregates:",{entityName:a,queryName:r,aggregateCount:n.Aggregates.length,aggregates:n.Aggregates});const E=await this.ExecuteGQL(S,{input:n});if(E&&E[r]){const p=E[r].AggregateResults;n.Aggregates?.length>0&&console.log("[GraphQLDataProvider] Received aggregate results:",{entityName:a,aggregateResultCount:p?.length||0,aggregateResults:p,aggregateExecutionTime:E[r].AggregateExecutionTime});const I=E[r].Results;if(I&&I.length>0){const v=o.Fields.filter(C=>C.CodeName!==C.Name&&C.CodeName!==void 0);I.forEach(C=>{this.ConvertBackToMJFields(C),v.forEach(N=>{C[N.Name]=C[N.CodeName]})})}return E[r]}}else throw"No parameters passed to RunView";return null}catch(r){throw c.LogError(r),r}}async InternalRunViews(e,t){try{let r=[],s=[],n=[];for(const l of e){let m="",R="";const S={};let E=null,p=null;if(l.ViewEntity)p=l.ViewEntity,E=p.Get("Entity");else{const{entityName:C,v:N}=await this.getEntityNameAndUserView(l,t);p=N,E=C}const I=this.EntityByName(E);if(!I)throw new Error(`Entity ${E} not found in metadata`);s.push(I);let h=!1;const v=c.getGraphQLTypeNameBase(I);l.ViewID?(m=`Run${v}ViewByID`,R="RunViewByIDInput",S.ViewID=l.ViewID):l.ViewName?(m=`Run${v}ViewByName`,R="RunViewByNameInput",S.ViewName=l.ViewName):(h=!0,m=`Run${v}DynamicView`,R="RunDynamicViewInput",S.EntityName=l.EntityName),S.ExtraFilter=l.ExtraFilter||"",S.OrderBy=l.OrderBy||"",S.UserSearchString=l.UserSearchString||"",S.Fields=l.Fields,S.IgnoreMaxRows=l.IgnoreMaxRows||!1,l.MaxRows!==void 0&&(S.MaxRows=l.MaxRows),l.StartRow!==void 0&&(S.StartRow=l.StartRow),l.AfterKey&&(S.AfterKey={KeyValuePairs:l.AfterKey.KeyValuePairs}),S.ForceAuditLog=l.ForceAuditLog||!1,S.ResultType=l.ResultType||"simple",l.AuditLogDescription&&l.AuditLogDescription.length>0&&(S.AuditLogDescription=l.AuditLogDescription),l.BypassCache!==void 0&&(S.BypassCache=l.BypassCache),l.DataSource!==void 0&&(S.DataSource=l.DataSource),h||(S.ExcludeUserViewRunID=l.ExcludeUserViewRunID||"",S.ExcludeDataFromAllPriorViewRuns=l.ExcludeDataFromAllPriorViewRuns||!1,S.OverrideExcludeFilter=l.OverrideExcludeFilter||"",S.SaveViewResults=l.SaveViewResults||!1),l.Aggregates&&l.Aggregates.length>0&&(S.Aggregates=l.Aggregates.map(C=>({expression:C.expression,alias:C.alias}))),r.push(S),n.push(...this.getViewRunTimeFieldList(I,p,l,h))}const i=e.some(l=>l.Aggregates&&l.Aggregates.length>0)?`
|
|
397
397
|
AggregateResults {
|
|
398
398
|
alias
|
|
399
399
|
expression
|
|
@@ -418,7 +418,7 @@ ${e.stackFrames}`:this.stack}}function j(g){return g instanceof x?g:new x(G(g))}
|
|
|
418
418
|
Success
|
|
419
419
|
ErrorMessage${i}
|
|
420
420
|
}
|
|
421
|
-
}`,y=await this.ExecuteGQL(o,{input:r});if(y&&y.RunViews){const l=y.RunViews;for(const[
|
|
421
|
+
}`,y=await this.ExecuteGQL(o,{input:r});if(y&&y.RunViews){const l=y.RunViews;for(const[m,R]of l.entries())R.Results=R.Results.map(S=>{let E=JSON.parse(S.Data);return this.ConvertBackToMJFields(E),E});return l}return null}catch(r){throw c.LogError(r),r}}async RunViewsWithCacheCheck(e,t){try{const r=e.map(o=>({params:{EntityName:o.params.EntityName||"",ExtraFilter:o.params.ExtraFilter||"",OrderBy:o.params.OrderBy||"",Fields:o.params.Fields,UserSearchString:o.params.UserSearchString||"",IgnoreMaxRows:o.params.IgnoreMaxRows||!1,MaxRows:o.params.MaxRows,StartRow:o.params.StartRow,AfterKey:o.params.AfterKey?{KeyValuePairs:o.params.AfterKey.KeyValuePairs}:null,ForceAuditLog:o.params.ForceAuditLog||!1,AuditLogDescription:o.params.AuditLogDescription||"",ResultType:o.params.ResultType||"simple",Aggregates:o.params.Aggregates??null,DataSource:o.params.DataSource},cacheStatus:o.cacheStatus?{maxUpdatedAt:o.cacheStatus.maxUpdatedAt,rowCount:o.cacheStatus.rowCount}:null})),s=u.gql`
|
|
422
422
|
query RunViewsWithCacheCheckQuery($input: [RunViewWithCacheCheckInput!]!) {
|
|
423
423
|
RunViewsWithCacheCheck(input: $input) {
|
|
424
424
|
success
|
|
@@ -457,7 +457,7 @@ ${e.stackFrames}`:this.stack}}function j(g){return g instanceof x?g:new x(G(g))}
|
|
|
457
457
|
}
|
|
458
458
|
}
|
|
459
459
|
}
|
|
460
|
-
`,a=(await this.ExecuteGQL(s,{input:r}))?.RunViewsWithCacheCheck;if(!a)return{success:!1,results:[],errorMessage:"No response from server"};const i=a.results.map((o,y)=>{const l=e[y];if(o.status==="differential"&&o.differentialData){const
|
|
460
|
+
`,a=(await this.ExecuteGQL(s,{input:r}))?.RunViewsWithCacheCheck;if(!a)return{success:!1,results:[],errorMessage:"No response from server"};const i=a.results.map((o,y)=>{const l=e[y];if(o.status==="differential"&&o.differentialData){const m=o.differentialData.updatedRows.map(R=>{const S=JSON.parse(R.Data);return this.ConvertBackToMJFields(S),S});return{viewIndex:o.viewIndex,status:o.status,results:void 0,differentialData:{updatedRows:m,deletedRecordIDs:o.differentialData.deletedRecordIDs},maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}}if(o.status==="stale"&&o.Results){const m=o.Results.map(S=>{const E=JSON.parse(S.Data);return this.ConvertBackToMJFields(E),E}),R=o.aggregateResults?.map(S=>({expression:S.expression,alias:S.alias,value:S.value!==void 0&&S.value!==null?JSON.parse(S.value):null,error:S.error}));return{viewIndex:o.viewIndex,status:o.status,results:m,maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage,aggregateResults:R}}return{viewIndex:o.viewIndex,status:o.status,results:void 0,maxUpdatedAt:o.maxUpdatedAt,rowCount:o.rowCount,errorMessage:o.errorMessage}});return{success:a.success,results:i,errorMessage:a.errorMessage}}catch(r){return c.LogError(r),{success:!1,results:[],errorMessage:r instanceof Error?r.message:String(r)}}}async getEntityNameAndUserView(e,t){let r,s;if(e.EntityName)r=e.EntityName;else if(e.ViewID)s=await _.ViewInfo.GetViewEntity(e.ViewID,t),r=s.Entity;else if(e.ViewName)s=await _.ViewInfo.GetViewEntityByName(e.ViewName,t),r=s.Entity;else throw new Error("No EntityName, ViewID or ViewName passed to RunView");return{entityName:r,v:s}}getViewRunTimeFieldList(e,t,r,s){const n=[];if(r.Fields){for(const a of e.PrimaryKeys)r.Fields.find(i=>i.trim().toLowerCase()===a.Name.toLowerCase())===void 0&&n.push(b.MapFieldName(a.Name));r.Fields.forEach(a=>{n.push(b.MapFieldName(a))})}else if(s)e.Fields.forEach(a=>{a.IsBinaryFieldType||n.push(b.MapFieldName(a.CodeName))});else{for(const a of e.PrimaryKeys)n.find(i=>i.trim().toLowerCase()===a.Name.toLowerCase())===void 0&&n.push(b.MapFieldName(a.Name));t.Columns.forEach(a=>{a.hidden===!1&&!n.find(i=>i.trim().toLowerCase()===a.EntityField?.Name.trim().toLowerCase())&&a.EntityField&&n.push(b.MapFieldName(a.EntityField.CodeName))})}return n}get ProviderType(){return c.ProviderType.Network}async GetRecordChanges(e,t){try{const r={EntityName:"MJ: Record Changes",ExtraFilter:`RecordID = '${t.Values()}' AND Entity = '${e}'`},s=await this.RunView(r);return s?s.Results.sort((n,a)=>n.ChangedAt>a.ChangedAt?-1:1):null}catch(r){throw c.LogError(r),r}}async GetRecordDependencies(e,t){try{const r=u.gql`query GetRecordDependenciesQuery ($entityName: String!, $CompositeKey: CompositeKeyInputType!) {
|
|
461
461
|
GetRecordDependencies(entityName: $entityName, CompositeKey: $CompositeKey) {
|
|
462
462
|
EntityName
|
|
463
463
|
RelatedEntityName
|
|
@@ -532,32 +532,34 @@ ${e.stackFrames}`:this.stack}}function j(g){return g instanceof x?g:new x(G(g))}
|
|
|
532
532
|
Message
|
|
533
533
|
}
|
|
534
534
|
}
|
|
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}}}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(
|
|
536
|
-
${e.Fields.map(
|
|
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}}}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(p=>({FieldName:p.CodeName,Value:p.Value})),e.RegisterResultHistoryEntry(s);const i=c.getGraphQLTypeNameBase(e.EntityInfo),o=`${a}${i}`,y=this.GetDeniedReadFieldNamesForCurrentUser(e.EntityInfo),l=d(p=>y.has(p.trim().toLowerCase()),"isDeniedRead"),m=e.Fields.filter(p=>(!p.ReadOnly||p.IsPrimaryKey&&e.IsSaved)&&(p.IsPrimaryKey||!p.NotLoaded&&!l(p.Name))),R=` ${o}(input: $input) {
|
|
536
|
+
${e.Fields.filter(p=>!l(p.Name)).map(p=>b.MapFieldName(p.CodeName)).join(`
|
|
537
537
|
`)}
|
|
538
|
+
${this.FieldSecurityTransportSelection(e.EntityInfo)}
|
|
538
539
|
}`,S=u.gql`mutation ${a}${i} ($input: ${o}Input!) {
|
|
539
|
-
${
|
|
540
|
+
${R}
|
|
540
541
|
}
|
|
541
|
-
`;for(let
|
|
542
|
+
`;for(let p=0;p<m.length;p++){const I=m[p];let h=e.Get(I.Name);if(h)switch(I.EntityFieldInfo.TSType){case c.EntityFieldTSType.Date:h=h.getTime();break;case c.EntityFieldTSType.Boolean:typeof h!="boolean"&&(h=parseInt(h)!==0);break;case c.EntityFieldTSType.Number:if(typeof h!="number"){const v=Number(h);isNaN(v)||(h=v)}break}h===null&&I.EntityFieldInfo.AllowsNull===!1&&(I.EntityFieldInfo.DefaultValue!==null?h=I.EntityFieldInfo.DefaultValue:I.FieldType===c.EntityFieldTSType.Number||I.FieldType===c.EntityFieldTSType.Boolean?h=0:h=""),n.input[b.MapFieldName(I.CodeName)]=h}const E=e.RestoreContext;if(E&&(n.input.RestoreContext___={SourceChangeID:E.SourceChangeID,Reason:E.Reason}),a.trim().toLowerCase()==="update"&&r.SkipOldValuesCheck===!1){const p=[];e.Fields.forEach(I=>{if(I.NotLoaded&&!I.IsPrimaryKey)return;let h=null;I.OldValue!==null&&I.OldValue!==void 0&&(I.EntityFieldInfo.TSType===c.EntityFieldTSType.Date?h=I.OldValue.getTime().toString():I.EntityFieldInfo.TSType===c.EntityFieldTSType.Boolean?h=I.OldValue===!0?"1":"0":typeof I.OldValue!="string"?h=I.OldValue.toString():h=I.OldValue),p.push({Key:b.MapFieldName(I.CodeName),Value:h})}),n.input.OldValues___=p}if(e.TransactionGroup){const p=[{varName:"input",inputType:o+"Input!"}];return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new c.TransactionItem(e,s.Type==="create"?"Create":"Update",R,n,{mutationName:o,mutationInputTypes:p},(I,h)=>{s.EndedAt=new Date,h&&I?(s.Success=!0,s.NewValues=this.ApplyServerFieldAccess(e.EntityInfo,this.ConvertBackToMJFields(I))):(s.Success=!1,s.Message="Transaction failed")})),!0}else{const p=await this.ExecuteGQL(S,n);if(p&&p[o])return s.Success=!0,s.EndedAt=new Date,s.NewValues=this.ApplyServerFieldAccess(e.EntityInfo,this.ConvertBackToMJFields(p[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=D.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(v=>v.Name.trim().toLowerCase()===t.KeyValuePairs[S].FieldName.trim().toLowerCase()).EntityFieldInfo,p=t.GetValueByIndex(S),I=E.GraphQLType;i.length>0&&(i+=", "),i+=`$${E.CodeName}: ${I}!`,a.length>0&&(a+=", ");const h=E.CodeName.startsWith("__mj_")?E.CodeName.replace("__mj_","_mj__"):E.CodeName;if(a+=`${h}: $${E.CodeName}`,E.TSType===c.EntityFieldTSType.Number){if(isNaN(t.GetValueByIndex(S)))throw new Error(`Primary Key value ${p} (${E.Name}) is not a valid number`);n[E.CodeName]=parseInt(p)}else n[E.CodeName]=p}const o=r&&r.length>0?this.getRelatedEntityString(e.EntityInfo,r):"",y=c.getGraphQLTypeNameBase(e.EntityInfo),l=this.GetDeniedReadFieldNamesForCurrentUser(e.EntityInfo),m=u.gql`query Single${y}${o.length>0?"Full":""} (${i}) {
|
|
542
543
|
${y}(${a}) {
|
|
543
|
-
${e.Fields.filter(
|
|
544
|
+
${e.Fields.filter(S=>!S.EntityFieldInfo.IsBinaryFieldType&&!l.has(S.Name.trim().toLowerCase())).map(S=>S.EntityFieldInfo.Name.trim().toLowerCase().startsWith("__mj_")?S.CodeName.replace("__mj_","_mj__"):S.CodeName).join(`
|
|
544
545
|
`)}
|
|
546
|
+
${this.FieldSecurityTransportSelection(e.EntityInfo)}
|
|
545
547
|
${o}
|
|
546
548
|
}
|
|
547
549
|
}
|
|
548
|
-
`,
|
|
550
|
+
`,R=await this.ExecuteGQL(m,n);return R&&R[y]?this.ApplyServerFieldAccess(e.EntityInfo,this.ConvertBackToMJFields(R[y])):null}catch(n){return c.LogError(n),null}}ConvertBackToMJFields(e){return b.ReverseMapFields(e),e}getRelatedEntityString(e,t){let r="";for(let s=0;s<e.RelatedEntities.length;s++)if(t.indexOf(e.RelatedEntities[s].RelatedEntity)>=0){const n=e.RelatedEntities[s],a=this.EntityByID(n.RelatedEntityID);let i="";n.Type.toLowerCase().trim()==="many to many"?i=`${n.RelatedEntityCodeName}_${n.JoinEntityJoinField.replace(/\s/g,"")}`:i=`${n.RelatedEntityCodeName}_${n.RelatedEntityJoinField.replace(/\s/g,"")}`,r+=`
|
|
549
551
|
${i} {
|
|
550
552
|
${a.Fields.map(o=>o.CodeName).join(`
|
|
551
553
|
`)}
|
|
552
554
|
}
|
|
553
|
-
`}return r}async Delete(e,t,r){const s=new c.BaseEntityResult;try{e.RegisterTransactionPreprocessing(),s.StartedAt=new Date,s.Type="delete",s.OriginalValues=e.Fields.map(
|
|
554
|
-
`),y+=`${
|
|
555
|
+
`}return r}async Delete(e,t,r){const s=new c.BaseEntityResult;try{e.RegisterTransactionPreprocessing(),s.StartedAt=new Date,s.Type="delete",s.OriginalValues=e.Fields.map(E=>({FieldName:E.CodeName,Value:E.Value})),e.RegisterResultHistoryEntry(s);const n={},a=[];let i="",o="",y="";for(let E of e.PrimaryKey.KeyValuePairs){const p=e.Fields.find(h=>h.Name.trim().toLowerCase()===E.FieldName.trim().toLowerCase());n[p.CodeName]=p.Value,a.push({varName:p.CodeName,inputType:p.EntityFieldInfo.GraphQLType+"!"});const I=p.CodeName.startsWith("__mj_")?p.CodeName.replace("__mj_","_mj__"):p.CodeName;i.length>0&&(i+=", "),i+=`${I}: $${p.CodeName}`,o.length>0&&(o+=", "),o+=`$${p.CodeName}: ${p.EntityFieldInfo.GraphQLType}!`,y.length>0&&(y+=`
|
|
556
|
+
`),y+=`${I}`}a.push({varName:"options___",inputType:"DeleteOptionsInput!"}),n.options___={SkipEntityAIActions:t?.SkipEntityAIActions??!1,SkipEntityActions:t?.SkipEntityActions??!1,ReplayOnly:t?.ReplayOnly??!1,IsParentEntityDelete:t?.IsParentEntityDelete??!1,SkipRecordChanges:t?.SkipRecordChanges??!1};const m="Delete"+c.getGraphQLTypeNameBase(e.EntityInfo),R=u.gql`${m}(${i}, options___: $options___) {
|
|
555
557
|
${y}
|
|
556
558
|
}
|
|
557
|
-
`,
|
|
558
|
-
${
|
|
559
|
+
`,S=u.gql`mutation ${m} (${o}, $options___: DeleteOptionsInput!) {
|
|
560
|
+
${R}
|
|
559
561
|
}
|
|
560
|
-
`;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new c.TransactionItem(e,"Delete",
|
|
562
|
+
`;if(e.TransactionGroup)return e.RaiseReadyForTransaction(),e.TransactionGroup.AddTransaction(new c.TransactionItem(e,"Delete",R,n,{mutationName:m,mutationInputTypes:a},(E,p)=>{if(s.EndedAt=new Date,p&&E){let I=!0;for(const h of e.PrimaryKey.KeyValuePairs)h.Value!==E[h.FieldName]&&(I=!1);I?s.Success=!0:(s.Success=!1,s.Message="Transaction failed to commit")}else s.Success=!1,s.Message="Transaction failed to commit"})),!0;{const E=await this.ExecuteGQL(S,n);if(E&&E[m]){const p=E[m];for(let I of e.PrimaryKey.KeyValuePairs){let h=p[I.FieldName],v=I.Value;if(typeof v=="number"&&(v=v.toString()),typeof h=="number"&&(h=h.toString()),v!==h)throw new Error(`Primary key value mismatch in server Delete response. Field: ${I.FieldName}, Original: ${v}, Returned: ${h}`)}return s.Success=!0,s.EndedAt=new Date,!0}else throw new Error(`Delete failed for ${e.EntityInfo.Name}: ${e.PrimaryKey.ToString()} `)}}catch(n){s.EndedAt=new Date,s.Success=!1,s.Message=n.response?.errors?.length>0?n.response.errors[0].message:n.message;const a=n.response?.errors?.[0]?.extensions;return s.Errors=D.DeserializeValidationErrors(a?.validationErrors),s.MessageIncludesErrors=s.Errors.length>0&&a?.messageIncludesValidationErrors===!0,c.LogError(n),!1}}async GetDatasetByName(e,t){const r=u.gql`query GetDatasetByName($DatasetName: String!, $ItemFilters: [DatasetItemFilterTypeGQL!]) {
|
|
561
563
|
GetDatasetByName(DatasetName: $DatasetName, ItemFilters: $ItemFilters) {
|
|
562
564
|
DatasetID
|
|
563
565
|
DatasetName
|
|
@@ -624,7 +626,7 @@ ${e.stackFrames}`:this.stack}}function j(g){return g instanceof x?g:new x(G(g))}
|
|
|
624
626
|
ErrorMessage
|
|
625
627
|
Result
|
|
626
628
|
}
|
|
627
|
-
}`,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 f.Instance.ExecuteGQL(e,t,r)}static async ExecuteGQLWithProgress(e,t,r,s=!0){return f.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[l,
|
|
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 f.Instance.ExecuteGQL(e,t,r)}static async ExecuteGQLWithProgress(e,t,r,s=!0){return f.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[l,m]of this._dynamicHeaders)y.setRequestHeader(l,m);y.upload&&r&&(y.upload.onprogress=l=>{if(l.lengthComputable&&l.total>0){const m=Math.min(100,Math.round(l.loaded/l.total*100));r({loaded:l.loaded,total:l.total,percent:m})}}),y.onload=async()=>{if(y.status>=200&&y.status<300)try{const l=JSON.parse(y.responseText);if(l.errors&&l.errors.length>0){const m=l.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(l.data)}catch(l){o(l)}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=f.Instance&&f.Instance._configData===this._configData;if(e&&f.Instance._refreshPromise)return f.Instance._refreshPromise;if(this._refreshPromise)return this._refreshPromise;console.log("[GraphQL] Starting token refresh..."),this._refreshPromise=this.performTokenRefresh(),e&&(f.Instance._refreshPromise=this._refreshPromise);try{await this._refreshPromise,console.log("[GraphQL] Token refresh completed successfully")}finally{this._refreshPromise=null,e&&f.Instance&&(f.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,f.Instance&&f.Instance._configData===this._configData&&(f.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 f.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()})}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__")+`
|
|
628
630
|
`:s.startsWith("_")||(t+=s+`
|
|
629
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=Y.createClient({url:this.ConfigData.WSURL,connectionParams:d(()=>({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:d(()=>!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:d(a=>{r.next(a.data)},"next"),error:d(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:d(()=>{r.complete()},"complete")});return()=>{this._activeSubscriptionCount--,n()}})}PushStatusUpdates(e=null){e||(e=this.sessionId);const t=Date.now(),r=this._pushStatusSubjects.get(e);if(r)return r.lastRequestedAt=t,new $.Observable(o=>{r.activeSubscribers++;const y=r.subject.subscribe(o);return()=>{const l=this._pushStatusSubjects.get(e);l&&l.activeSubscribers>0&&l.activeSubscribers--,y.unsubscribe()}});const s=u.gql`subscription StatusUpdates($sessionId: String!) {
|
|
630
632
|
statusUpdates(sessionId: $sessionId) {
|
|
@@ -633,7 +635,7 @@ ${e.stackFrames}`:this.stack}}function j(g){return g instanceof x?g:new x(G(g))}
|
|
|
633
635
|
sessionId
|
|
634
636
|
}
|
|
635
637
|
}
|
|
636
|
-
`,n=new $.Subject,a=this.getOrCreateWSClient(),i=new $.Subscription;return i.add(new $.Observable(o=>{const y=a.subscribe({query:s,variables:{sessionId:e}},{next:d(l=>{const
|
|
638
|
+
`,n=new $.Subject,a=this.getOrCreateWSClient(),i=new $.Subscription;return i.add(new $.Observable(o=>{const y=a.subscribe({query:s,variables:{sessionId:e}},{next:d(l=>{const m=this._pushStatusSubjects.get(e);m&&(m.lastEmissionAt=Date.now()),o.next(l.data.statusUpdates.message)},"next"),error:d(async l=>{const m=l;if(m?.extensions?.code==="JWT_EXPIRED"||m?.message?.includes("token has expired")||m?.message?.includes("JWT_EXPIRED")){console.log("[GraphQLDataProvider] PushStatusUpdates JWT token expired, refreshing and reconnecting...");try{await this.RefreshToken(),this.disposeWSClient(),o.complete()}catch(S){console.error("[GraphQLDataProvider] Failed to refresh token for PushStatusUpdates:",S),o.error(S)}}else o.error(l)},"error"),complete:d(()=>{o.complete()},"complete")});return this._activeSubscriptionCount++,()=>{this._activeSubscriptionCount--,y()}}).subscribe({next:d(o=>n.next(o),"next"),error:d(o=>{n.error(o),this._pushStatusSubjects.delete(e)},"error"),complete:d(()=>{n.complete(),this._pushStatusSubjects.delete(e)},"complete")})),this._pushStatusSubjects.set(e,{subject:n,subscription:i,createdAt:t,lastRequestedAt:t,lastEmissionAt:t,activeSubscribers:0}),new $.Observable(o=>{const y=this._pushStatusSubjects.get(e);y&&y.activeSubscribers++;const l=n.subscribe(o);return()=>{const m=this._pushStatusSubjects.get(e);m&&m.activeSubscribers>0&&m.activeSubscribers--,l.unsubscribe()}})}TaskGraphFrames(e){const t=d(o=>new $.Observable(y=>{o.activeSubscribers++;const l=o.subject.subscribe(y);return()=>{l.unsubscribe();const m=this._taskGraphFrameStreams.get(e);m&&(m.activeSubscribers--,m.activeSubscribers<=0&&(m.subscription.unsubscribe(),m.subject.complete(),this._taskGraphFrameStreams.delete(e)))}}),"attachTo"),r=this._taskGraphFrameStreams.get(e);if(r)return t(r);const s=u.gql`subscription TaskGraphFrames($parentTaskId: ID!) {
|
|
637
639
|
taskGraphFrames(parentTaskId: $parentTaskId) {
|
|
638
640
|
kind
|
|
639
641
|
parentTaskId
|
|
@@ -1183,28 +1185,28 @@ ${e.stackFrames}`:this.stack}}function j(g){return g instanceof x?g:new x(G(g))}
|
|
|
1183
1185
|
...ApplyResultFields
|
|
1184
1186
|
}
|
|
1185
1187
|
}
|
|
1186
|
-
${
|
|
1188
|
+
${A}
|
|
1187
1189
|
`,r=await this.dataProvider.ExecuteGQL(t,{input:{TargetListId:e.Delta.TargetListId,EntityName:e.Delta.EntityName,ToAdd:e.Delta.ToAdd,ToRemove:e.Delta.ToRemove,Unchanged:e.Delta.Unchanged,AddCount:e.Delta.Counts.Add,RemoveCount:e.Delta.Counts.Remove,UnchangedCount:e.Delta.Counts.Unchanged,SourceTotal:e.Delta.Counts.SourceTotal,TargetTotal:e.Delta.Counts.TargetTotal,DeltaToken:e.Delta.DeltaToken,ConfirmDrops:e.ConfirmDrops}});return T(r?.ApplyListDelta)}async MaterializeFromView(e,t){const r=u.gql`
|
|
1188
1190
|
mutation MaterializeListFromView($viewId: String!, $options: MaterializeOptionsInput!) {
|
|
1189
1191
|
MaterializeListFromView(viewId: $viewId, options: $options) {
|
|
1190
1192
|
...ApplyResultFields
|
|
1191
1193
|
}
|
|
1192
1194
|
}
|
|
1193
|
-
${
|
|
1195
|
+
${A}
|
|
1194
1196
|
`,s=await this.dataProvider.ExecuteGQL(r,{viewId:e,options:{ListName:t.ListName,CategoryId:t.CategoryId,Description:t.Description,RememberLineage:t.RememberLineage,UseSnapshot:t.UseSnapshot,RefreshMode:t.RefreshMode}});return T(s?.MaterializeListFromView)}async AddViewResultsToList(e,t){const r=u.gql`
|
|
1195
1197
|
mutation AddViewResultsToList($viewId: String!, $listId: String!) {
|
|
1196
1198
|
AddViewResultsToList(viewId: $viewId, listId: $listId) {
|
|
1197
1199
|
...ApplyResultFields
|
|
1198
1200
|
}
|
|
1199
1201
|
}
|
|
1200
|
-
${
|
|
1202
|
+
${A}
|
|
1201
1203
|
`,s=await this.dataProvider.ExecuteGQL(r,{viewId:e,listId:t});return T(s?.AddViewResultsToList)}async RefreshFromSource(e){const t=u.gql`
|
|
1202
1204
|
mutation RefreshListFromSource($listId: String!, $mode: String!, $confirmDrops: Boolean!) {
|
|
1203
1205
|
RefreshListFromSource(listId: $listId, mode: $mode, confirmDrops: $confirmDrops) {
|
|
1204
1206
|
...ApplyResultFields
|
|
1205
1207
|
}
|
|
1206
1208
|
}
|
|
1207
|
-
${
|
|
1209
|
+
${A}
|
|
1208
1210
|
`,r=await this.dataProvider.ExecuteGQL(t,{listId:e.ListId,mode:e.Mode,confirmDrops:e.ConfirmDrops});return T(r?.RefreshListFromSource)}async ComposeLists(e){const t=u.gql`
|
|
1209
1211
|
mutation ComposeLists($input: ComposeListsInput!) {
|
|
1210
1212
|
ComposeLists(input: $input) {
|
|
@@ -1219,7 +1221,7 @@ ${e.stackFrames}`:this.stack}}function j(g){return g instanceof x?g:new x(G(g))}
|
|
|
1219
1221
|
}
|
|
1220
1222
|
}
|
|
1221
1223
|
${q}
|
|
1222
|
-
`,r=await this.dataProvider.ExecuteGQL(t,{input:{ListID:e.ListID,Target:
|
|
1224
|
+
`,r=await this.dataProvider.ExecuteGQL(t,{input:{ListID:e.ListID,Target:Ne(e.Target),PermissionLevel:e.PermissionLevel}});return Q(r?.ShareList)}async Unshare(e){const t=u.gql`
|
|
1223
1225
|
mutation UnshareList($permissionId: String!) {
|
|
1224
1226
|
UnshareList(permissionId: $permissionId) {
|
|
1225
1227
|
...ShareResultFields
|
|
@@ -1270,7 +1272,7 @@ ${e.stackFrames}`:this.stack}}function j(g){return g instanceof x?g:new x(G(g))}
|
|
|
1270
1272
|
CreatedAt
|
|
1271
1273
|
}
|
|
1272
1274
|
}
|
|
1273
|
-
`;return((await this.dataProvider.ExecuteGQL(t,{listId:e}))?.ListSharesForList??[]).map(
|
|
1275
|
+
`;return((await this.dataProvider.ExecuteGQL(t,{listId:e}))?.ListSharesForList??[]).map(Me)}async ListsSharedWithMe(){const e=u.gql`
|
|
1274
1276
|
query ListsSharedWithMe {
|
|
1275
1277
|
ListsSharedWithMe {
|
|
1276
1278
|
ListID
|
|
@@ -1301,7 +1303,7 @@ ${e.stackFrames}`:this.stack}}function j(g){return g instanceof x?g:new x(G(g))}
|
|
|
1301
1303
|
}
|
|
1302
1304
|
DeltaToken
|
|
1303
1305
|
}
|
|
1304
|
-
`,
|
|
1306
|
+
`,A=u.gql`
|
|
1305
1307
|
fragment ApplyResultFields on ApplyListResultType {
|
|
1306
1308
|
Success
|
|
1307
1309
|
ResultCode
|
|
@@ -1320,7 +1322,7 @@ ${e.stackFrames}`:this.stack}}function j(g){return g instanceof x?g:new x(G(g))}
|
|
|
1320
1322
|
Message
|
|
1321
1323
|
PermissionID
|
|
1322
1324
|
}
|
|
1323
|
-
`;function
|
|
1325
|
+
`;function Ne(g){return g.kind==="user"?{Kind:"user",UserID:g.userId}:{Kind:"role",RoleID:g.roleId}}d(Ne,"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}}d(Q,"parseShareResult");function Me(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)}}d(Me,"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}}}d(U,"serializeListSource");function z(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(Ae),DeltaToken:e.DeltaToken}}d(z,"parseListDelta");function Ae(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}}d(Ae,"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}}d(T,"parseApplyResult");class Te{static{d(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`
|
|
1324
1326
|
mutation CreateAPIKey($input: CreateAPIKeyInput!) {
|
|
1325
1327
|
CreateAPIKey(input: $input) {
|
|
1326
1328
|
Success
|
|
@@ -1976,7 +1978,7 @@ ${e.stackFrames}`:this.stack}}function j(g){return g instanceof x?g:new x(G(g))}
|
|
|
1976
1978
|
PipelineSteps { Name Status DurationMs Message }
|
|
1977
1979
|
GitCommitSuccess APIRestarted
|
|
1978
1980
|
}
|
|
1979
|
-
}`,y={Connectors:e.map(
|
|
1981
|
+
}`,y={Connectors:e.map(m=>({CompanyIntegrationID:m.CompanyIntegrationID,SourceObjects:m.SourceObjects.map(R=>({SourceObjectID:R.SourceObjectID??null,SourceObjectName:R.SourceObjectName??null,Fields:R.Fields??null}))})),StartSync:t,FullSync:r,SyncScope:s},l=(await this._dataProvider.ExecuteGQL(o,{input:y,platform:n,skipGitCommit:a,skipRestart:i}))?.IntegrationApplyAllBatch;return l?{Success:l.Success,Message:l.Message,Steps:l.PipelineSteps,GitCommitSuccess:l.GitCommitSuccess,APIRestarted:l.APIRestarted,EntityMapsCreated:l.ConnectorResults?.[0]?.EntityMapsCreated,SyncRunID:l.ConnectorResults?.[0]?.SyncRunID,Warnings:l.ConnectorResults?.flatMap(m=>m.Warnings??[])}:{Success:!1,Message:"No response"}}catch(o){return{Success:!1,Message:o.message}}}async ApplyAll(e,t,r="sqlserver",s=!1,n=!1){try{const a=u.gql`mutation IntegrationApplyAll(
|
|
1980
1982
|
$input: ApplyAllInput!, $platform: String!, $skipGitCommit: Boolean!, $skipRestart: Boolean!
|
|
1981
1983
|
) {
|
|
1982
1984
|
IntegrationApplyAll(input: $input, platform: $platform, skipGitCommit: $skipGitCommit, skipRestart: $skipRestart) {
|
|
@@ -2018,5 +2020,5 @@ ${e.stackFrames}`:this.stack}}function j(g){return g instanceof x?g:new x(G(g))}
|
|
|
2018
2020
|
IntegrationGetConnectorCapabilities(companyIntegrationID: $companyIntegrationID) {
|
|
2019
2021
|
Success Message SupportsGet SupportsCreate SupportsUpdate SupportsDelete SupportsSearch
|
|
2020
2022
|
}
|
|
2021
|
-
}`;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:d(function(){return u.gql},"get")}),exports.ActionItemInput=Ee,exports.ActionItemOutput=De,exports.BrowserIndexedDBStorageProvider=B,exports.BrowserStorageProviderBase=k,exports.FieldMapper=L,exports.FireAndForgetHelper=w,exports.GetDataOutput=Ce,exports.GraphQLAIClient=O,exports.GraphQLActionClient=be,exports.GraphQLClassifyClient=Ge,exports.GraphQLClusterClient=xe,exports.GraphQLComponentRegistryClient=Qe,exports.GraphQLDataProvider=f,exports.GraphQLEncryptionClient=Te,exports.GraphQLFileStorageClient=_e,exports.GraphQLIntegrationClient=Oe,exports.GraphQLListsClient=Le,exports.GraphQLLiveKitClient=Fe,exports.GraphQLProviderConfigData=me,exports.GraphQLSearchClient=Ve,exports.GraphQLSystemUserClient=ve,exports.GraphQLTestingClient=qe,exports.GraphQLTransactionGroup=V,exports.GraphQLVersionHistoryClient=Ue,exports.PACKAGE_VERSION=
|
|
2023
|
+
}`;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:d(function(){return u.gql},"get")}),exports.ActionItemInput=Ee,exports.ActionItemOutput=De,exports.BrowserIndexedDBStorageProvider=B,exports.BrowserStorageProviderBase=k,exports.FieldMapper=L,exports.FireAndForgetHelper=w,exports.GetDataOutput=Ce,exports.GraphQLAIClient=O,exports.GraphQLActionClient=be,exports.GraphQLClassifyClient=Ge,exports.GraphQLClusterClient=xe,exports.GraphQLComponentRegistryClient=Qe,exports.GraphQLDataProvider=f,exports.GraphQLEncryptionClient=Te,exports.GraphQLFileStorageClient=_e,exports.GraphQLIntegrationClient=Oe,exports.GraphQLListsClient=Le,exports.GraphQLLiveKitClient=Fe,exports.GraphQLProviderConfigData=me,exports.GraphQLSearchClient=Ve,exports.GraphQLSystemUserClient=ve,exports.GraphQLTestingClient=qe,exports.GraphQLTransactionGroup=V,exports.GraphQLVersionHistoryClient=Ue,exports.PACKAGE_VERSION=M,exports.RoleInput=he,exports.RolesAndUsersInput=fe,exports.SafeGraphQLError=x,exports.SanitizeGraphQLError=G,exports.SimpleRemoteEntity=$e,exports.SimpleRemoteEntityField=Pe,exports.SimpleRemoteEntityOutput=we,exports.SyncDataAction=J,exports.SyncDataResult=Re,exports.SyncRolesAndUsersResult=pe,exports.ToSafeGraphQLError=j,exports.UserInput=Ie,exports.setupGraphQLClient=Se;
|
|
2022
2024
|
//# sourceMappingURL=index.cjs.map
|