@memberjunction/ng-workspace-initializer 6.2.0-edge.5 → 6.2.0-edge.6

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.
@@ -1 +1 @@
1
- {"version":3,"file":"workspace-initializer.service.d.ts","sourceRoot":"","sources":["../../../src/lib/services/workspace-initializer.service.ts"],"names":[],"mappings":"AAYA,OAAO,EAAE,UAAU,EAAE,gBAAgB,EAAiB,MAAM,kCAAkC,CAAC;AAE/F,OAAO,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AACzD,OAAO,EAAE,wBAAwB,EAAE,MAAM,kCAAkC,CAAC;AAC5E,OAAO,EAAE,oBAAoB,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAC;;AAW1G,qBAGa,2BAA2B;IAIpC,OAAO,CAAC,QAAQ;IAChB,OAAO,CAAC,wBAAwB;IAChC,OAAO,CAAC,YAAY;IALtB,OAAO,CAAC,sBAAsB,CAAS;gBAG7B,QAAQ,EAAE,UAAU,EACpB,wBAAwB,EAAE,wBAAwB,EAClD,YAAY,EAAE,YAAY;IAGpC;;;OAGG;IACG,mBAAmB,CACvB,KAAK,EAAE,MAAM,EACb,QAAQ,EAAE,gBAAgB,EAC1B,WAAW,EAAE,oBAAoB,GAChC,OAAO,CAAC,mBAAmB,CAAC;IA4F/B,mDAAmD;IAC7C,mBAAmB,CACvB,KAAK,EAAE,MAAM,EACb,QAAQ,EAAE,gBAAgB,EAC1B,WAAW,EAAE,oBAAoB,GAChC,OAAO,CAAC,mBAAmB,CAAC;IAI/B;;;OAGG;IACH,aAAa,CAAC,GAAG,EAAE,GAAG,GAAG,kBAAkB;IAsD3C,6CAA6C;IAC7C,aAAa,CAAC,GAAG,EAAE,GAAG,GAAG,kBAAkB;IAI3C;;;;;;OAMG;YACW,sBAAsB;IA6CpC;;;OAGG;IACH,OAAO,CAAC,kBAAkB;IA8B1B;;;OAGG;IACH,OAAO,CAAC,oBAAoB;IAuB5B;;;OAGG;IACH,OAAO,CAAC,yBAAyB;IAwCjC;;;OAGG;IACG,eAAe,CAAC,KAAK,EAAE,kBAAkB,EAAE,WAAW,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IAuBvF,+CAA+C;IACzC,eAAe,CAAC,KAAK,EAAE,kBAAkB,EAAE,WAAW,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;yCA9W5E,2BAA2B;6CAA3B,2BAA2B;CAiXvC"}
1
+ {"version":3,"file":"workspace-initializer.service.d.ts","sourceRoot":"","sources":["../../../src/lib/services/workspace-initializer.service.ts"],"names":[],"mappings":"AAYA,OAAO,EAAE,UAAU,EAAE,gBAAgB,EAAiB,MAAM,kCAAkC,CAAC;AAE/F,OAAO,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AACzD,OAAO,EAAE,wBAAwB,EAAE,MAAM,kCAAkC,CAAC;AAC5E,OAAO,EAAE,oBAAoB,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAC;;AAW1G,qBAGa,2BAA2B;IAIpC,OAAO,CAAC,QAAQ;IAChB,OAAO,CAAC,wBAAwB;IAChC,OAAO,CAAC,YAAY;IALtB,OAAO,CAAC,sBAAsB,CAAS;gBAG7B,QAAQ,EAAE,UAAU,EACpB,wBAAwB,EAAE,wBAAwB,EAClD,YAAY,EAAE,YAAY;IAGpC;;;OAGG;IACG,mBAAmB,CACvB,KAAK,EAAE,MAAM,EACb,QAAQ,EAAE,gBAAgB,EAC1B,WAAW,EAAE,oBAAoB,GAChC,OAAO,CAAC,mBAAmB,CAAC;IA4F/B,mDAAmD;IAC7C,mBAAmB,CACvB,KAAK,EAAE,MAAM,EACb,QAAQ,EAAE,gBAAgB,EAC1B,WAAW,EAAE,oBAAoB,GAChC,OAAO,CAAC,mBAAmB,CAAC;IAI/B;;;OAGG;IACH,aAAa,CAAC,GAAG,EAAE,GAAG,GAAG,kBAAkB;IAsD3C,6CAA6C;IAC7C,aAAa,CAAC,GAAG,EAAE,GAAG,GAAG,kBAAkB;IAI3C;;;;;;OAMG;YACW,sBAAsB;IAwDpC;;;OAGG;IACH,OAAO,CAAC,kBAAkB;IA8B1B;;;OAGG;IACH,OAAO,CAAC,oBAAoB;IAuB5B;;;OAGG;IACH,OAAO,CAAC,yBAAyB;IAwCjC;;;OAGG;IACG,eAAe,CAAC,KAAK,EAAE,kBAAkB,EAAE,WAAW,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IAuBvF,+CAA+C;IACzC,eAAe,CAAC,KAAK,EAAE,kBAAkB,EAAE,WAAW,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;yCAzX5E,2BAA2B;6CAA3B,2BAA2B;CA4XvC"}
@@ -6,7 +6,7 @@
6
6
  * error classification, and auth retry logic.
7
7
  */
8
8
  import { Injectable } from '@angular/core';
