@memberjunction/ng-base-application 6.2.0-edge.3 → 6.2.0-edge.5

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.
Files changed (35) hide show
  1. package/dist/lib/__tests__/base-application.test.js +103 -0
  2. package/dist/lib/__tests__/base-application.test.js.map +1 -1
  3. package/dist/lib/__tests__/permission-constrained-boot.test.d.ts +2 -0
  4. package/dist/lib/__tests__/permission-constrained-boot.test.d.ts.map +1 -0
  5. package/dist/lib/__tests__/permission-constrained-boot.test.js +114 -0
  6. package/dist/lib/__tests__/permission-constrained-boot.test.js.map +1 -0
  7. package/dist/lib/__tests__/tab-service-url-replacement.test.d.ts +2 -0
  8. package/dist/lib/__tests__/tab-service-url-replacement.test.d.ts.map +1 -0
  9. package/dist/lib/__tests__/tab-service-url-replacement.test.js +33 -0
  10. package/dist/lib/__tests__/tab-service-url-replacement.test.js.map +1 -0
  11. package/dist/lib/__tests__/workspace-journal.test.d.ts +2 -0
  12. package/dist/lib/__tests__/workspace-journal.test.d.ts.map +1 -0
  13. package/dist/lib/__tests__/workspace-journal.test.js +317 -0
  14. package/dist/lib/__tests__/workspace-journal.test.js.map +1 -0
  15. package/dist/lib/application-manager.d.ts +21 -0
  16. package/dist/lib/application-manager.d.ts.map +1 -1
  17. package/dist/lib/application-manager.js +59 -5
  18. package/dist/lib/application-manager.js.map +1 -1
  19. package/dist/lib/tab.service.d.ts +21 -0
  20. package/dist/lib/tab.service.d.ts.map +1 -1
  21. package/dist/lib/tab.service.js +34 -0
  22. package/dist/lib/tab.service.js.map +1 -1
  23. package/dist/lib/workspace-journal.d.ts +87 -0
  24. package/dist/lib/workspace-journal.d.ts.map +1 -0
  25. package/dist/lib/workspace-journal.js +123 -0
  26. package/dist/lib/workspace-journal.js.map +1 -0
  27. package/dist/lib/workspace-state-manager.d.ts +57 -1
  28. package/dist/lib/workspace-state-manager.d.ts.map +1 -1
  29. package/dist/lib/workspace-state-manager.js +159 -11
  30. package/dist/lib/workspace-state-manager.js.map +1 -1
  31. package/dist/public-api.d.ts +1 -0
  32. package/dist/public-api.d.ts.map +1 -1
  33. package/dist/public-api.js +1 -0
  34. package/dist/public-api.js.map +1 -1
  35. package/package.json +4 -4
@@ -2,7 +2,25 @@ import { Observable } from 'rxjs';
2
2
  import { IMetadataProvider } from '@memberjunction/core';
3
3
  import { WorkspaceConfiguration, WorkspaceTab } from './interfaces/workspace-configuration.interface';
4
4
  import { TabRequest } from './interfaces/tab-request.interface';
5
+ import { WorkspaceJournal } from './workspace-journal';
5
6
  import * as i0 from "@angular/core";
7
+ /**
8
+ * Options for {@link WorkspaceStateManager.Initialize}.
9
+ */
10
+ export interface WorkspaceInitializeOptions {
11
+ /**
12
+ * Adjusts the loaded configuration BEFORE it is published to any subscriber.
13
+ *
14
+ * The shell uses this to make a deep link win on a full page load: the URL's query params
15
+ * are written into the matching restored tab before the tab container mounts that tab's
16
+ * component. Applying them afterwards (when the resolver's queued tab request replays) is
17
+ * too late — the component has already initialised from the saved params, and an async
18
+ * init that writes its selection back can clobber the URL's params entirely.
19
+ *
20
+ * Return the same object for "no change"; a different object is published and persisted.
21
+ */
22
+ PrepareConfiguration?: (config: WorkspaceConfiguration) => WorkspaceConfiguration | Promise<WorkspaceConfiguration>;
23
+ }
6
24
  /**
7
25
  * Manages workspace state including tabs, layout, and persistence.
8
26
  *
@@ -16,6 +34,23 @@ export declare class WorkspaceStateManager {
16
34
  private loading$;
17
35
  private tabBarVisible$;
18
36
  private initialized;
37
+ /** The user this manager was initialized for (journal key). */
38
+ private userId;
39
+ /** A configuration change has been requested but not yet handed to the database. */
40
+ private savePending;
41
+ /**
42
+ * The database save currently running, if any. Saves run one at a time: they share one
43
+ * `MJ: Workspaces` entity instance, and a flush on page hide must not start a second
44
+ * `Save()` on it while the debounced one is still in flight.
45
+ */
46
+ private saveInFlight;
47
+ /** The serialized configuration the in-flight save is writing (journaled — see WorkspaceJournalEntry.InFlightConfiguration). */
48
+ private inFlightConfiguration;
49
+ /**
50
+ * Synchronous browser-local snapshot of the newest configuration — see {@link WorkspaceJournal}.
51
+ * Replaceable for tests.
52
+ */
53
+ Journal: WorkspaceJournal;
19
54
  /**
20
55
  * Optional predicate identifying tabs that belong to the MAIN layout.
21
56
  * Tabs failing the predicate (e.g. record tabs under the records-style
@@ -99,7 +134,7 @@ export declare class WorkspaceStateManager {
99
134
  /**
100
135
  * Initialize the workspace state for a user
101
136
  */
