mnfst 0.5.336 → 0.5.337

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.
@@ -580,6 +580,14 @@ function initializeAuthStore() {
580
580
  try { const saved = JSON.parse(raw || 'null'); return saved?.isAuthenticated ? (saved.user?.$id || null) : null; } catch { return null; }
581
581
  }
582
582
 
583
+ // Last signed-in identity this browser mirrored: a hint only, never trusted as identity
584
+ function persistedIdentity() {
585
+ try {
586
+ const saved = JSON.parse(localStorage.getItem(STORAGE_KEY) || 'null');
587
+ return saved?.isAuthenticated === true && saved.user?.$id ? { userId: saved.user.$id, isAnonymous: saved.isAnonymous === true } : null;
588
+ } catch { return null; }
589
+ }
590
+
583
591
  // Identity this tab is showing data for: while unverified, the last one mirrored
584
592
  function shownUserId(store, mirrored) {
585
593
  if (store.user?.$id) return store.user.$id;
@@ -721,6 +729,7 @@ function initializeAuthStore() {
721
729
  editingMember: null, // Current member being edited: { teamId, membershipId, roles }
722
730
  _initialized: false,
723
731
  _initializing: false,
732
+ _initAnnounced: false, // manifest:auth:initialized has fired
724
733
  _appwrite: null,
725
734
  _guestAuto: false,
726
735
  _guestManual: false,
@@ -729,6 +738,7 @@ function initializeAuthStore() {
729
738
  _crossTabTeams: null, // latest cross-tab team load; older ones skip their writes
730
739
  _teamsEpoch: 0, // bumped by every team reset; an in-flight listTeams from an older one is discarded
731
740
  _authEpoch: 0, // bumped by every identity change; an in-flight recheck from an older epoch is dropped
741
+ _prefetchWaitMs: 3000, // longest the boot teams load waits on its prefetched list
732
742
  _recheckTimer: null,
733
743
  _recheckAttempt: 0,
734
744
  guestManualEnabled: false,
@@ -742,6 +752,7 @@ function initializeAuthStore() {
742
752
  _allRolesCacheByTeam: {}, // Cache roles per team ID
743
753
  _rolePermanentCache: {}, // Cache permanent role status per team: { teamId: { roleName: true/false } }
744
754
  _userGeneratedRolesCache: {},
755
+ _permissionRefresh: null, // last finished permission refresh: { seq, teamId, memberships }
745
756
 
746
757
  // Permission cache methods (always available, return safe defaults)
747
758
  canInviteMembers() {
@@ -916,6 +927,7 @@ function initializeAuthStore() {
916
927
 
917
928
  // Hoisted so the post-init background team load (below) can read it.
918
929
  let appwriteConfig = null;
930
+ let earlyTeams = null;
919
931
 
920
932
  try {
921
933
  const appwrite = await config.getAppwriteClient();
@@ -936,7 +948,9 @@ function initializeAuthStore() {
936
948
 
937
949
  // Try to restore existing session
938
950
  try {
939
- await this._restoreSession(appwrite);
951
+ const restoring = this._restoreSession(appwrite);
952
+ earlyTeams = this._prefetchTeams(appwrite, appwriteConfig);
953
+ await restoring;
940
954
 
941
955
  // Team loading is deferred (not awaited) — runs in the background after
942
956
  // manifest:auth:initialized so a session gate isn't held up by it.
@@ -977,6 +991,7 @@ function initializeAuthStore() {
977
991
 
978
992
  // Fire as soon as identity is known, before teams load, so a session
979
993
  // gate / splash clears in a few hundred ms.
994
+ this._initAnnounced = true;
980
995
  window.dispatchEvent(new CustomEvent('manifest:auth:initialized', {
981
996
  detail: {
982
997
  isAuthenticated: this.isAuthenticated,
@@ -990,7 +1005,9 @@ function initializeAuthStore() {
990
1005
  if (appwriteConfig && this.isAuthenticated && appwriteConfig.teams
991
1006
  && (!this.isAnonymous || appwriteConfig.guestTeams)) {
992
1007
  const owner = this.user?.$id;
993
- this._loadTeamsAndSeed(appwriteConfig)
1008
+ const prefetched = earlyTeams && earlyTeams.userId === owner && earlyTeams.authEpoch === this._authEpoch
1009
+ && earlyTeams.teamsEpoch === this._teamsEpoch ? earlyTeams : null;
1010
+ this._loadTeamsAndSeed(appwriteConfig, { prefetched })
994
1011
  .then(() => {
995
1012
  if (!this.isAuthenticated || this.user?.$id !== owner) return;
996
1013
  window.dispatchEvent(new CustomEvent('manifest:auth:teams-loaded', {
@@ -1003,8 +1020,15 @@ function initializeAuthStore() {
1003
1020
 
1004
1021
  // Adopt the session Appwrite reports (throws when there is none or it is unreachable)
1005
1022
  async _restoreSession(appwrite, isCurrent = () => true) {
1006
- const user = await appwrite.account.get();
1007
- const sessionsResponse = await appwrite.account.listSessions();
1023
+ // Both in flight when a session is likely; account.get's error still wins
1024
+ const userRequest = appwrite.account.get();
1025
+ let sessionsRequest = null;
1026
+ if (persistedIdentity()) {
1027
+ try { sessionsRequest = Promise.resolve(appwrite.account.listSessions()); } catch (error) { sessionsRequest = Promise.reject(error); }
1028
+ sessionsRequest.catch(() => { });
1029
+ }
1030
+ const user = await userRequest;
1031
+ const sessionsResponse = await (sessionsRequest || appwrite.account.listSessions());
1008
1032
  if (!isCurrent()) return false;
1009
1033
  this.user = user;
1010
1034
  const allSessions = sessionsResponse.sessions || [];
@@ -1051,6 +1075,20 @@ function initializeAuthStore() {
1051
1075
  return true;
1052
1076
  },
1053
1077
 
1078
+ // Boot teams list issued alongside the identity check for the mirrored identity; listTeams uses it only for that identity
1079
+ _prefetchTeams(appwrite, cfg) {
1080
+ const hint = persistedIdentity();
1081
+ if (!hint || !cfg?.teams || typeof appwrite?.teams?.list !== 'function') return null;
1082
+ if (hint.isAnonymous && (!cfg.guestTeams || (!this._guestAuto && !this._guestManual))) return null;
1083
+ let request;
1084
+ try {
1085
+ request = Promise.resolve(appwrite.teams.list({ queries: [] })).then(value => ({ value }), error => ({ error }));
1086
+ } catch (error) {
1087
+ return null;
1088
+ }
1089
+ return { userId: hint.userId, authEpoch: this._authEpoch, teamsEpoch: this._teamsEpoch, request, used: false };
1090
+ },
1091
+
1054
1092
  // Offline-booted tab: re-run the session check once Appwrite is reachable
1055
1093
  async _recheckSession() {
1056
1094
  if (!this._sessionUnverified || this._rechecking || !this._appwrite) return;
@@ -1155,7 +1193,7 @@ function initializeAuthStore() {
1155
1193
 
1156
1194
  // Load the user's teams and seed configured defaults. Shared by the guest,
1157
1195
  // magic-link, OAuth, and init/restore paths.
1158
- async _loadTeamsAndSeed(appwriteConfig, { seed = true } = {}) {
1196
+ async _loadTeamsAndSeed(appwriteConfig, { seed = true, prefetched = null } = {}) {
1159
1197
  const cfg = appwriteConfig || await config.getAppwriteConfig();
1160
1198
  if (!cfg?.teams) {
1161
1199
  return;
@@ -1175,7 +1213,7 @@ function initializeAuthStore() {
1175
1213
  // Always load the user's real teams. Capture the result — never seed defaults
1176
1214
  // off an unconfirmed team list: a failed/incomplete load must not read as
1177
1215
  // "teamless" and mint a duplicate tenant (the settle-window mis-provision).
1178
- const loadResult = await this.listTeams();
1216
+ const loadResult = prefetched ? await this.listTeams([], '', { prefetched }) : await this.listTeams();
1179
1217
  if (!needsSeed) {
1180
1218
  return;
1181
1219
  }
@@ -1479,6 +1517,7 @@ window.ManifestAppwriteAuthStore = {
1479
1517
 
1480
1518
  // Initialize auth plugin - orchestrates all modules
1481
1519
  let _pluginInitializing = false;
1520
+ let _initHandled = false;
1482
1521
  async function initializeAppwriteAuthPlugin() {
1483
1522
  if (_pluginInitializing) {
1484
1523
  return;
@@ -1505,7 +1544,20 @@ async function initializeAppwriteAuthPlugin() {
1505
1544
  }
1506
1545
 
1507
1546
  // After store init, process callbacks and validate config
1508
- window.addEventListener('manifest:auth:initialized', async () => {
1547
+ const onInitialized = async () => {
1548
+ if (_initHandled) return;
1549
+ _initHandled = true;
1550
+ const callbacks = window.ManifestAppwriteAuthCallbacks;
1551
+ const callbackInfo = callbacks ? callbacks.detect() : null;
1552
+ // Store methods this work calls attach on the other modules' 100 ms timers: wait briefly for them
1553
+ const needed = [];
1554
+ if (store._guestAuto) needed.push('_createAnonymousSession');
1555
+ if (callbackInfo?.hasCallback && !callbackInfo.isOAuth) needed.push(callbackInfo.isTeamInvite ? 'acceptInvite' : 'handleMagicLinkCallback');
1556
+ const missing = () => needed.filter(name => typeof store[name] !== 'function');
1557
+ for (let i = 0; i < 40 && missing().length; i++) {
1558
+ await new Promise(r => setTimeout(r, 50));
1559
+ }
1560
+ if (missing().length) console.warn('[Manifest Appwrite Auth] Auth modules not ready after init:', missing().join(', '));
1509
1561
  // Validate role configuration if roles module is loaded
1510
1562
  if (store.validateRoleConfig) {
1511
1563
  const validation = await store.validateRoleConfig();
@@ -1517,18 +1569,18 @@ async function initializeAppwriteAuthPlugin() {
1517
1569
  }
1518
1570
 
1519
1571
  // Process callbacks after store is initialized
1520
- if (window.ManifestAppwriteAuthCallbacks) {
1521
- const callbackInfo = window.ManifestAppwriteAuthCallbacks.detect();
1522
- if (callbackInfo.hasCallback || callbackInfo.hasExpired) {
1523
- window.ManifestAppwriteAuthCallbacks.process(callbackInfo);
1524
- }
1572
+ if (callbacks && (callbackInfo.hasCallback || callbackInfo.hasExpired)) {
1573
+ callbacks.process(callbackInfo);
1525
1574
  }
1526
1575
 
1527
1576
  // If no session and guest-auto is enabled, create guest session (not while the session check is unreachable)
1528
1577
  if (!store.isAuthenticated && !store._sessionUnverified && store._guestAuto && store._createAnonymousSession) {
1529
1578
  store._createAnonymousSession();
1530
1579
  }
1531
- }, { once: true });
1580
+ };
1581
+ // Init may have finished inside the start delay
1582
+ if (store._initAnnounced) onInitialized();
1583
+ else window.addEventListener('manifest:auth:initialized', onInitialized, { once: true });
1532
1584
 
1533
1585
  _pluginInitializing = false;
1534
1586
  } else {
@@ -1841,7 +1893,7 @@ function initializeTeamsCore() {
1841
1893
  };
1842
1894
 
1843
1895
  // List user's teams
1844
- store.listTeams = async function (queries = [], search = '') {
1896
+ store.listTeams = async function (queries = [], search = '', { prefetched = null } = {}) {
1845
1897
  if (!this._appwrite) {
1846
1898
  this._appwrite = await config.getAppwriteClient();
1847
1899
  }
@@ -1867,7 +1919,19 @@ function initializeTeamsCore() {
1867
1919
  if (search && search.trim().length > 0) {
1868
1920
  params.search = search;
1869
1921
  }
1870
- const result = await this._appwrite.teams.list(params);
1922
+ // Boot prefetch: only for this identity and epoch, once; a failed or superseded one falls through to a fresh list
1923
+ let result = null;
1924
+ if (prefetched && !prefetched.used && Array.isArray(queries) && queries.length === 0 && !params.search
1925
+ && prefetched.userId === owner && prefetched.teamsEpoch === generation && prefetched.authEpoch === this._authEpoch) {
1926
+ prefetched.used = true;
1927
+ // A hung prefetch is abandoned after a bounded wait; its late answer is ignored
1928
+ let timer;
1929
+ const early = await Promise.race([prefetched.request, new Promise(r => { timer = setTimeout(() => r({ timedOut: true }), this._prefetchWaitMs ?? 3000); })]);
1930
+ clearTimeout(timer);
1931
+ if (stale()) return discarded;
1932
+ if (!early.timedOut && !early.error && early.value && prefetched.authEpoch === this._authEpoch) result = early.value;
1933
+ }
1934
+ if (!result) result = await this._appwrite.teams.list(params);
1871
1935
  if (stale()) return discarded;
1872
1936
 
1873
1937
  // Update store with teams
@@ -2403,6 +2467,8 @@ function initializeTeamsCore() {
2403
2467
  // Refresh teams list if needed (only once per event batch)
2404
2468
  // This also refreshes roles/permissions since they're stored in team preferences
2405
2469
  if (shouldRefreshTeams && !this._teamsRealtimeSubscribing) {
2470
+ // Prefs may have changed elsewhere
2471
+ if (typeof invalidateRolesCache === 'function') invalidateRolesCache();
2406
2472
  this._teamsRealtimeSubscribing = true;
2407
2473
  if (this.listTeams) {
2408
2474
  this.listTeams().finally(() => {
@@ -2625,6 +2691,7 @@ function initializeTeamsCore() {
2625
2691
  this._teamsPollInterval = setInterval(async () => {
2626
2692
  if (this.isAuthenticated && this.listTeams) {
2627
2693
  try {
2694
+ if (typeof invalidateRolesCache === 'function') invalidateRolesCache();
2628
2695
  await this.listTeams();
2629
2696
  } catch (error) {
2630
2697
  console.warn('[Manifest Appwrite Auth] Teams polling error:', error);
@@ -2663,11 +2730,7 @@ function initializeTeamsCore() {
2663
2730
  this.error = null;
2664
2731
 
2665
2732
  try {
2666
- invalidateRolesCache(teamId);
2667
- const result = await this._appwrite.teams.updatePrefs({
2668
- teamId: teamId,
2669
- prefs: prefs
2670
- });
2733
+ const result = await writeTeamPrefs(this._appwrite, teamId, prefs);
2671
2734
 
2672
2735
  return { success: true, prefs: result };
2673
2736
  } catch (error) {
@@ -3283,7 +3346,13 @@ function initializeTeamsRolesDefaults() {
3283
3346
  let deletedRoles = [];
3284
3347
  try {
3285
3348
  if (this._appwrite && this._appwrite.teams) {
3286
- const prefs = await this._appwrite.teams.getPrefs({ teamId });
3349
+ // Shared prefs read; a cached failure other than 404 is retried as its own read
3350
+ const fresh = () => this._appwrite.teams.getPrefs({ teamId }).then(prefs => ({ prefs }), error => ({ error }));
3351
+ const shared = typeof readTeamPrefs === 'function';
3352
+ let read = shared ? await readTeamPrefs(teamId, this._appwrite) : await fresh();
3353
+ if (shared && read.error && !String(read.error.message || '').includes('could not be found')) read = await fresh();
3354
+ if (read.error) throw read.error;
3355
+ const prefs = read.prefs;
3287
3356
  // Deleted template roles are stored in team preferences under 'deletedTemplateRoles'
3288
3357
  if (prefs && prefs.deletedTemplateRoles && Array.isArray(prefs.deletedTemplateRoles)) {
3289
3358
  deletedRoles = prefs.deletedTemplateRoles;
@@ -3354,11 +3423,7 @@ function initializeTeamsRolesDefaults() {
3354
3423
  roles: updatedRoles,
3355
3424
  deletedTemplateRoles: deletedRoles // Update deleted list in team preferences
3356
3425
  };
3357
- invalidateRolesCache(teamId);
3358
- await this._appwrite.teams.updatePrefs({
3359
- teamId: teamId,
3360
- prefs: updatedPrefs
3361
- });
3426
+ await writeTeamPrefs(this._appwrite, teamId, updatedPrefs);
3362
3427
 
3363
3428
  // Also remove from localStorage for backwards compatibility (if it exists)
3364
3429
  try {
@@ -3458,11 +3523,7 @@ function initializeTeamsRolesDefaults() {
3458
3523
  ...currentPrefs,
3459
3524
  roles: updatedRoles
3460
3525
  };
3461
- invalidateRolesCache(teamId);
3462
- await this._appwrite.teams.updatePrefs({
3463
- teamId: teamId,
3464
- prefs: updatedPrefs
3465
- });
3526
+ await writeTeamPrefs(this._appwrite, teamId, updatedPrefs);
3466
3527
 
3467
3528
  // Refresh cache for this team
3468
3529
  if (this.getAllRoles) {
@@ -3610,40 +3671,42 @@ function roleHasAllOwnerPermissions(roleName, memberRoles) {
3610
3671
  return OWNER_PERMISSIONS.every(perm => permissions.includes(perm));
3611
3672
  }
3612
3673
 
3613
- // User-generated roles live in team prefs; one read per team is shared by every permission check
3614
- // for a short window and dropped on any auth change or prefs write
3674
+ // Team prefs (user-generated roles, deleted template roles): one read per team shared for a short
3675
+ // window; dropped on any identity change, around every prefs write and on a realtime team update
3615
3676
  const ROLES_CACHE_TTL_MS = 15000;
3616
- const rolesCache = new Map(); // teamId -> { at, promise }
3677
+ const rolesCache = new Map(); // teamId -> { at, promise of { prefs } | { error } }
3617
3678
  function invalidateRolesCache(teamId) { if (teamId === undefined) rolesCache.clear(); else rolesCache.delete(teamId); }
3618
3679
  if (typeof window !== 'undefined') {
3619
- ['manifest:auth:login', 'manifest:auth:logout', 'manifest:auth:anonymous', 'manifest:auth:session-cleared', 'manifest:auth:initialized', 'manifest:auth:teams-loaded']
3680
+ ['manifest:auth:login', 'manifest:auth:logout', 'manifest:auth:anonymous', 'manifest:auth:session-cleared', 'manifest:auth:initialized']
3620
3681
  .forEach(type => window.addEventListener(type, () => invalidateRolesCache()));
3621
3682
  }
3622
3683
 
3623
- async function getUserGeneratedRoles(teamId, appwrite) {
3624
- if (!appwrite || !appwrite.teams) {
3625
- return null;
3626
- }
3684
+ function readTeamPrefs(teamId, appwrite) {
3627
3685
  const hit = rolesCache.get(teamId);
3628
3686
  if (hit && Date.now() - hit.at < ROLES_CACHE_TTL_MS) return hit.promise;
3629
- const promise = readUserGeneratedRoles(teamId, appwrite);
3687
+ let request;
3688
+ try { request = Promise.resolve(appwrite.teams.getPrefs({ teamId })); } catch (error) { request = Promise.reject(error); }
3689
+ const promise = request.then(prefs => ({ prefs }), error => ({ error }));
3630
3690
  rolesCache.set(teamId, { at: Date.now(), promise });
3631
- promise.catch(() => rolesCache.delete(teamId)); // a null result (no custom roles) is a valid, cached answer
3632
3691
  return promise;
3633
3692
  }
3634
3693
 
3635
- async function readUserGeneratedRoles(teamId, appwrite) {
3694
+ async function writeTeamPrefs(appwrite, teamId, prefs) {
3695
+ invalidateRolesCache(teamId);
3636
3696
  try {
3637
- const prefs = await appwrite.teams.getPrefs({ teamId });
3638
- return prefs?.roles || null;
3639
- } catch (error) {
3640
- // Prefs may lack roles, or team deleted (404) → null
3641
- if (error.message && error.message.includes('could not be found')) {
3642
- return null;
3643
- }
3644
- // For other errors, also return null (team preferences might not exist yet)
3697
+ return await appwrite.teams.updatePrefs({ teamId, prefs });
3698
+ } finally {
3699
+ invalidateRolesCache(teamId);
3700
+ }
3701
+ }
3702
+
3703
+ async function getUserGeneratedRoles(teamId, appwrite) {
3704
+ if (!appwrite || !appwrite.teams) {
3645
3705
  return null;
3646
3706
  }
3707
+ // A failed read (404, no prefs yet) is "no custom roles"
3708
+ const { prefs } = await readTeamPrefs(teamId, appwrite);
3709
+ return prefs?.roles || null;
3647
3710
  }
3648
3711
 
3649
3712
  // Merge manifest roles with user-generated roles (user-generated overrides manifest)
@@ -4084,11 +4147,7 @@ function initializeTeamsUserRoles() {
4084
4147
  ...currentPrefs,
4085
4148
  roles: updatedRoles
4086
4149
  };
4087
- invalidateRolesCache(teamId);
4088
- await this._appwrite.teams.updatePrefs({
4089
- teamId: teamId,
4090
- prefs: updatedPrefs
4091
- });
4150
+ await writeTeamPrefs(this._appwrite, teamId, updatedPrefs);
4092
4151
 
4093
4152
  // Refresh permission cache to update UI
4094
4153
  if (this.refreshPermissionCache) {
@@ -4203,11 +4262,7 @@ function initializeTeamsUserRoles() {
4203
4262
  ...currentPrefs,
4204
4263
  roles: updatedRoles
4205
4264
  };
4206
- invalidateRolesCache(teamId);
4207
- await this._appwrite.teams.updatePrefs({
4208
- teamId: teamId,
4209
- prefs: updatedPrefs
4210
- });
4265
+ await writeTeamPrefs(this._appwrite, teamId, updatedPrefs);
4211
4266
 
4212
4267
  // Refresh permission cache to update UI
4213
4268
  if (this.refreshPermissionCache) {
@@ -4305,11 +4360,7 @@ function initializeTeamsUserRoles() {
4305
4360
  ...currentPrefs,
4306
4361
  roles: updatedRoles
4307
4362
  };
4308
- invalidateRolesCache(teamId);
4309
- await this._appwrite.teams.updatePrefs({
4310
- teamId: teamId,
4311
- prefs: updatedPrefs
4312
- });
4363
+ await writeTeamPrefs(this._appwrite, teamId, updatedPrefs);
4313
4364
 
4314
4365
  // Update all memberships that have the old role name to use the new role name
4315
4366
  // This prevents data drift where role names in memberships don't match role definitions
@@ -4471,12 +4522,7 @@ function initializeTeamsUserRoles() {
4471
4522
  deletedTemplateRoles: deletedRoles
4472
4523
  };
4473
4524
 
4474
- invalidateRolesCache(teamId);
4475
-
4476
- await this._appwrite.teams.updatePrefs({
4477
- teamId: teamId,
4478
- prefs: updatedPrefs
4479
- });
4525
+ await writeTeamPrefs(this._appwrite, teamId, updatedPrefs);
4480
4526
  }
4481
4527
  } catch (e) {
4482
4528
  // Fallback to localStorage for backwards compatibility
@@ -4508,11 +4554,7 @@ function initializeTeamsUserRoles() {
4508
4554
  ...currentPrefs,
4509
4555
  roles: updatedRoles
4510
4556
  };
4511
- invalidateRolesCache(teamId);
4512
- await this._appwrite.teams.updatePrefs({
4513
- teamId: teamId,
4514
- prefs: updatedPrefs
4515
- });
4557
+ await writeTeamPrefs(this._appwrite, teamId, updatedPrefs);
4516
4558
  }
4517
4559
 
4518
4560
  // Update per-team cache for this specific team (create new object reference for reactivity)
@@ -4735,7 +4777,10 @@ function initializeTeamsMembers() {
4735
4777
  if (search && search.trim().length > 0) {
4736
4778
  params.search = search;
4737
4779
  }
4738
- const result = await this._appwrite.teams.listMemberships(params);
4780
+ const request = this._appwrite.teams.listMemberships(params);
4781
+ // The current team's prefs are needed next (display roles, permissions): read them alongside
4782
+ if (this.currentTeam?.$id === teamId && this.getUserGeneratedRoles) this.getUserGeneratedRoles(teamId).catch(() => { });
4783
+ const result = await request;
4739
4784
  let memberships = result.memberships || [];
4740
4785
 
4741
4786
  // Enhance memberships with user email if missing
@@ -5220,6 +5265,8 @@ function initializeTeamsConvenience() {
5220
5265
  if (!store._allRolesCacheByTeam) store._allRolesCacheByTeam = {};
5221
5266
  if (!store._userGeneratedRolesCache) store._userGeneratedRolesCache = {};
5222
5267
 
5268
+ const sameMembers = (a, b) => Array.isArray(a) && Array.isArray(b) && a.length === b.length && a.every((m, i) => m === b[i]);
5269
+
5223
5270
  // Update permission cache when team changes
5224
5271
  const updatePermissionCache = async function () {
5225
5272
  if (!this.currentTeam || !this.currentTeamMemberships || !this.user) {
@@ -5232,57 +5279,48 @@ function initializeTeamsConvenience() {
5232
5279
  }
5233
5280
 
5234
5281
  const teamId = this.currentTeam.$id;
5282
+ const memberships = this.currentTeamMemberships;
5235
5283
  const permissions = ['inviteMembers', 'updateMembers', 'removeMembers', 'renameTeam', 'deleteTeam', 'manageRoles'];
5236
5284
 
5237
- // Cache permissions
5285
+ // Computed first, written only if the team and its members are unchanged (a newer refresh owns them otherwise)
5286
+ const permissionCache = {};
5238
5287
  for (const perm of permissions) {
5239
- if (this.hasTeamPermission) {
5240
- const hasPerm = await this.hasTeamPermission(perm);
5241
- this._permissionCache[perm] = hasPerm;
5242
- } else {
5243
- this._permissionCache[perm] = false;
5244
- }
5288
+ permissionCache[perm] = this.hasTeamPermission ? await this.hasTeamPermission(perm) : false;
5245
5289
  }
5290
+ const userRole = this.getUserRole ? await this.getUserRole() : null;
5246
5291
 
5247
- // Cache user role
5248
- if (this.getUserRole) {
5249
- this._userRoleCache = await this.getUserRole();
5250
- } else {
5251
- this._userRoleCache = null;
5252
- }
5253
-
5254
- // Cache all roles
5292
+ let rolesCopy = {};
5293
+ const userGenerated = {};
5255
5294
  if (this.getAllRoles) {
5256
5295
  const allRoles = await this.getAllRoles(teamId);
5257
- // Create new object reference to ensure Alpine reactivity
5258
- const rolesCopy = allRoles ? { ...allRoles } : {};
5259
- this._allRolesCache = rolesCopy;
5260
- // Also cache by team ID for per-team lookups (create new object reference)
5261
- if (!this._allRolesCacheByTeam) this._allRolesCacheByTeam = {};
5262
- this._allRolesCacheByTeam[teamId] = { ...rolesCopy };
5296
+ rolesCopy = allRoles ? { ...allRoles } : {};
5263
5297
 
5264
5298
  // Pre-populate permanent role cache for all roles (for isRoleDeletable to work)
5265
5299
  if (!this._rolePermanentCache) this._rolePermanentCache = {};
5266
5300
  if (!this._rolePermanentCache[teamId]) this._rolePermanentCache[teamId] = {};
5267
5301
  if (this.isRolePermanent) {
5268
5302
  for (const roleName of Object.keys(rolesCopy)) {
5269
- // Pre-cache permanent status for all roles
5270
5303
  await this.isRolePermanent(teamId, roleName);
5271
5304
  }
5272
5305
  }
5273
5306
 
5274
- // Cache which roles are user-generated (always check, no feature flag needed)
5275
- this._userGeneratedRolesCache = {};
5276
- if (this._allRolesCache && this.isUserGeneratedRole) {
5277
- for (const roleName of Object.keys(this._allRolesCache)) {
5278
- this._userGeneratedRolesCache[roleName] = await this.isUserGeneratedRole(teamId, roleName);
5307
+ // Which roles are user-generated
5308
+ if (this.isUserGeneratedRole) {
5309
+ for (const roleName of Object.keys(rolesCopy)) {
5310
+ userGenerated[roleName] = await this.isUserGeneratedRole(teamId, roleName);
5279
5311
  }
5280
5312
  }
5281
- } else {
5282
- this._allRolesCache = {};
5283
- if (!this._allRolesCacheByTeam) this._allRolesCacheByTeam = {};
5284
- this._allRolesCacheByTeam[teamId] = {};
5285
5313
  }
5314
+
5315
+ // Per-team roles are correct for their key either way
5316
+ if (!this._allRolesCacheByTeam) this._allRolesCacheByTeam = {};
5317
+ this._allRolesCacheByTeam[teamId] = { ...rolesCopy };
5318
+ if (this.currentTeam?.$id !== teamId || !sameMembers(memberships, this.currentTeamMemberships)) return;
5319
+ this._permissionCache = permissionCache;
5320
+ this._userRoleCache = userRole;
5321
+ this._allRolesCache = rolesCopy;
5322
+ this._userGeneratedRolesCache = userGenerated;
5323
+ this._permissionRefresh = { seq: (this._permissionRefresh?.seq || 0) + 1, teamId, memberships };
5286
5324
  };
5287
5325
 
5288
5326
  // Public method to refresh permission cache
@@ -5512,7 +5550,8 @@ function initializeTeamsConvenience() {
5512
5550
  }
5513
5551
  if (team && team.$id && this.listMemberships) {
5514
5552
  const result = await this.listMemberships(team.$id);
5515
- if (result.success) {
5553
+ // A later viewTeam owns the members list once it has switched team
5554
+ if (result.success && this.currentTeam?.$id === team.$id) {
5516
5555
  this.currentTeamMemberships = result.memberships || [];
5517
5556
  }
5518
5557
  }
@@ -6055,9 +6094,13 @@ function initializeTeamsConvenience() {
6055
6094
  if (store.viewTeam && !store._viewTeamWrapped) {
6056
6095
  const originalViewTeam = store.viewTeam;
6057
6096
  store.viewTeam = async function (team) {
6097
+ const before = this._permissionRefresh?.seq || 0;
6058
6098
  const result = await originalViewTeam.call(this, team);
6059
- // Update cache after viewing team (which loads memberships)
6060
- if (updatePermissionCache) {
6099
+ // listMemberships refreshes for the current team; refresh here only if that did not cover this team and these members
6100
+ const last = this._permissionRefresh;
6101
+ const covered = !!(last && last.seq > before && team?.$id && this.currentTeam?.$id === team.$id
6102
+ && last.teamId === team.$id && sameMembers(last.memberships, this.currentTeamMemberships));
6103
+ if (!covered && updatePermissionCache) {
6061
6104
  await updatePermissionCache.call(this);
6062
6105
  }
6063
6106
  // Update available permissions for autocomplete