@memberjunction/react-runtime 5.1.0 → 5.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/.turbo/turbo-build.log
CHANGED
|
@@ -1,32 +1,32 @@
|
|
|
1
1
|
|
|
2
|
-
> @memberjunction/react-runtime@5.
|
|
2
|
+
> @memberjunction/react-runtime@5.2.0 build
|
|
3
3
|
> npm run build:node && npm run build:umd
|
|
4
4
|
|
|
5
5
|
|
|
6
|
-
> @memberjunction/react-runtime@5.
|
|
6
|
+
> @memberjunction/react-runtime@5.2.0 build:node
|
|
7
7
|
> tsc
|
|
8
8
|
|
|
9
9
|
|
|
10
|
-
> @memberjunction/react-runtime@5.
|
|
10
|
+
> @memberjunction/react-runtime@5.2.0 build:umd
|
|
11
11
|
> webpack --config webpack.umd.config.cjs
|
|
12
12
|
|
|
13
13
|
[BABEL] Note: The code generator has deoptimised the styling of /home/runner/work/MJ/MJ/packages/MJCoreEntities/dist/generated/entity_subclasses.js as it exceeds the max of 500KB.
|
|
14
|
-
asset [1m[33mruntime.umd.js[39m[22m [1m[33m2.
|
|
15
|
-
asset [1m[32m324.runtime.umd.js[39m[22m
|
|
14
|
+
asset [1m[33mruntime.umd.js[39m[22m [1m[33m2.23 MiB[39m[22m [1m[32m[emitted][39m[22m [1m[32m[minimized][39m[22m [1m[33m[big][39m[22m (name: main) 1 related asset
|
|
15
|
+
asset [1m[32m324.runtime.umd.js[39m[22m 114 KiB [1m[32m[emitted][39m[22m [1m[32m[minimized][39m[22m
|
|
16
16
|
asset [1m[32m490.runtime.umd.js[39m[22m 61.7 KiB [1m[32m[emitted][39m[22m [1m[32m[minimized][39m[22m (id hint: vendors)
|
|
17
|
-
orphan modules 5.
|
|
17
|
+
orphan modules 5.46 MiB [1m[33m[orphan][39m[22m 487 modules
|
|
18
18
|
runtime modules 6.94 KiB 10 modules
|
|
19
|
-
built modules 5.
|
|
19
|
+
built modules 5.57 MiB [1m[33m[built][39m[22m
|
|
20
20
|
modules by path [1m../../../node_modules/[39m[22m 780 KiB 23 modules
|
|
21
|
-
modules by path [1m../../MJCoreEntities/dist/[39m[22m 3.
|
|
22
|
-
[1m../../MJCoreEntities/dist/index.js +
|
|
21
|
+
modules by path [1m../../MJCoreEntities/dist/[39m[22m 3.14 MiB
|
|
22
|
+
[1m../../MJCoreEntities/dist/index.js + 23 modules[39m[22m 3.12 MiB [1m[33m[built][39m[22m [1m[33m[code generated][39m[22m
|
|
23
23
|
[1m../../MJCoreEntities/dist/engines/UserViewEngine.js[39m[22m 18.7 KiB [1m[33m[built][39m[22m [1m[33m[code generated][39m[22m
|
|
24
|
-
modules by path [1m../../MJGlobal/dist/[39m[22m
|
|
25
|
-
[1m../../MJGlobal/dist/index.js + 16 modules[39m[22m
|
|
24
|
+
modules by path [1m../../MJGlobal/dist/[39m[22m 193 KiB
|
|
25
|
+
[1m../../MJGlobal/dist/index.js + 16 modules[39m[22m 193 KiB [1m[33m[built][39m[22m [1m[33m[code generated][39m[22m
|
|
26
26
|
[1m../../MJGlobal/dist/ lazy strict namespace object[39m[22m 160 bytes [1m[33m[built][39m[22m [1m[33m[code generated][39m[22m
|
|
27
27
|
[1m./dist/index.js + 27 modules[39m[22m 420 KiB [1m[33m[built][39m[22m [1m[33m[code generated][39m[22m
|
|
28
|
-
[1m../../MJCore/dist/index.js + 71 modules[39m[22m
|
|
29
|
-
[1m../../GraphQLDataProvider/dist/index.mjs[39m[22m
|
|
28
|
+
[1m../../MJCore/dist/index.js + 71 modules[39m[22m 985 KiB [1m[33m[built][39m[22m [1m[33m[code generated][39m[22m
|
|
29
|
+
[1m../../GraphQLDataProvider/dist/index.mjs[39m[22m 114 KiB [1m[33m[built][39m[22m [1m[33m[code generated][39m[22m
|
|
30
30
|
|
|
31
31
|
[1m[33mWARNING[39m[22m in [1m../../MJGlobal/dist/DynamicPackageLoader.js[39m[22m [1m[32m80:21-44[39m[22m
|
|
32
32
|
[1mCritical dependency: the request of a dependency is an expression[39m[22m
|
|
@@ -39,4 +39,4 @@ built modules 5.55 MiB [1m[33m[built][39m[22m
|
|
|
39
39
|
1 warning has detailed information that is not shown.
|
|
40
40
|
Use 'stats.errorDetails: true' resp. '--stats-error-details' to show it.
|
|
41
41
|
|
|
42
|
-
webpack 5.105.0 compiled with [1m[33m1 warning[39m[22m in
|
|
42
|
+
webpack 5.105.0 compiled with [1m[33m1 warning[39m[22m in 129986 ms
|
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,19 @@
|
|
|
1
1
|
# @memberjunction/react-runtime
|
|
2
2
|
|
|
3
|
+
## 5.2.0
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- 5e5fab6: Standardize entity subclass naming with MJ-prefix rename map in CodeGen, update cross-package references to use new names, add share/edit/delete UI triggers to collections dashboard, add dbEncrypt CLI config, and fix stale entity name references in migration JSON config columns
|
|
8
|
+
- Updated dependencies [5e5fab6]
|
|
9
|
+
- Updated dependencies [06d889c]
|
|
10
|
+
- Updated dependencies [3542cb6]
|
|
11
|
+
- @memberjunction/core-entities@5.2.0
|
|
12
|
+
- @memberjunction/core@5.2.0
|
|
13
|
+
- @memberjunction/graphql-dataprovider@5.2.0
|
|
14
|
+
- @memberjunction/interactive-component-types@5.2.0
|
|
15
|
+
- @memberjunction/global@5.2.0
|
|
16
|
+
|
|
3
17
|
## 5.1.0
|
|
4
18
|
|
|
5
19
|
### Patch Changes
|
package/dist/324.runtime.umd.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";(this.webpackChunkMJReactRuntime=this.webpackChunkMJReactRuntime||[]).push([[324],{324(e,t,r){r.r(t),r.d(t,{ActionItemInput:()=>M,ActionItemOutput:()=>
|
|
1
|
+
"use strict";(this.webpackChunkMJReactRuntime=this.webpackChunkMJReactRuntime||[]).push([[324],{324(e,t,r){r.r(t),r.d(t,{ActionItemInput:()=>M,ActionItemOutput:()=>L,BrowserIndexedDBStorageProvider:()=>w,BrowserStorageProviderBase:()=>R,FieldMapper:()=>g,GetDataOutput:()=>T,GraphQLAIClient:()=>I,GraphQLActionClient:()=>_,GraphQLComponentRegistryClient:()=>k,GraphQLDataProvider:()=>f,GraphQLEncryptionClient:()=>O,GraphQLFileStorageClient:()=>j,GraphQLProviderConfigData:()=>P,GraphQLSystemUserClient:()=>G,GraphQLTestingClient:()=>K,GraphQLTransactionGroup:()=>h,GraphQLVersionHistoryClient:()=>J,RoleInput:()=>v,RolesAndUsersInput:()=>N,SimpleRemoteEntity:()=>V,SimpleRemoteEntityField:()=>F,SimpleRemoteEntityOutput:()=>U,SyncDataAction:()=>x,SyncDataResult:()=>Q,SyncRolesAndUsersResult:()=>$,UserInput:()=>A,gql:()=>s.J1,setupGraphQLClient:()=>C});var s=r(215),a=r(454),n=r(429),o=r(600),i=r(49),u=r(226),c=r(497),l=r(718),d=r(292),m=r(196),y=Object.defineProperty,p=(e,t)=>y(e,"name",{value:t,configurable:!0});class g{static{p(this,"FieldMapper")}constructor(){this._fieldMap={__mj_CreatedAt:"_mj__CreatedAt",__mj_UpdatedAt:"_mj__UpdatedAt",__mj_DeletedAt:"_mj__DeletedAt"}}MapFields(e){if(e)for(const t in e)t in this._fieldMap&&(e[this._fieldMap[t]]=e[t],delete e[t]);return e}MapFieldName(e){return this._fieldMap[e]??e}ReverseMapFieldName(e){return Object.entries(this._fieldMap).find(([t,r])=>r===e)?.[0]??e}ReverseMapFields(e){const t=Object.fromEntries(Object.entries(this._fieldMap).map(([e,t])=>[t,e]));for(const r in e)r in t&&(e[t[r]]=e[r],delete e[r]);return e}}class h extends a.VH{static{p(this,"GraphQLTransactionGroup")}constructor(e){super(),this._provider=e}async HandleSubmit(){const e=s.J1`
|
|
2
2
|
mutation ExecuteTransactionGroup($group: TransactionInputType!) {
|
|
3
3
|
ExecuteTransactionGroup(group: $group) {
|
|
4
4
|
Success
|
|
@@ -179,7 +179,7 @@
|
|
|
179
179
|
error
|
|
180
180
|
}
|
|
181
181
|
}
|
|
182
|
-
`,r={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},a=await this._dataProvider.ExecuteGQL(t,r);if(!a?.EmbedText)throw new Error("Invalid response from server");const n=a.EmbedText;return{embeddings:Array.isArray(e.textToEmbed)?n.embeddings:n.embeddings[0],modelName:n.modelName,vectorDimensions:n.vectorDimensions,error:n.error}}catch(t){const r=t;return(0,a.ZI)(`Error generating embeddings: ${r}`),{embeddings:(Array.isArray(e.textToEmbed),[]),modelName:"Unknown",vectorDimensions:0,error:r.message||"Unknown error occurred"}}}}const S="default";class R{static{p(this,"BrowserStorageProviderBase")}constructor(){this._storage=new Map}getCategoryMap(e){const t=e||S;let r=this._storage.get(t);return r||(r=new Map,this._storage.set(t,r)),r}async GetItem(e,t){return this.getCategoryMap(t||S).get(e)??null}async SetItem(e,t,r){this.getCategoryMap(r||S).set(e,t)}async Remove(e,t){this.getCategoryMap(t||S).delete(e)}async ClearCategory(e){const t=e||S;this._storage.delete(t)}async GetCategoryKeys(e){const t=this._storage.get(e||S);return t?Array.from(t.keys()):[]}}const D=["mj:default","mj:Metadata","mj:RunViewCache","mj:RunQueryCache","mj:DatasetCache"],
|
|
182
|
+
`,r={textToEmbed:Array.isArray(e.textToEmbed)?e.textToEmbed:[e.textToEmbed],modelSize:e.modelSize},a=await this._dataProvider.ExecuteGQL(t,r);if(!a?.EmbedText)throw new Error("Invalid response from server");const n=a.EmbedText;return{embeddings:Array.isArray(e.textToEmbed)?n.embeddings:n.embeddings[0],modelName:n.modelName,vectorDimensions:n.vectorDimensions,error:n.error}}catch(t){const r=t;return(0,a.ZI)(`Error generating embeddings: ${r}`),{embeddings:(Array.isArray(e.textToEmbed),[]),modelName:"Unknown",vectorDimensions:0,error:r.message||"Unknown error occurred"}}}}const S="default";class R{static{p(this,"BrowserStorageProviderBase")}constructor(){this._storage=new Map}getCategoryMap(e){const t=e||S;let r=this._storage.get(t);return r||(r=new Map,this._storage.set(t,r)),r}async GetItem(e,t){return this.getCategoryMap(t||S).get(e)??null}async SetItem(e,t,r){this.getCategoryMap(r||S).set(e,t)}async Remove(e,t){this.getCategoryMap(t||S).delete(e)}async ClearCategory(e){const t=e||S;this._storage.delete(t)}async GetCategoryKeys(e){const t=this._storage.get(e||S);return t?Array.from(t.keys()):[]}}const D=["mj:default","mj:Metadata","mj:RunViewCache","mj:RunQueryCache","mj:DatasetCache"],E="Metadata_KVPairs";class w extends R{static{p(this,"BrowserIndexedDBStorageProvider")}constructor(){super(),this._dbReady=!1,this.dbPromise=(0,m.P2)("MJ_Metadata",3,{upgrade(e){try{e.objectStoreNames.contains(E)&&e.deleteObjectStore(E);for(const t of D)e.objectStoreNames.contains(t)||e.createObjectStore(t)}catch(e){(0,a.Q1)({error:e,message:e?.message})}}}),this.dbPromise.then(()=>{this._dbReady=!0}).catch(e=>{(0,a.Q1)({error:e,message:"IndexedDB initialization failed: "+e?.message})})}isKnownCategory(e){const t=`mj:${e}`;return D.includes(t)}getStoreName(e){const t=e||S;return this.isKnownCategory(t)?`mj:${t}`:"mj:default"}getStoreKey(e,t){const r=t||S;return this.isKnownCategory(r)?e:`[${r}]:${e}`}async SetItem(e,t,r){try{const s=await this.dbPromise,a=this.getStoreName(r),n=this.getStoreKey(e,r),o=s.transaction(a,"readwrite");await o.objectStore(a).put(t,n),await o.done}catch(s){(0,a.Q1)({error:s,message:s?.message}),await super.SetItem(e,t,r)}}async GetItem(e,t){try{const r=await this.dbPromise,s=this.getStoreName(t),a=this.getStoreKey(e,t);return await r.transaction(s).objectStore(s).get(a)??null}catch(r){return(0,a.Q1)({error:r,message:r?.message}),await super.GetItem(e,t)}}async Remove(e,t){try{const r=await this.dbPromise,s=this.getStoreName(t),a=this.getStoreKey(e,t),n=r.transaction(s,"readwrite");await n.objectStore(s).delete(a),await n.done}catch(r){(0,a.Q1)({error:r,message:r?.message}),await super.Remove(e,t)}}async ClearCategory(e){try{const t=await this.dbPromise,r=e||S,s=this.getStoreName(e);if(this.isKnownCategory(r)){const e=t.transaction(s,"readwrite");await e.objectStore(s).clear(),await e.done}else{const e=`[${r}]:`,s=t.transaction("mj:default","readwrite"),a=s.objectStore("mj:default"),n=await a.getAllKeys();for(const t of n)"string"==typeof t&&t.startsWith(e)&&await a.delete(t);await s.done}}catch(t){(0,a.Q1)({error:t,message:t?.message}),await super.ClearCategory(e)}}async GetCategoryKeys(e){try{const t=await this.dbPromise,r=e||S,s=this.getStoreName(e),a=await t.transaction(s,"readonly").objectStore(s).getAllKeys();if(this.isKnownCategory(r))return a.map(e=>String(e));const n=`[${r}]:`;return a.map(e=>String(e)).filter(e=>e.startsWith(n)).map(e=>e.slice(n.length))}catch(t){return(0,a.Q1)({error:t,message:t?.message}),await super.GetCategoryKeys(e)}}}class P extends a.dZ{static{p(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 RefreshTokenFunction(){return this.Data.RefreshFunction}constructor(e,t,r,s,a,n,o,i,u){super({Token:e,URL:t,WSURL:r,MJAPIKey:i,UserAPIKey:u,RefreshTokenFunction:s},a,n,o)}}class f extends a.Dn{static{p(this,"GraphQLDataProvider")}constructor(){super(),this._refreshPromise=null,this._innerCurrentUserQueryString=`CurrentUser {\n ${this.userInfoString()}\n MJUserRoles_UserIDArray {\n ${this.userRoleInfoString()}\n }\n }\n `,this._currentUserQuery=s.J1`query CurrentUserAndRoles {
|
|
183
183
|
${this._innerCurrentUserQueryString}
|
|
184
184
|
}`,this._wsClient=null,this._wsClientCreatedAt=null,this._pushStatusSubjects=new Map,this._activeSubscriptionCount=0,this.WS_CLIENT_MAX_AGE_MS=18e5,this.SUBSCRIPTION_CLEANUP_INTERVAL_MS=3e5,this.SUBSCRIPTION_IDLE_TIMEOUT_MS=6e5,this._subscriptionCleanupTimer=null,this._isCleaningUp=!1,f._instance||(f._instance=this)}static get Instance(){return f._instance}get ConfigData(){return this._configData}get AI(){return this._aiClient||(this._aiClient=new I(this)),this._aiClient}get DatabaseConnection(){throw new Error("DatabaseConnection not implemented for the GraphQLDataProvider")}get InstanceConnectionString(){return this._configData.URL}GenerateUUID(){return(0,l.A)()}get LocalStoragePrefix(){if(void 0===this._configData||void 0===this._configData.URL)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)):(f.Instance._configData=e,void 0===f.Instance._sessionId&&(f.Instance._sessionId=await this.GetPreferredUUID(s)),f.Instance._client||(f.Instance._client=this.CreateNewGraphQLClient(e.URL,e.Token,f.Instance._sessionId,e.MJAPIKey,e.UserAPIKey)),await f.Instance.SaveStoredSessionID(f.Instance._sessionId),this._sessionId=f.Instance._sessionId,this._client=f.Instance._client),super.Config(e)}catch(e){throw(0,a.ZI)(e),e}}get sessionId(){return this._sessionId}get AllowRefresh(){return!0}async GetCurrentUser(){const e=await this.ExecuteGQL(this._currentUserQuery,null);if(e){const t=this.ConvertBackToMJFields(e.CurrentUser),r=t.MJUserRoles_UserIDArray.map(e=>this.ConvertBackToMJFields(e));return t.MJUserRoles_UserIDArray=r,new a.oq(this,{...t,UserRoles:r})}}async RunReport(e,t){const r=s.J1`
|
|
185
185
|
query GetReportDataQuery ($ReportID: String!) {
|
|
@@ -190,7 +190,13 @@
|
|
|
190
190
|
ExecutionTime
|
|
191
191
|
ErrorMessage
|
|
192
192
|
}
|
|
193
|
-
}`,a=await this.ExecuteGQL(r,{ReportID:e.ReportID});if(a&&a.GetReportData)return{ReportID:e.ReportID,Success:a.GetReportData.Success,Results:JSON.parse(a.GetReportData.Results),RowCount:a.GetReportData.RowCount,ExecutionTime:a.GetReportData.ExecutionTime,ErrorMessage:a.GetReportData.ErrorMessage}}async InternalRunQuery(e,t){if(e.QueryID)return this.RunQueryByID(e.QueryID,e.CategoryID,e.CategoryPath,t,e.Parameters,e.MaxRows,e.StartRow);if(e.QueryName)return this.RunQueryByName(e.QueryName,e.CategoryID,e.CategoryPath,t,e.Parameters,e.MaxRows,e.StartRow);throw new Error("No QueryID or QueryName provided to RunQuery")}async
|
|
193
|
+
}`,a=await this.ExecuteGQL(r,{ReportID:e.ReportID});if(a&&a.GetReportData)return{ReportID:e.ReportID,Success:a.GetReportData.Success,Results:JSON.parse(a.GetReportData.Results),RowCount:a.GetReportData.RowCount,ExecutionTime:a.GetReportData.ExecutionTime,ErrorMessage:a.GetReportData.ErrorMessage}}async InternalRunQuery(e,t){if(e.SQL)return this.RunAdhocQuery(e.SQL,e.MaxRows);if(e.QueryID)return this.RunQueryByID(e.QueryID,e.CategoryID,e.CategoryPath,t,e.Parameters,e.MaxRows,e.StartRow);if(e.QueryName)return this.RunQueryByName(e.QueryName,e.CategoryID,e.CategoryPath,t,e.Parameters,e.MaxRows,e.StartRow);throw new Error("No SQL, QueryID, or QueryName provided to RunQuery")}async RunAdhocQuery(e,t,r){const a=s.J1`
|
|
194
|
+
query ExecuteAdhocQuery($input: AdhocQueryInput!) {
|
|
195
|
+
ExecuteAdhocQuery(input: $input) {
|
|
196
|
+
${this.QueryReturnFieldList}
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
`,n={SQL:e};void 0!==r&&(n.TimeoutSeconds=r);const o=await this.ExecuteGQL(a,{input:n});return o?.ExecuteAdhocQuery?this.TransformQueryPayload(o.ExecuteAdhocQuery):{QueryID:"",QueryName:"Ad-Hoc Query",Success:!1,Results:[],RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:"Ad-hoc query execution failed — no response from server"}}async InternalRunQueries(e,t){const r=s.J1`
|
|
194
200
|
query RunQueriesBatch($input: [RunQueryInput!]!) {
|
|
195
201
|
RunQueries(input: $input) {
|
|
196
202
|
${this.QueryReturnFieldList}
|
|
@@ -412,14 +418,14 @@
|
|
|
412
418
|
ErrorMessage
|
|
413
419
|
Result
|
|
414
420
|
}
|
|
415
|
-
}`,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)}throw new Error("GraphQL query failed")}catch(e){throw(0,a.ZI)(e),e}}static async ExecuteGQL(e,t,r=!0){return f.Instance.ExecuteGQL(e,t,r)}async ExecuteGQL(e,t,r=!0){try{return await this._client.request(e,t)}catch(s){if(console.error("[GraphQL] ExecuteGQL error caught:",{hasResponse:!!s?.response,hasErrors:!!s?.response?.errors,errorCount:s?.response?.errors?.length,firstError:s?.response?.errors?.[0],errorCode:s?.response?.errors?.[0]?.extensions?.code,errorMessage:s?.response?.errors?.[0]?.message,fullError:s}),s&&s.response&&s.response.errors?.length>0){if("JWT_EXPIRED"===s.response.errors[0]?.extensions?.code?.toUpperCase().trim()){if(r)return await this.RefreshToken(),await this.ExecuteGQL(e,t,!1);throw(0,a.ZI)("JWT_EXPIRED and refreshTokenIfNeeded is false"),s}throw s}throw(0,a.ZI)(s),s}}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)throw new Error("No refresh token function provided");{const e=await this._configData.Data.RefreshTokenFunction();if(!e)throw new Error("Refresh token function returned null or undefined token");{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)}}}static async RefreshToken(){return f.Instance.RefreshToken()}CreateNewGraphQLClient(e,t,r,a,n){const o={"x-session-id":r};return t&&(o.authorization="Bearer "+t),a&&(o["x-mj-api-key"]=a),n&&(o["x-api-key"]=n),new s.l4(e,{headers:o})}userInfoString(){return this.infoString(new a.oq(null,null))}userRoleInfoString(){return this.infoString(new a.St(null))}infoString(e){let t="";const r=Object.keys(e);for(const e of r)e.startsWith("__mj_")?t+=e.replace("__mj_","_mj__")+"\n ":e.startsWith("_")||(t+=e+"\n ");return t}get LocalStorageProvider(){return this._localStorageProvider||(typeof indexedDB<"u"?this._localStorageProvider=new
|
|
421
|
+
}`,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)}throw new Error("GraphQL query failed")}catch(e){throw(0,a.ZI)(e),e}}static async ExecuteGQL(e,t,r=!0){return f.Instance.ExecuteGQL(e,t,r)}async ExecuteGQL(e,t,r=!0){try{return await this._client.request(e,t)}catch(s){if(console.error("[GraphQL] ExecuteGQL error caught:",{hasResponse:!!s?.response,hasErrors:!!s?.response?.errors,errorCount:s?.response?.errors?.length,firstError:s?.response?.errors?.[0],errorCode:s?.response?.errors?.[0]?.extensions?.code,errorMessage:s?.response?.errors?.[0]?.message,fullError:s}),s&&s.response&&s.response.errors?.length>0){if("JWT_EXPIRED"===s.response.errors[0]?.extensions?.code?.toUpperCase().trim()){if(r)return await this.RefreshToken(),await this.ExecuteGQL(e,t,!1);throw(0,a.ZI)("JWT_EXPIRED and refreshTokenIfNeeded is false"),s}throw s}throw(0,a.ZI)(s),s}}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)throw new Error("No refresh token function provided");{const e=await this._configData.Data.RefreshTokenFunction();if(!e)throw new Error("Refresh token function returned null or undefined token");{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)}}}static async RefreshToken(){return f.Instance.RefreshToken()}CreateNewGraphQLClient(e,t,r,a,n){const o={"x-session-id":r};return t&&(o.authorization="Bearer "+t),a&&(o["x-mj-api-key"]=a),n&&(o["x-api-key"]=n),new s.l4(e,{headers:o})}userInfoString(){return this.infoString(new a.oq(null,null))}userRoleInfoString(){return this.infoString(new a.St(null))}infoString(e){let t="";const r=Object.keys(e);for(const e of r)e.startsWith("__mj_")?t+=e.replace("__mj_","_mj__")+"\n ":e.startsWith("_")||(t+=e+"\n ");return t}get LocalStorageProvider(){return this._localStorageProvider||(typeof indexedDB<"u"?this._localStorageProvider=new w:this._localStorageProvider=new a.KW),this._localStorageProvider}get Metadata(){return this}getOrCreateWSClient(){const e=Date.now();return this._wsClient&&this._wsClientCreatedAt&&e-this._wsClientCreatedAt>this.WS_CLIENT_MAX_AGE_MS&&0===this._activeSubscriptionCount&&this.disposeWSClient(),this._wsClient||(this._wsClient=(0,c.UU)({url:this.ConfigData.WSURL,connectionParams:{Authorization:"Bearer "+this.ConfigData.Token},keepAlive:3e4,retryAttempts:3,shouldRetry:p(()=>!0,"shouldRetry")}),this._wsClientCreatedAt=e,this._subscriptionCleanupTimer||(this._subscriptionCleanupTimer=setInterval(()=>{this.cleanupStaleSubscriptions()},this.SUBSCRIPTION_CLEANUP_INTERVAL_MS))),this._wsClient}disposeWSClient(){if(this._wsClient){try{this._wsClient.dispose()}catch(e){console.error("[GraphQLDataProvider] Error disposing WebSocket client:",e)}this._wsClient=null,this._wsClientCreatedAt=null}}completeAllSubjects(){this._pushStatusSubjects.forEach((e,t)=>{try{e.subject.complete(),e.subscription.unsubscribe()}catch(e){console.error(`[GraphQLDataProvider] Error cleaning up subject for ${t}:`,e)}}),this._pushStatusSubjects.clear()}cleanupStaleSubscriptions(){if(!this._isCleaningUp){this._isCleaningUp=!0;try{const e=Date.now(),t=(this._pushStatusSubjects.size,Array.from(this._pushStatusSubjects.entries())),r=[];t.forEach(([t,s])=>{const a=e-s.lastRequestedAt,n=e-s.lastEmissionAt;0===s.activeSubscribers&&a>=this.SUBSCRIPTION_IDLE_TIMEOUT_MS&&n>=this.SUBSCRIPTION_IDLE_TIMEOUT_MS&&(console.log(`[GraphQLDataProvider] Marking session ${t} for cleanup: activeSubscribers=${s.activeSubscribers}, timeSinceRequested=${Math.round(a/1e3)}s, timeSinceEmission=${Math.round(n/1e3)}s`),r.push(t))}),r.forEach(e=>{const t=this._pushStatusSubjects.get(e);if(t)try{t.subject.complete(),t.subscription.unsubscribe(),this._pushStatusSubjects.delete(e),console.log(`[GraphQLDataProvider] Cleaned up stale subscription for session: ${e}`)}catch(t){console.error(`[GraphQLDataProvider] Error cleaning up subscription for ${e}:`,t)}}),r.length>0&&console.log(`[GraphQLDataProvider] Cleaned up ${r.length} stale subscription(s)`),0===this._pushStatusSubjects.size&&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 o.c(r=>{const s=this.getOrCreateWSClient();this._activeSubscriptionCount++;const a=s.subscribe({query:e,variables:t},{next:p(e=>{r.next(e.data)},"next"),error:p(async e=>{const t=e;if("JWT_EXPIRED"===t?.extensions?.code||t?.message?.includes("token has expired")||t?.message?.includes("JWT_EXPIRED")){console.log("[GraphQLDataProvider] WebSocket JWT token expired, refreshing and reconnecting...");try{await this.RefreshToken(),this.disposeWSClient(),r.complete()}catch(e){console.error("[GraphQLDataProvider] Failed to refresh token for WebSocket:",e),r.error(e)}}else r.error(e)},"error"),complete:p(()=>{r.complete()},"complete")});return()=>{this._activeSubscriptionCount--,a()}})}PushStatusUpdates(e=null){e||(e=this.sessionId);const t=Date.now(),r=this._pushStatusSubjects.get(e);if(r)return r.lastRequestedAt=t,new o.c(t=>{r.activeSubscribers++;const s=r.subject.subscribe(t);return()=>{const t=this._pushStatusSubjects.get(e);t&&t.activeSubscribers>0&&t.activeSubscribers--,s.unsubscribe()}});const a=s.J1`subscription StatusUpdates($sessionId: String!) {
|
|
416
422
|
statusUpdates(sessionId: $sessionId) {
|
|
417
423
|
date
|
|
418
424
|
message
|
|
419
425
|
sessionId
|
|
420
426
|
}
|
|
421
427
|
}
|
|
422
|
-
`,n=new i.B,c=this.getOrCreateWSClient(),l=new u.yU;return l.add(new o.c(t=>{const r=c.subscribe({query:a,variables:{sessionId:e}},{next:p(r=>{const s=this._pushStatusSubjects.get(e);s&&(s.lastEmissionAt=Date.now()),t.next(r.data.statusUpdates.message)},"next"),error:p(async e=>{const r=e;if("JWT_EXPIRED"===r?.extensions?.code||r?.message?.includes("token has expired")||r?.message?.includes("JWT_EXPIRED")){console.log("[GraphQLDataProvider] PushStatusUpdates JWT token expired, refreshing and reconnecting...");try{await this.RefreshToken(),this.disposeWSClient(),t.complete()}catch(e){console.error("[GraphQLDataProvider] Failed to refresh token for PushStatusUpdates:",e),t.error(e)}}else t.error(e)},"error"),complete:p(()=>{t.complete()},"complete")});return this._activeSubscriptionCount++,()=>{this._activeSubscriptionCount--,r()}}).subscribe({next:p(e=>n.next(e),"next"),error:p(t=>{n.error(t),this._pushStatusSubjects.delete(e)},"error"),complete:p(()=>{n.complete(),this._pushStatusSubjects.delete(e)},"complete")})),this._pushStatusSubjects.set(e,{subject:n,subscription:l,createdAt:t,lastRequestedAt:t,lastEmissionAt:t,activeSubscribers:0}),new o.c(t=>{const r=this._pushStatusSubjects.get(e);r&&r.activeSubscribers++;const s=n.subscribe(t);return()=>{const t=this._pushStatusSubjects.get(e);t&&t.activeSubscribers>0&&t.activeSubscribers--,s.unsubscribe()}})}disposeWebSocketResources(){this._subscriptionCleanupTimer&&(clearInterval(this._subscriptionCleanupTimer),this._subscriptionCleanupTimer=null),this.completeAllSubjects(),this._activeSubscriptionCount=0,this.disposeWSClient()}async FindISAChildEntity(e,t,r){if(!e.IsParentType)return null;try{const r=await this.ExecuteGQL("query FindISAChildEntity($EntityName: String!, $RecordID: String!) {\n FindISAChildEntity(EntityName: $EntityName, RecordID: $RecordID) {\n Success\n ChildEntityName\n ErrorMessage\n }\n }",{EntityName:e.Name,RecordID:t});return r?.FindISAChildEntity?.Success&&r.FindISAChildEntity.ChildEntityName?{ChildEntityName:r.FindISAChildEntity.ChildEntityName}:null}catch(t){return(0,a.ZI)(`FindISAChildEntity failed for ${e.Name}: ${t}`),null}}async FindISAChildEntities(e,t,r){if(!e.IsParentType)return[];try{const r=await this.ExecuteGQL("query FindISAChildEntities($EntityName: String!, $RecordID: String!) {\n FindISAChildEntities(EntityName: $EntityName, RecordID: $RecordID) {\n Success\n ChildEntityNames\n ErrorMessage\n }\n }",{EntityName:e.Name,RecordID:t});return r?.FindISAChildEntities?.Success&&r.FindISAChildEntities.ChildEntityNames?r.FindISAChildEntities.ChildEntityNames.map(e=>({ChildEntityName:e})):[]}catch(t){return(0,a.ZI)(`FindISAChildEntities failed for ${e.Name}: ${t}`),[]}}}async function C(e){const t=new f;return(0,a.YE)(t),await t.Config(e),await a.jF.Instance.Startup(),d.rt.Instance.RaiseEvent({event:d.UK.LoggedIn,eventCode:null,component:this,args:null}),t}p(C,"setupGraphQLClient");class ${static{p(this,"SyncRolesAndUsersResult")}}class v{static{p(this,"RoleInput")}}class A{static{p(this,"UserInput")}}class N{static{p(this,"RolesAndUsersInput")}}var b,x=((b=x||{}).Create="Create",b.Update="Update",b.CreateOrUpdate="CreateOrUpdate",b.Delete="Delete",b.DeleteWithFilter="DeleteWithFilter",b);class M{static{p(this,"ActionItemInput")}}class G{static{p(this,"SyncDataResult")}constructor(){this.Results=[]}}class Q{static{p(this,"ActionItemOutput")}}class L{static{p(this,"GraphQLSystemUserClient")}get Client(){return this._client}constructor(e,t,r,a){const n={"x-session-id":r};this._sessionId=r,t&&(n.authorization="Bearer "+t),a&&(n["x-mj-api-key"]=a),this._client=new s.l4(e,{headers:n})}async GetData(e,t){try{const r=await this.Client.request("query GetData($input: GetDataInputType!) {\n GetData(input: $input) {\n Success\n ErrorMessages\n Queries\n Results\n }\n }",{input:{Queries:e,Token:t}});return r&&r.GetData?{Success:r.GetData.Success,Results:r.GetData.Results.map(e=>e?(0,d.NG)(e):null),ErrorMessages:r.GetData.ErrorMessages,Queries:r.GetData.Queries}:{Success:!1,Results:[],ErrorMessages:r.GetData?.ErrorMessages??["Unknown error"],Queries:r.GetData?.Queries??e}}catch(t){let r=t instanceof Error?t.message:String(t);const s=r.match(/Error: ([^:]+)\./);if(s&&(r=s[1]+"."),(0,a.l9)()){const e=`GraphQLSystemUserClient::GetData - Error getting data - ${t}`;(0,a.ZI)(e)}return{Success:!1,Results:[],ErrorMessages:[r],Queries:e}}}async GetAllRemoteEntities(){try{const e=await this.Client.request("query GetAllEntities {\n GetAllEntities {\n Success\n ErrorMessage\n Results {\n ID\n Name\n Description\n SchemaName\n BaseView\n BaseTable\n CodeName\n ClassName\n Fields {\n ID\n Name\n Description\n Type\n AllowsNull\n MaxLength\n }\n }\n }\n }");return e&&e.GetAllEntities?e.GetAllEntities:{Success:!1,Results:[],ErrorMessage:e.GetAllEntities?.ErrorMessage??"Unknown error"}}catch(e){return(0,a.ZI)(`GraphQLSystemUserClient::GetAllRemoteEntities - Error getting remote entities - ${e}`),{Success:!1,Results:[],ErrorMessage:e}}}async SyncData(e){try{const t=await this.Client.request("mutation SyncData($items: [ActionItemInputType!]!) {\n SyncData(items: $items) {\n Success\n Results {\n Success\n ErrorMessage\n EntityName\n Type\n PrimaryKey {\n KeyValuePairs {\n FieldName\n Value \n }\n }\n AlternateKey {\n KeyValuePairs {\n FieldName\n Value \n }\n }\n DeleteFilter\n RecordJSON\n }\n }\n }",{items:e});return t&&t.SyncData?t.SyncData:{Success:!1,Results:[]}}catch(e){return(0,a.ZI)(`GraphQLSystemUserClient::SyncData - Error syncing data - ${e}`),{Success:!1,Results:[]}}}async SyncRolesAndUsers(e){try{const t=await this.Client.request("mutation SyncRolesAndUsers($data: RolesAndUsersInputType!) {\n SyncRolesAndUsers(data: $data) {\n Success\n }\n }",{data:e});return t&&t.SyncRolesAndUsers?t.SyncRolesAndUsers:{Success:!1}}catch(e){return(0,a.ZI)(`GraphQLSystemUserClient::SyncRolesAndUsers - Error syncing roles and users - ${e}`),{Success:!1}}}async RunViewByName(e){try{const t=await this.Client.request("query RunViewByNameSystemUser($input: RunViewByNameInput!) {\n RunViewByNameSystemUser(input: $input) {\n Results {\n PrimaryKey {\n FieldName\n Value\n }\n EntityID\n Data\n }\n UserViewRunID\n RowCount\n TotalRowCount\n ExecutionTime\n ErrorMessage\n Success\n }\n }",{input:e});return t&&t.RunViewByNameSystemUser?t.RunViewByNameSystemUser:{Results:[],Success:!1,ErrorMessage:"Failed to execute view by name"}}catch(e){return(0,a.ZI)(`GraphQLSystemUserClient::RunViewByNameSystemUser - Error running view by name - ${e}`),{Results:[],Success:!1,ErrorMessage:e.toString()}}}async RunViewByID(e){try{const t=await this.Client.request("query RunViewByIDSystemUser($input: RunViewByIDInput!) {\n RunViewByIDSystemUser(input: $input) {\n Results {\n PrimaryKey {\n FieldName\n Value\n }\n EntityID\n Data\n }\n UserViewRunID\n RowCount\n TotalRowCount\n ExecutionTime\n ErrorMessage\n Success\n }\n }",{input:e});return t&&t.RunViewByIDSystemUser?t.RunViewByIDSystemUser:{Results:[],Success:!1,ErrorMessage:"Failed to execute view by ID"}}catch(e){return(0,a.ZI)(`GraphQLSystemUserClient::RunViewByIDSystemUser - Error running view by ID - ${e}`),{Results:[],Success:!1,ErrorMessage:e.toString()}}}async RunDynamicView(e){try{const t=await this.Client.request("query RunDynamicViewSystemUser($input: RunDynamicViewInput!) {\n RunDynamicViewSystemUser(input: $input) {\n Results {\n PrimaryKey {\n FieldName\n Value\n }\n EntityID\n Data\n }\n UserViewRunID\n RowCount\n TotalRowCount\n ExecutionTime\n ErrorMessage\n Success\n }\n }",{input:e});return t&&t.RunDynamicViewSystemUser?t.RunDynamicViewSystemUser:{Results:[],Success:!1,ErrorMessage:"Failed to execute dynamic view"}}catch(e){return(0,a.ZI)(`GraphQLSystemUserClient::RunDynamicViewSystemUser - Error running dynamic view - ${e}`),{Results:[],Success:!1,ErrorMessage:e.toString()}}}async RunViews(e){try{const t=await this.Client.request("query RunViewsSystemUser($input: [RunViewGenericInput!]!) {\n RunViewsSystemUser(input: $input) {\n Results {\n PrimaryKey {\n FieldName\n Value\n }\n EntityID\n Data\n }\n UserViewRunID\n RowCount\n TotalRowCount\n ExecutionTime\n ErrorMessage\n Success\n }\n }",{input:e});return t&&t.RunViewsSystemUser?t.RunViewsSystemUser:[]}catch(e){return(0,a.ZI)(`GraphQLSystemUserClient::RunViewsSystemUser - Error running views - ${e}`),[]}}async GetQueryData(e){try{if(void 0!==e.Parameters&&Array.isArray(e.Parameters))throw new Error("Parameters must be a JSON object, not an array. Use {} for empty parameters instead of [].");const t="query GetQueryDataSystemUser($QueryID: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int) {\n GetQueryDataSystemUser(QueryID: $QueryID, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {\n QueryID\n QueryName\n Success\n Results\n RowCount\n TotalRowCount\n ExecutionTime\n ErrorMessage\n AppliedParameters\n }\n }",r={QueryID:e.QueryID};void 0!==e.CategoryID&&(r.CategoryID=e.CategoryID),void 0!==e.CategoryPath&&(r.CategoryPath=e.CategoryPath),void 0!==e.Parameters&&(r.Parameters=e.Parameters),void 0!==e.MaxRows&&(r.MaxRows=e.MaxRows),void 0!==e.StartRow&&(r.StartRow=e.StartRow);const s=await this.Client.request(t,r);return s&&s.GetQueryDataSystemUser?{...s.GetQueryDataSystemUser,Results:s.GetQueryDataSystemUser.Results?(0,d.NG)(s.GetQueryDataSystemUser.Results):null}:{QueryID:e.QueryID,QueryName:"",Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:"Query execution failed"}}catch(t){return(0,a.ZI)(`GraphQLSystemUserClient::GetQueryDataSystemUser - Error executing query - ${t}`),{QueryID:e.QueryID,QueryName:"",Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:t.toString()}}}async GetQueryDataByName(e){try{if(void 0!==e.Parameters&&Array.isArray(e.Parameters))throw new Error("Parameters must be a JSON object, not an array. Use {} for empty parameters instead of [].");const t="query GetQueryDataByNameSystemUser($QueryName: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int) {\n GetQueryDataByNameSystemUser(QueryName: $QueryName, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {\n QueryID\n QueryName\n Success\n Results\n RowCount\n TotalRowCount\n ExecutionTime\n ErrorMessage\n AppliedParameters\n }\n }",r={QueryName:e.QueryName};void 0!==e.CategoryID&&(r.CategoryID=e.CategoryID),void 0!==e.CategoryPath&&(r.CategoryPath=e.CategoryPath),void 0!==e.Parameters&&(r.Parameters=e.Parameters),void 0!==e.MaxRows&&(r.MaxRows=e.MaxRows),void 0!==e.StartRow&&(r.StartRow=e.StartRow);const s=await this.Client.request(t,r);return s&&s.GetQueryDataByNameSystemUser?{...s.GetQueryDataByNameSystemUser,Results:s.GetQueryDataByNameSystemUser.Results?(0,d.NG)(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(0,a.ZI)(`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=await this.Client.request("mutation CreateQuerySystemUser($input: CreateQuerySystemUserInput!) {\n CreateQuerySystemUser(input: $input) {\n Success\n ErrorMessage\n ID\n Name\n Description\n CategoryID\n Category\n SQL\n Status\n QualityRank\n EmbeddingVector\n EmbeddingModelID\n EmbeddingModelName\n Fields {\n ID\n QueryID\n Name\n Description\n Sequence\n SQLBaseType\n SQLFullType\n SourceEntityID\n SourceEntity\n SourceFieldName\n IsComputed\n ComputationDescription\n IsSummary\n SummaryDescription\n }\n Parameters {\n ID\n QueryID\n Name\n Description\n Type\n IsRequired\n DefaultValue\n SampleValue\n ValidationFilters\n }\n Entities {\n ID\n QueryID\n EntityID\n Entity\n }\n Permissions {\n ID\n QueryID\n RoleID\n Role\n }\n }\n }",{input:e});return t&&t.CreateQuerySystemUser?t.CreateQuerySystemUser:{Success:!1,ErrorMessage:"Failed to create query"}}catch(e){return(0,a.ZI)(`GraphQLSystemUserClient::CreateQuery - Error creating query - ${e}`),{Success:!1,ErrorMessage:e.toString()}}}async UpdateQuery(e){try{const t=await this.Client.request("mutation UpdateQuerySystemUser($input: UpdateQuerySystemUserInput!) {\n UpdateQuerySystemUser(input: $input) {\n Success\n ErrorMessage\n ID\n Name\n Description\n CategoryID\n Category\n SQL\n Status\n QualityRank\n EmbeddingVector\n EmbeddingModelID\n EmbeddingModelName\n Fields {\n ID\n QueryID\n Name\n Description\n Sequence\n SQLBaseType\n SQLFullType\n SourceEntityID\n SourceEntity\n SourceFieldName\n IsComputed\n ComputationDescription\n IsSummary\n SummaryDescription\n }\n Parameters {\n ID\n QueryID\n Name\n Description\n Type\n IsRequired\n DefaultValue\n SampleValue\n ValidationFilters\n }\n Entities {\n ID\n QueryID\n EntityID\n Entity\n }\n Permissions {\n ID\n QueryID\n RoleID\n Role\n }\n }\n }",{input:e});return t&&t.UpdateQuerySystemUser?t.UpdateQuerySystemUser:{Success:!1,ErrorMessage:"Failed to update query"}}catch(e){return(0,a.ZI)(`GraphQLSystemUserClient::UpdateQuery - Error updating query - ${e}`),{Success:!1,ErrorMessage:e.toString()}}}async DeleteQuery(e,t){try{if(!e||""===e.trim())return(0,a.ZI)("GraphQLSystemUserClient::DeleteQuery - Invalid query ID: ID cannot be null or empty"),{Success:!1,ErrorMessage:"Invalid query ID: ID cannot be null or empty"};const r="mutation DeleteQuerySystemResolver($ID: String!, $options: DeleteOptionsInput) {\n DeleteQuerySystemResolver(ID: $ID, options: $options) {\n Success\n ErrorMessage\n ID\n Name\n }\n }",s={ID:e};void 0!==t&&(s.options={SkipEntityAIActions:t.SkipEntityAIActions??!1,SkipEntityActions:t.SkipEntityActions??!1,ReplayOnly:t.ReplayOnly??!1,IsParentEntityDelete:t.IsParentEntityDelete??!1});const n=await this.Client.request(r,s);return n&&n.DeleteQuerySystemResolver?n.DeleteQuerySystemResolver:{Success:!1,ErrorMessage:"Failed to delete query"}}catch(e){let t="";if(e instanceof Error){if(t=e.message,"cause"in e&&e.cause){const r=e.cause;t+=` | Cause: ${r.message||r}`,"code"in r&&(t+=` | Code: ${r.code}`)}if("response"in e){const r=e.response;r?.status&&(t+=` | HTTP Status: ${r.status}`),r?.errors&&(t+=` | GraphQL Errors: ${JSON.stringify(r.errors)}`)}e.stack&&console.error("DeleteQuery stack trace:",e.stack)}else t=String(e);return(0,a.ZI)(`GraphQLSystemUserClient::DeleteQuery - Error deleting query - ${t}`),{Success:!1,ErrorMessage:t}}}async RunAIPrompt(e){try{const t=s.J1`
|
|
428
|
+
`,n=new i.B,c=this.getOrCreateWSClient(),l=new u.yU;return l.add(new o.c(t=>{const r=c.subscribe({query:a,variables:{sessionId:e}},{next:p(r=>{const s=this._pushStatusSubjects.get(e);s&&(s.lastEmissionAt=Date.now()),t.next(r.data.statusUpdates.message)},"next"),error:p(async e=>{const r=e;if("JWT_EXPIRED"===r?.extensions?.code||r?.message?.includes("token has expired")||r?.message?.includes("JWT_EXPIRED")){console.log("[GraphQLDataProvider] PushStatusUpdates JWT token expired, refreshing and reconnecting...");try{await this.RefreshToken(),this.disposeWSClient(),t.complete()}catch(e){console.error("[GraphQLDataProvider] Failed to refresh token for PushStatusUpdates:",e),t.error(e)}}else t.error(e)},"error"),complete:p(()=>{t.complete()},"complete")});return this._activeSubscriptionCount++,()=>{this._activeSubscriptionCount--,r()}}).subscribe({next:p(e=>n.next(e),"next"),error:p(t=>{n.error(t),this._pushStatusSubjects.delete(e)},"error"),complete:p(()=>{n.complete(),this._pushStatusSubjects.delete(e)},"complete")})),this._pushStatusSubjects.set(e,{subject:n,subscription:l,createdAt:t,lastRequestedAt:t,lastEmissionAt:t,activeSubscribers:0}),new o.c(t=>{const r=this._pushStatusSubjects.get(e);r&&r.activeSubscribers++;const s=n.subscribe(t);return()=>{const t=this._pushStatusSubjects.get(e);t&&t.activeSubscribers>0&&t.activeSubscribers--,s.unsubscribe()}})}disposeWebSocketResources(){this._subscriptionCleanupTimer&&(clearInterval(this._subscriptionCleanupTimer),this._subscriptionCleanupTimer=null),this.completeAllSubjects(),this._activeSubscriptionCount=0,this.disposeWSClient()}async FindISAChildEntity(e,t,r){if(!e.IsParentType)return null;try{const r=await this.ExecuteGQL("query FindISAChildEntity($EntityName: String!, $RecordID: String!) {\n FindISAChildEntity(EntityName: $EntityName, RecordID: $RecordID) {\n Success\n ChildEntityName\n ErrorMessage\n }\n }",{EntityName:e.Name,RecordID:t});return r?.FindISAChildEntity?.Success&&r.FindISAChildEntity.ChildEntityName?{ChildEntityName:r.FindISAChildEntity.ChildEntityName}:null}catch(t){return(0,a.ZI)(`FindISAChildEntity failed for ${e.Name}: ${t}`),null}}async FindISAChildEntities(e,t,r){if(!e.IsParentType)return[];try{const r=await this.ExecuteGQL("query FindISAChildEntities($EntityName: String!, $RecordID: String!) {\n FindISAChildEntities(EntityName: $EntityName, RecordID: $RecordID) {\n Success\n ChildEntityNames\n ErrorMessage\n }\n }",{EntityName:e.Name,RecordID:t});return r?.FindISAChildEntities?.Success&&r.FindISAChildEntities.ChildEntityNames?r.FindISAChildEntities.ChildEntityNames.map(e=>({ChildEntityName:e})):[]}catch(t){return(0,a.ZI)(`FindISAChildEntities failed for ${e.Name}: ${t}`),[]}}}async function C(e){const t=new f;return(0,a.YE)(t),await t.Config(e),await a.jF.Instance.Startup(),d.rt.Instance.RaiseEvent({event:d.UK.LoggedIn,eventCode:null,component:this,args:null}),t}p(C,"setupGraphQLClient");class ${static{p(this,"SyncRolesAndUsersResult")}}class v{static{p(this,"RoleInput")}}class A{static{p(this,"UserInput")}}class N{static{p(this,"RolesAndUsersInput")}}var b,x=((b=x||{}).Create="Create",b.Update="Update",b.CreateOrUpdate="CreateOrUpdate",b.Delete="Delete",b.DeleteWithFilter="DeleteWithFilter",b);class M{static{p(this,"ActionItemInput")}}class Q{static{p(this,"SyncDataResult")}constructor(){this.Results=[]}}class L{static{p(this,"ActionItemOutput")}}class G{static{p(this,"GraphQLSystemUserClient")}get Client(){return this._client}constructor(e,t,r,a){const n={"x-session-id":r};this._sessionId=r,t&&(n.authorization="Bearer "+t),a&&(n["x-mj-api-key"]=a),this._client=new s.l4(e,{headers:n})}async GetData(e,t){try{const r=await this.Client.request("query GetData($input: GetDataInputType!) {\n GetData(input: $input) {\n Success\n ErrorMessages\n Queries\n Results\n }\n }",{input:{Queries:e,Token:t}});return r&&r.GetData?{Success:r.GetData.Success,Results:r.GetData.Results.map(e=>e?(0,d.NG)(e):null),ErrorMessages:r.GetData.ErrorMessages,Queries:r.GetData.Queries}:{Success:!1,Results:[],ErrorMessages:r.GetData?.ErrorMessages??["Unknown error"],Queries:r.GetData?.Queries??e}}catch(t){let r=t instanceof Error?t.message:String(t);const s=r.match(/Error: ([^:]+)\./);if(s&&(r=s[1]+"."),(0,a.l9)()){const e=`GraphQLSystemUserClient::GetData - Error getting data - ${t}`;(0,a.ZI)(e)}return{Success:!1,Results:[],ErrorMessages:[r],Queries:e}}}async GetAllRemoteEntities(){try{const e=await this.Client.request("query GetAllEntities {\n GetAllEntities {\n Success\n ErrorMessage\n Results {\n ID\n Name\n Description\n SchemaName\n BaseView\n BaseTable\n CodeName\n ClassName\n Fields {\n ID\n Name\n Description\n Type\n AllowsNull\n MaxLength\n }\n }\n }\n }");return e&&e.GetAllEntities?e.GetAllEntities:{Success:!1,Results:[],ErrorMessage:e.GetAllEntities?.ErrorMessage??"Unknown error"}}catch(e){return(0,a.ZI)(`GraphQLSystemUserClient::GetAllRemoteEntities - Error getting remote entities - ${e}`),{Success:!1,Results:[],ErrorMessage:e}}}async SyncData(e){try{const t=await this.Client.request("mutation SyncData($items: [ActionItemInputType!]!) {\n SyncData(items: $items) {\n Success\n Results {\n Success\n ErrorMessage\n EntityName\n Type\n PrimaryKey {\n KeyValuePairs {\n FieldName\n Value \n }\n }\n AlternateKey {\n KeyValuePairs {\n FieldName\n Value \n }\n }\n DeleteFilter\n RecordJSON\n }\n }\n }",{items:e});return t&&t.SyncData?t.SyncData:{Success:!1,Results:[]}}catch(e){return(0,a.ZI)(`GraphQLSystemUserClient::SyncData - Error syncing data - ${e}`),{Success:!1,Results:[]}}}async SyncRolesAndUsers(e){try{const t=await this.Client.request("mutation SyncRolesAndUsers($data: RolesAndUsersInputType!) {\n SyncRolesAndUsers(data: $data) {\n Success\n }\n }",{data:e});return t&&t.SyncRolesAndUsers?t.SyncRolesAndUsers:{Success:!1}}catch(e){return(0,a.ZI)(`GraphQLSystemUserClient::SyncRolesAndUsers - Error syncing roles and users - ${e}`),{Success:!1}}}async RunViewByName(e){try{const t=await this.Client.request("query RunViewByNameSystemUser($input: RunViewByNameInput!) {\n RunViewByNameSystemUser(input: $input) {\n Results {\n PrimaryKey {\n FieldName\n Value\n }\n EntityID\n Data\n }\n UserViewRunID\n RowCount\n TotalRowCount\n ExecutionTime\n ErrorMessage\n Success\n }\n }",{input:e});return t&&t.RunViewByNameSystemUser?t.RunViewByNameSystemUser:{Results:[],Success:!1,ErrorMessage:"Failed to execute view by name"}}catch(e){return(0,a.ZI)(`GraphQLSystemUserClient::RunViewByNameSystemUser - Error running view by name - ${e}`),{Results:[],Success:!1,ErrorMessage:e.toString()}}}async RunViewByID(e){try{const t=await this.Client.request("query RunViewByIDSystemUser($input: RunViewByIDInput!) {\n RunViewByIDSystemUser(input: $input) {\n Results {\n PrimaryKey {\n FieldName\n Value\n }\n EntityID\n Data\n }\n UserViewRunID\n RowCount\n TotalRowCount\n ExecutionTime\n ErrorMessage\n Success\n }\n }",{input:e});return t&&t.RunViewByIDSystemUser?t.RunViewByIDSystemUser:{Results:[],Success:!1,ErrorMessage:"Failed to execute view by ID"}}catch(e){return(0,a.ZI)(`GraphQLSystemUserClient::RunViewByIDSystemUser - Error running view by ID - ${e}`),{Results:[],Success:!1,ErrorMessage:e.toString()}}}async RunDynamicView(e){try{const t=await this.Client.request("query RunDynamicViewSystemUser($input: RunDynamicViewInput!) {\n RunDynamicViewSystemUser(input: $input) {\n Results {\n PrimaryKey {\n FieldName\n Value\n }\n EntityID\n Data\n }\n UserViewRunID\n RowCount\n TotalRowCount\n ExecutionTime\n ErrorMessage\n Success\n }\n }",{input:e});return t&&t.RunDynamicViewSystemUser?t.RunDynamicViewSystemUser:{Results:[],Success:!1,ErrorMessage:"Failed to execute dynamic view"}}catch(e){return(0,a.ZI)(`GraphQLSystemUserClient::RunDynamicViewSystemUser - Error running dynamic view - ${e}`),{Results:[],Success:!1,ErrorMessage:e.toString()}}}async RunViews(e){try{const t=await this.Client.request("query RunViewsSystemUser($input: [RunViewGenericInput!]!) {\n RunViewsSystemUser(input: $input) {\n Results {\n PrimaryKey {\n FieldName\n Value\n }\n EntityID\n Data\n }\n UserViewRunID\n RowCount\n TotalRowCount\n ExecutionTime\n ErrorMessage\n Success\n }\n }",{input:e});return t&&t.RunViewsSystemUser?t.RunViewsSystemUser:[]}catch(e){return(0,a.ZI)(`GraphQLSystemUserClient::RunViewsSystemUser - Error running views - ${e}`),[]}}async GetQueryData(e){try{if(void 0!==e.Parameters&&Array.isArray(e.Parameters))throw new Error("Parameters must be a JSON object, not an array. Use {} for empty parameters instead of [].");const t="query GetQueryDataSystemUser($QueryID: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int) {\n GetQueryDataSystemUser(QueryID: $QueryID, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {\n QueryID\n QueryName\n Success\n Results\n RowCount\n TotalRowCount\n ExecutionTime\n ErrorMessage\n AppliedParameters\n }\n }",r={QueryID:e.QueryID};void 0!==e.CategoryID&&(r.CategoryID=e.CategoryID),void 0!==e.CategoryPath&&(r.CategoryPath=e.CategoryPath),void 0!==e.Parameters&&(r.Parameters=e.Parameters),void 0!==e.MaxRows&&(r.MaxRows=e.MaxRows),void 0!==e.StartRow&&(r.StartRow=e.StartRow);const s=await this.Client.request(t,r);return s&&s.GetQueryDataSystemUser?{...s.GetQueryDataSystemUser,Results:s.GetQueryDataSystemUser.Results?(0,d.NG)(s.GetQueryDataSystemUser.Results):null}:{QueryID:e.QueryID,QueryName:"",Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:"Query execution failed"}}catch(t){return(0,a.ZI)(`GraphQLSystemUserClient::GetQueryDataSystemUser - Error executing query - ${t}`),{QueryID:e.QueryID,QueryName:"",Success:!1,Results:null,RowCount:0,TotalRowCount:0,ExecutionTime:0,ErrorMessage:t.toString()}}}async GetQueryDataByName(e){try{if(void 0!==e.Parameters&&Array.isArray(e.Parameters))throw new Error("Parameters must be a JSON object, not an array. Use {} for empty parameters instead of [].");const t="query GetQueryDataByNameSystemUser($QueryName: String!, $CategoryID: String, $CategoryPath: String, $Parameters: JSONObject, $MaxRows: Int, $StartRow: Int) {\n GetQueryDataByNameSystemUser(QueryName: $QueryName, CategoryID: $CategoryID, CategoryPath: $CategoryPath, Parameters: $Parameters, MaxRows: $MaxRows, StartRow: $StartRow) {\n QueryID\n QueryName\n Success\n Results\n RowCount\n TotalRowCount\n ExecutionTime\n ErrorMessage\n AppliedParameters\n }\n }",r={QueryName:e.QueryName};void 0!==e.CategoryID&&(r.CategoryID=e.CategoryID),void 0!==e.CategoryPath&&(r.CategoryPath=e.CategoryPath),void 0!==e.Parameters&&(r.Parameters=e.Parameters),void 0!==e.MaxRows&&(r.MaxRows=e.MaxRows),void 0!==e.StartRow&&(r.StartRow=e.StartRow);const s=await this.Client.request(t,r);return s&&s.GetQueryDataByNameSystemUser?{...s.GetQueryDataByNameSystemUser,Results:s.GetQueryDataByNameSystemUser.Results?(0,d.NG)(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(0,a.ZI)(`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=await this.Client.request("mutation CreateQuerySystemUser($input: CreateQuerySystemUserInput!) {\n CreateQuerySystemUser(input: $input) {\n Success\n ErrorMessage\n ID\n Name\n Description\n CategoryID\n Category\n SQL\n Status\n QualityRank\n EmbeddingVector\n EmbeddingModelID\n EmbeddingModelName\n Fields {\n ID\n QueryID\n Name\n Description\n Sequence\n SQLBaseType\n SQLFullType\n SourceEntityID\n SourceEntity\n SourceFieldName\n IsComputed\n ComputationDescription\n IsSummary\n SummaryDescription\n }\n Parameters {\n ID\n QueryID\n Name\n Description\n Type\n IsRequired\n DefaultValue\n SampleValue\n ValidationFilters\n }\n Entities {\n ID\n QueryID\n EntityID\n Entity\n }\n Permissions {\n ID\n QueryID\n RoleID\n Role\n }\n }\n }",{input:e});return t&&t.CreateQuerySystemUser?t.CreateQuerySystemUser:{Success:!1,ErrorMessage:"Failed to create query"}}catch(e){return(0,a.ZI)(`GraphQLSystemUserClient::CreateQuery - Error creating query - ${e}`),{Success:!1,ErrorMessage:e.toString()}}}async UpdateQuery(e){try{const t=await this.Client.request("mutation UpdateQuerySystemUser($input: UpdateQuerySystemUserInput!) {\n UpdateQuerySystemUser(input: $input) {\n Success\n ErrorMessage\n ID\n Name\n Description\n CategoryID\n Category\n SQL\n Status\n QualityRank\n EmbeddingVector\n EmbeddingModelID\n EmbeddingModelName\n Fields {\n ID\n QueryID\n Name\n Description\n Sequence\n SQLBaseType\n SQLFullType\n SourceEntityID\n SourceEntity\n SourceFieldName\n IsComputed\n ComputationDescription\n IsSummary\n SummaryDescription\n }\n Parameters {\n ID\n QueryID\n Name\n Description\n Type\n IsRequired\n DefaultValue\n SampleValue\n ValidationFilters\n }\n Entities {\n ID\n QueryID\n EntityID\n Entity\n }\n Permissions {\n ID\n QueryID\n RoleID\n Role\n }\n }\n }",{input:e});return t&&t.UpdateQuerySystemUser?t.UpdateQuerySystemUser:{Success:!1,ErrorMessage:"Failed to update query"}}catch(e){return(0,a.ZI)(`GraphQLSystemUserClient::UpdateQuery - Error updating query - ${e}`),{Success:!1,ErrorMessage:e.toString()}}}async DeleteQuery(e,t){try{if(!e||""===e.trim())return(0,a.ZI)("GraphQLSystemUserClient::DeleteQuery - Invalid query ID: ID cannot be null or empty"),{Success:!1,ErrorMessage:"Invalid query ID: ID cannot be null or empty"};const r="mutation DeleteQuerySystemResolver($ID: String!, $options: DeleteOptionsInput) {\n DeleteQuerySystemResolver(ID: $ID, options: $options) {\n Success\n ErrorMessage\n ID\n Name\n }\n }",s={ID:e};void 0!==t&&(s.options={SkipEntityAIActions:t.SkipEntityAIActions??!1,SkipEntityActions:t.SkipEntityActions??!1,ReplayOnly:t.ReplayOnly??!1,IsParentEntityDelete:t.IsParentEntityDelete??!1});const n=await this.Client.request(r,s);return n&&n.DeleteQuerySystemResolver?n.DeleteQuerySystemResolver:{Success:!1,ErrorMessage:"Failed to delete query"}}catch(e){let t="";if(e instanceof Error){if(t=e.message,"cause"in e&&e.cause){const r=e.cause;t+=` | Cause: ${r.message||r}`,"code"in r&&(t+=` | Code: ${r.code}`)}if("response"in e){const r=e.response;r?.status&&(t+=` | HTTP Status: ${r.status}`),r?.errors&&(t+=` | GraphQL Errors: ${JSON.stringify(r.errors)}`)}e.stack&&console.error("DeleteQuery stack trace:",e.stack)}else t=String(e);return(0,a.ZI)(`GraphQLSystemUserClient::DeleteQuery - Error deleting query - ${t}`),{Success:!1,ErrorMessage:t}}}async RunAIPrompt(e){try{const t=s.J1`
|
|
423
429
|
query RunAIPromptSystemUser(
|
|
424
430
|
$promptId: String!,
|
|
425
431
|
$data: String,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"component-manager.js","sourceRoot":"","sources":["../../src/component-manager/component-manager.ts"],"names":[],"mappings":"AAMA,OAAO,EAAY,QAAQ,EAAE,QAAQ,EAAE,MAAM,sBAAsB,CAAC;AACpE,OAAO,EAAE,uBAAuB,EAAqD,MAAM,+BAA+B,CAAC;AAkB3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,EAAE,CAAC,CAAC;IAC3B,CAAC;IAKO,eAAe,CAAC,IAAmB,EAAE,OAAoB;QAC/D,MAAM,QAAQ,GAAG,IAAI,CAAC,QAAQ,IAAI,OAAO,CAAC;QAC1C,MAAM,SAAS,GAAG,IAAI,CAAC,SAAS,IAAI,OAAO,CAAC,gBAAgB,IAAI,QAAQ,CAAC;QACzE,MAAM,OAAO,GAAG,IAAI,CAAC,OAAO,IAAI,OAAO,CAAC,cAAc,IAAI,QAAQ,CAAC;QACnE,OAAO,GAAG,QAAQ,IAAI,SAAS,IAAI,IAAI,CAAC,IAAI,IAAI,OAAO,EAAE,CAAC;IAC5D,CAAC;IAKD,UAAU;QACR,IAAI,CAAC,UAAU,CAAC,KAAK,EAAE,CAAC;QACxB,IAAI,CAAC,qBAAqB,CAAC,KAAK,EAAE,CAAC;QACnC,IAAI,CAAC,eAAe,CAAC,KAAK,EAAE,CAAC;QAC7B,IAAI,CAAC,GAAG,CAAC,oBAAoB,CAAC,CAAC;IACjC,CAAC;IAKD,aAAa;QAKX,OAAO;YACL,cAAc,EAAE,IAAI,CAAC,UAAU,CAAC,IAAI;YACpC,kBAAkB,EAAE,IAAI,CAAC,qBAAqB,CAAC,IAAI;YACnD,YAAY,EAAE,IAAI,CAAC,eAAe,CAAC,IAAI;SACxC,CAAC;IACJ,CAAC;IAKO,GAAG,CAAC,OAAe,EAAE,IAAU;QACrC,IAAI,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC;YACtB,OAAO,CAAC,GAAG,CAAC,yBAAyB,OAAO,EAAE,EAAE,IAAI,IAAI,EAAE,CAAC,CAAC;QAC9D,CAAC;IACH,CAAC;CACF","sourcesContent":["/**\n * @fileoverview Unified Component Manager implementation\n * Handles all component operations efficiently with proper caching and registry tracking\n */\n\nimport { ComponentSpec, ComponentLibraryDependency } from '@memberjunction/interactive-component-types';\nimport { UserInfo, Metadata, LogError } from '@memberjunction/core';\nimport { ComponentMetadataEngine, MJComponentLibraryEntity, ComponentEntityExtended } from '@memberjunction/core-entities';\n\nimport { ComponentCompiler } from '../compiler';\nimport { ComponentRegistry } from '../registry';\nimport { RuntimeContext, ComponentObject } from '../types';\nimport {\n LoadOptions,\n LoadResult,\n HierarchyResult,\n ComponentManagerConfig,\n CacheEntry,\n ResolutionMode\n} from './types';\n\n/**\n * Unified component management system that handles all component operations\n * efficiently with proper caching and registry tracking.\n */\nexport class ComponentManager {\n private compiler: ComponentCompiler;\n private registry: ComponentRegistry;\n private runtimeContext: RuntimeContext;\n private config: ComponentManagerConfig;\n \n // Caching\n private fetchCache: Map<string, CacheEntry> = new Map();\n private registryNotifications: Set<string> = new Set();\n private loadingPromises: Map<string, Promise<LoadResult>> = new Map();\n \n // Metadata engine\n private componentEngine = ComponentMetadataEngine.Instance;\n private graphQLClient: any = null;\n \n constructor(\n compiler: ComponentCompiler,\n registry: ComponentRegistry,\n runtimeContext: RuntimeContext,\n config: ComponentManagerConfig = {}\n ) {\n this.compiler = compiler;\n this.registry = registry;\n this.runtimeContext = runtimeContext;\n this.config = {\n debug: false,\n maxCacheSize: 100,\n cacheTTL: 3600000, // 1 hour\n enableUsageTracking: true,\n dependencyBatchSize: 5,\n fetchTimeout: 30000,\n ...config\n };\n \n this.log('ComponentManager initialized', {\n debug: this.config.debug,\n cacheTTL: this.config.cacheTTL,\n usageTracking: this.config.enableUsageTracking\n });\n }\n \n /**\n * Main entry point - intelligently handles all component operations\n */\n async loadComponent(\n spec: ComponentSpec,\n options: LoadOptions = {}\n ): Promise<LoadResult> {\n const startTime = Date.now();\n const componentKey = this.getComponentKey(spec, options);\n \n this.log(`Loading component: ${spec.name}`, { \n key: componentKey, \n location: spec.location,\n registry: spec.registry,\n forceRefresh: options.forceRefresh \n });\n \n // Check if already loading to prevent duplicate work\n const existingPromise = this.loadingPromises.get(componentKey);\n if (existingPromise && !options.forceRefresh) {\n this.log(`Component already loading: ${spec.name}, waiting...`);\n return existingPromise;\n }\n \n // Create loading promise\n const loadPromise = this.doLoadComponent(spec, options, componentKey, startTime);\n this.loadingPromises.set(componentKey, loadPromise);\n \n try {\n const result = await loadPromise;\n return result;\n } finally {\n this.loadingPromises.delete(componentKey);\n }\n }\n \n /**\n * Internal method that does the actual loading\n */\n private async doLoadComponent(\n spec: ComponentSpec,\n options: LoadOptions,\n componentKey: string,\n startTime: number\n ): Promise<LoadResult> {\n const errors: LoadResult['errors'] = [];\n \n try {\n // STEP 1: Check if already loaded in ComponentRegistry\n const namespace = spec.namespace || options.defaultNamespace || 'Global';\n const version = spec.version || options.defaultVersion || 'latest';\n \n const existing = this.registry.get(spec.name, namespace, version);\n if (existing && !options.forceRefresh && !options.forceRecompile) {\n this.log(`Component found in registry: ${spec.name}`);\n \n // Still need to notify registry for usage tracking\n if (options.trackUsage !== false) {\n await this.notifyRegistryUsageIfNeeded(spec, componentKey);\n }\n \n // Get cached spec if available\n const cachedEntry = this.fetchCache.get(componentKey);\n \n return {\n success: true,\n component: existing,\n spec: cachedEntry?.spec || spec,\n fromCache: true\n };\n }\n \n // STEP 2: Fetch full spec if needed\n let fullSpec = spec;\n if (this.needsFetch(spec)) {\n this.log(`Fetching component spec: ${spec.name}`);\n try {\n fullSpec = await this.fetchComponentSpec(spec, options.contextUser, {\n resolutionMode: options.resolutionMode\n });\n\n // Cache the fetched spec\n this.fetchCache.set(componentKey, {\n spec: fullSpec,\n fetchedAt: new Date(),\n hash: await this.calculateHash(fullSpec),\n usageNotified: false\n });\n } catch (error) {\n errors.push({\n message: `Failed to fetch component: ${error instanceof Error ? error.message : String(error)}`,\n phase: 'fetch',\n componentName: spec.name\n });\n throw error;\n }\n } else {\n // Log when we skip fetching because code is already provided\n if (spec.location === 'registry' && spec.code) {\n this.log(`Skipping fetch for registry component: ${spec.name} (code already provided)`, {\n location: spec.location,\n registry: spec.registry\n });\n }\n // Also cache the spec if it has code to avoid re-fetching\n if (spec.code && !this.fetchCache.has(componentKey)) {\n this.fetchCache.set(componentKey, {\n spec: fullSpec,\n fetchedAt: new Date(),\n hash: await this.calculateHash(fullSpec),\n usageNotified: false\n });\n }\n }\n \n // STEP 3: Notify registry of usage (exactly once per session)\n if (options.trackUsage !== false) {\n await this.notifyRegistryUsageIfNeeded(fullSpec, componentKey);\n }\n \n // STEP 4: Compile if needed\n let compiledComponent = existing;\n if (!compiledComponent || options.forceRecompile) {\n this.log(`Compiling component: ${spec.name}`);\n try {\n compiledComponent = await this.compileComponent(fullSpec, options);\n } catch (error) {\n errors.push({\n message: `Failed to compile component: ${error instanceof Error ? error.message : String(error)}`,\n phase: 'compile',\n componentName: spec.name\n });\n throw error;\n }\n }\n \n // STEP 5: Register in ComponentRegistry\n if (!existing || options.forceRefresh || options.forceRecompile) {\n this.log(`Registering component: ${spec.name}`);\n this.registry.register(\n fullSpec.name,\n compiledComponent,\n namespace,\n version\n );\n }\n \n // STEP 6: Process dependencies recursively\n const dependencies: Record<string, ComponentObject> = {};\n if (fullSpec.dependencies && fullSpec.dependencies.length > 0) {\n this.log(`Loading ${fullSpec.dependencies.length} dependencies for ${spec.name}`);\n \n // Load dependencies in batches for efficiency\n const depResults = await this.loadDependenciesBatched(\n fullSpec.dependencies,\n { ...options, isDependent: true }\n );\n \n for (const result of depResults) {\n if (result.success && result.component) {\n const depSpec = fullSpec.dependencies.find(d => \n d.name === (result.spec?.name || '')\n );\n if (depSpec) {\n dependencies[depSpec.name] = result.component;\n }\n } else if (result.errors) {\n errors.push(...result.errors);\n }\n }\n }\n \n const elapsed = Date.now() - startTime;\n this.log(`Component loaded successfully: ${spec.name} (${elapsed}ms)`, {\n fromCache: false,\n dependencyCount: Object.keys(dependencies).length\n });\n \n return {\n success: errors.length === 0,\n component: compiledComponent,\n spec: fullSpec,\n fromCache: false,\n dependencies,\n errors: errors.length > 0 ? errors : undefined\n };\n \n } catch (error) {\n const elapsed = Date.now() - startTime;\n this.log(`Failed to load component: ${spec.name} (${elapsed}ms)`, error);\n \n return {\n success: false,\n fromCache: false,\n errors: errors.length > 0 ? errors : [{\n message: error instanceof Error ? error.message : String(error),\n phase: 'fetch',\n componentName: spec.name\n }]\n };\n }\n }\n \n /**\n * Load a complete hierarchy efficiently\n */\n async loadHierarchy(\n rootSpec: ComponentSpec,\n options: LoadOptions = {}\n ): Promise<HierarchyResult> {\n const startTime = Date.now();\n const loaded: string[] = [];\n const errors: HierarchyResult['errors'] = [];\n const components: Record<string, ComponentObject> = {};\n const stats = {\n fromCache: 0,\n fetched: 0,\n compiled: 0,\n totalTime: 0\n };\n \n this.log(`Loading component hierarchy: ${rootSpec.name}`, {\n location: rootSpec.location,\n registry: rootSpec.registry\n });\n \n try {\n // Initialize component engine if needed (skip in browser context where it doesn't exist)\n if (this.componentEngine && typeof this.componentEngine.Config === 'function') {\n await this.componentEngine.Config(false, options.contextUser);\n }\n \n // Load the root component and all its dependencies\n const result = await this.loadComponentRecursive(\n rootSpec,\n options,\n loaded,\n errors,\n components,\n stats,\n new Set()\n );\n \n stats.totalTime = Date.now() - startTime;\n \n this.log(`Hierarchy loaded: ${rootSpec.name}`, {\n success: errors.length === 0,\n loadedCount: loaded.length,\n errors: errors.length,\n ...stats\n });\n \n // Unwrap components before returning\n // Components are ComponentObject wrappers, but consumers expect just the React components\n const unwrappedComponents: Record<string, ComponentObject> = {};\n for (const [name, componentObject] of Object.entries(components)) {\n if (componentObject && typeof componentObject === 'object' && 'component' in componentObject) {\n // Extract the actual React component function\n unwrappedComponents[name] = (componentObject as any).component;\n } else {\n // Already a function or something else - use as-is\n unwrappedComponents[name] = componentObject;\n }\n }\n \n return {\n success: errors.length === 0,\n rootComponent: result.component,\n resolvedSpec: result.spec,\n loadedComponents: loaded,\n errors,\n components: unwrappedComponents,\n stats\n };\n \n } catch (error) {\n stats.totalTime = Date.now() - startTime;\n \n this.log(`Failed to load hierarchy: ${rootSpec.name}`, error);\n \n return {\n success: false,\n loadedComponents: loaded,\n errors: [...errors, {\n message: error instanceof Error ? error.message : String(error),\n phase: 'fetch',\n componentName: rootSpec.name\n }],\n stats\n };\n }\n }\n \n /**\n * Recursively load a component and its dependencies\n */\n private async loadComponentRecursive(\n spec: ComponentSpec,\n options: LoadOptions,\n loaded: string[],\n errors: HierarchyResult['errors'],\n components: Record<string, ComponentObject>,\n stats: HierarchyResult['stats'],\n visited: Set<string>\n ): Promise<LoadResult> {\n const componentKey = this.getComponentKey(spec, options);\n \n // Prevent circular dependencies\n if (visited.has(componentKey)) {\n this.log(`Circular dependency detected: ${spec.name}`);\n return {\n success: true,\n component: components[spec.name],\n spec,\n fromCache: true\n };\n }\n visited.add(componentKey);\n \n // Load this component\n const result = await this.loadComponent(spec, options);\n \n if (result.success && result.component) {\n loaded.push(spec.name);\n components[spec.name] = result.component;\n \n // Update stats\n if (stats) {\n if (result.fromCache) stats.fromCache++;\n else {\n stats.fetched++;\n stats.compiled++;\n }\n }\n \n // Load dependencies\n if (result.spec?.dependencies) {\n for (const dep of result.spec.dependencies) {\n // Normalize dependency spec for local registry lookup\n const depSpec = { ...dep };\n // OPTIMIZATION: If the dependency already has code (from registry population),\n // we can skip fetching and go straight to compilation\n if (depSpec.code) {\n this.log(`Dependency ${depSpec.name} already has code (from registry population), optimizing load`);\n }\n\n // If location is \"registry\" with undefined registry, ensure it's treated as local\n // This follows the convention that registry components with undefined registry\n // should be looked up in the local ComponentMetadataEngine\n if (depSpec.location === 'registry' && !depSpec.registry) {\n // Explicitly set to undefined for clarity (it may already be undefined)\n depSpec.registry = undefined;\n\n // Log for debugging\n this.log(`Dependency ${depSpec.name} is a local registry component (registry=undefined)`);\n }\n\n await this.loadComponentRecursive(\n depSpec,\n { ...options, isDependent: true },\n loaded,\n errors,\n components,\n stats,\n visited\n );\n }\n }\n } else if (result.errors) {\n errors.push(...result.errors);\n }\n \n return result;\n }\n \n /**\n * Load dependencies in batches for efficiency\n */\n private async loadDependenciesBatched(\n dependencies: ComponentSpec[],\n options: LoadOptions\n ): Promise<LoadResult[]> {\n const batchSize = this.config.dependencyBatchSize || 5;\n const results: LoadResult[] = [];\n \n for (let i = 0; i < dependencies.length; i += batchSize) {\n const batch = dependencies.slice(i, i + batchSize);\n const batchPromises = batch.map(dep => this.loadComponent(dep, options));\n const batchResults = await Promise.all(batchPromises);\n results.push(...batchResults);\n }\n \n return results;\n }\n \n /**\n * Check if a component needs to be fetched from a registry\n */\n private needsFetch(spec: ComponentSpec): boolean {\n // Need to fetch if:\n // 1. It's a registry component without code\n // 2. It's missing required fields\n return spec.location === 'registry' && !spec.code;\n }\n \n /**\n * Fetch a component specification from a registry (local or external)\n * \n * Convention: When location === 'registry' and registry === undefined,\n * the component is looked up in the local ComponentMetadataEngine.\n * This allows components to reference local registry components without\n * having to know if they're embedded or registry-based.\n */\n private async fetchComponentSpec(\n spec: ComponentSpec,\n contextUser?: UserInfo,\n options?: { resolutionMode?: ResolutionMode }\n ): Promise<ComponentSpec> {\n // Check cache first\n const cacheKey = this.getComponentKey(spec, {});\n const cached = this.fetchCache.get(cacheKey);\n \n if (cached && this.isCacheValid(cached)) {\n this.log(`Using cached spec for: ${spec.name}`);\n return cached.spec;\n }\n \n // Handle LOCAL registry components (registry is null/undefined)\n if (!spec.registry) {\n this.log(`Fetching from local registry: ${spec.name}`);\n \n // Find component in local ComponentMetadataEngine\n const localComponent = this.componentEngine.Components?.find(\n (c: ComponentEntityExtended) => {\n // Match by name (case-insensitive for better compatibility)\n const nameMatch = c.Name?.toLowerCase() === spec.name?.toLowerCase();\n \n // Match by namespace if provided (handle different formats)\n const namespaceMatch = !spec.namespace || c.Namespace?.toLowerCase() === spec.namespace?.toLowerCase();\n\n if (nameMatch && !namespaceMatch) {\n }\n \n return nameMatch && namespaceMatch;\n }\n );\n \n if (!localComponent) {\n throw new Error(`Local component not found: ${spec.name}`);\n }\n \n // Parse specification from local component\n if (!localComponent.Specification) {\n throw new Error(`Local component ${spec.name} has no specification`);\n }\n \n const fullSpec = JSON.parse(localComponent.Specification);\n \n // Cache it\n this.fetchCache.set(cacheKey, {\n spec: fullSpec,\n fetchedAt: new Date(),\n usageNotified: false\n });\n \n return fullSpec;\n }\n \n // Handle EXTERNAL registry components (registry has a name)\n // Initialize GraphQL client if needed\n if (!this.graphQLClient) {\n await this.initializeGraphQLClient();\n }\n \n if (!this.graphQLClient) {\n throw new Error('GraphQL client not available for registry fetching');\n }\n \n // Fetch from external registry\n this.log(`Fetching from external registry: ${spec.registry}/${spec.name}`);\n \n const fullSpec = await this.graphQLClient.GetRegistryComponent({\n registryName: spec.registry,\n namespace: spec.namespace || 'Global',\n name: spec.name,\n version: spec.version || 'latest'\n });\n \n if (!fullSpec) {\n throw new Error(`Component not found in registry: ${spec.registry}/${spec.name}`);\n }\n \n // Apply resolution mode if specified\n const processedSpec = this.applyResolutionMode(fullSpec, spec, options?.resolutionMode);\n \n // Cache it\n this.fetchCache.set(cacheKey, {\n spec: processedSpec,\n fetchedAt: new Date(),\n usageNotified: false\n });\n \n return processedSpec;\n }\n \n /**\n * Apply resolution mode to a fetched spec (recursively including dependencies)\n */\n private applyResolutionMode(\n fullSpec: ComponentSpec,\n originalSpec: ComponentSpec,\n resolutionMode?: ResolutionMode\n ): ComponentSpec {\n let processedSpec: ComponentSpec;\n \n if (resolutionMode === 'embed') {\n // Convert to embedded format for test harness\n processedSpec = {\n ...fullSpec,\n location: 'embedded',\n registry: undefined,\n // namespace and name can stay for identification\n };\n } else {\n // Default: preserve-metadata mode\n // Keep original registry metadata but include fetched code\n processedSpec = {\n ...fullSpec,\n location: originalSpec.location,\n registry: originalSpec.registry,\n namespace: originalSpec.namespace || fullSpec.namespace,\n name: originalSpec.name || fullSpec.name\n };\n }\n \n // Recursively apply resolution mode to dependencies\n if (processedSpec.dependencies && processedSpec.dependencies.length > 0) {\n processedSpec.dependencies = processedSpec.dependencies.map(dep => {\n // For dependencies, use the dep itself as both full and original spec\n // since they've already been fetched and processed\n return this.applyResolutionMode(dep, dep, resolutionMode);\n });\n }\n \n return processedSpec;\n }\n\n /**\n * Compile a component specification\n */\n private async compileComponent(\n spec: ComponentSpec,\n options: LoadOptions\n ): Promise<ComponentObject> {\n // Get all available libraries - use passed libraries or fall back to ComponentMetadataEngine\n const allLibraries = options.allLibraries || this.componentEngine.ComponentLibraries || [];\n \n // Filter valid libraries\n const validLibraries = spec.libraries?.filter(lib => \n lib && lib.name && lib.globalVariable && \n lib.name !== 'unknown' && lib.globalVariable !== 'undefined'\n );\n \n // Compile the component\n const result = await this.compiler.compile({\n componentName: spec.name,\n componentCode: spec.code || '',\n libraries: validLibraries,\n dependencies: spec.dependencies,\n allLibraries\n });\n \n if (!result.success || !result.component) {\n throw new Error(result.error?.message || 'Compilation failed');\n }\n \n // Add loaded libraries to runtime context\n if (result.loadedLibraries && result.loadedLibraries.size > 0) {\n if (!this.runtimeContext.libraries) {\n this.runtimeContext.libraries = {};\n }\n result.loadedLibraries.forEach((value, key) => {\n this.runtimeContext.libraries![key] = value;\n });\n }\n \n // Get the component object from the factory\n const componentObject = result.component.factory(\n this.runtimeContext,\n undefined, // styles\n {} // components - will be injected by parent\n );\n \n return componentObject;\n }\n \n /**\n * Notify registry of component usage for licensing\n * Only happens once per component per session\n */\n private async notifyRegistryUsageIfNeeded(\n spec: ComponentSpec,\n componentKey: string\n ): Promise<void> {\n if (!spec.registry || !this.config.enableUsageTracking) {\n return; // Only for external registry components with tracking enabled\n }\n \n const notificationKey = `${spec.registry}:${componentKey}`;\n if (this.registryNotifications.has(notificationKey)) {\n this.log(`Usage already notified for: ${spec.name}`);\n return; // Already notified this session\n }\n \n try {\n // In the future, make lightweight usage notification call to registry\n // For now, the fetch itself serves as the notification\n this.log(`Notifying registry usage for: ${spec.name}`);\n this.registryNotifications.add(notificationKey);\n \n // Update cache entry\n const cached = this.fetchCache.get(componentKey);\n if (cached) {\n cached.usageNotified = true;\n }\n } catch (error) {\n // Log but don't fail - usage tracking shouldn't break component loading\n console.warn(`Failed to notify registry usage for ${componentKey}:`, error);\n }\n }\n \n /**\n * Initialize GraphQL client for registry operations\n */\n private async initializeGraphQLClient(): Promise<void> {\n try {\n const provider = Metadata?.Provider;\n if (provider && (provider as any).ExecuteGQL) {\n const { GraphQLComponentRegistryClient } = await import('@memberjunction/graphql-dataprovider');\n this.graphQLClient = new GraphQLComponentRegistryClient(provider as any);\n this.log('GraphQL client initialized');\n }\n } catch (error) {\n LogError(`Failed to initialize GraphQL client: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n \n /**\n * Check if a cache entry is still valid\n */\n private isCacheValid(entry: CacheEntry): boolean {\n const age = Date.now() - entry.fetchedAt.getTime();\n return age < (this.config.cacheTTL || 3600000);\n }\n \n /**\n * Calculate a hash for a component spec (for cache validation)\n */\n private async calculateHash(spec: ComponentSpec): Promise<string> {\n // Simple hash based on spec content\n const content = JSON.stringify({\n name: spec.name,\n version: spec.version,\n code: spec.code,\n libraries: spec.libraries\n });\n \n // Simple hash function (in production, use crypto)\n let hash = 0;\n for (let i = 0; i < content.length; i++) {\n const char = content.charCodeAt(i);\n hash = ((hash << 5) - hash) + char;\n hash = hash & hash; // Convert to 32bit integer\n }\n return hash.toString(16);\n }\n \n /**\n * Generate a unique key for a component\n */\n private getComponentKey(spec: ComponentSpec, options: LoadOptions): string {\n const registry = spec.registry || 'local';\n const namespace = spec.namespace || options.defaultNamespace || 'Global';\n const version = spec.version || options.defaultVersion || 'latest';\n return `${registry}:${namespace}:${spec.name}:${version}`;\n }\n \n /**\n * Clear all caches\n */\n clearCache(): void {\n this.fetchCache.clear();\n this.registryNotifications.clear();\n this.loadingPromises.clear();\n this.log('All caches cleared');\n }\n \n /**\n * Get cache statistics\n */\n getCacheStats(): {\n fetchCacheSize: number;\n notificationsCount: number;\n loadingCount: number;\n } {\n return {\n fetchCacheSize: this.fetchCache.size,\n notificationsCount: this.registryNotifications.size,\n loadingCount: this.loadingPromises.size\n };\n }\n \n /**\n * Log a message if debug is enabled\n */\n private log(message: string, data?: any): void {\n if (this.config.debug) {\n console.log(`🎯 [ComponentManager] ${message}`, data || '');\n }\n }\n}"]}
|
|
1
|
+
{"version":3,"file":"component-manager.js","sourceRoot":"","sources":["../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les all component operations efficiently with proper caching and registry tracking\n */\n\nimport { ComponentSpec, ComponentLibraryDependency } from '@memberjunction/interactive-component-types';\nimport { UserInfo, Metadata, LogError } from '@memberjunction/core';\nimport { ComponentMetadataEngine, MJComponentLibraryEntity, MJComponentEntityExtended } from '@memberjunction/core-entities';\n\nimport { ComponentCompiler } from '../compiler';\nimport { ComponentRegistry } from '../registry';\nimport { RuntimeContext, ComponentObject } from '../types';\nimport {\n LoadOptions,\n LoadResult,\n HierarchyResult,\n ComponentManagerConfig,\n CacheEntry,\n ResolutionMode\n} from './types';\n\n/**\n * Unified component management system that handles all component operations\n * efficiently with proper caching and registry tracking.\n */\nexport class ComponentManager {\n private compiler: ComponentCompiler;\n private registry: ComponentRegistry;\n private runtimeContext: RuntimeContext;\n private config: ComponentManagerConfig;\n \n // Caching\n private fetchCache: Map<string, CacheEntry> = new Map();\n private registryNotifications: Set<string> = new Set();\n private loadingPromises: Map<string, Promise<LoadResult>> = new Map();\n \n // Metadata engine\n private componentEngine = ComponentMetadataEngine.Instance;\n private graphQLClient: any = null;\n \n constructor(\n compiler: ComponentCompiler,\n registry: ComponentRegistry,\n runtimeContext: RuntimeContext,\n config: ComponentManagerConfig = {}\n ) {\n this.compiler = compiler;\n this.registry = registry;\n this.runtimeContext = runtimeContext;\n this.config = {\n debug: false,\n maxCacheSize: 100,\n cacheTTL: 3600000, // 1 hour\n enableUsageTracking: true,\n dependencyBatchSize: 5,\n fetchTimeout: 30000,\n ...config\n };\n \n this.log('ComponentManager initialized', {\n debug: this.config.debug,\n cacheTTL: this.config.cacheTTL,\n usageTracking: this.config.enableUsageTracking\n });\n }\n \n /**\n * Main entry point - intelligently handles all component operations\n */\n async loadComponent(\n spec: ComponentSpec,\n options: LoadOptions = {}\n ): Promise<LoadResult> {\n const startTime = Date.now();\n const componentKey = this.getComponentKey(spec, options);\n \n this.log(`Loading component: ${spec.name}`, { \n key: componentKey, \n location: spec.location,\n registry: spec.registry,\n forceRefresh: options.forceRefresh \n });\n \n // Check if already loading to prevent duplicate work\n const existingPromise = this.loadingPromises.get(componentKey);\n if (existingPromise && !options.forceRefresh) {\n this.log(`Component already loading: ${spec.name}, waiting...`);\n return existingPromise;\n }\n \n // Create loading promise\n const loadPromise = this.doLoadComponent(spec, options, componentKey, startTime);\n this.loadingPromises.set(componentKey, loadPromise);\n \n try {\n const result = await loadPromise;\n return result;\n } finally {\n this.loadingPromises.delete(componentKey);\n }\n }\n \n /**\n * Internal method that does the actual loading\n */\n private async doLoadComponent(\n spec: ComponentSpec,\n options: LoadOptions,\n componentKey: string,\n startTime: number\n ): Promise<LoadResult> {\n const errors: LoadResult['errors'] = [];\n \n try {\n // STEP 1: Check if already loaded in ComponentRegistry\n const namespace = spec.namespace || options.defaultNamespace || 'Global';\n const version = spec.version || options.defaultVersion || 'latest';\n \n const existing = this.registry.get(spec.name, namespace, version);\n if (existing && !options.forceRefresh && !options.forceRecompile) {\n this.log(`Component found in registry: ${spec.name}`);\n \n // Still need to notify registry for usage tracking\n if (options.trackUsage !== false) {\n await this.notifyRegistryUsageIfNeeded(spec, componentKey);\n }\n \n // Get cached spec if available\n const cachedEntry = this.fetchCache.get(componentKey);\n \n return {\n success: true,\n component: existing,\n spec: cachedEntry?.spec || spec,\n fromCache: true\n };\n }\n \n // STEP 2: Fetch full spec if needed\n let fullSpec = spec;\n if (this.needsFetch(spec)) {\n this.log(`Fetching component spec: ${spec.name}`);\n try {\n fullSpec = await this.fetchComponentSpec(spec, options.contextUser, {\n resolutionMode: options.resolutionMode\n });\n\n // Cache the fetched spec\n this.fetchCache.set(componentKey, {\n spec: fullSpec,\n fetchedAt: new Date(),\n hash: await this.calculateHash(fullSpec),\n usageNotified: false\n });\n } catch (error) {\n errors.push({\n message: `Failed to fetch component: ${error instanceof Error ? error.message : String(error)}`,\n phase: 'fetch',\n componentName: spec.name\n });\n throw error;\n }\n } else {\n // Log when we skip fetching because code is already provided\n if (spec.location === 'registry' && spec.code) {\n this.log(`Skipping fetch for registry component: ${spec.name} (code already provided)`, {\n location: spec.location,\n registry: spec.registry\n });\n }\n // Also cache the spec if it has code to avoid re-fetching\n if (spec.code && !this.fetchCache.has(componentKey)) {\n this.fetchCache.set(componentKey, {\n spec: fullSpec,\n fetchedAt: new Date(),\n hash: await this.calculateHash(fullSpec),\n usageNotified: false\n });\n }\n }\n \n // STEP 3: Notify registry of usage (exactly once per session)\n if (options.trackUsage !== false) {\n await this.notifyRegistryUsageIfNeeded(fullSpec, componentKey);\n }\n \n // STEP 4: Compile if needed\n let compiledComponent = existing;\n if (!compiledComponent || options.forceRecompile) {\n this.log(`Compiling component: ${spec.name}`);\n try {\n compiledComponent = await this.compileComponent(fullSpec, options);\n } catch (error) {\n errors.push({\n message: `Failed to compile component: ${error instanceof Error ? error.message : String(error)}`,\n phase: 'compile',\n componentName: spec.name\n });\n throw error;\n }\n }\n \n // STEP 5: Register in ComponentRegistry\n if (!existing || options.forceRefresh || options.forceRecompile) {\n this.log(`Registering component: ${spec.name}`);\n this.registry.register(\n fullSpec.name,\n compiledComponent,\n namespace,\n version\n );\n }\n \n // STEP 6: Process dependencies recursively\n const dependencies: Record<string, ComponentObject> = {};\n if (fullSpec.dependencies && fullSpec.dependencies.length > 0) {\n this.log(`Loading ${fullSpec.dependencies.length} dependencies for ${spec.name}`);\n \n // Load dependencies in batches for efficiency\n const depResults = await this.loadDependenciesBatched(\n fullSpec.dependencies,\n { ...options, isDependent: true }\n );\n \n for (const result of depResults) {\n if (result.success && result.component) {\n const depSpec = fullSpec.dependencies.find(d => \n d.name === (result.spec?.name || '')\n );\n if (depSpec) {\n dependencies[depSpec.name] = result.component;\n }\n } else if (result.errors) {\n errors.push(...result.errors);\n }\n }\n }\n \n const elapsed = Date.now() - startTime;\n this.log(`Component loaded successfully: ${spec.name} (${elapsed}ms)`, {\n fromCache: false,\n dependencyCount: Object.keys(dependencies).length\n });\n \n return {\n success: errors.length === 0,\n component: compiledComponent,\n spec: fullSpec,\n fromCache: false,\n dependencies,\n errors: errors.length > 0 ? errors : undefined\n };\n \n } catch (error) {\n const elapsed = Date.now() - startTime;\n this.log(`Failed to load component: ${spec.name} (${elapsed}ms)`, error);\n \n return {\n success: false,\n fromCache: false,\n errors: errors.length > 0 ? errors : [{\n message: error instanceof Error ? error.message : String(error),\n phase: 'fetch',\n componentName: spec.name\n }]\n };\n }\n }\n \n /**\n * Load a complete hierarchy efficiently\n */\n async loadHierarchy(\n rootSpec: ComponentSpec,\n options: LoadOptions = {}\n ): Promise<HierarchyResult> {\n const startTime = Date.now();\n const loaded: string[] = [];\n const errors: HierarchyResult['errors'] = [];\n const components: Record<string, ComponentObject> = {};\n const stats = {\n fromCache: 0,\n fetched: 0,\n compiled: 0,\n totalTime: 0\n };\n \n this.log(`Loading component hierarchy: ${rootSpec.name}`, {\n location: rootSpec.location,\n registry: rootSpec.registry\n });\n \n try {\n // Initialize component engine if needed (skip in browser context where it doesn't exist)\n if (this.componentEngine && typeof this.componentEngine.Config === 'function') {\n await this.componentEngine.Config(false, options.contextUser);\n }\n \n // Load the root component and all its dependencies\n const result = await this.loadComponentRecursive(\n rootSpec,\n options,\n loaded,\n errors,\n components,\n stats,\n new Set()\n );\n \n stats.totalTime = Date.now() - startTime;\n \n this.log(`Hierarchy loaded: ${rootSpec.name}`, {\n success: errors.length === 0,\n loadedCount: loaded.length,\n errors: errors.length,\n ...stats\n });\n \n // Unwrap components before returning\n // Components are ComponentObject wrappers, but consumers expect just the React components\n const unwrappedComponents: Record<string, ComponentObject> = {};\n for (const [name, componentObject] of Object.entries(components)) {\n if (componentObject && typeof componentObject === 'object' && 'component' in componentObject) {\n // Extract the actual React component function\n unwrappedComponents[name] = (componentObject as any).component;\n } else {\n // Already a function or something else - use as-is\n unwrappedComponents[name] = componentObject;\n }\n }\n \n return {\n success: errors.length === 0,\n rootComponent: result.component,\n resolvedSpec: result.spec,\n loadedComponents: loaded,\n errors,\n components: unwrappedComponents,\n stats\n };\n \n } catch (error) {\n stats.totalTime = Date.now() - startTime;\n \n this.log(`Failed to load hierarchy: ${rootSpec.name}`, error);\n \n return {\n success: false,\n loadedComponents: loaded,\n errors: [...errors, {\n message: error instanceof Error ? error.message : String(error),\n phase: 'fetch',\n componentName: rootSpec.name\n }],\n stats\n };\n }\n }\n \n /**\n * Recursively load a component and its dependencies\n */\n private async loadComponentRecursive(\n spec: ComponentSpec,\n options: LoadOptions,\n loaded: string[],\n errors: HierarchyResult['errors'],\n components: Record<string, ComponentObject>,\n stats: HierarchyResult['stats'],\n visited: Set<string>\n ): Promise<LoadResult> {\n const componentKey = this.getComponentKey(spec, options);\n \n // Prevent circular dependencies\n if (visited.has(componentKey)) {\n this.log(`Circular dependency detected: ${spec.name}`);\n return {\n success: true,\n component: components[spec.name],\n spec,\n fromCache: true\n };\n }\n visited.add(componentKey);\n \n // Load this component\n const result = await this.loadComponent(spec, options);\n \n if (result.success && result.component) {\n loaded.push(spec.name);\n components[spec.name] = result.component;\n \n // Update stats\n if (stats) {\n if (result.fromCache) stats.fromCache++;\n else {\n stats.fetched++;\n stats.compiled++;\n }\n }\n \n // Load dependencies\n if (result.spec?.dependencies) {\n for (const dep of result.spec.dependencies) {\n // Normalize dependency spec for local registry lookup\n const depSpec = { ...dep };\n // OPTIMIZATION: If the dependency already has code (from registry population),\n // we can skip fetching and go straight to compilation\n if (depSpec.code) {\n this.log(`Dependency ${depSpec.name} already has code (from registry population), optimizing load`);\n }\n\n // If location is \"registry\" with undefined registry, ensure it's treated as local\n // This follows the convention that registry components with undefined registry\n // should be looked up in the local ComponentMetadataEngine\n if (depSpec.location === 'registry' && !depSpec.registry) {\n // Explicitly set to undefined for clarity (it may already be undefined)\n depSpec.registry = undefined;\n\n // Log for debugging\n this.log(`Dependency ${depSpec.name} is a local registry component (registry=undefined)`);\n }\n\n await this.loadComponentRecursive(\n depSpec,\n { ...options, isDependent: true },\n loaded,\n errors,\n components,\n stats,\n visited\n );\n }\n }\n } else if (result.errors) {\n errors.push(...result.errors);\n }\n \n return result;\n }\n \n /**\n * Load dependencies in batches for efficiency\n */\n private async loadDependenciesBatched(\n dependencies: ComponentSpec[],\n options: LoadOptions\n ): Promise<LoadResult[]> {\n const batchSize = this.config.dependencyBatchSize || 5;\n const results: LoadResult[] = [];\n \n for (let i = 0; i < dependencies.length; i += batchSize) {\n const batch = dependencies.slice(i, i + batchSize);\n const batchPromises = batch.map(dep => this.loadComponent(dep, options));\n const batchResults = await Promise.all(batchPromises);\n results.push(...batchResults);\n }\n \n return results;\n }\n \n /**\n * Check if a component needs to be fetched from a registry\n */\n private needsFetch(spec: ComponentSpec): boolean {\n // Need to fetch if:\n // 1. It's a registry component without code\n // 2. It's missing required fields\n return spec.location === 'registry' && !spec.code;\n }\n \n /**\n * Fetch a component specification from a registry (local or external)\n * \n * Convention: When location === 'registry' and registry === undefined,\n * the component is looked up in the local ComponentMetadataEngine.\n * This allows components to reference local registry components without\n * having to know if they're embedded or registry-based.\n */\n private async fetchComponentSpec(\n spec: ComponentSpec,\n contextUser?: UserInfo,\n options?: { resolutionMode?: ResolutionMode }\n ): Promise<ComponentSpec> {\n // Check cache first\n const cacheKey = this.getComponentKey(spec, {});\n const cached = this.fetchCache.get(cacheKey);\n \n if (cached && this.isCacheValid(cached)) {\n this.log(`Using cached spec for: ${spec.name}`);\n return cached.spec;\n }\n \n // Handle LOCAL registry components (registry is null/undefined)\n if (!spec.registry) {\n this.log(`Fetching from local registry: ${spec.name}`);\n \n // Find component in local ComponentMetadataEngine\n const localComponent = this.componentEngine.Components?.find(\n (c: MJComponentEntityExtended) => {\n // Match by name (case-insensitive for better compatibility)\n const nameMatch = c.Name?.toLowerCase() === spec.name?.toLowerCase();\n \n // Match by namespace if provided (handle different formats)\n const namespaceMatch = !spec.namespace || c.Namespace?.toLowerCase() === spec.namespace?.toLowerCase();\n\n if (nameMatch && !namespaceMatch) {\n }\n \n return nameMatch && namespaceMatch;\n }\n );\n \n if (!localComponent) {\n throw new Error(`Local component not found: ${spec.name}`);\n }\n \n // Parse specification from local component\n if (!localComponent.Specification) {\n throw new Error(`Local component ${spec.name} has no specification`);\n }\n \n const fullSpec = JSON.parse(localComponent.Specification);\n \n // Cache it\n this.fetchCache.set(cacheKey, {\n spec: fullSpec,\n fetchedAt: new Date(),\n usageNotified: false\n });\n \n return fullSpec;\n }\n \n // Handle EXTERNAL registry components (registry has a name)\n // Initialize GraphQL client if needed\n if (!this.graphQLClient) {\n await this.initializeGraphQLClient();\n }\n \n if (!this.graphQLClient) {\n throw new Error('GraphQL client not available for registry fetching');\n }\n \n // Fetch from external registry\n this.log(`Fetching from external registry: ${spec.registry}/${spec.name}`);\n \n const fullSpec = await this.graphQLClient.GetRegistryComponent({\n registryName: spec.registry,\n namespace: spec.namespace || 'Global',\n name: spec.name,\n version: spec.version || 'latest'\n });\n \n if (!fullSpec) {\n throw new Error(`Component not found in registry: ${spec.registry}/${spec.name}`);\n }\n \n // Apply resolution mode if specified\n const processedSpec = this.applyResolutionMode(fullSpec, spec, options?.resolutionMode);\n \n // Cache it\n this.fetchCache.set(cacheKey, {\n spec: processedSpec,\n fetchedAt: new Date(),\n usageNotified: false\n });\n \n return processedSpec;\n }\n \n /**\n * Apply resolution mode to a fetched spec (recursively including dependencies)\n */\n private applyResolutionMode(\n fullSpec: ComponentSpec,\n originalSpec: ComponentSpec,\n resolutionMode?: ResolutionMode\n ): ComponentSpec {\n let processedSpec: ComponentSpec;\n \n if (resolutionMode === 'embed') {\n // Convert to embedded format for test harness\n processedSpec = {\n ...fullSpec,\n location: 'embedded',\n registry: undefined,\n // namespace and name can stay for identification\n };\n } else {\n // Default: preserve-metadata mode\n // Keep original registry metadata but include fetched code\n processedSpec = {\n ...fullSpec,\n location: originalSpec.location,\n registry: originalSpec.registry,\n namespace: originalSpec.namespace || fullSpec.namespace,\n name: originalSpec.name || fullSpec.name\n };\n }\n \n // Recursively apply resolution mode to dependencies\n if (processedSpec.dependencies && processedSpec.dependencies.length > 0) {\n processedSpec.dependencies = processedSpec.dependencies.map(dep => {\n // For dependencies, use the dep itself as both full and original spec\n // since they've already been fetched and processed\n return this.applyResolutionMode(dep, dep, resolutionMode);\n });\n }\n \n return processedSpec;\n }\n\n /**\n * Compile a component specification\n */\n private async compileComponent(\n spec: ComponentSpec,\n options: LoadOptions\n ): Promise<ComponentObject> {\n // Get all available libraries - use passed libraries or fall back to ComponentMetadataEngine\n const allLibraries = options.allLibraries || this.componentEngine.ComponentLibraries || [];\n \n // Filter valid libraries\n const validLibraries = spec.libraries?.filter(lib => \n lib && lib.name && lib.globalVariable && \n lib.name !== 'unknown' && lib.globalVariable !== 'undefined'\n );\n \n // Compile the component\n const result = await this.compiler.compile({\n componentName: spec.name,\n componentCode: spec.code || '',\n libraries: validLibraries,\n dependencies: spec.dependencies,\n allLibraries\n });\n \n if (!result.success || !result.component) {\n throw new Error(result.error?.message || 'Compilation failed');\n }\n \n // Add loaded libraries to runtime context\n if (result.loadedLibraries && result.loadedLibraries.size > 0) {\n if (!this.runtimeContext.libraries) {\n this.runtimeContext.libraries = {};\n }\n result.loadedLibraries.forEach((value, key) => {\n this.runtimeContext.libraries![key] = value;\n });\n }\n \n // Get the component object from the factory\n const componentObject = result.component.factory(\n this.runtimeContext,\n undefined, // styles\n {} // components - will be injected by parent\n );\n \n return componentObject;\n }\n \n /**\n * Notify registry of component usage for licensing\n * Only happens once per component per session\n */\n private async notifyRegistryUsageIfNeeded(\n spec: ComponentSpec,\n componentKey: string\n ): Promise<void> {\n if (!spec.registry || !this.config.enableUsageTracking) {\n return; // Only for external registry components with tracking enabled\n }\n \n const notificationKey = `${spec.registry}:${componentKey}`;\n if (this.registryNotifications.has(notificationKey)) {\n this.log(`Usage already notified for: ${spec.name}`);\n return; // Already notified this session\n }\n \n try {\n // In the future, make lightweight usage notification call to registry\n // For now, the fetch itself serves as the notification\n this.log(`Notifying registry usage for: ${spec.name}`);\n this.registryNotifications.add(notificationKey);\n \n // Update cache entry\n const cached = this.fetchCache.get(componentKey);\n if (cached) {\n cached.usageNotified = true;\n }\n } catch (error) {\n // Log but don't fail - usage tracking shouldn't break component loading\n console.warn(`Failed to notify registry usage for ${componentKey}:`, error);\n }\n }\n \n /**\n * Initialize GraphQL client for registry operations\n */\n private async initializeGraphQLClient(): Promise<void> {\n try {\n const provider = Metadata?.Provider;\n if (provider && (provider as any).ExecuteGQL) {\n const { GraphQLComponentRegistryClient } = await import('@memberjunction/graphql-dataprovider');\n this.graphQLClient = new GraphQLComponentRegistryClient(provider as any);\n this.log('GraphQL client initialized');\n }\n } catch (error) {\n LogError(`Failed to initialize GraphQL client: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n \n /**\n * Check if a cache entry is still valid\n */\n private isCacheValid(entry: CacheEntry): boolean {\n const age = Date.now() - entry.fetchedAt.getTime();\n return age < (this.config.cacheTTL || 3600000);\n }\n \n /**\n * Calculate a hash for a component spec (for cache validation)\n */\n private async calculateHash(spec: ComponentSpec): Promise<string> {\n // Simple hash based on spec content\n const content = JSON.stringify({\n name: spec.name,\n version: spec.version,\n code: spec.code,\n libraries: spec.libraries\n });\n \n // Simple hash function (in production, use crypto)\n let hash = 0;\n for (let i = 0; i < content.length; i++) {\n const char = content.charCodeAt(i);\n hash = ((hash << 5) - hash) + char;\n hash = hash & hash; // Convert to 32bit integer\n }\n return hash.toString(16);\n }\n \n /**\n * Generate a unique key for a component\n */\n private getComponentKey(spec: ComponentSpec, options: LoadOptions): string {\n const registry = spec.registry || 'local';\n const namespace = spec.namespace || options.defaultNamespace || 'Global';\n const version = spec.version || options.defaultVersion || 'latest';\n return `${registry}:${namespace}:${spec.name}:${version}`;\n }\n \n /**\n * Clear all caches\n */\n clearCache(): void {\n this.fetchCache.clear();\n this.registryNotifications.clear();\n this.loadingPromises.clear();\n this.log('All caches cleared');\n }\n \n /**\n * Get cache statistics\n */\n getCacheStats(): {\n fetchCacheSize: number;\n notificationsCount: number;\n loadingCount: number;\n } {\n return {\n fetchCacheSize: this.fetchCache.size,\n notificationsCount: this.registryNotifications.size,\n loadingCount: this.loadingPromises.size\n };\n }\n \n /**\n * Log a message if debug is enabled\n */\n private log(message: string, data?: any): void {\n if (this.config.debug) {\n console.log(`🎯 [ComponentManager] ${message}`, data || '');\n }\n }\n}"]}
|