102
- Initialize(userId: string): Promise<void>;
137
+ Initialize(userId: string, options?: WorkspaceInitializeOptions): Promise<void>;
103
138
  /**
104
139
  * Ephemeral mode: when `window.__MJ_EPHEMERAL_WORKSPACE__ === true` is set
105
140
  * (only baked into the regression test Explorer build via Dockerfile.explorer),
@@ -113,14 +148,35 @@ export declare class WorkspaceStateManager {
113
148
  * Load workspace from database using UserInfoEngine for centralized, cached access
114
149
  */
115
150
  private loadWorkspace;
151
+ /**
152
+ * Runs the caller's {@link WorkspaceInitializeOptions.PrepareConfiguration} hook, then
153
+ * publishes the result as the first configuration. Persists when the hook (or the journal)
154
+ * changed what the server holds.
155
+ */
156
+ private publishInitialConfiguration;
116
157
  /**
117
158
  * Persist configuration to database (debounced)
118
159
  */
119
160
  private persistConfiguration;
161
+ /**
162
+ * Runs the debounced save if one is still pending (a flush may already have run it). Saves are
163
+ * serialised: a call while one is in flight waits for it, then saves whatever is still pending.
164
+ */
165
+ private runPendingSave;
166
+ /**
167
+ * Persist any change still waiting in the save debounce NOW. Called automatically on
168
+ * `pagehide` and when the page becomes hidden; hosts may also call it before a deliberate
169
+ * reload or sign-out. A no-op when nothing is pending.
170
+ */
171
+ FlushPendingSave(): Promise<void>;
172
+ /** True while a configuration change is waiting for the debounced database save. */
173
+ get HasPendingSave(): boolean;
120
174
  /**
121
175
  * Request a save (will be debounced)
122
176
  */
123
177
  private requestSave;
178
+ /** Synchronously snapshot the current configuration to the browser journal. */
179
+ private writeJournal;
124
180
  /**
125
181
  * Update configuration and request save
126
182
  */
@@ -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AQG;IACH,MAAM,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI;IAY3B;;OAEG;IACH,SAAS,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI;IAgB9B;;OAEG;IACH,YAAY,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI;IAkBjC;;OAEG;IACH,kBAAkB,CAAC,MAAM,EAAE,MAAM,EAAE,GAAG,IAAI;IAe1C;;OAEG;IACH,YAAY,CAAC,MAAM,EAAE,sBAAsB,CAAC,QAAQ,CAAC,GAAG,IAAI;IAU5D;;;OAGG;IACH,mBAAmB,CAAC,aAAa,EAAE,sBAAsB,CAAC,eAAe,CAAC,GAAG,IAAI;IAUjF;;OAEG;IACH,MAAM,CAAC,KAAK,EAAE,MAAM,GAAG,YAAY,GAAG,SAAS;IAI/C;;OAEG;IACH,UAAU,CAAC,KAAK,EAAE,MAAM,GAAG,YAAY,EAAE;IAIzC;;OAEG;IACH,cAAc,CAAC,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,IAAI;IAgBrD;;;;;OAKG;IACH,sBAAsB,CAAC,KAAK,EAAE,MAAM,EAAE,YAAY,EAAE,OAAO,CAAC,YAAY,CAAC,eAAe,CAAC,CAAC,GAAG,IAAI;IAyBjG;;;;;;;;;OASG;IACH,yBAAyB,CAAC,KAAK,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,GAAG,IAAI;IA2BnE;;OAEG;IACH,cAAc,IAAI,MAAM,GAAG,IAAI;IAI/B;;OAEG;IACH,OAAO,CAAC,YAAY;yCAr/BT,qBAAqB;6CAArB,qBAAqB;CA4/BjC"}
@@ -4,6 +4,7 @@ import { debounceTime } from 'rxjs/operators';
4
4
  import { Metadata, LogStatus } from '@memberjunction/core';
