@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.
- package/dist/lib/__tests__/base-application.test.js +103 -0
- package/dist/lib/__tests__/base-application.test.js.map +1 -1
- package/dist/lib/__tests__/permission-constrained-boot.test.d.ts +2 -0
- package/dist/lib/__tests__/permission-constrained-boot.test.d.ts.map +1 -0
- package/dist/lib/__tests__/permission-constrained-boot.test.js +114 -0
- package/dist/lib/__tests__/permission-constrained-boot.test.js.map +1 -0
- package/dist/lib/__tests__/tab-service-url-replacement.test.d.ts +2 -0
- package/dist/lib/__tests__/tab-service-url-replacement.test.d.ts.map +1 -0
- package/dist/lib/__tests__/tab-service-url-replacement.test.js +33 -0
- package/dist/lib/__tests__/tab-service-url-replacement.test.js.map +1 -0
- package/dist/lib/__tests__/workspace-journal.test.d.ts +2 -0
- package/dist/lib/__tests__/workspace-journal.test.d.ts.map +1 -0
- package/dist/lib/__tests__/workspace-journal.test.js +317 -0
- package/dist/lib/__tests__/workspace-journal.test.js.map +1 -0
- package/dist/lib/application-manager.d.ts +21 -0
- package/dist/lib/application-manager.d.ts.map +1 -1
- package/dist/lib/application-manager.js +59 -5
- package/dist/lib/application-manager.js.map +1 -1
- package/dist/lib/tab.service.d.ts +21 -0
- package/dist/lib/tab.service.d.ts.map +1 -1
- package/dist/lib/tab.service.js +34 -0
- package/dist/lib/tab.service.js.map +1 -1
- package/dist/lib/workspace-journal.d.ts +87 -0
- package/dist/lib/workspace-journal.d.ts.map +1 -0
- package/dist/lib/workspace-journal.js +123 -0
- package/dist/lib/workspace-journal.js.map +1 -0
- package/dist/lib/workspace-state-manager.d.ts +57 -1
- package/dist/lib/workspace-state-manager.d.ts.map +1 -1
- package/dist/lib/workspace-state-manager.js +159 -11
- package/dist/lib/workspace-state-manager.js.map +1 -1
- package/dist/public-api.d.ts +1 -0
- package/dist/public-api.d.ts.map +1 -1
- package/dist/public-api.js +1 -0
- package/dist/public-api.js.map +1 -1
- package/package.json +4 -4
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* TabService's record-URL replacement mark: after a record is deleted, the URL
|
|
3
|
+
* sync leaving that record's URL replaces its history entry (so browser Back
|
|
4
|
+
* can't reopen a deleted record). The mark is keyed by the record, not by "the
|
|
5
|
+
* next sync", and is consumed exactly once.
|
|
6
|
+
*/
|
|
7
|
+
import { describe, it, expect, vi } from 'vitest';
|
|
8
|
+
vi.mock('@angular/core', () => ({
|
|
9
|
+
Injectable: () => (target) => target,
|
|
10
|
+
}));
|
|
11
|
+
import { TabService } from '../tab.service';
|
|
12
|
+
describe('TabService record URL replacement', () => {
|
|
13
|
+
it('replaces nothing without a mark', () => {
|
|
14
|
+
const service = new TabService();
|
|
15
|
+
expect(service.ConsumeRecordUrlReplacement('MJ: Widgets', 'w1')).toBe(false);
|
|
16
|
+
});
|
|
17
|
+
it('replaces only when leaving the marked record, then clears the mark', () => {
|
|
18
|
+
const service = new TabService();
|
|
19
|
+
service.MarkRecordUrlForReplacement('MJ: Widgets', 'w1');
|
|
20
|
+
// An unrelated sync landing first must not consume the mark.
|
|
21
|
+
expect(service.ConsumeRecordUrlReplacement('MJ: Widgets', 'w2')).toBe(false);
|
|
22
|
+
expect(service.ConsumeRecordUrlReplacement('mj: widgets', 'W1')).toBe(true);
|
|
23
|
+
expect(service.ConsumeRecordUrlReplacement('MJ: Widgets', 'w1')).toBe(false);
|
|
24
|
+
});
|
|
25
|
+
it('keeps only the latest mark', () => {
|
|
26
|
+
const service = new TabService();
|
|
27
|
+
service.MarkRecordUrlForReplacement('MJ: Widgets', 'w1');
|
|
28
|
+
service.MarkRecordUrlForReplacement('MJ: Widgets', 'w2');
|
|
29
|
+
expect(service.ConsumeRecordUrlReplacement('MJ: Widgets', 'w1')).toBe(false);
|
|
30
|
+
expect(service.ConsumeRecordUrlReplacement('MJ: Widgets', 'w2')).toBe(true);
|
|
31
|
+
});
|
|
32
|
+
});
|
|
33
|
+
//# sourceMappingURL=tab-service-url-replacement.test.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tab-service-url-replacement.test.js","sourceRoot":"","sources":["../../../src/lib/__tests__/tab-service-url-replacement.test.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EAAE,QAAQ,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,QAAQ,CAAC;AAElD,EAAE,CAAC,IAAI,CAAC,eAAe,EAAE,GAAG,EAAE,CAAC,CAAC;IAC9B,UAAU,EAAE,GAAG,EAAE,CAAC,CAAC,MAAgB,EAAE,EAAE,CAAC,MAAM;CAC/C,CAAC,CAAC,CAAC;AAEJ,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAE5C,QAAQ,CAAC,mCAAmC,EAAE,GAAG,EAAE;IACjD,EAAE,CAAC,iCAAiC,EAAE,GAAG,EAAE;QACzC,MAAM,OAAO,GAAG,IAAI,UAAU,EAAE,CAAC;QACjC,MAAM,CAAC,OAAO,CAAC,2BAA2B,CAAC,aAAa,EAAE,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IAC/E,CAAC,CAAC,CAAC;IAEH,EAAE,CAAC,oEAAoE,EAAE,GAAG,EAAE;QAC5E,MAAM,OAAO,GAAG,IAAI,UAAU,EAAE,CAAC;QACjC,OAAO,CAAC,2BAA2B,CAAC,aAAa,EAAE,IAAI,CAAC,CAAC;QAEzD,6DAA6D;QAC7D,MAAM,CAAC,OAAO,CAAC,2BAA2B,CAAC,aAAa,EAAE,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QAE7E,MAAM,CAAC,OAAO,CAAC,2BAA2B,CAAC,aAAa,EAAE,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QAC5E,MAAM,CAAC,OAAO,CAAC,2BAA2B,CAAC,aAAa,EAAE,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IAC/E,CAAC,CAAC,CAAC;IAEH,EAAE,CAAC,4BAA4B,EAAE,GAAG,EAAE;QACpC,MAAM,OAAO,GAAG,IAAI,UAAU,EAAE,CAAC;QACjC,OAAO,CAAC,2BAA2B,CAAC,aAAa,EAAE,IAAI,CAAC,CAAC;QACzD,OAAO,CAAC,2BAA2B,CAAC,aAAa,EAAE,IAAI,CAAC,CAAC;QACzD,MAAM,CAAC,OAAO,CAAC,2BAA2B,CAAC,aAAa,EAAE,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QAC7E,MAAM,CAAC,OAAO,CAAC,2BAA2B,CAAC,aAAa,EAAE,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IAC9E,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC","sourcesContent":["/**\n * TabService's record-URL replacement mark: after a record is deleted, the URL\n * sync leaving that record's URL replaces its history entry (so browser Back\n * can't reopen a deleted record). The mark is keyed by the record, not by \"the\n * next sync\", and is consumed exactly once.\n */\nimport { describe, it, expect, vi } from 'vitest';\n\nvi.mock('@angular/core', () => ({\n Injectable: () => (target: Function) => target,\n}));\n\nimport { TabService } from '../tab.service';\n\ndescribe('TabService record URL replacement', () => {\n it('replaces nothing without a mark', () => {\n const service = new TabService();\n expect(service.ConsumeRecordUrlReplacement('MJ: Widgets', 'w1')).toBe(false);\n });\n\n it('replaces only when leaving the marked record, then clears the mark', () => {\n const service = new TabService();\n service.MarkRecordUrlForReplacement('MJ: Widgets', 'w1');\n\n // An unrelated sync landing first must not consume the mark.\n expect(service.ConsumeRecordUrlReplacement('MJ: Widgets', 'w2')).toBe(false);\n\n expect(service.ConsumeRecordUrlReplacement('mj: widgets', 'W1')).toBe(true);\n expect(service.ConsumeRecordUrlReplacement('MJ: Widgets', 'w1')).toBe(false);\n });\n\n it('keeps only the latest mark', () => {\n const service = new TabService();\n service.MarkRecordUrlForReplacement('MJ: Widgets', 'w1');\n service.MarkRecordUrlForReplacement('MJ: Widgets', 'w2');\n expect(service.ConsumeRecordUrlReplacement('MJ: Widgets', 'w1')).toBe(false);\n expect(service.ConsumeRecordUrlReplacement('MJ: Widgets', 'w2')).toBe(true);\n });\n});\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"workspace-journal.test.d.ts","sourceRoot":"","sources":["../../../src/lib/__tests__/workspace-journal.test.ts"],"names":[],"mappings":""}
|
|
@@ -0,0 +1,317 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A refresh within a few seconds of a workspace change used to come back one step behind: the
|
|
3
|
+
* change was only in memory until the 500ms debounce fired AND the async entity save landed.
|
|
4
|
+
* These tests pin the fix — a synchronous browser journal, a flush on page hide, and the
|
|
5
|
+
* PrepareConfiguration hook the shell uses to make a deep link win over the saved workspace.
|
|
6
|
+
*/
|
|
7
|
+
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
|
8
|
+
import { ShouldUseWorkspaceJournal, WorkspaceJournal } from '../workspace-journal';
|
|
9
|
+
vi.mock('@angular/core', () => ({
|
|
10
|
+
Injectable: () => (target) => target,
|
|
11
|
+
}));
|
|
12
|
+
vi.mock('@memberjunction/core', () => ({
|
|
13
|
+
Metadata: class {
|
|
14
|
+
},
|
|
15
|
+
LogError: vi.fn(),
|
|
16
|
+
LogStatus: vi.fn(),
|
|
17
|
+
}));
|
|
18
|
+
/** A minimal stand-in for MJWorkspaceEntity: Save() stamps a new server __mj_UpdatedAt. */
|
|
19
|
+
class FakeWorkspace {
|
|
20
|
+
ID = 'WS-1';
|
|
21
|
+
UserID = 'user-1';
|
|
22
|
+
Configuration = '';
|
|
23
|
+
__mj_UpdatedAt = new Date('2026-10-01T10:00:00.000Z');
|
|
24
|
+
saves = [];
|
|
25
|
+
Save = vi.fn(async () => {
|
|
26
|
+
this.saves.push(this.Configuration);
|
|
27
|
+
this.__mj_UpdatedAt = new Date(this.__mj_UpdatedAt.getTime() + 60_000);
|
|
28
|
+
return true;
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
const engineState = { workspaces: [], constrained: false };
|
|
32
|
+
vi.mock('@memberjunction/core-entities', () => ({
|
|
33
|
+
UserInfoEngine: {
|
|
34
|
+
get Instance() {
|
|
35
|
+
return {
|
|
36
|
+
get IsPermissionConstrained() { return engineState.constrained; },
|
|
37
|
+
get Workspaces() { return engineState.workspaces; },
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
},
|
|
41
|
+
MJWorkspaceEntity: class {
|
|
42
|
+
},
|
|
43
|
+
}));
|
|
44
|
+
import { WorkspaceStateManager } from '../workspace-state-manager';
|
|
45
|
+
class MemoryStorage {
|
|
46
|
+
data = new Map();
|
|
47
|
+
getItem(key) { return this.data.get(key) ?? null; }
|
|
48
|
+
setItem(key, value) { this.data.set(key, value); }
|
|
49
|
+
removeItem(key) { this.data.delete(key); }
|
|
50
|
+
}
|
|
51
|
+
function config(tabIds, active, params) {
|
|
52
|
+
return {
|
|
53
|
+
version: 1,
|
|
54
|
+
activeTabId: active,
|
|
55
|
+
theme: 'light',
|
|
56
|
+
preferences: { tabPosition: 'top', showTabIcons: true, autoSaveInterval: 5000 },
|
|
57
|
+
tabs: tabIds.map((id, i) => ({
|
|
58
|
+
id, applicationId: 'app-1', title: id, resourceTypeId: '', resourceRecordId: '', isPinned: true, sequence: i,
|
|
59
|
+
lastAccessedAt: '2026-10-01T10:00:00.000Z',
|
|
60
|
+
configuration: params ? { resourceType: 'Custom', queryParams: params } : { resourceType: 'Custom' }
|
|
61
|
+
}))
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
function managerWith(storage) {
|
|
65
|
+
const m = new WorkspaceStateManager();
|
|
66
|
+
m.Journal = new WorkspaceJournal(() => storage);
|
|
67
|
+
return m;
|
|
68
|
+
}
|
|
69
|
+
describe('ShouldUseWorkspaceJournal', () => {
|
|
70
|
+
const entry = (base, ws = 'WS-1') => ({ Version: 1, UserID: 'user-1', WorkspaceID: ws, BaseUpdatedAt: base, Configuration: config(['a'], 'a') });
|
|
71
|
+
it('wins when the server row has not been saved since the snapshot base', () => {
|
|
72
|
+
expect(ShouldUseWorkspaceJournal(entry('2026-10-01T10:00:00.000Z'), 'WS-1', new Date('2026-10-01T10:00:00.000Z'))).toBe(true);
|
|
73
|
+
});
|
|
74
|
+
it('wins over an OLDER row (a stale locally cached copy)', () => {
|
|
75
|
+
expect(ShouldUseWorkspaceJournal(entry('2026-10-01T10:05:00.000Z'), 'ws-1', '2026-10-01T10:00:00.000Z')).toBe(true);
|
|
76
|
+
});
|
|
77
|
+
it('loses to a row saved later by something this browser never saw (another device)', () => {
|
|
78
|
+
expect(ShouldUseWorkspaceJournal(entry('2026-10-01T10:00:00.000Z'), 'WS-1', new Date('2026-10-01T10:00:01.000Z'))).toBe(false);
|
|
79
|
+
});
|
|
80
|
+
it('loses when it belongs to another workspace row, or has no base to compare', () => {
|
|
81
|
+
expect(ShouldUseWorkspaceJournal(entry('2026-10-01T10:00:00.000Z', 'WS-2'), 'WS-1', new Date('2026-10-01T09:00:00.000Z'))).toBe(false);
|
|
82
|
+
expect(ShouldUseWorkspaceJournal(entry(null), 'WS-1', new Date('2026-10-01T09:00:00.000Z'))).toBe(false);
|
|
83
|
+
expect(ShouldUseWorkspaceJournal(null, 'WS-1', null)).toBe(false);
|
|
84
|
+
});
|
|
85
|
+
it('wins over a later row that is exactly its own in-flight save (landed after the page unloaded)', () => {
|
|
86
|
+
const inFlight = JSON.stringify(config(['a', 'b'], 'b'));
|
|
87
|
+
const e = { ...entry('2026-10-01T10:00:00.000Z'), InFlightConfiguration: inFlight };
|
|
88
|
+
expect(ShouldUseWorkspaceJournal(e, 'WS-1', new Date('2026-10-01T10:01:00.000Z'), inFlight)).toBe(true);
|
|
89
|
+
expect(ShouldUseWorkspaceJournal(e, 'WS-1', new Date('2026-10-01T10:01:00.000Z'), JSON.stringify(config(['z'], 'z'))), 'another device\'s row still wins').toBe(false);
|
|
90
|
+
});
|
|
91
|
+
it('is used for a session with no workspace row only when the entry has none either', () => {
|
|
92
|
+
expect(ShouldUseWorkspaceJournal(entry(null, null), null, null)).toBe(true);
|
|
93
|
+
expect(ShouldUseWorkspaceJournal(entry(null, 'WS-1'), null, null)).toBe(false);
|
|
94
|
+
});
|
|
95
|
+
});
|
|
96
|
+
describe('WorkspaceJournal', () => {
|
|
97
|
+
it('ignores unreadable, foreign-user and wrong-version entries, and survives a throwing storage', () => {
|
|
98
|
+
const storage = new MemoryStorage();
|
|
99
|
+
const journal = new WorkspaceJournal(() => storage);
|
|
100
|
+
storage.setItem(WorkspaceJournal.KeyFor('user-1'), '{not json');
|
|
101
|
+
expect(journal.Read('user-1')).toBeNull();
|
|
102
|
+
storage.setItem(WorkspaceJournal.KeyFor('user-1'), JSON.stringify({ Version: 2, UserID: 'user-1', Configuration: config([], null) }));
|
|
103
|
+
expect(journal.Read('user-1')).toBeNull();
|
|
104
|
+
const throwing = new WorkspaceJournal(() => { throw new Error('SecurityError'); });
|
|
105
|
+
expect(() => throwing.Write({ Version: 1, UserID: 'u', WorkspaceID: null, BaseUpdatedAt: null, Configuration: config([], null) })).not.toThrow();
|
|
106
|
+
expect(throwing.Read('u')).toBeNull();
|
|
107
|
+
});
|
|
108
|
+
});
|
|
109
|
+
describe('WorkspaceStateManager — refresh inside the save window', () => {
|
|
110
|
+
beforeEach(() => {
|
|
111
|
+
engineState.constrained = false;
|
|
112
|
+
engineState.workspaces = [];
|
|
113
|
+
});
|
|
114
|
+
it('journals every change synchronously, before the debounced save runs', () => {
|
|
115
|
+
const storage = new MemoryStorage();
|
|
116
|
+
const ws = new FakeWorkspace();
|
|
117
|
+
ws.Configuration = JSON.stringify(config(['a', 'b'], 'a'));
|
|
118
|
+
engineState.workspaces = [ws];
|
|
119
|
+
const m = managerWith(storage);
|
|
120
|
+
return m.Initialize('user-1').then(() => {
|
|
121
|
+
m.SetActiveTab('b');
|
|
122
|
+
const entry = m.Journal.Read('user-1');
|
|
123
|
+
expect(entry?.Configuration.activeTabId).toBe('b');
|
|
124
|
+
expect(ws.Save, 'nothing has reached the database yet').not.toHaveBeenCalled();
|
|
125
|
+
expect(m.HasPendingSave).toBe(true);
|
|
126
|
+
});
|
|
127
|
+
});
|
|
128
|
+
it('a reload that finds the row one step behind restores the journal and re-saves it', async () => {
|
|
129
|
+
const storage = new MemoryStorage();
|
|
130
|
+
// Session 1: a change is made, the page is reloaded before any save lands.
|
|
131
|
+
const ws1 = new FakeWorkspace();
|
|
132
|
+
ws1.Configuration = JSON.stringify(config(['a', 'b'], 'a'));
|
|
133
|
+
engineState.workspaces = [ws1];
|
|
134
|
+
const first = managerWith(storage);
|
|
135
|
+
await first.Initialize('user-1');
|
|
136
|
+
first.SetActiveTab('b');
|
|
137
|
+
// Session 2: the server row is still the pre-change one.
|
|
138
|
+
const ws2 = new FakeWorkspace();
|
|
139
|
+
ws2.Configuration = JSON.stringify(config(['a', 'b'], 'a'));
|
|
140
|
+
engineState.workspaces = [ws2];
|
|
141
|
+
const second = managerWith(storage);
|
|
142
|
+
await second.Initialize('user-1');
|
|
143
|
+
expect(second.GetConfiguration()?.activeTabId, 'the newest change survived the reload').toBe('b');
|
|
144
|
+
expect(second.HasPendingSave, 'the restored snapshot is queued for the database').toBe(true);
|
|
145
|
+
await second.FlushPendingSave();
|
|
146
|
+
expect(JSON.parse(ws2.saves[0]).activeTabId).toBe('b');
|
|
147
|
+
});
|
|
148
|
+
it('a row saved later elsewhere beats the local journal', async () => {
|
|
149
|
+
const storage = new MemoryStorage();
|
|
150
|
+
const ws1 = new FakeWorkspace();
|
|
151
|
+
ws1.Configuration = JSON.stringify(config(['a', 'b'], 'a'));
|
|
152
|
+
engineState.workspaces = [ws1];
|
|
153
|
+
const first = managerWith(storage);
|
|
154
|
+
await first.Initialize('user-1');
|
|
155
|
+
first.SetActiveTab('b');
|
|
156
|
+
const ws2 = new FakeWorkspace();
|
|
157
|
+
ws2.Configuration = JSON.stringify(config(['a', 'c'], 'c'));
|
|
158
|
+
ws2.__mj_UpdatedAt = new Date('2026-10-02T00:00:00.000Z'); // saved by another device afterwards
|
|
159
|
+
engineState.workspaces = [ws2];
|
|
160
|
+
const second = managerWith(storage);
|
|
161
|
+
await second.Initialize('user-1');
|
|
162
|
+
expect(second.GetConfiguration()?.activeTabId).toBe('c');
|
|
163
|
+
expect(second.HasPendingSave).toBe(false);
|
|
164
|
+
});
|
|
165
|
+
it('FlushPendingSave persists immediately, then the debounce has nothing left to do', async () => {
|
|
166
|
+
vi.useFakeTimers();
|
|
167
|
+
try {
|
|
168
|
+
const storage = new MemoryStorage();
|
|
169
|
+
const ws = new FakeWorkspace();
|
|
170
|
+
ws.Configuration = JSON.stringify(config(['a', 'b'], 'a'));
|
|
171
|
+
engineState.workspaces = [ws];
|
|
172
|
+
const m = managerWith(storage);
|
|
173
|
+
await m.Initialize('user-1');
|
|
174
|
+
m.SetActiveTab('b');
|
|
175
|
+
await m.FlushPendingSave();
|
|
176
|
+
expect(ws.Save).toHaveBeenCalledTimes(1);
|
|
177
|
+
expect(JSON.parse(ws.saves[0]).activeTabId).toBe('b');
|
|
178
|
+
await vi.advanceTimersByTimeAsync(1000);
|
|
179
|
+
expect(ws.Save, 'the debounced save must not run a second time').toHaveBeenCalledTimes(1);
|
|
180
|
+
// The journal is re-based on the stamp the save produced, so the next load trusts it.
|
|
181
|
+
expect(m.Journal.Read('user-1')?.BaseUpdatedAt).toBe(ws.__mj_UpdatedAt.toISOString());
|
|
182
|
+
}
|
|
183
|
+
finally {
|
|
184
|
+
vi.useRealTimers();
|
|
185
|
+
}
|
|
186
|
+
});
|
|
187
|
+
it('a change made while a save is in flight survives that save landing after the page unloaded', async () => {
|
|
188
|
+
const storage = new MemoryStorage();
|
|
189
|
+
const ws1 = new FakeWorkspace();
|
|
190
|
+
ws1.Configuration = JSON.stringify(config(['a', 'b', 'c'], 'a'));
|
|
191
|
+
engineState.workspaces = [ws1];
|
|
192
|
+
let landSave = () => undefined;
|
|
193
|
+
ws1.Save.mockImplementationOnce(() => new Promise(resolve => { landSave = () => resolve(true); }));
|
|
194
|
+
const first = managerWith(storage);
|
|
195
|
+
await first.Initialize('user-1');
|
|
196
|
+
first.SetActiveTab('b');
|
|
197
|
+
const saving = first.FlushPendingSave(); // save of B is now in flight
|
|
198
|
+
first.SetActiveTab('c'); // change C journaled while it flies
|
|
199
|
+
const unloadSnapshot = new Map(storage.data); // the page unloads here; B still lands on the server
|
|
200
|
+
landSave();
|
|
201
|
+
await saving;
|
|
202
|
+
const ws2 = new FakeWorkspace();
|
|
203
|
+
ws2.Configuration = ws1.Configuration; // the server row holds exactly what the save of B sent ...
|
|
204
|
+
ws2.__mj_UpdatedAt = new Date('2026-10-01T10:01:00.000Z'); // ... stamped after the journal's base
|
|
205
|
+
engineState.workspaces = [ws2];
|
|
206
|
+
const reloaded = new MemoryStorage();
|
|
207
|
+
reloaded.data = unloadSnapshot;
|
|
208
|
+
const second = managerWith(reloaded);
|
|
209
|
+
await second.Initialize('user-1');
|
|
210
|
+
expect(second.GetConfiguration()?.activeTabId, 'C was not discarded in favour of the older B').toBe('c');
|
|
211
|
+
});
|
|
212
|
+
it('runs one save at a time: a flush during an in-flight save waits for it, then saves the newest change', async () => {
|
|
213
|
+
const storage = new MemoryStorage();
|
|
214
|
+
const ws = new FakeWorkspace();
|
|
215
|
+
ws.Configuration = JSON.stringify(config(['a', 'b', 'c'], 'a'));
|
|
216
|
+
engineState.workspaces = [ws];
|
|
217
|
+
let landFirst = () => undefined;
|
|
218
|
+
let concurrent = 0;
|
|
219
|
+
let maxConcurrent = 0;
|
|
220
|
+
const original = ws.Save.getMockImplementation();
|
|
221
|
+
ws.Save.mockImplementation(async () => {
|
|
222
|
+
concurrent++;
|
|
223
|
+
maxConcurrent = Math.max(maxConcurrent, concurrent);
|
|
224
|
+
if (ws.saves.length === 0) {
|
|
225
|
+
await new Promise(resolve => { landFirst = resolve; });
|
|
226
|
+
}
|
|
227
|
+
const ok = await original();
|
|
228
|
+
concurrent--;
|
|
229
|
+
return ok;
|
|
230
|
+
});
|
|
231
|
+
const m = managerWith(storage);
|
|
232
|
+
await m.Initialize('user-1');
|
|
233
|
+
m.SetActiveTab('b');
|
|
234
|
+
const firstSave = m.FlushPendingSave();
|
|
235
|
+
m.SetActiveTab('c');
|
|
236
|
+
const secondFlush = m.FlushPendingSave(); // e.g. pagehide while the debounced save flies
|
|
237
|
+
await Promise.resolve();
|
|
238
|
+
expect(ws.Save, 'the second save waits for the first').toHaveBeenCalledTimes(1);
|
|
239
|
+
landFirst();
|
|
240
|
+
await Promise.all([firstSave, secondFlush]);
|
|
241
|
+
expect(maxConcurrent).toBe(1);
|
|
242
|
+
expect(ws.saves.map(c => JSON.parse(c).activeTabId)).toEqual(['b', 'c']);
|
|
243
|
+
});
|
|
244
|
+
it('flushes on pagehide', async () => {
|
|
245
|
+
const listeners = new Map();
|
|
246
|
+
vi.stubGlobal('window', { addEventListener: (name, fn) => listeners.set(name, fn) });
|
|
247
|
+
vi.stubGlobal('document', { visibilityState: 'visible', addEventListener: (name, fn) => listeners.set(`doc:${name}`, fn) });
|
|
248
|
+
try {
|
|
249
|
+
const storage = new MemoryStorage();
|
|
250
|
+
const ws = new FakeWorkspace();
|
|
251
|
+
ws.Configuration = JSON.stringify(config(['a', 'b'], 'a'));
|
|
252
|
+
engineState.workspaces = [ws];
|
|
253
|
+
const m = managerWith(storage);
|
|
254
|
+
await m.Initialize('user-1');
|
|
255
|
+
m.SetActiveTab('b');
|
|
256
|
+
listeners.get('pagehide')?.();
|
|
257
|
+
await Promise.resolve();
|
|
258
|
+
expect(ws.Save).toHaveBeenCalledTimes(1);
|
|
259
|
+
expect(listeners.has('doc:visibilitychange')).toBe(true);
|
|
260
|
+
}
|
|
261
|
+
finally {
|
|
262
|
+
vi.unstubAllGlobals();
|
|
263
|
+
}
|
|
264
|
+
});
|
|
265
|
+
});
|
|
266
|
+
describe('WorkspaceStateManager.Initialize — PrepareConfiguration', () => {
|
|
267
|
+
beforeEach(() => {
|
|
268
|
+
engineState.constrained = false;
|
|
269
|
+
engineState.workspaces = [];
|
|
270
|
+
});
|
|
271
|
+
it('publishes the PREPARED configuration as the very first value, and persists it', async () => {
|
|
272
|
+
const ws = new FakeWorkspace();
|
|
273
|
+
ws.Configuration = JSON.stringify(config(['a', 'b'], 'a', { ballot: 'old' }));
|
|
274
|
+
engineState.workspaces = [ws];
|
|
275
|
+
const m = managerWith(new MemoryStorage());
|
|
276
|
+
const seen = [];
|
|
277
|
+
m.Configuration.subscribe(c => { if (c)
|
|
278
|
+
seen.push(c.activeTabId); });
|
|
279
|
+
await m.Initialize('user-1', {
|
|
280
|
+
PrepareConfiguration: c => ({ ...c, activeTabId: 'b' })
|
|
281
|
+
});
|
|
282
|
+
expect(seen, 'no subscriber ever saw the unprepared configuration').toEqual(['b']);
|
|
283
|
+
expect(m.HasPendingSave).toBe(true);
|
|
284
|
+
});
|
|
285
|
+
it('a hook that returns the same object changes nothing and queues no save', async () => {
|
|
286
|
+
const ws = new FakeWorkspace();
|
|
287
|
+
ws.Configuration = JSON.stringify(config(['a'], 'a'));
|
|
288
|
+
engineState.workspaces = [ws];
|
|
289
|
+
const m = managerWith(new MemoryStorage());
|
|
290
|
+
await m.Initialize('user-1', { PrepareConfiguration: c => c });
|
|
291
|
+
expect(m.HasPendingSave).toBe(false);
|
|
292
|
+
});
|
|
293
|
+
it('a brand-new user (no workspace row yet) gets the hook too, and a journal seeded on the new row', async () => {
|
|
294
|
+
const created = new FakeWorkspace();
|
|
295
|
+
const m = managerWith(new MemoryStorage());
|
|
296
|
+
m.Provider = {
|
|
297
|
+
CurrentUser: { ID: 'user-1' },
|
|
298
|
+
GetEntityObject: async () => created,
|
|
299
|
+
};
|
|
300
|
+
await m.Initialize('user-1', {
|
|
301
|
+
PrepareConfiguration: c => ({ ...c, activeTabId: 'deep-linked' })
|
|
302
|
+
});
|
|
303
|
+
expect(m.GetConfiguration()?.activeTabId).toBe('deep-linked');
|
|
304
|
+
expect(m.Journal.Read('user-1')?.WorkspaceID).toBe('WS-1');
|
|
305
|
+
});
|
|
306
|
+
it('a throwing hook never blocks startup', async () => {
|
|
307
|
+
const ws = new FakeWorkspace();
|
|
308
|
+
ws.Configuration = JSON.stringify(config(['a'], 'a'));
|
|
309
|
+
engineState.workspaces = [ws];
|
|
310
|
+
const m = managerWith(new MemoryStorage());
|
|
311
|
+
const err = vi.spyOn(console, 'error').mockImplementation(() => undefined);
|
|
312
|
+
await m.Initialize('user-1', { PrepareConfiguration: () => { throw new Error('boom'); } });
|
|
313
|
+
expect(m.GetConfiguration()?.activeTabId).toBe('a');
|
|
314
|
+
err.mockRestore();
|
|
315
|
+
});
|
|
316
|
+
});
|
|
317
|
+
//# sourceMappingURL=workspace-journal.test.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"workspace-journal.test.js","sourceRoot":"","sources":["../../../src/lib/__tests__/workspace-journal.test.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EAAE,QAAQ,EAAE,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,UAAU,EAAE,MAAM,QAAQ,CAAC;AAE9D,OAAO,EACL,yBAAyB,EACzB,gBAAgB,EAGjB,MAAM,sBAAsB,CAAC;AAE9B,EAAE,CAAC,IAAI,CAAC,eAAe,EAAE,GAAG,EAAE,CAAC,CAAC;IAC9B,UAAU,EAAE,GAAG,EAAE,CAAC,CAAC,MAAgB,EAAE,EAAE,CAAC,MAAM;CAC/C,CAAC,CAAC,CAAC;AAEJ,EAAE,CAAC,IAAI,CAAC,sBAAsB,EAAE,GAAG,EAAE,CAAC,CAAC;IACrC,QAAQ,EAAE;KAAQ;IAClB,QAAQ,EAAE,EAAE,CAAC,EAAE,EAAE;IACjB,SAAS,EAAE,EAAE,CAAC,EAAE,EAAE;CACnB,CAAC,CAAC,CAAC;AAEJ,2FAA2F;AAC3F,MAAM,aAAa;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E,EAAE,oBAAoB,EAAE,GAAG,EAAE,GAAG,MAAM,IAAI,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;QAC3F,MAAM,CAAC,CAAC,CAAC,gBAAgB,EAAE,EAAE,WAAW,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;QACpD,GAAG,CAAC,WAAW,EAAE,CAAC;IACpB,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC","sourcesContent":["/**\n * A refresh within a few seconds of a workspace change used to come back one step behind: the\n * change was only in memory until the 500ms debounce fired AND the async entity save landed.\n * These tests pin the fix — a synchronous browser journal, a flush on page hide, and the\n * PrepareConfiguration hook the shell uses to make a deep link win over the saved workspace.\n */\nimport { describe, it, expect, vi, beforeEach } from 'vitest';\nimport type { WorkspaceConfiguration } from '../interfaces/workspace-configuration.interface';\nimport {\n ShouldUseWorkspaceJournal,\n WorkspaceJournal,\n WorkspaceJournalEntry,\n WorkspaceJournalStorage\n} from '../workspace-journal';\n\nvi.mock('@angular/core', () => ({\n Injectable: () => (target: Function) => target,\n}));\n\nvi.mock('@memberjunction/core', () => ({\n Metadata: class {},\n LogError: vi.fn(),\n LogStatus: vi.fn(),\n}));\n\n/** A minimal stand-in for MJWorkspaceEntity: Save() stamps a new server __mj_UpdatedAt. */\nclass FakeWorkspace {\n ID = 'WS-1';\n UserID = 'user-1';\n Configuration = '';\n __mj_UpdatedAt: Date = new Date('2026-10-01T10:00:00.000Z');\n saves: string[] = [];\n Save = vi.fn(async () => {\n this.saves.push(this.Configuration);\n this.__mj_UpdatedAt = new Date(this.__mj_UpdatedAt.getTime() + 60_000);\n return true;\n });\n}\n\nconst engineState: { workspaces: FakeWorkspace[]; constrained: boolean } = { workspaces: [], constrained: false };\n\nvi.mock('@memberjunction/core-entities', () => ({\n UserInfoEngine: {\n get Instance() {\n return {\n get IsPermissionConstrained() { return engineState.constrained; },\n get Workspaces() { return engineState.workspaces; },\n };\n }\n },\n MJWorkspaceEntity: class {},\n}));\n\nimport { WorkspaceStateManager } from '../workspace-state-manager';\n\nclass MemoryStorage implements WorkspaceJournalStorage {\n data = new Map<string, string>();\n getItem(key: string): string | null { return this.data.get(key) ?? null; }\n setItem(key: string, value: string): void { this.data.set(key, value); }\n removeItem(key: string): void { this.data.delete(key); }\n}\n\nfunction config(tabIds: string[], active: string | null, params?: Record<string, string>): WorkspaceConfiguration {\n return {\n version: 1,\n activeTabId: active,\n theme: 'light',\n preferences: { tabPosition: 'top', showTabIcons: true, autoSaveInterval: 5000 },\n tabs: tabIds.map((id, i) => ({\n id, applicationId: 'app-1', title: id, resourceTypeId: '', resourceRecordId: '', isPinned: true, sequence: i,\n lastAccessedAt: '2026-10-01T10:00:00.000Z',\n configuration: params ? { resourceType: 'Custom', queryParams: params } : { resourceType: 'Custom' }\n }))\n };\n}\n\nfunction managerWith(storage: MemoryStorage): WorkspaceStateManager {\n const m = new WorkspaceStateManager();\n m.Journal = new WorkspaceJournal(() => storage);\n return m;\n}\n\ndescribe('ShouldUseWorkspaceJournal', () => {\n const entry = (base: string | null, ws: string | null = 'WS-1'): WorkspaceJournalEntry =>\n ({ Version: 1, UserID: 'user-1', WorkspaceID: ws, BaseUpdatedAt: base, Configuration: config(['a'], 'a') });\n\n it('wins when the server row has not been saved since the snapshot base', () => {\n expect(ShouldUseWorkspaceJournal(entry('2026-10-01T10:00:00.000Z'), 'WS-1', new Date('2026-10-01T10:00:00.000Z'))).toBe(true);\n });\n it('wins over an OLDER row (a stale locally cached copy)', () => {\n expect(ShouldUseWorkspaceJournal(entry('2026-10-01T10:05:00.000Z'), 'ws-1', '2026-10-01T10:00:00.000Z')).toBe(true);\n });\n it('loses to a row saved later by something this browser never saw (another device)', () => {\n expect(ShouldUseWorkspaceJournal(entry('2026-10-01T10:00:00.000Z'), 'WS-1', new Date('2026-10-01T10:00:01.000Z'))).toBe(false);\n });\n it('loses when it belongs to another workspace row, or has no base to compare', () => {\n expect(ShouldUseWorkspaceJournal(entry('2026-10-01T10:00:00.000Z', 'WS-2'), 'WS-1', new Date('2026-10-01T09:00:00.000Z'))).toBe(false);\n expect(ShouldUseWorkspaceJournal(entry(null), 'WS-1', new Date('2026-10-01T09:00:00.000Z'))).toBe(false);\n expect(ShouldUseWorkspaceJournal(null, 'WS-1', null)).toBe(false);\n });\n it('wins over a later row that is exactly its own in-flight save (landed after the page unloaded)', () => {\n const inFlight = JSON.stringify(config(['a', 'b'], 'b'));\n const e = { ...entry('2026-10-01T10:00:00.000Z'), InFlightConfiguration: inFlight };\n expect(ShouldUseWorkspaceJournal(e, 'WS-1', new Date('2026-10-01T10:01:00.000Z'), inFlight)).toBe(true);\n expect(ShouldUseWorkspaceJournal(e, 'WS-1', new Date('2026-10-01T10:01:00.000Z'), JSON.stringify(config(['z'], 'z'))), 'another device\\'s row still wins').toBe(false);\n });\n it('is used for a session with no workspace row only when the entry has none either', () => {\n expect(ShouldUseWorkspaceJournal(entry(null, null), null, null)).toBe(true);\n expect(ShouldUseWorkspaceJournal(entry(null, 'WS-1'), null, null)).toBe(false);\n });\n});\n\ndescribe('WorkspaceJournal', () => {\n it('ignores unreadable, foreign-user and wrong-version entries, and survives a throwing storage', () => {\n const storage = new MemoryStorage();\n const journal = new WorkspaceJournal(() => storage);\n storage.setItem(WorkspaceJournal.KeyFor('user-1'), '{not json');\n expect(journal.Read('user-1')).toBeNull();\n storage.setItem(WorkspaceJournal.KeyFor('user-1'), JSON.stringify({ Version: 2, UserID: 'user-1', Configuration: config([], null) }));\n expect(journal.Read('user-1')).toBeNull();\n\n const throwing = new WorkspaceJournal(() => { throw new Error('SecurityError'); });\n expect(() => throwing.Write({ Version: 1, UserID: 'u', WorkspaceID: null, BaseUpdatedAt: null, Configuration: config([], null) })).not.toThrow();\n expect(throwing.Read('u')).toBeNull();\n });\n});\n\ndescribe('WorkspaceStateManager — refresh inside the save window', () => {\n beforeEach(() => {\n engineState.constrained = false;\n engineState.workspaces = [];\n });\n\n it('journals every change synchronously, before the debounced save runs', () => {\n const storage = new MemoryStorage();\n const ws = new FakeWorkspace();\n ws.Configuration = JSON.stringify(config(['a', 'b'], 'a'));\n engineState.workspaces = [ws];\n const m = managerWith(storage);\n return m.Initialize('user-1').then(() => {\n m.SetActiveTab('b');\n const entry = m.Journal.Read('user-1');\n expect(entry?.Configuration.activeTabId).toBe('b');\n expect(ws.Save, 'nothing has reached the database yet').not.toHaveBeenCalled();\n expect(m.HasPendingSave).toBe(true);\n });\n });\n\n it('a reload that finds the row one step behind restores the journal and re-saves it', async () => {\n const storage = new MemoryStorage();\n // Session 1: a change is made, the page is reloaded before any save lands.\n const ws1 = new FakeWorkspace();\n ws1.Configuration = JSON.stringify(config(['a', 'b'], 'a'));\n engineState.workspaces = [ws1];\n const first = managerWith(storage);\n await first.Initialize('user-1');\n first.SetActiveTab('b');\n\n // Session 2: the server row is still the pre-change one.\n const ws2 = new FakeWorkspace();\n ws2.Configuration = JSON.stringify(config(['a', 'b'], 'a'));\n engineState.workspaces = [ws2];\n const second = managerWith(storage);\n await second.Initialize('user-1');\n\n expect(second.GetConfiguration()?.activeTabId, 'the newest change survived the reload').toBe('b');\n expect(second.HasPendingSave, 'the restored snapshot is queued for the database').toBe(true);\n await second.FlushPendingSave();\n expect(JSON.parse(ws2.saves[0]).activeTabId).toBe('b');\n });\n\n it('a row saved later elsewhere beats the local journal', async () => {\n const storage = new MemoryStorage();\n const ws1 = new FakeWorkspace();\n ws1.Configuration = JSON.stringify(config(['a', 'b'], 'a'));\n engineState.workspaces = [ws1];\n const first = managerWith(storage);\n await first.Initialize('user-1');\n first.SetActiveTab('b');\n\n const ws2 = new FakeWorkspace();\n ws2.Configuration = JSON.stringify(config(['a', 'c'], 'c'));\n ws2.__mj_UpdatedAt = new Date('2026-10-02T00:00:00.000Z'); // saved by another device afterwards\n engineState.workspaces = [ws2];\n const second = managerWith(storage);\n await second.Initialize('user-1');\n expect(second.GetConfiguration()?.activeTabId).toBe('c');\n expect(second.HasPendingSave).toBe(false);\n });\n\n it('FlushPendingSave persists immediately, then the debounce has nothing left to do', async () => {\n vi.useFakeTimers();\n try {\n const storage = new MemoryStorage();\n const ws = new FakeWorkspace();\n ws.Configuration = JSON.stringify(config(['a', 'b'], 'a'));\n engineState.workspaces = [ws];\n const m = managerWith(storage);\n await m.Initialize('user-1');\n m.SetActiveTab('b');\n await m.FlushPendingSave();\n expect(ws.Save).toHaveBeenCalledTimes(1);\n expect(JSON.parse(ws.saves[0]).activeTabId).toBe('b');\n await vi.advanceTimersByTimeAsync(1000);\n expect(ws.Save, 'the debounced save must not run a second time').toHaveBeenCalledTimes(1);\n // The journal is re-based on the stamp the save produced, so the next load trusts it.\n expect(m.Journal.Read('user-1')?.BaseUpdatedAt).toBe(ws.__mj_UpdatedAt.toISOString());\n } finally {\n vi.useRealTimers();\n }\n });\n\n it('a change made while a save is in flight survives that save landing after the page unloaded', async () => {\n const storage = new MemoryStorage();\n const ws1 = new FakeWorkspace();\n ws1.Configuration = JSON.stringify(config(['a', 'b', 'c'], 'a'));\n engineState.workspaces = [ws1];\n let landSave: () => void = () => undefined;\n ws1.Save.mockImplementationOnce(() => new Promise<boolean>(resolve => { landSave = () => resolve(true); }));\n const first = managerWith(storage);\n await first.Initialize('user-1');\n\n first.SetActiveTab('b');\n const saving = first.FlushPendingSave(); // save of B is now in flight\n first.SetActiveTab('c'); // change C journaled while it flies\n const unloadSnapshot = new Map(storage.data); // the page unloads here; B still lands on the server\n landSave();\n await saving;\n\n const ws2 = new FakeWorkspace();\n ws2.Configuration = ws1.Configuration; // the server row holds exactly what the save of B sent ...\n ws2.__mj_UpdatedAt = new Date('2026-10-01T10:01:00.000Z'); // ... stamped after the journal's base\n engineState.workspaces = [ws2];\n const reloaded = new MemoryStorage();\n reloaded.data = unloadSnapshot;\n const second = managerWith(reloaded);\n await second.Initialize('user-1');\n expect(second.GetConfiguration()?.activeTabId, 'C was not discarded in favour of the older B').toBe('c');\n });\n\n it('runs one save at a time: a flush during an in-flight save waits for it, then saves the newest change', async () => {\n const storage = new MemoryStorage();\n const ws = new FakeWorkspace();\n ws.Configuration = JSON.stringify(config(['a', 'b', 'c'], 'a'));\n engineState.workspaces = [ws];\n let landFirst: () => void = () => undefined;\n let concurrent = 0;\n let maxConcurrent = 0;\n const original = ws.Save.getMockImplementation();\n ws.Save.mockImplementation(async () => {\n concurrent++;\n maxConcurrent = Math.max(maxConcurrent, concurrent);\n if (ws.saves.length === 0) {\n await new Promise<void>(resolve => { landFirst = resolve; });\n }\n const ok = await original!();\n concurrent--;\n return ok;\n });\n const m = managerWith(storage);\n await m.Initialize('user-1');\n\n m.SetActiveTab('b');\n const firstSave = m.FlushPendingSave();\n m.SetActiveTab('c');\n const secondFlush = m.FlushPendingSave(); // e.g. pagehide while the debounced save flies\n await Promise.resolve();\n expect(ws.Save, 'the second save waits for the first').toHaveBeenCalledTimes(1);\n landFirst();\n await Promise.all([firstSave, secondFlush]);\n expect(maxConcurrent).toBe(1);\n expect(ws.saves.map(c => JSON.parse(c).activeTabId)).toEqual(['b', 'c']);\n });\n\n it('flushes on pagehide', async () => {\n const listeners = new Map<string, () => void>();\n vi.stubGlobal('window', { addEventListener: (name: string, fn: () => void) => listeners.set(name, fn) });\n vi.stubGlobal('document', { visibilityState: 'visible', addEventListener: (name: string, fn: () => void) => listeners.set(`doc:${name}`, fn) });\n try {\n const storage = new MemoryStorage();\n const ws = new FakeWorkspace();\n ws.Configuration = JSON.stringify(config(['a', 'b'], 'a'));\n engineState.workspaces = [ws];\n const m = managerWith(storage);\n await m.Initialize('user-1');\n m.SetActiveTab('b');\n listeners.get('pagehide')?.();\n await Promise.resolve();\n expect(ws.Save).toHaveBeenCalledTimes(1);\n expect(listeners.has('doc:visibilitychange')).toBe(true);\n } finally {\n vi.unstubAllGlobals();\n }\n });\n});\n\ndescribe('WorkspaceStateManager.Initialize — PrepareConfiguration', () => {\n beforeEach(() => {\n engineState.constrained = false;\n engineState.workspaces = [];\n });\n\n it('publishes the PREPARED configuration as the very first value, and persists it', async () => {\n const ws = new FakeWorkspace();\n ws.Configuration = JSON.stringify(config(['a', 'b'], 'a', { ballot: 'old' }));\n engineState.workspaces = [ws];\n const m = managerWith(new MemoryStorage());\n const seen: (string | null)[] = [];\n m.Configuration.subscribe(c => { if (c) seen.push(c.activeTabId); });\n\n await m.Initialize('user-1', {\n PrepareConfiguration: c => ({ ...c, activeTabId: 'b' })\n });\n\n expect(seen, 'no subscriber ever saw the unprepared configuration').toEqual(['b']);\n expect(m.HasPendingSave).toBe(true);\n });\n\n it('a hook that returns the same object changes nothing and queues no save', async () => {\n const ws = new FakeWorkspace();\n ws.Configuration = JSON.stringify(config(['a'], 'a'));\n engineState.workspaces = [ws];\n const m = managerWith(new MemoryStorage());\n await m.Initialize('user-1', { PrepareConfiguration: c => c });\n expect(m.HasPendingSave).toBe(false);\n });\n\n it('a brand-new user (no workspace row yet) gets the hook too, and a journal seeded on the new row', async () => {\n const created = new FakeWorkspace();\n const m = managerWith(new MemoryStorage());\n m.Provider = {\n CurrentUser: { ID: 'user-1' },\n GetEntityObject: async () => created,\n } as unknown as WorkspaceStateManager['Provider'];\n await m.Initialize('user-1', {\n PrepareConfiguration: c => ({ ...c, activeTabId: 'deep-linked' })\n });\n expect(m.GetConfiguration()?.activeTabId).toBe('deep-linked');\n expect(m.Journal.Read('user-1')?.WorkspaceID).toBe('WS-1');\n });\n\n it('a throwing hook never blocks startup', async () => {\n const ws = new FakeWorkspace();\n ws.Configuration = JSON.stringify(config(['a'], 'a'));\n engineState.workspaces = [ws];\n const m = managerWith(new MemoryStorage());\n const err = vi.spyOn(console, 'error').mockImplementation(() => undefined);\n await m.Initialize('user-1', { PrepareConfiguration: () => { throw new Error('boom'); } });\n expect(m.GetConfiguration()?.activeTabId).toBe('a');\n err.mockRestore();\n });\n});\n"]}
|
|
@@ -129,6 +129,27 @@ export declare class ApplicationManager {
|
|
|
129
129
|
* This can be called to refresh after configuration changes.
|
|
130
130
|
*/
|
|
131
131
|
private loadUserApplicationConfig;
|
|
132
|
+
/**
|
|
133
|
+
* The apps a permission-constrained session (e.g. an external magic-link user) is offered when it
|
|
134
|
+
* cannot read its own `MJ: User Applications` rows: what a brand-new user would get —
|
|
135
|
+
* DefaultForNewUser apps the user may access, in DefaultSequence order — but held in memory
|
|
136
|
+
* only, never saved as records. When the session cannot read application roles either, access
|
|
137
|
+
* cannot be judged (an unreadable role list reads as "open to everyone"), so nothing is offered;
|
|
138
|
+
* an app-locked session still reaches its scoped app through {@link AdoptSessionApplication}.
|
|
139
|
+
*/
|
|
140
|
+
private permissionConstrainedSessionApps;
|
|
141
|
+
/**
|
|
142
|
+
* Makes an application the SESSION is scoped to available in {@link Applications} when the
|
|
143
|
+
* user's own app list does not include it — an app-locked session (a magic-link invite scoped
|
|
144
|
+
* to one app) whose user cannot read, or has no, `MJ: User Applications` rows. In memory only:
|
|
145
|
+
* no record is created. The scope comes from the server-signed session, and the server still
|
|
146
|
+
* enforces every entity permission inside the app.
|
|
147
|
+
*
|
|
148
|
+
* @param appId - the application the session is restricted to
|
|
149
|
+
* @returns true when the app was added (so {@link Applications} re-emits); false when it was
|
|
150
|
+
* already available or is not an active application at all
|
|
151
|
+
*/
|
|
152
|
+
AdoptSessionApplication(appId: string): boolean;
|
|
132
153
|
/**
|
|
133
154
|
* Creates UserApplication records for apps with DefaultForNewUser=true and Status='Active'.
|
|
134
155
|
* Called when a user has no existing UserApplication records (self-healing).
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"application-manager.d.ts","sourceRoot":"","sources":["../../src/lib/application-manager.ts"],"names":[],"mappings":"AACA,OAAO,EAAmB,UAAU,EAAE,MAAM,MAAM,CAAC;AAEnD,OAAO,EAAkE,iBAAiB,EAA8B,MAAM,sBAAsB,CAAC;AACrJ,OAAO,EAAE,uBAAuB,EAAkB,MAAM,+BAA+B,CAAC;AACxF,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;;AAErD;;GAEG;AACH,MAAM,WAAW,aAAa;IAC5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,6 +1,6 @@
|
|
|
1
1
|
import { Injectable } from '@angular/core';
|
|
2
2
|
import { BehaviorSubject } from 'rxjs';
|
|
3
|
-
import { MJGlobal, MJEventType, UUIDsEqual } from '@memberjunction/global';
|
|
3
|
+
import { IndexByUUID, MJGlobal, MJEventType, UUIDsEqual } from '@memberjunction/global';
|
|
4
4
|
import { Metadata, LogError, LogStatus, StartupManager } from '@memberjunction/core';
|
|
5
5
|
import { UserInfoEngine } from '@memberjunction/core-entities';
|
|
6
6
|
import { BaseApplication } from './base-application';
|
|
@@ -121,7 +121,11 @@ export class ApplicationManager {
|
|
|
121
121
|
MJGlobal.Instance.GetEventListener(true).subscribe(async (event) => {
|
|
122
122
|
if (event.event === MJEventType.LoggedIn) {
|
|
123
123
|
await StartupManager.Instance.Startup(); // make sure this is done
|
|
124
|
-
|
|
124
|
+
// Fire-and-forget from an event callback: loadApplications() already logs its failure
|
|
125
|
+
// and resolves WhenReady() waiters before rethrowing (for callers that await it), so
|
|
126
|
+
// the rethrow has nobody to land on here — catch it rather than leave an unhandled
|
|
127
|
+
// rejection on the page.
|
|
128
|
+
this.loadApplications().catch(() => { });
|
|
125
129
|
this.subscribeToEngineChanges();
|
|
126
130
|
}
|
|
127
131
|
});
|
|
@@ -257,7 +261,13 @@ export class ApplicationManager {
|
|
|
257
261
|
// Attempt one recovery by force-refreshing UserInfoEngine before giving up.
|
|
258
262
|
const activeApps = this.applications$.value;
|
|
259
263
|
const hasMetadataApps = md.Applications.some(a => a.Status === 'Active');
|
|
260
|
-
|
|
264
|
+
// A permission-constrained session (e.g. an external magic-link user holding only
|
|
265
|
+
// 'Magic Link Baseline' plus a granted role) has zero user apps BY DESIGN — that is
|
|
266
|
+
// not cache corruption, and a forced engine refresh cannot grant read access. Without
|
|
267
|
+
// this guard the recovery log below read UserApplications, which throws
|
|
268
|
+
// PermissionConstrainedError, and loadApplications() rejected unhandled at every boot.
|
|
269
|
+
if (activeApps.length === 0 && hasMetadataApps && !ApplicationManager._recoveryAttempted
|
|
270
|
+
&& !UserInfoEngine.Instance.IsPermissionConstrained) {
|
|
261
271
|
ApplicationManager._recoveryAttempted = true;
|
|
262
272
|
const activeAppCount = md.Applications.filter(a => a.Status === 'Active').length;
|
|
263
273
|
const engineHealthy = UserInfoEngine.Instance.AllPropertiesLoadedSuccessfully;
|
|
@@ -297,9 +307,10 @@ export class ApplicationManager {
|
|
|
297
307
|
// If the engine can't read user application data, skip the self-healing path —
|
|
298
308
|
// a permission-denied user is NOT the same as a new user with no records.
|
|
299
309
|
if (engine.IsPermissionConstrained) {
|
|
300
|
-
|
|
310
|
+
const sessionApps = this.permissionConstrainedSessionApps(allApps);
|
|
311
|
+
LogStatus(`${this.constructor.name}: UserInfoEngine is permission-constrained, skipping application config load; ${sessionApps.length} default app(s) offered for this session`);
|
|
301
312
|
this.userAppConfigs$.next([]);
|
|
302
|
-
this.applications$.next(
|
|
313
|
+
this.applications$.next(sessionApps);
|
|
303
314
|
return;
|
|
304
315
|
}
|
|
305
316
|
let userApps = engine.UserApplications;
|
|
@@ -326,6 +337,49 @@ export class ApplicationManager {
|
|
|
326
337
|
this.userAppConfigs$.next(userAppConfigs);
|
|
327
338
|
this.applications$.next(activeApps);
|
|
328
339
|
}
|
|
340
|
+
/**
|
|
341
|
+
* The apps a permission-constrained session (e.g. an external magic-link user) is offered when it
|
|
342
|
+
* cannot read its own `MJ: User Applications` rows: what a brand-new user would get —
|
|
343
|
+
* DefaultForNewUser apps the user may access, in DefaultSequence order — but held in memory
|
|
344
|
+
* only, never saved as records. When the session cannot read application roles either, access
|
|
345
|
+
* cannot be judged (an unreadable role list reads as "open to everyone"), so nothing is offered;
|
|
346
|
+
* an app-locked session still reaches its scoped app through {@link AdoptSessionApplication}.
|
|
347
|
+
*/
|
|
348
|
+
permissionConstrainedSessionApps(allApps) {
|
|
349
|
+
const engine = UserInfoEngine.Instance;
|
|
350
|
+
if (engine.IsPropertyPermissionConstrained('_applicationRoles')) {
|
|
351
|
+
return [];
|
|
352
|
+
}
|
|
353
|
+
const defaults = this.Provider.Applications
|
|
354
|
+
.filter(a => a.DefaultForNewUser && a.Status === 'Active' && engine.UserHasApplicationAccess(a.ID))
|
|
355
|
+
.sort((a, b) => (a.DefaultSequence ?? 100) - (b.DefaultSequence ?? 100));
|
|
356
|
+
const appsByID = IndexByUUID(allApps);
|
|
357
|
+
return defaults
|
|
358
|
+
.map(info => appsByID.Get(info.ID))
|
|
359
|
+
.filter((app) => !!app);
|
|
360
|
+
}
|
|
361
|
+
/**
|
|
362
|
+
* Makes an application the SESSION is scoped to available in {@link Applications} when the
|
|
363
|
+
* user's own app list does not include it — an app-locked session (a magic-link invite scoped
|
|
364
|
+
* to one app) whose user cannot read, or has no, `MJ: User Applications` rows. In memory only:
|
|
365
|
+
* no record is created. The scope comes from the server-signed session, and the server still
|
|
366
|
+
* enforces every entity permission inside the app.
|
|
367
|
+
*
|
|
368
|
+
* @param appId - the application the session is restricted to
|
|
369
|
+
* @returns true when the app was added (so {@link Applications} re-emits); false when it was
|
|
370
|
+
* already available or is not an active application at all
|
|
371
|
+
*/
|
|
372
|
+
AdoptSessionApplication(appId) {
|
|
373
|
+
if (!appId || this.GetAppById(appId)) {
|
|
374
|
+
return false;
|
|
375
|
+
}
|
|
376
|
+
const app = this.allApplications$.value.find(a => UUIDsEqual(a.ID, appId));
|
|
377
|
+
if (!app) {
|
|
378
|
+
return false;
|
|
379
|
+
}
|
|
380
|
+
this.applications$.next([...this.applications$.value, app]);
|
|
381
|
+
return true;
|
|
382
|
+
}
|
|
329
383
|
/**
|
|
330
384
|
* Creates UserApplication records for apps with DefaultForNewUser=true and Status='Active'.
|
|
331
385
|
* Called when a user has no existing UserApplication records (self-healing).
|