9
- import { LogStatus, Metadata, RunView } from '@memberjunction/core';
9
+ import { LogStatus, LogStatusEx, Metadata, RunView } from '@memberjunction/core';
10
10
  import { setupGraphQLClient, GraphQLProviderConfigData, GraphQLDataProvider } from '@memberjunction/graphql-dataprovider';
11
11
  import { AuthErrorType } from '@memberjunction/ng-auth-services';
12
12
  import { SharedService } from '@memberjunction/ng-shared';
@@ -62,12 +62,12 @@ export class WorkspaceInitializerService {
62
62
  }
63
63
  await setupGraphQLClient(config);
64
64
  const end = Date.now();
65
- console.log(`[Workspace] GraphQL client setup complete: ${end - start}ms`);
65
+ LogStatus(`[Workspace] GraphQL client setup complete: ${end - start}ms`);
66
66
  // Subscribe to cross-server cache invalidation events via GraphQL WebSocket
67
67
  // This enables real-time data refresh when other servers modify entities
68
68
  if (GraphQLDataProvider.Instance) {
69
69
  GraphQLDataProvider.Instance.SubscribeToCacheInvalidation();
70
- console.log('✓ Cache invalidation subscription active');
70
+ LogStatus('✓ Cache invalidation subscription active');
71
71
  }
72
72
  // 2. Load metadata and validate user
73
73
  await SharedService.RefreshData(true);
@@ -192,6 +192,7 @@ export class WorkspaceInitializerService {
192
192
  ResultType: 'entity_object',
193
193
  });
194
194
  let theme = result.Success ? result.Results?.[0] : undefined;
195
+ let everyQuerySucceeded = result.Success;
195
196
  // User's selection is gone/inactive — fall back to the org default.