5
5
  import { UserInfoEngine } from '@memberjunction/core-entities';
6
6
  import { CreateDefaultWorkspaceConfiguration } from './interfaces/workspace-configuration.interface';
7
+ import { BrowserWorkspaceJournalStorage, ShouldUseWorkspaceJournal, WorkspaceJournal } from './workspace-journal';
7
8
  import * as i0 from "@angular/core";
8
9
  /**
9
10
  * Manages workspace state including tabs, layout, and persistence.
@@ -18,6 +19,23 @@ export class WorkspaceStateManager {
18
19
  loading$ = new BehaviorSubject(false);
19
20
  tabBarVisible$ = new BehaviorSubject(true);
20
21
  initialized = false;
22
+ /** The user this manager was initialized for (journal key). */
23
+ userId = null;
24
+ /** A configuration change has been requested but not yet handed to the database. */
25
+ savePending = false;
26
+ /**
27
+ * The database save currently running, if any. Saves run one at a time: they share one
28
+ * `MJ: Workspaces` entity instance, and a flush on page hide must not start a second
29
+ * `Save()` on it while the debounced one is still in flight.
30
+ */
31
+ saveInFlight = null;
32
+ /** The serialized configuration the in-flight save is writing (journaled — see WorkspaceJournalEntry.InFlightConfiguration). */
33
+ inFlightConfiguration = null;
34
+ /**
35
+ * Synchronous browser-local snapshot of the newest configuration — see {@link WorkspaceJournal}.
36
+ * Replaceable for tests.
37
+ */
38
+ Journal = new WorkspaceJournal(BrowserWorkspaceJournalStorage);
21
39
  /**
22
40
  * Optional predicate identifying tabs that belong to the MAIN layout.
23
41
  * Tabs failing the predicate (e.g. record tabs under the records-style
@@ -87,8 +105,22 @@ export class WorkspaceStateManager {
87
105
  // Set up debounced saves
88
106
  this.saveRequest$.pipe(debounceTime(500) // Wait 500ms after last change
89
107
  ).subscribe(() => {
90
- this.persistConfiguration();
108
+ this.runPendingSave();
91
109
  });
110
+ // Flush the debounced save when the page is going away or being backgrounded, so a
111
+ // refresh/close inside the debounce window doesn't drop the newest change. (The journal
112
+ // already holds it locally; this gets it to the database too.) beforeunload is avoided
113
+ // deliberately: registering it makes the page ineligible for the back/forward cache.
114
+ if (typeof window !== 'undefined' && typeof window.addEventListener === 'function') {
115
+ window.addEventListener('pagehide', () => { void this.FlushPendingSave(); });
116
+ if (typeof document !== 'undefined') {
117
+ document.addEventListener('visibilitychange', () => {
118
+ if (document.visibilityState === 'hidden') {
119
+ void this.FlushPendingSave();
120
+ }
121
+ });
122
+ }
123
+ }
92
124
  // Update tab bar visibility whenever configuration changes
93
125
  this.configuration$.subscribe(config => {
94
126
  if (config) {
@@ -146,13 +178,14 @@ export class WorkspaceStateManager {
146
178
  /**
147
179
  * Initialize the workspace state for a user
148
180
  */