196
197
  if (!theme && selectedId) {
197
198
  result = await rv.RunView({
@@ -201,8 +202,18 @@ export class WorkspaceInitializerService {
201
202
  ResultType: 'entity_object',
202
203
  });
203
204
  theme = result.Success ? result.Results?.[0] : undefined;
205
+ everyQuerySucceeded = everyQuerySucceeded && result.Success;
204
206
  }
205
207
  if (!theme) {
208
+ // The org has no active brand (and the user's selection is gone). A brand restored from
209
+ // localStorage before bootstrap (RestorePersistedBrandOverlay) would otherwise keep
210
+ // painting forever — a retired brand on the sign-in page and through the session, for
211
+ // every browser that ever loaded it. Clear it only when EVERY query above succeeded: a
212
+ // failed selection query followed by an empty org-default query proves nothing about the
213
+ // selection, and a transient read failure must not wipe a perfectly good cached brand.
214
+ if (everyQuerySucceeded) {
215
+ this.themeService.ClearBrandOverlay();
216
+ }
206
217
  return;
207
218
  }
208
219
  this.themeService.RegisterBrandTheme({
@@ -222,7 +233,7 @@ export class WorkspaceInitializerService {
222
233
  await this.themeService.ApplyBrandOverlay(theme.ID);
223
234
  }
224
235
  catch (err) {
225
- LogStatus(`Org brand theme bootstrap skipped: ${err instanceof Error ? err.message : String(err)}`);
236
+ LogStatusEx({ message: `Org brand theme bootstrap skipped: ${err instanceof Error ? err.message : String(err)}`, verboseOnly: true });
226
237
  }
227
238
  }
228
239
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"workspace-initializer.service.js","sourceRoot":"","sources":["../../../src/lib/services/workspace-initializer.service.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAC3C,OAAO,EAAY,SAAS,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,sBAAsB,CAAC;AAE9E,OAAO,EAAE,kBAAkB,EAAE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C1D,YAAY,CAAC,OAAO,CAAC,QAAQ,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC,CAAC;YAEzD,MAAM,MAAM,GAAG,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,QAAQ,EAAE,EAAE,MAAM,EAAE,WAAW,EAAE,EAAE,CAAC,CAAC;YAC1E,MAAM,aAAa,CAAC,MAAM,CAAC,CAAC;YAE5B,OAAO,IAAI,CAAC;QACd,CAAC;QAED,OAAO,KAAK,CAAC;IACf,CAAC;IAED,+CAA+C;IAC/C,KAAK,CAAC,eAAe,CAAC,KAAyB,EAAE,WAAmB;QAClE,OAAO,IAAI,CAAC,eAAe,CAAC,KAAK,EAAE,WAAW,CAAC,CAAC;IAClD,CAAC;qHAhXU,2BAA2B;gEAA3B,2BAA2B,WAA3B,2BAA2B,mBAF1B,MAAM;;iFAEP,2BAA2B;cAHvC,UAAU;eAAC;gBACV,UAAU,EAAE,MAAM;aACnB","sourcesContent":["/**\n * Workspace Initializer Service\n *\n * Extracted from MJExplorer AppComponent to make workspace initialization reusable\n * across all MemberJunction applications. Handles GraphQL setup, user validation,\n * error classification, and auth retry logic.\n */\n\nimport { Injectable } from '@angular/core';\nimport { LogError, LogStatus, Metadata, RunView } from '@memberjunction/core';\nimport { MJThemeEntity } from '@memberjunction/core-entities';\nimport { setupGraphQLClient, GraphQLProviderConfigData, GraphQLDataProvider } from '@memberjunction/graphql-dataprovider';\nimport { MJAuthBase, StandardUserInfo, AuthErrorType } from '@memberjunction/ng-auth-services';\nimport { SharedService } from '@memberjunction/ng-shared';\nimport { ThemeService } from '@memberjunction/ng-shared';\nimport { StartupValidationService } from '@memberjunction/ng-explorer-core';\nimport { WorkspaceEnvironment, WorkspaceInitResult, WorkspaceInitError } from '../models/workspace-types';\nimport { lastValueFrom } from 'rxjs';\n\n/**\n * The server's permission error for a user who cannot read their own roles. The entity is named\n * `MJ: User Roles` since v5 (older servers say `User Roles`). SetupGraphQLClient appends it to its\n * own message when the boot's metadata download fails for that reason (#4887). Intentionally\n * duplicated in ng-bootstrap's MJInitializationService, which classifies the same boot error.\n */\nconst NO_USER_ROLES_PERMISSION_TEXT = /does not have read permissions on (MJ: )?User Roles/;\n\n@Injectable({\n providedIn: 'root'\n})\nexport class WorkspaceInitializerService {\n private _sessionExpiredHandled = false;\n\n constructor(\n private authBase: MJAuthBase,\n private startupValidationService: StartupValidationService,\n private themeService: ThemeService\n ) { }\n\n /**\n * Initialize workspace with authenticated user\n * Replaces all the logic from AppComponent.handleLogin()\n */\n async InitializeWorkspace(\n token: string,\n userInfo: StandardUserInfo,\n environment: WorkspaceEnvironment\n ): Promise<WorkspaceInitResult> {\n if (!token) {\n return {\n success: false,\n error: {\n type: 'unknown',\n message: 'No token provided',\n userMessage: 'Authentication token is missing. Please log in again.',\n shouldRetry: false\n }\n };\n }\n\n try {\n const start = Date.now();\n\n // 1. Setup GraphQL client with token refresh callback\n const config = new GraphQLProviderConfigData(\n token,\n environment.GRAPHQL_URI,\n environment.GRAPHQL_WS_URI,\n async () => {\n // v3.0 API - clean abstraction, no provider-specific logic!\n const token = await this.authBase.refreshToken();\n return token.idToken;\n },\n environment.MJ_CORE_SCHEMA_NAME\n );\n config.OnAuthenticationError = (error: Error) => this.handleSessionExpired(error);\n if (environment.MJAPI_URI) {\n config.MJAPIURL = environment.MJAPI_URI;\n }\n\n await setupGraphQLClient(config);\n const end = Date.now();\n console.log(`[Workspace] GraphQL client setup complete: ${end - start}ms`);\n\n // Subscribe to cross-server cache invalidation events via GraphQL WebSocket\n // This enables real-time data refresh when other servers modify entities\n if (GraphQLDataProvider.Instance) {\n GraphQLDataProvider.Instance.SubscribeToCacheInvalidation();\n console.log('✓ Cache invalidation subscription active');\n }\n\n // 2. Load metadata and validate user\n await SharedService.RefreshData(true);\n await this.themeService.Initialize();\n await this.applyDefaultBrandTheme();\n // This service runs the one-time app login flow and is wiring up the global\n // Metadata.Provider via setupGraphQLClient above. There is no per-component\n // provider scope here.\n const md = new Metadata(); // global-provider-ok: bootstrap — wires the app's single global provider\n\n if (!md.CurrentUser) {\n return {\n success: false,\n error: {\n type: 'no_access',\n message: \"User doesn't have access to the application\",\n userMessage: \"You don't have access to the application, contact your system administrator.\",\n shouldRetry: false\n }\n };\n }\n\n // 3. Run startup validation checks (with small delay for initialization)\n setTimeout(() => {\n this.startupValidationService.validateSystemSetup();\n }, 500);\n\n // Clear any JWT retry timestamps on successful login\n localStorage.removeItem('jwt-retry-ts');\n\n return {\n success: true\n };\n } catch (err: any) {\n console.error('[Workspace] initializeWorkspace caught error:', err);\n console.error('[Workspace] Error message:', err?.message);\n console.error('[Workspace] Error stack:', err?.stack);\n if (err?.response?.errors) {\n console.error('[Workspace] GraphQL errors:', JSON.stringify(err.response.errors, null, 2));\n }\n const error = this.ClassifyError(err);\n console.error('[Workspace] Classified as:', error.type, '-', error.message);\n return {\n success: false,\n error\n };\n }\n }\n\n /** @deprecated Use {@link InitializeWorkspace}. */\n async initializeWorkspace(\n token: string,\n userInfo: StandardUserInfo,\n environment: WorkspaceEnvironment\n ): Promise<WorkspaceInitResult> {\n return this.InitializeWorkspace(token, userInfo, environment);\n }\n\n /**\n * Classify errors into actionable types\n * Replaces AppComponent error handling logic\n */\n ClassifyError(err: any): WorkspaceInitError {\n // Check for no-roles error first (highest priority)\n if (this.isNoUserRolesError(err)) {\n // Add the validation issue through the service\n this.startupValidationService.addNoRolesValidationIssue();\n\n return {\n type: 'no_roles',\n message: err.message || 'No user roles assigned',\n userMessage: 'Your account does not have any roles assigned. Please contact your administrator.',\n shouldRetry: false\n };\n }\n\n // Check for access denied\n if (err.message?.includes(\"don't have access\")) {\n return {\n type: 'no_access',\n message: err.message,\n userMessage: err.message,\n shouldRetry: false\n };\n }\n\n // Check for token expiration\n const authError = this.authBase.classifyError(err);\n if (authError.type === AuthErrorType.TOKEN_EXPIRED) {\n return {\n type: 'token_expired',\n message: authError.message,\n userMessage: authError.userMessage || 'Your session has expired. Please log in again.',\n shouldRetry: true\n };\n }\n\n // Network errors\n if (err.message?.includes('network') || err.message?.includes('fetch')) {\n return {\n type: 'network',\n message: err.message,\n userMessage: 'Network error. Please check your connection and try again.',\n shouldRetry: true\n };\n }\n\n // Unknown error\n return {\n type: 'unknown',\n message: err.message || 'Unknown error',\n userMessage: 'An unexpected error occurred. Please try again.',\n shouldRetry: false\n };\n }\n\n /** @deprecated Use {@link ClassifyError}. */\n classifyError(err: any): WorkspaceInitError {\n return this.ClassifyError(err);\n }\n\n /**\n * Org theming bootstrap: after metadata + ThemeService are ready, apply\n * the brand theme the user last chose (a starred theme they swapped to), falling back\n * to the org default. Derives the overlay via the theme engine and applies it always-on\n * (under the user's light/dark choice). Non-fatal — a missing Theme entity (older DBs)\n * or no theme simply leaves the stock MJ theme in place.\n */\n private async applyDefaultBrandTheme(): Promise<void> {\n try {\n const rv = new RunView();\n // Prefer the user's last-applied brand theme; fall back to the org default.\n const selectedId = this.themeService.GetSelectedBrandThemeId();\n let result = await rv.RunView<MJThemeEntity>({\n EntityName: 'MJ: Themes',\n ExtraFilter: selectedId ? `ID = '${selectedId}' AND Status = 'Active'` : \"IsDefault = 1 AND Status = 'Active'\",\n MaxRows: 1,\n ResultType: 'entity_object',\n });\n let theme = result.Success ? result.Results?.[0] : undefined;\n // User's selection is gone/inactive — fall back to the org default.\n if (!theme && selectedId) {\n result = await rv.RunView<MJThemeEntity>({\n EntityName: 'MJ: Themes',\n ExtraFilter: \"IsDefault = 1 AND Status = 'Active'\",\n MaxRows: 1,\n ResultType: 'entity_object',\n });\n theme = result.Success ? result.Results?.[0] : undefined;\n }\n if (!theme) {\n return;\n }\n this.themeService.RegisterBrandTheme({\n id: theme.ID,\n name: theme.Name,\n seeds: theme.Seeds,\n description: theme.Description ?? undefined,\n overrides: theme.Overrides ?? undefined,\n customCss: theme.CustomCSS ?? undefined,\n logos: {\n lightMarkURL: theme.LightMarkURL ?? undefined,\n darkMarkURL: theme.DarkMarkURL ?? undefined,\n wordmarkURL: theme.WordmarkURL ?? undefined,\n monochromeURL: theme.MonochromeURL ?? undefined,\n },\n });\n await this.themeService.ApplyBrandOverlay(theme.ID);\n } catch (err) {\n LogStatus(`Org brand theme bootstrap skipped: ${err instanceof Error ? err.message : String(err)}`);\n }\n }\n\n /**\n * Helper function to safely check if an error is related to missing user roles\n * Extracted from AppComponent.isNoUserRolesError()\n */\n private isNoUserRolesError(err: any): boolean {\n try {\n // Check if error has response with errors array\n if (!err || typeof err !== 'object') return false;\n\n // Check for GraphQL-style errors\n if (err.response && Array.isArray(err.response.errors)) {\n return err.response.errors.some((e: any) =>\n e && e.message && typeof e.message === 'string' &&\n NO_USER_ROLES_PERMISSION_TEXT.test(e.message)\n );\n }\n\n // Check for error message directly on the error object\n if (err.message && typeof err.message === 'string') {\n return NO_USER_ROLES_PERMISSION_TEXT.test(err.message);\n }\n\n // Check for nested error object\n if (err.error && typeof err.error === 'object') {\n return this.isNoUserRolesError(err.error);\n }\n\n return false;\n } catch (e) {\n console.error('Error while checking for user roles error:', e);\n return false;\n }\n }\n\n /**\n * Called when token refresh fails irrecoverably mid-session.\n * Shows a brief notification overlay, then forces logout to clear caches and redirect to login.\n */\n private handleSessionExpired(error: Error): void {\n // Guard against multiple concurrent calls (e.g., parallel GraphQL requests all failing)\n if (this._sessionExpiredHandled) {\n return;\n }\n this._sessionExpiredHandled = true;\n\n console.warn('[Workspace] Session expired, forcing re-authentication:', error.message);\n\n this.showSessionExpiredOverlay();\n\n // Give the user a moment to read the message, then logout\n setTimeout(async () => {\n try {\n await this.authBase.logout();\n } catch (logoutError) {\n console.error('[Workspace] Error during forced logout:', logoutError);\n // Last resort: reload the page to clear state\n window.location.reload();\n }\n }, 3000);\n }\n\n /**\n * Creates a simple DOM overlay notifying the user their session has expired.\n * Uses inline styles so it works regardless of Angular component encapsulation.\n */\n private showSessionExpiredOverlay(): void {\n const overlay = document.createElement('div');\n overlay.setAttribute('style', [\n 'position: fixed',\n 'inset: 0',\n 'z-index: 999999',\n 'display: flex',\n 'align-items: center',\n 'justify-content: center',\n 'background: rgba(0, 0, 0, 0.6)',\n 'backdrop-filter: blur(4px)',\n ].join(';'));\n\n const card = document.createElement('div');\n card.setAttribute('style', [\n 'background: var(--mj-bg-surface, #fff)',\n 'color: var(--mj-text-primary, #333)',\n 'border-radius: 12px',\n 'padding: 32px 40px',\n 'max-width: 420px',\n 'text-align: center',\n 'box-shadow: 0 8px 32px rgba(0, 0, 0, 0.25)',\n 'font-family: -apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, sans-serif',\n ].join(';'));\n\n card.innerHTML = `\n <div style=\"font-size: 40px; margin-bottom: 16px;\">\n <i class=\"fa-solid fa-clock\" style=\"color: var(--mj-status-warning, #ef6c00);\"></i>\n </div>\n <h2 style=\"margin: 0 0 8px; font-size: 20px; font-weight: 600;\">Session Expired</h2>\n <p style=\"margin: 0 0 16px; font-size: 14px; color: var(--mj-text-secondary, #666);\">\n Your session has expired. You will be redirected to log in again.\n </p>\n <div style=\"font-size: 13px; color: var(--mj-text-muted, #999);\">Redirecting...</div>\n `;\n\n overlay.appendChild(card);\n document.body.appendChild(overlay);\n }\n\n /**\n * Handle authentication retry with backoff\n * Replaces AppComponent.handleAuthRetry() logic\n */\n async HandleAuthRetry(error: WorkspaceInitError, currentPath: string): Promise<boolean> {\n if (!error.shouldRetry) {\n return false;\n }\n\n const retryKey = 'auth-retry-dt';\n const lastRetryDateTime = localStorage.getItem(retryKey);\n const yesterday = +new Date(Date.now() - 1 * 24 * 60 * 60 * 1000);\n const retriedRecently = lastRetryDateTime && +new Date(lastRetryDateTime) > yesterday;\n\n if (!retriedRecently && error.type === 'token_expired') {\n LogStatus('JWT Expired, retrying once: ' + error.message);\n localStorage.setItem(retryKey, new Date().toISOString());\n\n const login$ = this.authBase.login({ appState: { target: currentPath } });\n await lastValueFrom(login$);\n\n return true;\n }\n\n return false;\n }\n\n /** @deprecated Use {@link HandleAuthRetry}. */\n async handleAuthRetry(error: WorkspaceInitError, currentPath: string): Promise<boolean> {\n return this.HandleAuthRetry(error, currentPath);\n }\n}\n"]}
1
+ {"version":3,"file":"workspace-initializer.service.js","sourceRoot":"","sources":["../../../src/lib/services/workspace-initializer.service.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAC3C,OAAO,EAAY,SAAS,EAAE,WAAW,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,sBAAsB,CAAC;AAE3F,OAAO,EAAE,kBAAkB,EAAE,yBAAyB,EAAE,mBAAmB,EAAE,MAAM,sCAAsC,CAAC;AAC1H,OAAO,EAAgC,aAAa,EAAE,MAAM,kCAAkC,CAAC;AAC/F,OAAO,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAI1D,OAAO,EAAE,aAAa,EAAE,MAAM,MAAM,CAAC;;;;;AAErC;;;;;GAKG;AACH,MAAM,6BAA6B,GAAG,qDAAqD,CAAC;AAK5F,MAAM,OAAO,2BAA2B;IAI5B;IACA;IACA;IALF,sBAAsB,GAAG,KAAK,CAAC;IAEvC,YACU,QAAoB,EACpB,wBAAkD,EAClD,YAA0B;QAF1B,aAAQ,GAAR,QAAQ,CAAY;QACpB,6BAAwB,GAAxB,wBAAwB,CAA0B;QAClD,iBAAY,GAAZ,YAAY,CAAc;IAChC,CAAC;IAEL;;;OAGG;IACH,KAAK,CAAC,mBAAmB,CACvB,KAAa,EACb,QAA0B,EAC1B,WAAiC;QAEjC,IAAI,CAAC,KAAK,EAAE,CAAC;YACX,OAAO;gBACL,OAAO,EAAE,KAAK;gBACd,KAAK,EAAE;oBACL,IAAI,EAAE,SAAS;oBACf,OAAO,EAAE,mBAAmB;oBAC5B,WAAW,EAAE,uDAAuD;oBACpE,WAAW,EAAE,KAAK;iBACnB;aACF,CAAC;QACJ,CAAC;QAED,IAAI,CAAC;YACH,MAAM,KAAK,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;YAEzB,sDAAsD;YACtD,MAAM,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ACV,UAAU,EAAE,MAAM;aACnB","sourcesContent":["/**\n * Workspace Initializer Service\n *\n * Extracted from MJExplorer AppComponent to make workspace initialization reusable\n * across all MemberJunction applications. Handles GraphQL setup, user validation,\n * error classification, and auth retry logic.\n */\n\nimport { Injectable } from '@angular/core';\nimport { LogError, LogStatus, LogStatusEx, Metadata, RunView } from '@memberjunction/core';\nimport { MJThemeEntity } from '@memberjunction/core-entities';\nimport { setupGraphQLClient, GraphQLProviderConfigData, GraphQLDataProvider } from '@memberjunction/graphql-dataprovider';\nimport { MJAuthBase, StandardUserInfo, AuthErrorType } from '@memberjunction/ng-auth-services';\nimport { SharedService } from '@memberjunction/ng-shared';\nimport { ThemeService } from '@memberjunction/ng-shared';\nimport { StartupValidationService } from '@memberjunction/ng-explorer-core';\nimport { WorkspaceEnvironment, WorkspaceInitResult, WorkspaceInitError } from '../models/workspace-types';\nimport { lastValueFrom } from 'rxjs';\n\n/**\n * The server's permission error for a user who cannot read their own roles. The entity is named\n * `MJ: User Roles` since v5 (older servers say `User Roles`). SetupGraphQLClient appends it to its\n * own message when the boot's metadata download fails for that reason (#4887). Intentionally\n * duplicated in ng-bootstrap's MJInitializationService, which classifies the same boot error.\n */\nconst NO_USER_ROLES_PERMISSION_TEXT = /does not have read permissions on (MJ: )?User Roles/;\n\n@Injectable({\n providedIn: 'root'\n})\nexport class WorkspaceInitializerService {\n private _sessionExpiredHandled = false;\n\n constructor(\n private authBase: MJAuthBase,\n private startupValidationService: StartupValidationService,\n private themeService: ThemeService\n ) { }\n\n /**\n * Initialize workspace with authenticated user\n * Replaces all the logic from AppComponent.handleLogin()\n */\n async InitializeWorkspace(\n token: string,\n userInfo: StandardUserInfo,\n environment: WorkspaceEnvironment\n ): Promise<WorkspaceInitResult> {\n if (!token) {\n return {\n success: false,\n error: {\n type: 'unknown',\n message: 'No token provided',\n userMessage: 'Authentication token is missing. Please log in again.',\n shouldRetry: false\n }\n };\n }\n\n try {\n const start = Date.now();\n\n // 1. Setup GraphQL client with token refresh callback\n const config = new GraphQLProviderConfigData(\n token,\n environment.GRAPHQL_URI,\n environment.GRAPHQL_WS_URI,\n async () => {\n // v3.0 API - clean abstraction, no provider-specific logic!\n const token = await this.authBase.refreshToken();\n return token.idToken;\n },\n environment.MJ_CORE_SCHEMA_NAME\n );\n config.OnAuthenticationError = (error: Error) => this.handleSessionExpired(error);\n if (environment.MJAPI_URI) {\n config.MJAPIURL = environment.MJAPI_URI;\n }\n\n await setupGraphQLClient(config);\n const end = Date.now();\n LogStatus(`[Workspace] GraphQL client setup complete: ${end - start}ms`);\n\n // Subscribe to cross-server cache invalidation events via GraphQL WebSocket\n // This enables real-time data refresh when other servers modify entities\n if (GraphQLDataProvider.Instance) {\n GraphQLDataProvider.Instance.SubscribeToCacheInvalidation();\n LogStatus('✓ Cache invalidation subscription active');\n }\n\n // 2. Load metadata and validate user\n await SharedService.RefreshData(true);\n await this.themeService.Initialize();\n await this.applyDefaultBrandTheme();\n // This service runs the one-time app login flow and is wiring up the global\n // Metadata.Provider via setupGraphQLClient above. There is no per-component\n // provider scope here.\n const md = new Metadata(); // global-provider-ok: bootstrap — wires the app's single global provider\n\n if (!md.CurrentUser) {\n return {\n success: false,\n error: {\n type: 'no_access',\n message: \"User doesn't have access to the application\",\n userMessage: \"You don't have access to the application, contact your system administrator.\",\n shouldRetry: false\n }\n };\n }\n\n // 3. Run startup validation checks (with small delay for initialization)\n setTimeout(() => {\n this.startupValidationService.validateSystemSetup();\n }, 500);\n\n // Clear any JWT retry timestamps on successful login\n localStorage.removeItem('jwt-retry-ts');\n\n return {\n success: true\n };\n } catch (err: any) {\n console.error('[Workspace] initializeWorkspace caught error:', err);\n console.error('[Workspace] Error message:', err?.message);\n console.error('[Workspace] Error stack:', err?.stack);\n if (err?.response?.errors) {\n console.error('[Workspace] GraphQL errors:', JSON.stringify(err.response.errors, null, 2));\n }\n const error = this.ClassifyError(err);\n console.error('[Workspace] Classified as:', error.type, '-', error.message);\n return {\n success: false,\n error\n };\n }\n }\n\n /** @deprecated Use {@link InitializeWorkspace}. */\n async initializeWorkspace(\n token: string,\n userInfo: StandardUserInfo,\n environment: WorkspaceEnvironment\n ): Promise<WorkspaceInitResult> {\n return this.InitializeWorkspace(token, userInfo, environment);\n }\n\n /**\n * Classify errors into actionable types\n * Replaces AppComponent error handling logic\n */\n ClassifyError(err: any): WorkspaceInitError {\n // Check for no-roles error first (highest priority)\n if (this.isNoUserRolesError(err)) {\n // Add the validation issue through the service\n this.startupValidationService.addNoRolesValidationIssue();\n\n return {\n type: 'no_roles',\n message: err.message || 'No user roles assigned',\n userMessage: 'Your account does not have any roles assigned. Please contact your administrator.',\n shouldRetry: false\n };\n }\n\n // Check for access denied\n if (err.message?.includes(\"don't have access\")) {\n return {\n type: 'no_access',\n message: err.message,\n userMessage: err.message,\n shouldRetry: false\n };\n }\n\n // Check for token expiration\n const authError = this.authBase.classifyError(err);\n if (authError.type === AuthErrorType.TOKEN_EXPIRED) {\n return {\n type: 'token_expired',\n message: authError.message,\n userMessage: authError.userMessage || 'Your session has expired. Please log in again.',\n shouldRetry: true\n };\n }\n\n // Network errors\n if (err.message?.includes('network') || err.message?.includes('fetch')) {\n return {\n type: 'network',\n message: err.message,\n userMessage: 'Network error. Please check your connection and try again.',\n shouldRetry: true\n };\n }\n\n // Unknown error\n return {\n type: 'unknown',\n message: err.message || 'Unknown error',\n userMessage: 'An unexpected error occurred. Please try again.',\n shouldRetry: false\n };\n }\n\n /** @deprecated Use {@link ClassifyError}. */\n classifyError(err: any): WorkspaceInitError {\n return this.ClassifyError(err);\n }\n\n /**\n * Org theming bootstrap: after metadata + ThemeService are ready, apply\n * the brand theme the user last chose (a starred theme they swapped to), falling back\n * to the org default. Derives the overlay via the theme engine and applies it always-on\n * (under the user's light/dark choice). Non-fatal — a missing Theme entity (older DBs)\n * or no theme simply leaves the stock MJ theme in place.\n */\n private async applyDefaultBrandTheme(): Promise<void> {\n try {\n const rv = new RunView();\n // Prefer the user's last-applied brand theme; fall back to the org default.\n const selectedId = this.themeService.GetSelectedBrandThemeId();\n let result = await rv.RunView<MJThemeEntity>({\n EntityName: 'MJ: Themes',\n ExtraFilter: selectedId ? `ID = '${selectedId}' AND Status = 'Active'` : \"IsDefault = 1 AND Status = 'Active'\",\n MaxRows: 1,\n ResultType: 'entity_object',\n });\n let theme = result.Success ? result.Results?.[0] : undefined;\n let everyQuerySucceeded = result.Success;\n // User's selection is gone/inactive — fall back to the org default.\n if (!theme && selectedId) {\n result = await rv.RunView<MJThemeEntity>({\n EntityName: 'MJ: Themes',\n ExtraFilter: \"IsDefault = 1 AND Status = 'Active'\",\n MaxRows: 1,\n ResultType: 'entity_object',\n });\n theme = result.Success ? result.Results?.[0] : undefined;\n everyQuerySucceeded = everyQuerySucceeded && result.Success;\n }\n if (!theme) {\n // The org has no active brand (and the user's selection is gone). A brand restored from\n // localStorage before bootstrap (RestorePersistedBrandOverlay) would otherwise keep\n // painting forever — a retired brand on the sign-in page and through the session, for\n // every browser that ever loaded it. Clear it only when EVERY query above succeeded: a\n // failed selection query followed by an empty org-default query proves nothing about the\n // selection, and a transient read failure must not wipe a perfectly good cached brand.\n if (everyQuerySucceeded) {\n this.themeService.ClearBrandOverlay();\n }\n return;\n }\n this.themeService.RegisterBrandTheme({\n id: theme.ID,\n name: theme.Name,\n seeds: theme.Seeds,\n description: theme.Description ?? undefined,\n overrides: theme.Overrides ?? undefined,\n customCss: theme.CustomCSS ?? undefined,\n logos: {\n lightMarkURL: theme.LightMarkURL ?? undefined,\n darkMarkURL: theme.DarkMarkURL ?? undefined,\n wordmarkURL: theme.WordmarkURL ?? undefined,\n monochromeURL: theme.MonochromeURL ?? undefined,\n },\n });\n await this.themeService.ApplyBrandOverlay(theme.ID);\n } catch (err) {\n LogStatusEx({ message: `Org brand theme bootstrap skipped: ${err instanceof Error ? err.message : String(err)}`, verboseOnly: true });\n }\n }\n\n /**\n * Helper function to safely check if an error is related to missing user roles\n * Extracted from AppComponent.isNoUserRolesError()\n */\n private isNoUserRolesError(err: any): boolean {\n try {\n // Check if error has response with errors array\n if (!err || typeof err !== 'object') return false;\n\n // Check for GraphQL-style errors\n if (err.response && Array.isArray(err.response.errors)) {\n return err.response.errors.some((e: any) =>\n e && e.message && typeof e.message === 'string' &&\n NO_USER_ROLES_PERMISSION_TEXT.test(e.message)\n );\n }\n\n // Check for error message directly on the error object\n if (err.message && typeof err.message === 'string') {\n return NO_USER_ROLES_PERMISSION_TEXT.test(err.message);\n }\n\n // Check for nested error object\n if (err.error && typeof err.error === 'object') {\n return this.isNoUserRolesError(err.error);\n }\n\n return false;\n } catch (e) {\n console.error('Error while checking for user roles error:', e);\n return false;\n }\n }\n\n /**\n * Called when token refresh fails irrecoverably mid-session.\n * Shows a brief notification overlay, then forces logout to clear caches and redirect to login.\n */\n private handleSessionExpired(error: Error): void {\n // Guard against multiple concurrent calls (e.g., parallel GraphQL requests all failing)\n if (this._sessionExpiredHandled) {\n return;\n }\n this._sessionExpiredHandled = true;\n\n console.warn('[Workspace] Session expired, forcing re-authentication:', error.message);\n\n this.showSessionExpiredOverlay();\n\n // Give the user a moment to read the message, then logout\n setTimeout(async () => {\n try {\n await this.authBase.logout();\n } catch (logoutError) {\n console.error('[Workspace] Error during forced logout:', logoutError);\n // Last resort: reload the page to clear state\n window.location.reload();\n }\n }, 3000);\n }\n\n /**\n * Creates a simple DOM overlay notifying the user their session has expired.\n * Uses inline styles so it works regardless of Angular component encapsulation.\n */\n private showSessionExpiredOverlay(): void {\n const overlay = document.createElement('div');\n overlay.setAttribute('style', [\n 'position: fixed',\n 'inset: 0',\n 'z-index: 999999',\n 'display: flex',\n 'align-items: center',\n 'justify-content: center',\n 'background: rgba(0, 0, 0, 0.6)',\n 'backdrop-filter: blur(4px)',\n ].join(';'));\n\n const card = document.createElement('div');\n card.setAttribute('style', [\n 'background: var(--mj-bg-surface, #fff)',\n 'color: var(--mj-text-primary, #333)',\n 'border-radius: 12px',\n 'padding: 32px 40px',\n 'max-width: 420px',\n 'text-align: center',\n 'box-shadow: 0 8px 32px rgba(0, 0, 0, 0.25)',\n 'font-family: -apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, sans-serif',\n ].join(';'));\n\n card.innerHTML = `\n <div style=\"font-size: 40px; margin-bottom: 16px;\">\n <i class=\"fa-solid fa-clock\" style=\"color: var(--mj-status-warning, #ef6c00);\"></i>\n </div>\n <h2 style=\"margin: 0 0 8px; font-size: 20px; font-weight: 600;\">Session Expired</h2>\n <p style=\"margin: 0 0 16px; font-size: 14px; color: var(--mj-text-secondary, #666);\">\n Your session has expired. You will be redirected to log in again.\n </p>\n <div style=\"font-size: 13px; color: var(--mj-text-muted, #999);\">Redirecting...</div>\n `;\n\n overlay.appendChild(card);\n document.body.appendChild(overlay);\n }\n\n /**\n * Handle authentication retry with backoff\n * Replaces AppComponent.handleAuthRetry() logic\n */\n async HandleAuthRetry(error: WorkspaceInitError, currentPath: string): Promise<boolean> {\n if (!error.shouldRetry) {\n return false;\n }\n\n const retryKey = 'auth-retry-dt';\n const lastRetryDateTime = localStorage.getItem(retryKey);\n const yesterday = +new Date(Date.now() - 1 * 24 * 60 * 60 * 1000);\n const retriedRecently = lastRetryDateTime && +new Date(lastRetryDateTime) > yesterday;\n\n if (!retriedRecently && error.type === 'token_expired') {\n LogStatus('JWT Expired, retrying once: ' + error.message);\n localStorage.setItem(retryKey, new Date().toISOString());\n\n const login$ = this.authBase.login({ appState: { target: currentPath } });\n await lastValueFrom(login$);\n\n return true;\n }\n\n return false;\n }\n\n /** @deprecated Use {@link HandleAuthRetry}. */\n async handleAuthRetry(error: WorkspaceInitError, currentPath: string): Promise<boolean> {\n return this.HandleAuthRetry(error, currentPath);\n }\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@memberjunction/ng-workspace-initializer",
3
- "version": "6.2.0-edge.5",
3
+ "version": "6.2.0-edge.6",
4
4
  "description": "MemberJunction: Workspace Initialization Service and Components",
5
5
  "main": "./dist/public-api.js",
6
6
  "typings": "./dist/public-api.d.ts",
@@ -17,7 +17,8 @@
17
17
  "license": "BUSL-1.1",
18
18
  "devDependencies": {
19
19
  "@angular/compiler": "21.2.22",
20
- "@angular/compiler-cli": "21.2.22"
20
+ "@angular/compiler-cli": "21.2.22",
21
+ "vitest": "^4.0.18"
21
22
  },
22
23
  "peerDependencies": {
23
24
  "@angular/common": "^21.2.22",
@@ -25,15 +26,15 @@
25
26
  "@angular/forms": "^21.2.22"
26
27
  },
27
28
  "dependencies": {
28
- "@memberjunction/core": "6.2.0-edge.5",
29
- "@memberjunction/core-entities": "6.2.0-edge.5",
30
- "@memberjunction/global": "6.2.0-edge.5",
31
- "@memberjunction/theme-engine": "6.2.0-edge.5",
32
- "@memberjunction/graphql-dataprovider": "6.2.0-edge.5",
33
- "@memberjunction/ng-auth-services": "6.2.0-edge.5",
34
- "@memberjunction/ng-explorer-core": "6.2.0-edge.5",
35
- "@memberjunction/ng-shared": "6.2.0-edge.5",
36
- "@memberjunction/ng-shared-generic": "6.2.0-edge.5",
29
+ "@memberjunction/core": "6.2.0-edge.6",
30
+ "@memberjunction/core-entities": "6.2.0-edge.6",
31
+ "@memberjunction/global": "6.2.0-edge.6",
32
+ "@memberjunction/theme-engine": "6.2.0-edge.6",
33
+ "@memberjunction/graphql-dataprovider": "6.2.0-edge.6",
34
+ "@memberjunction/ng-auth-services": "6.2.0-edge.6",
35
+ "@memberjunction/ng-explorer-core": "6.2.0-edge.6",
36
+ "@memberjunction/ng-shared": "6.2.0-edge.6",
37
+ "@memberjunction/ng-shared-generic": "6.2.0-edge.6",
37
38
  "rxjs": "^7.8.2",
38
39
  "tslib": "^2.8.1"
39
40
  },
@@ -44,7 +45,7 @@
44
45
  },
45
46
  "mjUILayer": "surface",
46
47
  "scripts": {
47
- "test": "echo \"No tests configured yet\"",
48
+ "test": "vitest run",
48
49
  "build": "ngc"
49
50
  }
50
51
  }