149
- async Initialize(userId) {
181
+ async Initialize(userId, options) {
150
182
  if (this.initialized) {
151
183
  return;
152
184
  }
153
185
  this.loading$.next(true);
186
+ this.userId = userId;
154
187
  try {
155
- await this.loadWorkspace(userId);
188
+ await this.loadWorkspace(userId, options);
156
189
  this.initialized = true;
157
190
  }
158
191
  finally {
@@ -174,7 +207,7 @@ export class WorkspaceStateManager {
174
207
  /**
175
208
  * Load workspace from database using UserInfoEngine for centralized, cached access
176
209
  */
177
- async loadWorkspace(userId) {
210
+ async loadWorkspace(userId, options) {
178
211
  if (this.isEphemeral()) {
179
212
  // Test mode — skip server load entirely. Just emit a default config so the
180
213
  // workspace starts clean for this BrowserContext. No MJWorkspaceEntity is
@@ -187,7 +220,13 @@ export class WorkspaceStateManager {
187
220
  // Permission-denied ≠ empty — don't auto-create a workspace for denied users.
188
221
  if (engine.IsPermissionConstrained) {
189
222
  LogStatus('[WorkspaceStateManager] UserInfoEngine is permission-constrained, using default workspace configuration');
190
- this.configuration$.next(CreateDefaultWorkspaceConfiguration());
223
+ // No server row to persist to, but the browser journal still carries this session's
224
+ // tabs across a refresh.
225
+ const journal = this.Journal.Read(userId);
226
+ const base = ShouldUseWorkspaceJournal(journal, null, null) && journal
227
+ ? journal.Configuration
228
+ : CreateDefaultWorkspaceConfiguration();
229
+ await this.publishInitialConfiguration(base, options, false);
191
230
  return;
192
231
  }
193
232
  const workspaces = engine.Workspaces;
@@ -196,10 +235,19 @@ export class WorkspaceStateManager {
196
235
  this.workspace$.next(workspace);
197
236
  // Parse configuration or create default
198
237
  const configJson = workspace.Configuration;
199
- const config = configJson
238
+ const serverConfig = configJson
200
239
  ? JSON.parse(configJson)
201
240
  : CreateDefaultWorkspaceConfiguration();
202
- this.configuration$.next(config);
241
+ // A refresh inside the debounce/save window left a newer snapshot in the journal than
242
+ // the row we just read (or the row came from a stale local cache): the journal wins,
243
+ // and is pushed to the database.
244
+ const journal = this.Journal.Read(userId);
245
+ const useJournal = ShouldUseWorkspaceJournal(journal, workspace.ID, workspace.__mj_UpdatedAt, configJson) && journal != null
246
+ && JSON.stringify(journal.Configuration) !== JSON.stringify(serverConfig);
247
+ if (useJournal) {
248
+ LogStatus('[WorkspaceStateManager] Restoring workspace from the local journal (newer than the saved row)');
249
+ }
250
+ await this.publishInitialConfiguration(useJournal && journal ? journal.Configuration : serverConfig, options, useJournal);
203
251
  }
204
252
  else {
205
253
  // Create new workspace for user
@@ -211,7 +259,9 @@ export class WorkspaceStateManager {
211
259
  const saveResult = await workspace.Save();
212
260
  if (saveResult) {
213
261
  this.workspace$.next(workspace);
214
- this.configuration$.next(CreateDefaultWorkspaceConfiguration());
262
+ // Through the same path as a loaded row, so a brand-new user's first boot also gets the
263
+ // PrepareConfiguration hook (deep-link precedence) and a journal seeded on the new row.
264
+ await this.publishInitialConfiguration(CreateDefaultWorkspaceConfiguration(), options, false);
215
265
  }
216
266
  else {
217
267
  console.error('[WorkspaceStateManager.loadWorkspace] Failed to save workspace');
@@ -219,6 +269,31 @@ export class WorkspaceStateManager {
219
269
  }
220
270
  }
221
271
  }
272
+ /**
273
+ * Runs the caller's {@link WorkspaceInitializeOptions.PrepareConfiguration} hook, then
274
+ * publishes the result as the first configuration. Persists when the hook (or the journal)
275
+ * changed what the server holds.
276
+ */
277
+ async publishInitialConfiguration(config, options, alreadyDiffersFromServer) {
278
+ let prepared = config;
279
+ if (options?.PrepareConfiguration) {
280
+ try {
281
+ prepared = await options.PrepareConfiguration(config);
282
+ }
283
+ catch (e) {
284
+ // The hook is an enhancement (deep-link precedence); never let it block startup.
285
+ console.error('[WorkspaceStateManager] PrepareConfiguration failed; using the loaded configuration', e);
286
+ prepared = config;
287
+ }
288
+ }
289
+ this.configuration$.next(prepared);
290
+ if (alreadyDiffersFromServer || prepared !== config) {
291
+ this.requestSave();
292
+ }
293
+ else {
294
+ this.writeJournal(); // seed / re-base the snapshot on the row as loaded
295
+ }
296
+ }
222
297
  /**
223
298
  * Persist configuration to database (debounced)
224
299
  */
@@ -231,16 +306,87 @@ export class WorkspaceStateManager {
231
306
  const workspace = this.workspace$.value;
232
307
  const config = this.configuration$.value;
233
308
  if (workspace && config) {
234
- workspace.Configuration = JSON.stringify(config);
235
- await workspace.Save();
309
+ const json = JSON.stringify(config);
310
+ workspace.Configuration = json;
311
+ // Journal what this save writes BEFORE it is sent: if the page unloads while it is in flight
312
+ // and the write still lands, the next load recognises the newer row as this browser's own.
313
+ this.inFlightConfiguration = json;
314
+ this.writeJournal();
315
+ try {
316
+ await workspace.Save();
317
+ }
318
+ finally {
319
+ this.inFlightConfiguration = null;
320
+ // Re-base the journal on the stamp this save produced (a failed save leaves the stamp, and
321
+ // so the base, unchanged). The CURRENT configuration is written, not the one just saved:
322
+ // any change made while the save was in flight is newer still, and must keep winning.
323
+ this.writeJournal();
324
+ }
325
+ }
326
+ }
327
+ /**
328
+ * Runs the debounced save if one is still pending (a flush may already have run it). Saves are
329
+ * serialised: a call while one is in flight waits for it, then saves whatever is still pending.
330
+ */
331
+ runPendingSave() {
332
+ if (this.saveInFlight) {
333
+ return this.saveInFlight.then(() => this.runPendingSave());
334
+ }
335
+ if (!this.savePending) {
336
+ return Promise.resolve();
236
337
  }
338
+ this.savePending = false;
339
+ const run = this.persistConfiguration()
340
+ .catch((e) => {
341
+ // A failed save leaves the change in the journal; the next change (or load) retries it.
342
+ console.error('[WorkspaceStateManager] Workspace save failed', e);
343
+ })
344
+ .finally(() => {
345
+ if (this.saveInFlight === run) {
346
+ this.saveInFlight = null;
347
+ }
348
+ });
349
+ this.saveInFlight = run;
350
+ return run;
351
+ }
352
+ /**
353
+ * Persist any change still waiting in the save debounce NOW. Called automatically on
354
+ * `pagehide` and when the page becomes hidden; hosts may also call it before a deliberate
355
+ * reload or sign-out. A no-op when nothing is pending.
356
+ */
357
+ FlushPendingSave() {
358
+ return this.runPendingSave();
359
+ }
360
+ /** True while a configuration change is waiting for the debounced database save. */
361
+ get HasPendingSave() {
362
+ return this.savePending;
237
363
  }
238
364
  /**
239
365
  * Request a save (will be debounced)
240
366
  */
241
367
  requestSave() {
368
+ this.savePending = true;
369
+ this.writeJournal();
242
370
  this.saveRequest$.next();
243
371
  }
372
+ /** Synchronously snapshot the current configuration to the browser journal. */
373
+ writeJournal() {
374
+ const config = this.configuration$.value;
375
+ if (!config || !this.userId || this.isEphemeral()) {
376
+ return;
377
+ }
378
+ const workspace = this.workspace$.value;
379
+ // Typed Date, but a value that crossed the wire can still be an ISO string at runtime.
380
+ const base = workspace?.__mj_UpdatedAt;
381
+ this.Journal.Write({
382
+ Version: 1,
383
+ UserID: this.userId,
384
+ WorkspaceID: workspace?.ID ?? null,
385
+ BaseUpdatedAt: base instanceof Date ? base.toISOString() : (base ?? null),
386
+ InFlightConfiguration: this.inFlightConfiguration,
387
+ Configuration: config
388
+ });
389
+ }
244
390
  /**
245
391
  * Update configuration and request save
246
392
  */
@@ -255,7 +401,9 @@ export class WorkspaceStateManager {
255
401
  async ResetConfiguration() {
256
402
  const defaultConfig = CreateDefaultWorkspaceConfiguration();
257
403
  this.configuration$.next(defaultConfig);
258
- await this.persistConfiguration();
404
+ this.savePending = true;
405
+ this.writeJournal(); // the reset must also replace a (possibly corrupt) local snapshot
406
+ await this.runPendingSave(); // serialised with any save already in flight
259
407
  }
260
408
  /**
261
409
  * Force creation of a new tab, never replacing temporary tabs