solid-logic 6.0.0-1 → 6.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/dist/authSession/authSession.cjs.js +1 -1
  2. package/dist/authSession/authSession.cjs.js.map +1 -1
  3. package/dist/authSession/authSession.esm.js +25 -10
  4. package/dist/authSession/authSession.esm.js.map +1 -1
  5. package/dist/authSession/events.cjs.js.map +1 -1
  6. package/dist/authSession/events.esm.js.map +1 -1
  7. package/dist/authSession/flagAuthorizationOnTransitions.cjs.js +2 -0
  8. package/dist/authSession/flagAuthorizationOnTransitions.cjs.js.map +1 -0
  9. package/dist/authSession/flagAuthorizationOnTransitions.esm.js +59 -0
  10. package/dist/authSession/flagAuthorizationOnTransitions.esm.js.map +1 -0
  11. package/dist/authSession/identityState.cjs.js +2 -0
  12. package/dist/authSession/identityState.cjs.js.map +1 -0
  13. package/dist/authSession/identityState.esm.js +198 -0
  14. package/dist/authSession/identityState.esm.js.map +1 -0
  15. package/dist/authn/SolidAuthnLogic.cjs.js +1 -1
  16. package/dist/authn/SolidAuthnLogic.cjs.js.map +1 -1
  17. package/dist/authn/SolidAuthnLogic.esm.js +47 -40
  18. package/dist/authn/SolidAuthnLogic.esm.js.map +1 -1
  19. package/dist/index.cjs.js +1 -1
  20. package/dist/index.cjs.js.map +1 -1
  21. package/dist/index.esm.js +10 -9
  22. package/dist/index.esm.js.map +1 -1
  23. package/dist/logic/solidLogic.cjs.js +1 -1
  24. package/dist/logic/solidLogic.cjs.js.map +1 -1
  25. package/dist/logic/solidLogic.esm.js +35 -30
  26. package/dist/logic/solidLogic.esm.js.map +1 -1
  27. package/dist/logic/solidLogicSingleton.cjs.js +1 -1
  28. package/dist/logic/solidLogicSingleton.cjs.js.map +1 -1
  29. package/dist/logic/solidLogicSingleton.esm.js +14 -13
  30. package/dist/logic/solidLogicSingleton.esm.js.map +1 -1
  31. package/dist/resource/resourceLogic.cjs.js +1 -1
  32. package/dist/resource/resourceLogic.cjs.js.map +1 -1
  33. package/dist/resource/resourceLogic.esm.js +0 -15
  34. package/dist/resource/resourceLogic.esm.js.map +1 -1
  35. package/dist/util/utilityLogic.cjs.js +2 -2
  36. package/dist/util/utilityLogic.cjs.js.map +1 -1
  37. package/dist/util/utilityLogic.esm.js +62 -55
  38. package/dist/util/utilityLogic.esm.js.map +1 -1
  39. package/package.json +2 -2
@@ -1,2 +1,2 @@
1
- const e=require("./session.cjs.js"),t=require("./issuer.cjs.js"),n=require("./events.cjs.js");var r=e._session,i=typeof r.login==`function`?r.login.bind(e._session):void 0;i&&(r.login=async(e,n)=>{if(e&&typeof e==`object`&&!Array.isArray(e)){let n=e.oidcIssuer??e.idp??e.issuer,r=e.redirectUrl??e.redirect_uri??e.redirectUri;if(typeof n==`string`&&typeof r==`string`)return i(await t.resolveIssuerForLogin(n),r)}return i(typeof e==`string`?await t.resolveIssuerForLogin(e):e,n)});var a=new n.SessionEvents,o=e._session.isActive??!!e._session.webId;typeof e._session.addEventListener==`function`&&e._session.addEventListener(`sessionStateChange`,()=>{let t=e._session.isActive??!!e._session.webId;o&&!t&&a.emit(`logout`),o=t});var s=Object.assign(e._session,{events:a});exports.authSession=s;
1
+ const e=require("./session.cjs.js"),t=require("./issuer.cjs.js"),n=require("./events.cjs.js"),r=require("./identityState.cjs.js");var i=e._session,a=typeof i.login==`function`?i.login.bind(e._session):void 0;a&&(i.login=async(e,n)=>{if(e&&typeof e==`object`&&!Array.isArray(e)){let n=e.oidcIssuer??e.idp??e.issuer,r=e.redirectUrl??e.redirect_uri??e.redirectUri;if(typeof n==`string`&&typeof r==`string`)return a(await t.resolveIssuerForLogin(n),r)}return a(typeof e==`string`?await t.resolveIssuerForLogin(e):e,n)});var o=new n.SessionEvents;r.subscribeIdentity(e._session,{onEvent:e=>o.emit(e),resync:()=>{let t=r.restoreSession(e._session);if(t)return t.then(()=>`changed`,e=>{let t=e instanceof Error?e.message:String(e);return/no session to restore/i.test(t)?`cleared`:`changed`})}});var s=Object.assign(e._session,{events:o});Object.defineProperty(s,"info",{enumerable:!0,configurable:!0,get(){return r.legacySessionInfo(e._session)},set(e){}}),exports.authSession=s;
2
2
  //# sourceMappingURL=authSession.cjs.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"authSession.cjs.js","names":[],"sources":["../../src/authSession/authSession.ts"],"sourcesContent":["/**\n * Auth session wiring.\n *\n * Takes the raw OIDC session from session.ts and layers on:\n * - Login compatibility shim (normalises legacy call-site signatures\n * and resolves the canonical issuer)\n * - SessionEvents shim (legacy EventEmitter-style API)\n * - Logout listener (emits 'logout' on session deactivation)\n *\n * Exports the fully assembled authSession.\n */\n\nimport type { Session as OidcSession } from '@uvdsl/solid-oidc-client-browser/core'\nimport { _session } from './session'\nimport { resolveIssuerForLogin } from './issuer'\nimport { SessionEvents } from './events'\n\ntype SessionCompatibilityShape = {\n webId?: string\n isActive?: boolean\n info?: {\n webId?: string\n isLoggedIn?: boolean\n }\n fetch?: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>\n authFetch?: (input: string | URL | Request, init?: RequestInit, dpopPayload?: any) => Promise<Response>\n}\n\ntype LoginOptionsLegacy = {\n oidcIssuer?: string\n idp?: string\n issuer?: string\n redirectUrl?: string\n redirect_uri?: string\n redirectUri?: string\n}\n\ntype LoginCompat = {\n (issuer: string, redirectUrl: string): Promise<unknown>\n (options: LoginOptionsLegacy): Promise<unknown>\n}\n\nexport type SessionWithLegacyEvents = Omit<OidcSession, 'login'> & SessionCompatibilityShape & {\n login: LoginCompat\n events: SessionEvents\n}\n\n// ---------------------------------------------------------------------------\n// Login compatibility shim\n// ---------------------------------------------------------------------------\n// Wraps _session.login() so that call sites with different calling\n// conventions all work. The underlying session expects:\n// login(issuer: string, redirectUrl: string)\n//\n// idpOrOptions can be:\n// - a string (issuer URL) — passed through with less resolution\n// - an options object with any of these field-name variants:\n// issuer: oidcIssuer | idp | issuer\n// redirect: redirectUrl | redirect_uri | redirectUri\n// (all redirect field names map to the same value: the URL the IdP\n// should send the browser back to after authentication)\n// - anything else — passed through to the underlying session as-is\n//\n// In all cases the issuer is resolved through\n// /.well-known/openid-configuration before redirect so the canonical\n// issuer host is used.\n\nconst sessionAny = _session as any\nconst originalLogin = typeof sessionAny.login === 'function'\n ? sessionAny.login.bind(_session)\n : undefined\n\nif (originalLogin) {\n const compatLogin = async (idpOrOptions: any, redirectUri?: string): Promise<unknown> => {\n if (idpOrOptions && typeof idpOrOptions === 'object' && !Array.isArray(idpOrOptions)) {\n const oidcIssuer = idpOrOptions.oidcIssuer ?? idpOrOptions.idp ?? idpOrOptions.issuer\n const redirectUrl = idpOrOptions.redirectUrl ?? idpOrOptions.redirect_uri ?? idpOrOptions.redirectUri\n if (typeof oidcIssuer === 'string' && typeof redirectUrl === 'string') {\n return originalLogin(await resolveIssuerForLogin(oidcIssuer), redirectUrl)\n }\n }\n if (typeof idpOrOptions === 'string') {\n return originalLogin(await resolveIssuerForLogin(idpOrOptions), redirectUri)\n }\n return originalLogin(idpOrOptions, redirectUri)\n }\n sessionAny.login = compatLogin as LoginCompat\n}\n\n// ---------------------------------------------------------------------------\n// Legacy event layer\n// ---------------------------------------------------------------------------\n\nconst events = new SessionEvents()\n\n// Emit the legacy 'logout' event when the session transitions from active to inactive.\n// 'login' and 'sessionRestore' are emitted in SolidAuthnLogic.checkUser()\n// because only that call site knows which path activated the session.\nlet _wasActive = (_session as any).isActive ?? Boolean((_session as any).webId)\nif (typeof (_session as unknown as EventTarget).addEventListener === 'function') {\n ;(_session as unknown as EventTarget).addEventListener('sessionStateChange', () => {\n const isNowActive = (_session as any).isActive ?? Boolean((_session as any).webId)\n if (_wasActive && !isNowActive) {\n events.emit('logout')\n }\n _wasActive = isNowActive\n })\n}\n\nexport const authSession: SessionWithLegacyEvents = Object.assign(\n _session as Omit<OidcSession, 'login'> & { login: LoginCompat },\n { events }\n)\n "],"mappings":"8FAmEA,IAAM,EAAa,EAAA,SACb,EAAgB,OAAO,EAAW,OAAU,WAC9C,EAAW,MAAM,KAAK,EAAA,QAAQ,EAC9B,IAAA,GAEA,IAcF,EAAW,MAAQ,MAbQ,EAAmB,IAA2C,CACvF,GAAI,GAAgB,OAAO,GAAiB,UAAY,CAAC,MAAM,QAAQ,CAAY,EAAG,CACpF,IAAM,EAAa,EAAa,YAAc,EAAa,KAAO,EAAa,OACzE,EAAc,EAAa,aAAe,EAAa,cAAgB,EAAa,YAC1F,GAAI,OAAO,GAAe,UAAY,OAAO,GAAgB,SAC3D,OAAO,EAAc,MAAM,EAAA,sBAAsB,CAAU,EAAG,CAAW,CAE7E,CAIA,OAFS,EADL,OAAO,GAAiB,SACL,MAAM,EAAA,sBAAsB,CAAY,EAE1C,EAF6C,CAAW,CAG/E,GAQF,IAAM,EAAS,IAAI,EAAA,cAKf,EAAc,EAAA,SAAiB,UAAY,EAAS,EAAA,SAAiB,MACrE,OAAQ,EAAA,SAAoC,kBAAqB,YAClE,EAAA,SAAqC,iBAAiB,yBAA4B,CACjF,IAAM,EAAe,EAAA,SAAiB,UAAY,EAAS,EAAA,SAAiB,MACxE,GAAc,CAAC,GACjB,EAAO,KAAK,QAAQ,EAEtB,EAAa,CACf,CAAC,EAGH,IAAa,EAAuC,OAAO,OACzD,EAAA,SACA,CAAE,QAAO,CACX"}
1
+ {"version":3,"file":"authSession.cjs.js","names":[],"sources":["../../src/authSession/authSession.ts"],"sourcesContent":["/**\n * Auth session wiring.\n *\n * Takes the raw OIDC session from session.ts and layers on:\n * - Login compatibility shim (normalises legacy call-site signatures\n * and resolves the canonical issuer)\n * - SessionEvents shim (legacy EventEmitter-style API)\n * - Logout listener (emits 'logout' on session deactivation)\n *\n * Exports the fully assembled authSession.\n */\n\nimport type { Session as OidcSession } from '@uvdsl/solid-oidc-client-browser/core'\nimport { _session } from './session'\nimport { resolveIssuerForLogin } from './issuer'\nimport { SessionEvents } from './events'\nimport { legacySessionInfo, restoreSession, subscribeIdentity, type SessionLike } from './identityState'\n\ntype SessionCompatibilityShape = {\n webId?: string\n isActive?: boolean\n info?: {\n webId?: string\n isLoggedIn?: boolean\n }\n fetch?: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>\n authFetch?: (input: string | URL | Request, init?: RequestInit, dpopPayload?: any) => Promise<Response>\n}\n\ntype LoginOptionsLegacy = {\n oidcIssuer?: string\n idp?: string\n issuer?: string\n redirectUrl?: string\n redirect_uri?: string\n redirectUri?: string\n}\n\ntype LoginCompat = {\n (issuer: string, redirectUrl: string): Promise<unknown>\n (options: LoginOptionsLegacy): Promise<unknown>\n}\n\nexport type SessionWithLegacyEvents = Omit<OidcSession, 'login'> & SessionCompatibilityShape & {\n login: LoginCompat\n events: SessionEvents\n}\n\n// ---------------------------------------------------------------------------\n// Login compatibility shim\n// ---------------------------------------------------------------------------\n// Wraps _session.login() so that call sites with different calling\n// conventions all work. The underlying session expects:\n// login(issuer: string, redirectUrl: string)\n//\n// idpOrOptions can be:\n// - a string (issuer URL) — passed through with less resolution\n// - an options object with any of these field-name variants:\n// issuer: oidcIssuer | idp | issuer\n// redirect: redirectUrl | redirect_uri | redirectUri\n// (all redirect field names map to the same value: the URL the IdP\n// should send the browser back to after authentication)\n// - anything else — passed through to the underlying session as-is\n//\n// In all cases the issuer is resolved through\n// /.well-known/openid-configuration before redirect so the canonical\n// issuer host is used.\n\nconst sessionAny = _session as any\nconst originalLogin = typeof sessionAny.login === 'function'\n ? sessionAny.login.bind(_session)\n : undefined\n\nif (originalLogin) {\n const compatLogin = async (idpOrOptions: any, redirectUri?: string): Promise<unknown> => {\n if (idpOrOptions && typeof idpOrOptions === 'object' && !Array.isArray(idpOrOptions)) {\n const oidcIssuer = idpOrOptions.oidcIssuer ?? idpOrOptions.idp ?? idpOrOptions.issuer\n const redirectUrl = idpOrOptions.redirectUrl ?? idpOrOptions.redirect_uri ?? idpOrOptions.redirectUri\n if (typeof oidcIssuer === 'string' && typeof redirectUrl === 'string') {\n return originalLogin(await resolveIssuerForLogin(oidcIssuer), redirectUrl)\n }\n }\n if (typeof idpOrOptions === 'string') {\n return originalLogin(await resolveIssuerForLogin(idpOrOptions), redirectUri)\n }\n return originalLogin(idpOrOptions, redirectUri)\n }\n sessionAny.login = compatLogin as LoginCompat\n}\n\n// ---------------------------------------------------------------------------\n// Legacy event layer\n// ---------------------------------------------------------------------------\n\nconst events = new SessionEvents()\n\n// 'login' and 'sessionRestore' are emitted in SolidAuthnLogic.checkUser()\n// because only that call site knows which path activated the session. Every\n// other identity transition is reported by the identity state, which watches\n// the session itself: 'logout' when the session goes inactive, 'sessionChange'\n// when the identity changes some other way — including a login/logout made in\n// another tab, which uvdsl does not broadcast as a state change and which is\n// noticed when this tab is refocused — and 'identityReplaced' when an\n// established identity is gone.\n//\n// The resync maps a backing store that no longer holds a session (a cross-tab\n// logout) to 'cleared'; the state bounds the wait and drops an answer that\n// belongs to an identity the session has left.\nconst resyncSession = (): unknown => {\n const restoring = restoreSession(_session as unknown as SessionLike)\n if (!restoring) return undefined\n return restoring.then(() => 'changed', (error: unknown) => {\n // A transient refresh/network failure is compared as it stands; a store\n // that has no session to restore means this tab's identity is gone.\n const message = error instanceof Error ? error.message : String(error)\n return /no session to restore/i.test(message) ? 'cleared' : 'changed'\n })\n}\nsubscribeIdentity(_session as unknown as SessionLike, {\n onEvent: (event) => events.emit(event),\n resync: resyncSession\n})\n\nexport const authSession: SessionWithLegacyEvents = Object.assign(\n _session as Omit<OidcSession, 'login'> & { login: LoginCompat },\n { events }\n)\n\n// Legacy `info` compatibility shape.\n// The uvdsl session stores state on `webId_`/`isActive_` and exposes them via\n// `webId`/`isActive` getters, but legacy consumers (e.g. solid-ui's\n// `loginStatusBox` widget, `SolidAuthnLogic.currentUser()`'s fallback path)\n// read `authSession.info.webId` / `authSession.info.isLoggedIn`. Expose those\n// as a derived value — and keep it derived: consumers snapshot and restore\n// `info`, and a retained value would report the previous identity after a\n// login/logout. Assignment is accepted and ignored so ordinary property\n// writes cannot throw; a test that needs to fake `info` redefines it.\nObject.defineProperty(authSession, 'info', {\n enumerable: true,\n configurable: true,\n get (): { webId?: string, isLoggedIn?: boolean } {\n return legacySessionInfo(_session as unknown as SessionLike)\n },\n set (_value: { webId?: string, isLoggedIn?: boolean } | undefined): void {\n // Accepted for legacy code that assigns snapshots; reads stay derived.\n }\n})\n "],"mappings":"kIAoEA,IAAM,EAAa,EAAA,SACb,EAAgB,OAAO,EAAW,OAAU,WAC9C,EAAW,MAAM,KAAK,EAAA,QAAQ,EAC9B,IAAA,GAEA,IAcF,EAAW,MAAQ,MAbQ,EAAmB,IAA2C,CACvF,GAAI,GAAgB,OAAO,GAAiB,UAAY,CAAC,MAAM,QAAQ,CAAY,EAAG,CACpF,IAAM,EAAa,EAAa,YAAc,EAAa,KAAO,EAAa,OACzE,EAAc,EAAa,aAAe,EAAa,cAAgB,EAAa,YAC1F,GAAI,OAAO,GAAe,UAAY,OAAO,GAAgB,SAC3D,OAAO,EAAc,MAAM,EAAA,sBAAsB,CAAU,EAAG,CAAW,CAE7E,CAIA,OAFS,EADL,OAAO,GAAiB,SACL,MAAM,EAAA,sBAAsB,CAAY,EAE1C,EAF6C,CAAW,CAG/E,GAQF,IAAM,EAAS,IAAI,EAAA,cAwBnB,EAAA,kBAAkB,EAAA,SAAoC,CACpD,QAAU,GAAU,EAAO,KAAK,CAAK,EACrC,WAZmC,CACnC,IAAM,EAAY,EAAA,eAAe,EAAA,QAAkC,EAC9D,KACL,OAAO,EAAU,SAAW,UAAY,GAAmB,CAGzD,IAAM,EAAU,aAAiB,MAAQ,EAAM,QAAU,OAAO,CAAK,EACrE,MAAO,yBAAyB,KAAK,CAAO,EAAI,UAAY,SAC9D,CAAC,CACH,CAIA,CAAC,EAED,IAAa,EAAuC,OAAO,OACzD,EAAA,SACA,CAAE,QAAO,CACX,EAWA,OAAO,eAAe,EAAa,OAAQ,CACzC,WAAY,GACZ,aAAc,GACd,KAAiD,CAC/C,OAAO,EAAA,kBAAkB,EAAA,QAAkC,CAC7D,EACA,IAAK,EAAoE,CAEzE,CACF,CAAC"}
@@ -1,22 +1,37 @@
1
1
  import { _session as e } from "./session.esm.js";
2
2
  import { resolveIssuerForLogin as t } from "./issuer.esm.js";
3
3
  import { SessionEvents as n } from "./events.esm.js";
4
+ import { legacySessionInfo as r, restoreSession as i, subscribeIdentity as a } from "./identityState.esm.js";
4
5
  //#region src/authSession/authSession.ts
5
- var r = e, i = typeof r.login == "function" ? r.login.bind(e) : void 0;
6
- i && (r.login = async (e, n) => {
6
+ var o = e, s = typeof o.login == "function" ? o.login.bind(e) : void 0;
7
+ s && (o.login = async (e, n) => {
7
8
  if (e && typeof e == "object" && !Array.isArray(e)) {
8
9
  let n = e.oidcIssuer ?? e.idp ?? e.issuer, r = e.redirectUrl ?? e.redirect_uri ?? e.redirectUri;
9
- if (typeof n == "string" && typeof r == "string") return i(await t(n), r);
10
+ if (typeof n == "string" && typeof r == "string") return s(await t(n), r);
10
11
  }
11
- return i(typeof e == "string" ? await t(e) : e, n);
12
+ return s(typeof e == "string" ? await t(e) : e, n);
12
13
  });
13
- var a = new n(), o = e.isActive ?? !!e.webId;
14
- typeof e.addEventListener == "function" && e.addEventListener("sessionStateChange", () => {
15
- let t = e.isActive ?? !!e.webId;
16
- o && !t && a.emit("logout"), o = t;
14
+ var c = new n();
15
+ a(e, {
16
+ onEvent: (e) => c.emit(e),
17
+ resync: () => {
18
+ let t = i(e);
19
+ if (t) return t.then(() => "changed", (e) => {
20
+ let t = e instanceof Error ? e.message : String(e);
21
+ return /no session to restore/i.test(t) ? "cleared" : "changed";
22
+ });
23
+ }
24
+ });
25
+ var l = Object.assign(e, { events: c });
26
+ Object.defineProperty(l, "info", {
27
+ enumerable: !0,
28
+ configurable: !0,
29
+ get() {
30
+ return r(e);
31
+ },
32
+ set(e) {}
17
33
  });
18
- var s = Object.assign(e, { events: a });
19
34
  //#endregion
20
- export { s as authSession };
35
+ export { l as authSession };
21
36
 
22
37
  //# sourceMappingURL=authSession.esm.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"authSession.esm.js","names":[],"sources":["../../src/authSession/authSession.ts"],"sourcesContent":["/**\n * Auth session wiring.\n *\n * Takes the raw OIDC session from session.ts and layers on:\n * - Login compatibility shim (normalises legacy call-site signatures\n * and resolves the canonical issuer)\n * - SessionEvents shim (legacy EventEmitter-style API)\n * - Logout listener (emits 'logout' on session deactivation)\n *\n * Exports the fully assembled authSession.\n */\n\nimport type { Session as OidcSession } from '@uvdsl/solid-oidc-client-browser/core'\nimport { _session } from './session'\nimport { resolveIssuerForLogin } from './issuer'\nimport { SessionEvents } from './events'\n\ntype SessionCompatibilityShape = {\n webId?: string\n isActive?: boolean\n info?: {\n webId?: string\n isLoggedIn?: boolean\n }\n fetch?: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>\n authFetch?: (input: string | URL | Request, init?: RequestInit, dpopPayload?: any) => Promise<Response>\n}\n\ntype LoginOptionsLegacy = {\n oidcIssuer?: string\n idp?: string\n issuer?: string\n redirectUrl?: string\n redirect_uri?: string\n redirectUri?: string\n}\n\ntype LoginCompat = {\n (issuer: string, redirectUrl: string): Promise<unknown>\n (options: LoginOptionsLegacy): Promise<unknown>\n}\n\nexport type SessionWithLegacyEvents = Omit<OidcSession, 'login'> & SessionCompatibilityShape & {\n login: LoginCompat\n events: SessionEvents\n}\n\n// ---------------------------------------------------------------------------\n// Login compatibility shim\n// ---------------------------------------------------------------------------\n// Wraps _session.login() so that call sites with different calling\n// conventions all work. The underlying session expects:\n// login(issuer: string, redirectUrl: string)\n//\n// idpOrOptions can be:\n// - a string (issuer URL) — passed through with less resolution\n// - an options object with any of these field-name variants:\n// issuer: oidcIssuer | idp | issuer\n// redirect: redirectUrl | redirect_uri | redirectUri\n// (all redirect field names map to the same value: the URL the IdP\n// should send the browser back to after authentication)\n// - anything else — passed through to the underlying session as-is\n//\n// In all cases the issuer is resolved through\n// /.well-known/openid-configuration before redirect so the canonical\n// issuer host is used.\n\nconst sessionAny = _session as any\nconst originalLogin = typeof sessionAny.login === 'function'\n ? sessionAny.login.bind(_session)\n : undefined\n\nif (originalLogin) {\n const compatLogin = async (idpOrOptions: any, redirectUri?: string): Promise<unknown> => {\n if (idpOrOptions && typeof idpOrOptions === 'object' && !Array.isArray(idpOrOptions)) {\n const oidcIssuer = idpOrOptions.oidcIssuer ?? idpOrOptions.idp ?? idpOrOptions.issuer\n const redirectUrl = idpOrOptions.redirectUrl ?? idpOrOptions.redirect_uri ?? idpOrOptions.redirectUri\n if (typeof oidcIssuer === 'string' && typeof redirectUrl === 'string') {\n return originalLogin(await resolveIssuerForLogin(oidcIssuer), redirectUrl)\n }\n }\n if (typeof idpOrOptions === 'string') {\n return originalLogin(await resolveIssuerForLogin(idpOrOptions), redirectUri)\n }\n return originalLogin(idpOrOptions, redirectUri)\n }\n sessionAny.login = compatLogin as LoginCompat\n}\n\n// ---------------------------------------------------------------------------\n// Legacy event layer\n// ---------------------------------------------------------------------------\n\nconst events = new SessionEvents()\n\n// Emit the legacy 'logout' event when the session transitions from active to inactive.\n// 'login' and 'sessionRestore' are emitted in SolidAuthnLogic.checkUser()\n// because only that call site knows which path activated the session.\nlet _wasActive = (_session as any).isActive ?? Boolean((_session as any).webId)\nif (typeof (_session as unknown as EventTarget).addEventListener === 'function') {\n ;(_session as unknown as EventTarget).addEventListener('sessionStateChange', () => {\n const isNowActive = (_session as any).isActive ?? Boolean((_session as any).webId)\n if (_wasActive && !isNowActive) {\n events.emit('logout')\n }\n _wasActive = isNowActive\n })\n}\n\nexport const authSession: SessionWithLegacyEvents = Object.assign(\n _session as Omit<OidcSession, 'login'> & { login: LoginCompat },\n { events }\n)\n "],"mappings":";;;;AAmEA,IAAM,IAAa,GACb,IAAgB,OAAO,EAAW,SAAU,aAC9C,EAAW,MAAM,KAAK,CAAQ,IAC9B,KAAA;AAEA,MAcF,EAAW,QAAQ,OAbQ,GAAmB,MAA2C;CACvF,IAAI,KAAgB,OAAO,KAAiB,YAAY,CAAC,MAAM,QAAQ,CAAY,GAAG;EACpF,IAAM,IAAa,EAAa,cAAc,EAAa,OAAO,EAAa,QACzE,IAAc,EAAa,eAAe,EAAa,gBAAgB,EAAa;EAC1F,IAAI,OAAO,KAAe,YAAY,OAAO,KAAgB,UAC3D,OAAO,EAAc,MAAM,EAAsB,CAAU,GAAG,CAAW;CAE7E;CAIA,OAFS,EADL,OAAO,KAAiB,WACL,MAAM,EAAsB,CAAY,IAE1C,GAF6C,CAAW;AAG/E;AAQF,IAAM,IAAS,IAAI,EAAc,GAK7B,IAAc,EAAiB,YAAY,EAAS,EAAiB;AACrE,OAAQ,EAAoC,oBAAqB,cAClE,EAAqC,iBAAiB,4BAA4B;CACjF,IAAM,IAAe,EAAiB,YAAY,EAAS,EAAiB;CAI5E,AAHI,KAAc,CAAC,KACjB,EAAO,KAAK,QAAQ,GAEtB,IAAa;AACf,CAAC;AAGH,IAAa,IAAuC,OAAO,OACzD,GACA,EAAE,UAAO,CACX"}
1
+ {"version":3,"file":"authSession.esm.js","names":[],"sources":["../../src/authSession/authSession.ts"],"sourcesContent":["/**\n * Auth session wiring.\n *\n * Takes the raw OIDC session from session.ts and layers on:\n * - Login compatibility shim (normalises legacy call-site signatures\n * and resolves the canonical issuer)\n * - SessionEvents shim (legacy EventEmitter-style API)\n * - Logout listener (emits 'logout' on session deactivation)\n *\n * Exports the fully assembled authSession.\n */\n\nimport type { Session as OidcSession } from '@uvdsl/solid-oidc-client-browser/core'\nimport { _session } from './session'\nimport { resolveIssuerForLogin } from './issuer'\nimport { SessionEvents } from './events'\nimport { legacySessionInfo, restoreSession, subscribeIdentity, type SessionLike } from './identityState'\n\ntype SessionCompatibilityShape = {\n webId?: string\n isActive?: boolean\n info?: {\n webId?: string\n isLoggedIn?: boolean\n }\n fetch?: (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>\n authFetch?: (input: string | URL | Request, init?: RequestInit, dpopPayload?: any) => Promise<Response>\n}\n\ntype LoginOptionsLegacy = {\n oidcIssuer?: string\n idp?: string\n issuer?: string\n redirectUrl?: string\n redirect_uri?: string\n redirectUri?: string\n}\n\ntype LoginCompat = {\n (issuer: string, redirectUrl: string): Promise<unknown>\n (options: LoginOptionsLegacy): Promise<unknown>\n}\n\nexport type SessionWithLegacyEvents = Omit<OidcSession, 'login'> & SessionCompatibilityShape & {\n login: LoginCompat\n events: SessionEvents\n}\n\n// ---------------------------------------------------------------------------\n// Login compatibility shim\n// ---------------------------------------------------------------------------\n// Wraps _session.login() so that call sites with different calling\n// conventions all work. The underlying session expects:\n// login(issuer: string, redirectUrl: string)\n//\n// idpOrOptions can be:\n// - a string (issuer URL) — passed through with less resolution\n// - an options object with any of these field-name variants:\n// issuer: oidcIssuer | idp | issuer\n// redirect: redirectUrl | redirect_uri | redirectUri\n// (all redirect field names map to the same value: the URL the IdP\n// should send the browser back to after authentication)\n// - anything else — passed through to the underlying session as-is\n//\n// In all cases the issuer is resolved through\n// /.well-known/openid-configuration before redirect so the canonical\n// issuer host is used.\n\nconst sessionAny = _session as any\nconst originalLogin = typeof sessionAny.login === 'function'\n ? sessionAny.login.bind(_session)\n : undefined\n\nif (originalLogin) {\n const compatLogin = async (idpOrOptions: any, redirectUri?: string): Promise<unknown> => {\n if (idpOrOptions && typeof idpOrOptions === 'object' && !Array.isArray(idpOrOptions)) {\n const oidcIssuer = idpOrOptions.oidcIssuer ?? idpOrOptions.idp ?? idpOrOptions.issuer\n const redirectUrl = idpOrOptions.redirectUrl ?? idpOrOptions.redirect_uri ?? idpOrOptions.redirectUri\n if (typeof oidcIssuer === 'string' && typeof redirectUrl === 'string') {\n return originalLogin(await resolveIssuerForLogin(oidcIssuer), redirectUrl)\n }\n }\n if (typeof idpOrOptions === 'string') {\n return originalLogin(await resolveIssuerForLogin(idpOrOptions), redirectUri)\n }\n return originalLogin(idpOrOptions, redirectUri)\n }\n sessionAny.login = compatLogin as LoginCompat\n}\n\n// ---------------------------------------------------------------------------\n// Legacy event layer\n// ---------------------------------------------------------------------------\n\nconst events = new SessionEvents()\n\n// 'login' and 'sessionRestore' are emitted in SolidAuthnLogic.checkUser()\n// because only that call site knows which path activated the session. Every\n// other identity transition is reported by the identity state, which watches\n// the session itself: 'logout' when the session goes inactive, 'sessionChange'\n// when the identity changes some other way — including a login/logout made in\n// another tab, which uvdsl does not broadcast as a state change and which is\n// noticed when this tab is refocused — and 'identityReplaced' when an\n// established identity is gone.\n//\n// The resync maps a backing store that no longer holds a session (a cross-tab\n// logout) to 'cleared'; the state bounds the wait and drops an answer that\n// belongs to an identity the session has left.\nconst resyncSession = (): unknown => {\n const restoring = restoreSession(_session as unknown as SessionLike)\n if (!restoring) return undefined\n return restoring.then(() => 'changed', (error: unknown) => {\n // A transient refresh/network failure is compared as it stands; a store\n // that has no session to restore means this tab's identity is gone.\n const message = error instanceof Error ? error.message : String(error)\n return /no session to restore/i.test(message) ? 'cleared' : 'changed'\n })\n}\nsubscribeIdentity(_session as unknown as SessionLike, {\n onEvent: (event) => events.emit(event),\n resync: resyncSession\n})\n\nexport const authSession: SessionWithLegacyEvents = Object.assign(\n _session as Omit<OidcSession, 'login'> & { login: LoginCompat },\n { events }\n)\n\n// Legacy `info` compatibility shape.\n// The uvdsl session stores state on `webId_`/`isActive_` and exposes them via\n// `webId`/`isActive` getters, but legacy consumers (e.g. solid-ui's\n// `loginStatusBox` widget, `SolidAuthnLogic.currentUser()`'s fallback path)\n// read `authSession.info.webId` / `authSession.info.isLoggedIn`. Expose those\n// as a derived value — and keep it derived: consumers snapshot and restore\n// `info`, and a retained value would report the previous identity after a\n// login/logout. Assignment is accepted and ignored so ordinary property\n// writes cannot throw; a test that needs to fake `info` redefines it.\nObject.defineProperty(authSession, 'info', {\n enumerable: true,\n configurable: true,\n get (): { webId?: string, isLoggedIn?: boolean } {\n return legacySessionInfo(_session as unknown as SessionLike)\n },\n set (_value: { webId?: string, isLoggedIn?: boolean } | undefined): void {\n // Accepted for legacy code that assigns snapshots; reads stay derived.\n }\n})\n "],"mappings":";;;;;AAoEA,IAAM,IAAa,GACb,IAAgB,OAAO,EAAW,SAAU,aAC9C,EAAW,MAAM,KAAK,CAAQ,IAC9B,KAAA;AAEA,MAcF,EAAW,QAAQ,OAbQ,GAAmB,MAA2C;CACvF,IAAI,KAAgB,OAAO,KAAiB,YAAY,CAAC,MAAM,QAAQ,CAAY,GAAG;EACpF,IAAM,IAAa,EAAa,cAAc,EAAa,OAAO,EAAa,QACzE,IAAc,EAAa,eAAe,EAAa,gBAAgB,EAAa;EAC1F,IAAI,OAAO,KAAe,YAAY,OAAO,KAAgB,UAC3D,OAAO,EAAc,MAAM,EAAsB,CAAU,GAAG,CAAW;CAE7E;CAIA,OAFS,EADL,OAAO,KAAiB,WACL,MAAM,EAAsB,CAAY,IAE1C,GAF6C,CAAW;AAG/E;AAQF,IAAM,IAAS,IAAI,EAAc;AAwBjC,EAAkB,GAAoC;CACpD,UAAU,MAAU,EAAO,KAAK,CAAK;CACrC,cAZmC;EACnC,IAAM,IAAY,EAAe,CAAkC;EAC9D,OACL,OAAO,EAAU,WAAW,YAAY,MAAmB;GAGzD,IAAM,IAAU,aAAiB,QAAQ,EAAM,UAAU,OAAO,CAAK;GACrE,OAAO,yBAAyB,KAAK,CAAO,IAAI,YAAY;EAC9D,CAAC;CACH;AAIA,CAAC;AAED,IAAa,IAAuC,OAAO,OACzD,GACA,EAAE,UAAO,CACX;AAWA,OAAO,eAAe,GAAa,QAAQ;CACzC,YAAY;CACZ,cAAc;CACd,MAAiD;EAC/C,OAAO,EAAkB,CAAkC;CAC7D;CACA,IAAK,GAAoE,CAEzE;AACF,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"events.cjs.js","names":[],"sources":["../../src/authSession/events.ts"],"sourcesContent":["/**\n * Legacy event compatibility layer.\n *\n * Pure EventEmitter-style shim — no side effects, no uvdsl dependencies.\n * Wired into the auth session by authSession.ts.\n */\n\ntype LegacyEventName = 'login' | 'logout' | 'sessionRestore'\ntype LegacyEventHandler = (...args: unknown[]) => void\n\n/**\n * Minimal EventEmitter-style shim so that existing consumers using\n * `authSession.events.on('login' | 'logout' | 'sessionRestore', handler)`\n * continue working without modification.\n *\n * Events are emitted by SolidAuthnLogic.checkUser() (login/sessionRestore)\n * and by the sessionStateChange listener in authSession.ts (logout).\n */\nexport class SessionEvents {\n private readonly listeners: Map<string, Set<LegacyEventHandler>> = new Map()\n\n on (event: LegacyEventName, handler: LegacyEventHandler): void {\n if (!this.listeners.has(event)) this.listeners.set(event, new Set())\n this.listeners.get(event)!.add(handler)\n }\n\n off (event: LegacyEventName, handler: LegacyEventHandler): void {\n this.listeners.get(event)?.delete(handler)\n }\n\n emit (event: LegacyEventName, ...args: unknown[]): void {\n this.listeners.get(event)?.forEach(h => h(...args))\n }\n}\n\n"],"mappings":"AAkBA,IAAa,EAAb,KAA2B,8BAC0C,IAAI,IAEvE,GAAI,EAAwB,EAAmC,CACxD,KAAK,UAAU,IAAI,CAAK,GAAG,KAAK,UAAU,IAAI,EAAO,IAAI,GAAK,EACnE,KAAK,UAAU,IAAI,CAAK,CAAC,CAAE,IAAI,CAAO,CACxC,CAEA,IAAK,EAAwB,EAAmC,CAC9D,KAAK,UAAU,IAAI,CAAK,CAAC,EAAE,OAAO,CAAO,CAC3C,CAEA,KAAM,EAAwB,GAAG,EAAuB,CACtD,KAAK,UAAU,IAAI,CAAK,CAAC,EAAE,QAAQ,GAAK,EAAE,GAAG,CAAI,CAAC,CACpD,CACF"}
1
+ {"version":3,"file":"events.cjs.js","names":[],"sources":["../../src/authSession/events.ts"],"sourcesContent":["/**\n * Legacy event compatibility layer.\n *\n * Pure EventEmitter-style shim — no side effects, no uvdsl dependencies.\n * Wired into the auth session by authSession.ts.\n */\n\nexport type LegacyEventName = 'identityReplaced' | 'login' | 'logout' | 'sessionChange' | 'sessionRestore'\ntype LegacyEventHandler = (...args: unknown[]) => void\n\n/**\n * Minimal EventEmitter-style shim so that existing consumers using\n * `authSession.events.on('login' | 'logout' | 'sessionRestore', handler)`\n * continue working without modification.\n *\n * Events are emitted by SolidAuthnLogic.checkUser() (login/sessionRestore)\n * and by the identity state in identityState.ts ('logout', 'sessionChange',\n * 'identityReplaced' — the event the reload helper subscribes to).\n */\nexport class SessionEvents {\n private readonly listeners: Map<string, Set<LegacyEventHandler>> = new Map()\n\n on (event: LegacyEventName, handler: LegacyEventHandler): void {\n if (!this.listeners.has(event)) this.listeners.set(event, new Set())\n this.listeners.get(event)!.add(handler)\n }\n\n off (event: LegacyEventName, handler: LegacyEventHandler): void {\n this.listeners.get(event)?.delete(handler)\n }\n\n emit (event: LegacyEventName, ...args: unknown[]): void {\n this.listeners.get(event)?.forEach(h => h(...args))\n }\n}\n"],"mappings":"AAmBA,IAAa,EAAb,KAA2B,8BAC0C,IAAI,IAEvE,GAAI,EAAwB,EAAmC,CACxD,KAAK,UAAU,IAAI,CAAK,GAAG,KAAK,UAAU,IAAI,EAAO,IAAI,GAAK,EACnE,KAAK,UAAU,IAAI,CAAK,CAAC,CAAE,IAAI,CAAO,CACxC,CAEA,IAAK,EAAwB,EAAmC,CAC9D,KAAK,UAAU,IAAI,CAAK,CAAC,EAAE,OAAO,CAAO,CAC3C,CAEA,KAAM,EAAwB,GAAG,EAAuB,CACtD,KAAK,UAAU,IAAI,CAAK,CAAC,EAAE,QAAQ,GAAK,EAAE,GAAG,CAAI,CAAC,CACpD,CACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"events.esm.js","names":[],"sources":["../../src/authSession/events.ts"],"sourcesContent":["/**\n * Legacy event compatibility layer.\n *\n * Pure EventEmitter-style shim — no side effects, no uvdsl dependencies.\n * Wired into the auth session by authSession.ts.\n */\n\ntype LegacyEventName = 'login' | 'logout' | 'sessionRestore'\ntype LegacyEventHandler = (...args: unknown[]) => void\n\n/**\n * Minimal EventEmitter-style shim so that existing consumers using\n * `authSession.events.on('login' | 'logout' | 'sessionRestore', handler)`\n * continue working without modification.\n *\n * Events are emitted by SolidAuthnLogic.checkUser() (login/sessionRestore)\n * and by the sessionStateChange listener in authSession.ts (logout).\n */\nexport class SessionEvents {\n private readonly listeners: Map<string, Set<LegacyEventHandler>> = new Map()\n\n on (event: LegacyEventName, handler: LegacyEventHandler): void {\n if (!this.listeners.has(event)) this.listeners.set(event, new Set())\n this.listeners.get(event)!.add(handler)\n }\n\n off (event: LegacyEventName, handler: LegacyEventHandler): void {\n this.listeners.get(event)?.delete(handler)\n }\n\n emit (event: LegacyEventName, ...args: unknown[]): void {\n this.listeners.get(event)?.forEach(h => h(...args))\n }\n}\n\n"],"mappings":";AAkBA,IAAa,IAAb,MAA2B;;mCAC0C,IAAI,IAAI;;CAE3E,GAAI,GAAwB,GAAmC;EAE7D,AADK,KAAK,UAAU,IAAI,CAAK,KAAG,KAAK,UAAU,IAAI,mBAAO,IAAI,IAAI,CAAC,GACnE,KAAK,UAAU,IAAI,CAAK,CAAC,CAAE,IAAI,CAAO;CACxC;CAEA,IAAK,GAAwB,GAAmC;EAC9D,KAAK,UAAU,IAAI,CAAK,CAAC,EAAE,OAAO,CAAO;CAC3C;CAEA,KAAM,GAAwB,GAAG,GAAuB;EACtD,KAAK,UAAU,IAAI,CAAK,CAAC,EAAE,SAAQ,MAAK,EAAE,GAAG,CAAI,CAAC;CACpD;AACF"}
1
+ {"version":3,"file":"events.esm.js","names":[],"sources":["../../src/authSession/events.ts"],"sourcesContent":["/**\n * Legacy event compatibility layer.\n *\n * Pure EventEmitter-style shim — no side effects, no uvdsl dependencies.\n * Wired into the auth session by authSession.ts.\n */\n\nexport type LegacyEventName = 'identityReplaced' | 'login' | 'logout' | 'sessionChange' | 'sessionRestore'\ntype LegacyEventHandler = (...args: unknown[]) => void\n\n/**\n * Minimal EventEmitter-style shim so that existing consumers using\n * `authSession.events.on('login' | 'logout' | 'sessionRestore', handler)`\n * continue working without modification.\n *\n * Events are emitted by SolidAuthnLogic.checkUser() (login/sessionRestore)\n * and by the identity state in identityState.ts ('logout', 'sessionChange',\n * 'identityReplaced' — the event the reload helper subscribes to).\n */\nexport class SessionEvents {\n private readonly listeners: Map<string, Set<LegacyEventHandler>> = new Map()\n\n on (event: LegacyEventName, handler: LegacyEventHandler): void {\n if (!this.listeners.has(event)) this.listeners.set(event, new Set())\n this.listeners.get(event)!.add(handler)\n }\n\n off (event: LegacyEventName, handler: LegacyEventHandler): void {\n this.listeners.get(event)?.delete(handler)\n }\n\n emit (event: LegacyEventName, ...args: unknown[]): void {\n this.listeners.get(event)?.forEach(h => h(...args))\n }\n}\n"],"mappings":";AAmBA,IAAa,IAAb,MAA2B;;mCAC0C,IAAI,IAAI;;CAE3E,GAAI,GAAwB,GAAmC;EAE7D,AADK,KAAK,UAAU,IAAI,CAAK,KAAG,KAAK,UAAU,IAAI,mBAAO,IAAI,IAAI,CAAC,GACnE,KAAK,UAAU,IAAI,CAAK,CAAC,CAAE,IAAI,CAAO;CACxC;CAEA,IAAK,GAAwB,GAAmC;EAC9D,KAAK,UAAU,IAAI,CAAK,CAAC,EAAE,OAAO,CAAO;CAC3C;CAEA,KAAM,GAAwB,GAAG,GAAuB;EACtD,KAAK,UAAU,IAAI,CAAK,CAAC,EAAE,SAAQ,MAAK,EAAE,GAAG,CAAI,CAAC;CACpD;AACF"}
@@ -0,0 +1,2 @@
1
+ const e=require("../util/debug.cjs.js"),t=require("./identityState.cjs.js");function n(t){try{let e=t.updater?.flagAuthorizationMetadata;if(typeof e!=`function`)throw Error(`flagAuthorizationMetadata is unavailable`);return e.call(t.updater),!0}catch(t){return e.warn(`Could not flag authorization metadata: ${String(t)}`),!1}}function r(e,r){let i=t.subscribeIdentity(r,{onTransition:()=>{let t=o(e);t.generation+=1,t.invalidationFailed=!n(e)}});return()=>i.unsubscribe()}var i=new WeakMap,a={generation:0,invalidationFailed:!1};function o(e){if(typeof e!=`object`||!e)return a;let t=i.get(e);return t||(t={generation:0,invalidationFailed:!1},i.set(e,t)),t}var s=3;async function c(t,r){let i=o(t),a=t.fetcher?.load;if(typeof a==`function`)for(let o=0;o<s;o++){let o=i.generation;if(!n(t))return;i.invalidationFailed=!1;try{await a.call(t.fetcher,r)}catch(t){e.warn(`Could not reload ${String(r)}: ${String(t)}`);return}if(o===i.generation)return t.updater?.editable?.(r)}}async function l(e,t){return!o(e).invalidationFailed&&e.updater?.editable?.(t)!==void 0?!0:await c(e,t)!==void 0}async function u(e,t){let n=o(e),r=n.generation,i=e.fetcher?.load;if(typeof i!=`function`)throw Error(`fetcher.load is unavailable`);return await i.call(e.fetcher,t),r===n.generation?l(e,t):await c(e,t)!==void 0}exports.ensureDocumentAuthorization=l,exports.flagAuthorizationOnSessionTransitions=r,exports.loadAuthorizedDocument=u;
2
+ //# sourceMappingURL=flagAuthorizationOnTransitions.cjs.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"flagAuthorizationOnTransitions.cjs.js","names":[],"sources":["../../src/authSession/flagAuthorizationOnTransitions.ts"],"sourcesContent":["/**\n * Session transitions invalidate the store's cached HTTP authorization\n * metadata.\n *\n * `UpdateManager.editable()` is a synchronous read of the responses recorded\n * under `fetcher.appNode`. Those responses are not keyed by identity, so a\n * document fetched anonymously (before a restore completed) or under a\n * previous WebID keeps answering for the old identity: a writable document can\n * look read-only after login, and a read-only one can look writable after\n * logout.\n *\n * `UpdateManager.flagAuthorizationMetadata()` marks every recorded response\n * out-of-date, so `editable()` answers \"unknown\" instead of the previous\n * identity's access. It is wired HERE, once, subscribed to the session's\n * identity state — so it covers every transition whichever path noticed it (a\n * session event, a token update, a refocus resync, a cookie probe), rather\n * than whichever events a call site remembered to listen for.\n *\n * The repair is then a plain `load()`: rdflib refetches a document whose\n * recorded answers are ALL flagged (linkeddata/rdflib.js#871, in 2.4.1), which\n * is exactly the state a transition leaves behind — and `checkEditable()`\n * heals the same way. Nothing forces a fetch by hand any more.\n *\n * REQUIRES rdflib >= 2.4.1: on 2.4.0 `load()` answered such a document from\n * the cache, so the decision points below could not re-establish an answer.\n */\n\nimport * as debug from '../util/debug'\nimport { subscribeIdentity, type SessionLike } from './identityState'\n\nexport type TransitionStore = {\n updater?: { flagAuthorizationMetadata?: () => void }\n}\n\nexport type AuthorizationStore = {\n fetcher?: { load?: (doc: unknown) => unknown }\n updater?: {\n editable?: (uri: unknown) => string | boolean | undefined\n flagAuthorizationMetadata?: () => void\n }\n}\n\n/**\n * Marks every recorded response out-of-date.\n *\n * @returns whether the store could be invalidated. A store without the API, or\n * one that throws, cannot be trusted afterwards — its answers stay definitive\n * for the previous identity until a later transition flags successfully.\n */\nfunction invalidate (store: AuthorizationStore): boolean {\n try {\n const flag = store.updater?.flagAuthorizationMetadata\n if (typeof flag !== 'function') {\n throw new Error('flagAuthorizationMetadata is unavailable')\n }\n flag.call(store.updater)\n return true\n } catch (error) {\n debug.warn(`Could not flag authorization metadata: ${String(error)}`)\n return false\n }\n}\n\n/**\n * Flags the store's authorization metadata on every identity transition.\n *\n * @returns the unsubscribe function — the caller owns the lifetime (it ends\n * with the session's subscription).\n */\nexport function flagAuthorizationOnSessionTransitions (\n store: TransitionStore,\n session: SessionLike\n): () => void {\n const onTransition = (): void => {\n const state = storeState(store)\n // Whose credentials a request would carry changed: every answer recorded\n // under the previous identity is suspect from here on.\n state.generation += 1\n state.invalidationFailed = !invalidate(store)\n }\n const subscription = subscribeIdentity(session, { onTransition })\n return () => subscription.unsubscribe()\n}\n\ntype StoreAuthorizationState = {\n /** Identity transitions observed for this store. */\n generation: number\n /**\n * The store could not invalidate its metadata on the last transition, so a\n * definitive answer is not evidence that it is current.\n */\n invalidationFailed: boolean\n}\n\n// Scoped per store: two `createSolidLogic` instances with different sessions\n// must not overtake each other's repairs, and a failed invalidation in one\n// store says nothing about another.\nconst storeStates = new WeakMap<object, StoreAuthorizationState>()\nconst sharedState: StoreAuthorizationState = { generation: 0, invalidationFailed: false }\n\nfunction storeState (store: unknown): StoreAuthorizationState {\n if (store === null || typeof store !== 'object') return sharedState\n let state = storeStates.get(store)\n if (!state) {\n state = { generation: 0, invalidationFailed: false }\n storeStates.set(store, state)\n }\n return state\n}\n\n/** How many times a repair is repeated when the identity keeps changing. */\nconst REPAIR_ATTEMPTS = 3\n\n/**\n * Re-establishes `doc`'s answer under the current identity: mark every\n * recorded response out-of-date — including one recorded AFTER the transition,\n * which the transition's own flag could not have marked — and load, which\n * refetches a fully flagged document.\n *\n * Each attempt is stamped with the store's transition generation and repeated\n * when the identity changed under it: the response then belongs to the\n * previous identity and must not answer for the current one, or a caller could\n * write under the new identity on the old identity's authorization. If the\n * identity keeps changing, the answer stays \"unknown\" — never stale.\n *\n * Returns `undefined` whenever the answer cannot be established: no load\n * capability, an invalidation that failed (the recorded answers are still\n * definitive for the previous identity), a failed load, or an identity that\n * changed throughout every attempt.\n */\nasync function repairDocument (\n store: AuthorizationStore,\n doc: unknown\n): Promise<string | boolean | undefined> {\n const state = storeState(store)\n const load = store.fetcher?.load\n if (typeof load !== 'function') return undefined\n for (let attempt = 0; attempt < REPAIR_ATTEMPTS; attempt++) {\n const generation = state.generation\n if (!invalidate(store)) return undefined\n state.invalidationFailed = false\n try {\n await load.call(store.fetcher, doc)\n } catch (error) {\n debug.warn(`Could not reload ${String(doc)}: ${String(error)}`)\n return undefined\n }\n // The read below is synchronous, so a generation that still matches means\n // no transition slipped in between the response and the answer.\n if (generation === state.generation) {\n return store.updater?.editable?.(doc)\n }\n }\n return undefined\n}\n\n/**\n * Make the store able to answer for `doc` under the current identity before\n * its cached triples are read or its editability gates a write. A flagged\n * store answers `undefined` and is repaired here; a store whose invalidation\n * FAILED still answers definitively for the previous identity, so it is\n * repaired too (and keeps being repaired until a later transition flags\n * successfully, since the failure says nothing about which other documents are\n * stale).\n *\n * Returns whether the answer was established. `false` means a repair was\n * needed and could not complete: the caller must not consume cached triples\n * from that document and must not offer a write on it.\n */\nexport async function ensureDocumentAuthorization (\n store: AuthorizationStore,\n doc: unknown\n): Promise<boolean> {\n const state = storeState(store)\n if (!state.invalidationFailed && store.updater?.editable?.(doc) !== undefined) {\n return true\n }\n return (await repairDocument(store, doc)) !== undefined\n}\n\n/**\n * Load a document and make sure its cached triples can be read under the\n * current identity. The load itself is generation-checked: a response begun\n * under the previous identity can be recorded AFTER\n * `flagAuthorizationMetadata()` ran (the flag only marks response nodes that\n * already existed), which leaves a definitive-looking answer from the old\n * identity behind — so an overtaken load is repaired instead of being trusted.\n *\n * Returns whether the document can be consumed (see\n * ensureDocumentAuthorization). Load errors propagate, as a plain `load()`\n * would.\n */\nexport async function loadAuthorizedDocument (\n store: AuthorizationStore,\n doc: unknown\n): Promise<boolean> {\n const state = storeState(store)\n const generation = state.generation\n const load = store.fetcher?.load\n if (typeof load !== 'function') {\n // A plain load() would fail on a store with no fetcher: this call loads\n // `doc`, so it must not answer \"consumed\" after skipping the load.\n throw new Error('fetcher.load is unavailable')\n }\n await load.call(store.fetcher, doc)\n if (generation !== state.generation) {\n return (await repairDocument(store, doc)) !== undefined\n }\n return ensureDocumentAuthorization(store, doc)\n}\n"],"mappings":"4EAiDA,SAAS,EAAY,EAAoC,CACvD,GAAI,CACF,IAAM,EAAO,EAAM,SAAS,0BAC5B,GAAI,OAAO,GAAS,WAClB,MAAU,MAAM,0CAA0C,EAG5D,OADA,EAAK,KAAK,EAAM,OAAO,EAChB,EACT,OAAS,EAAO,CAEd,OADA,EAAA,KAAW,0CAA0C,OAAO,CAAK,GAAG,EAC7D,EACT,CACF,CAQA,SAAgB,EACd,EACA,EACY,CAQZ,IAAM,EAAe,EAAA,kBAAkB,EAAS,CAAE,iBAPjB,CAC/B,IAAM,EAAQ,EAAW,CAAK,EAG9B,EAAM,YAAc,EACpB,EAAM,mBAAqB,CAAC,EAAW,CAAK,CAC9C,CAC+D,CAAC,EAChE,UAAa,EAAa,YAAY,CACxC,CAeA,IAAM,EAAc,IAAI,QAClB,EAAuC,CAAE,WAAY,EAAG,mBAAoB,EAAM,EAExF,SAAS,EAAY,EAAyC,CAC5D,GAAsB,OAAO,GAAU,WAAnC,EAA6C,OAAO,EACxD,IAAI,EAAQ,EAAY,IAAI,CAAK,EAKjC,OAJK,IACH,EAAQ,CAAE,WAAY,EAAG,mBAAoB,EAAM,EACnD,EAAY,IAAI,EAAO,CAAK,GAEvB,CACT,CAGA,IAAM,EAAkB,EAmBxB,eAAe,EACb,EACA,EACuC,CACvC,IAAM,EAAQ,EAAW,CAAK,EACxB,EAAO,EAAM,SAAS,KACxB,UAAO,GAAS,WACpB,IAAK,IAAI,EAAU,EAAG,EAAU,EAAiB,IAAW,CAC1D,IAAM,EAAa,EAAM,WACzB,GAAI,CAAC,EAAW,CAAK,EAAG,OACxB,EAAM,mBAAqB,GAC3B,GAAI,CACF,MAAM,EAAK,KAAK,EAAM,QAAS,CAAG,CACpC,OAAS,EAAO,CACd,EAAA,KAAW,oBAAoB,OAAO,CAAG,EAAE,IAAI,OAAO,CAAK,GAAG,EAC9D,MACF,CAGA,GAAI,IAAe,EAAM,WACvB,OAAO,EAAM,SAAS,WAAW,CAAG,CAExC,CAEF,CAeA,eAAsB,EACpB,EACA,EACkB,CAKlB,MAHI,CADU,EAAW,CACpB,CAAA,CAAM,oBAAsB,EAAM,SAAS,WAAW,CAAG,IAAM,IAAA,GAC3D,GAED,MAAM,EAAe,EAAO,CAAG,IAAO,IAAA,EAChD,CAcA,eAAsB,EACpB,EACA,EACkB,CAClB,IAAM,EAAQ,EAAW,CAAK,EACxB,EAAa,EAAM,WACnB,EAAO,EAAM,SAAS,KAC5B,GAAI,OAAO,GAAS,WAGlB,MAAU,MAAM,6BAA6B,EAM/C,OAJA,MAAM,EAAK,KAAK,EAAM,QAAS,CAAG,EAC9B,IAAe,EAAM,WAGlB,EAA4B,EAAO,CAAG,EAFnC,MAAM,EAAe,EAAO,CAAG,IAAO,IAAA,EAGlD"}
@@ -0,0 +1,59 @@
1
+ import { warn as e } from "../util/debug.esm.js";
2
+ import { subscribeIdentity as t } from "./identityState.esm.js";
3
+ //#region src/authSession/flagAuthorizationOnTransitions.ts
4
+ function n(t) {
5
+ try {
6
+ let e = t.updater?.flagAuthorizationMetadata;
7
+ if (typeof e != "function") throw Error("flagAuthorizationMetadata is unavailable");
8
+ return e.call(t.updater), !0;
9
+ } catch (t) {
10
+ return e(`Could not flag authorization metadata: ${String(t)}`), !1;
11
+ }
12
+ }
13
+ function r(e, r) {
14
+ let i = t(r, { onTransition: () => {
15
+ let t = o(e);
16
+ t.generation += 1, t.invalidationFailed = !n(e);
17
+ } });
18
+ return () => i.unsubscribe();
19
+ }
20
+ var i = /* @__PURE__ */ new WeakMap(), a = {
21
+ generation: 0,
22
+ invalidationFailed: !1
23
+ };
24
+ function o(e) {
25
+ if (typeof e != "object" || !e) return a;
26
+ let t = i.get(e);
27
+ return t || (t = {
28
+ generation: 0,
29
+ invalidationFailed: !1
30
+ }, i.set(e, t)), t;
31
+ }
32
+ var s = 3;
33
+ async function c(t, r) {
34
+ let i = o(t), a = t.fetcher?.load;
35
+ if (typeof a == "function") for (let o = 0; o < s; o++) {
36
+ let o = i.generation;
37
+ if (!n(t)) return;
38
+ i.invalidationFailed = !1;
39
+ try {
40
+ await a.call(t.fetcher, r);
41
+ } catch (t) {
42
+ e(`Could not reload ${String(r)}: ${String(t)}`);
43
+ return;
44
+ }
45
+ if (o === i.generation) return t.updater?.editable?.(r);
46
+ }
47
+ }
48
+ async function l(e, t) {
49
+ return !o(e).invalidationFailed && e.updater?.editable?.(t) !== void 0 ? !0 : await c(e, t) !== void 0;
50
+ }
51
+ async function u(e, t) {
52
+ let n = o(e), r = n.generation, i = e.fetcher?.load;
53
+ if (typeof i != "function") throw Error("fetcher.load is unavailable");
54
+ return await i.call(e.fetcher, t), r === n.generation ? l(e, t) : await c(e, t) !== void 0;
55
+ }
56
+ //#endregion
57
+ export { l as ensureDocumentAuthorization, r as flagAuthorizationOnSessionTransitions, u as loadAuthorizedDocument };
58
+
59
+ //# sourceMappingURL=flagAuthorizationOnTransitions.esm.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"flagAuthorizationOnTransitions.esm.js","names":[],"sources":["../../src/authSession/flagAuthorizationOnTransitions.ts"],"sourcesContent":["/**\n * Session transitions invalidate the store's cached HTTP authorization\n * metadata.\n *\n * `UpdateManager.editable()` is a synchronous read of the responses recorded\n * under `fetcher.appNode`. Those responses are not keyed by identity, so a\n * document fetched anonymously (before a restore completed) or under a\n * previous WebID keeps answering for the old identity: a writable document can\n * look read-only after login, and a read-only one can look writable after\n * logout.\n *\n * `UpdateManager.flagAuthorizationMetadata()` marks every recorded response\n * out-of-date, so `editable()` answers \"unknown\" instead of the previous\n * identity's access. It is wired HERE, once, subscribed to the session's\n * identity state — so it covers every transition whichever path noticed it (a\n * session event, a token update, a refocus resync, a cookie probe), rather\n * than whichever events a call site remembered to listen for.\n *\n * The repair is then a plain `load()`: rdflib refetches a document whose\n * recorded answers are ALL flagged (linkeddata/rdflib.js#871, in 2.4.1), which\n * is exactly the state a transition leaves behind — and `checkEditable()`\n * heals the same way. Nothing forces a fetch by hand any more.\n *\n * REQUIRES rdflib >= 2.4.1: on 2.4.0 `load()` answered such a document from\n * the cache, so the decision points below could not re-establish an answer.\n */\n\nimport * as debug from '../util/debug'\nimport { subscribeIdentity, type SessionLike } from './identityState'\n\nexport type TransitionStore = {\n updater?: { flagAuthorizationMetadata?: () => void }\n}\n\nexport type AuthorizationStore = {\n fetcher?: { load?: (doc: unknown) => unknown }\n updater?: {\n editable?: (uri: unknown) => string | boolean | undefined\n flagAuthorizationMetadata?: () => void\n }\n}\n\n/**\n * Marks every recorded response out-of-date.\n *\n * @returns whether the store could be invalidated. A store without the API, or\n * one that throws, cannot be trusted afterwards — its answers stay definitive\n * for the previous identity until a later transition flags successfully.\n */\nfunction invalidate (store: AuthorizationStore): boolean {\n try {\n const flag = store.updater?.flagAuthorizationMetadata\n if (typeof flag !== 'function') {\n throw new Error('flagAuthorizationMetadata is unavailable')\n }\n flag.call(store.updater)\n return true\n } catch (error) {\n debug.warn(`Could not flag authorization metadata: ${String(error)}`)\n return false\n }\n}\n\n/**\n * Flags the store's authorization metadata on every identity transition.\n *\n * @returns the unsubscribe function — the caller owns the lifetime (it ends\n * with the session's subscription).\n */\nexport function flagAuthorizationOnSessionTransitions (\n store: TransitionStore,\n session: SessionLike\n): () => void {\n const onTransition = (): void => {\n const state = storeState(store)\n // Whose credentials a request would carry changed: every answer recorded\n // under the previous identity is suspect from here on.\n state.generation += 1\n state.invalidationFailed = !invalidate(store)\n }\n const subscription = subscribeIdentity(session, { onTransition })\n return () => subscription.unsubscribe()\n}\n\ntype StoreAuthorizationState = {\n /** Identity transitions observed for this store. */\n generation: number\n /**\n * The store could not invalidate its metadata on the last transition, so a\n * definitive answer is not evidence that it is current.\n */\n invalidationFailed: boolean\n}\n\n// Scoped per store: two `createSolidLogic` instances with different sessions\n// must not overtake each other's repairs, and a failed invalidation in one\n// store says nothing about another.\nconst storeStates = new WeakMap<object, StoreAuthorizationState>()\nconst sharedState: StoreAuthorizationState = { generation: 0, invalidationFailed: false }\n\nfunction storeState (store: unknown): StoreAuthorizationState {\n if (store === null || typeof store !== 'object') return sharedState\n let state = storeStates.get(store)\n if (!state) {\n state = { generation: 0, invalidationFailed: false }\n storeStates.set(store, state)\n }\n return state\n}\n\n/** How many times a repair is repeated when the identity keeps changing. */\nconst REPAIR_ATTEMPTS = 3\n\n/**\n * Re-establishes `doc`'s answer under the current identity: mark every\n * recorded response out-of-date — including one recorded AFTER the transition,\n * which the transition's own flag could not have marked — and load, which\n * refetches a fully flagged document.\n *\n * Each attempt is stamped with the store's transition generation and repeated\n * when the identity changed under it: the response then belongs to the\n * previous identity and must not answer for the current one, or a caller could\n * write under the new identity on the old identity's authorization. If the\n * identity keeps changing, the answer stays \"unknown\" — never stale.\n *\n * Returns `undefined` whenever the answer cannot be established: no load\n * capability, an invalidation that failed (the recorded answers are still\n * definitive for the previous identity), a failed load, or an identity that\n * changed throughout every attempt.\n */\nasync function repairDocument (\n store: AuthorizationStore,\n doc: unknown\n): Promise<string | boolean | undefined> {\n const state = storeState(store)\n const load = store.fetcher?.load\n if (typeof load !== 'function') return undefined\n for (let attempt = 0; attempt < REPAIR_ATTEMPTS; attempt++) {\n const generation = state.generation\n if (!invalidate(store)) return undefined\n state.invalidationFailed = false\n try {\n await load.call(store.fetcher, doc)\n } catch (error) {\n debug.warn(`Could not reload ${String(doc)}: ${String(error)}`)\n return undefined\n }\n // The read below is synchronous, so a generation that still matches means\n // no transition slipped in between the response and the answer.\n if (generation === state.generation) {\n return store.updater?.editable?.(doc)\n }\n }\n return undefined\n}\n\n/**\n * Make the store able to answer for `doc` under the current identity before\n * its cached triples are read or its editability gates a write. A flagged\n * store answers `undefined` and is repaired here; a store whose invalidation\n * FAILED still answers definitively for the previous identity, so it is\n * repaired too (and keeps being repaired until a later transition flags\n * successfully, since the failure says nothing about which other documents are\n * stale).\n *\n * Returns whether the answer was established. `false` means a repair was\n * needed and could not complete: the caller must not consume cached triples\n * from that document and must not offer a write on it.\n */\nexport async function ensureDocumentAuthorization (\n store: AuthorizationStore,\n doc: unknown\n): Promise<boolean> {\n const state = storeState(store)\n if (!state.invalidationFailed && store.updater?.editable?.(doc) !== undefined) {\n return true\n }\n return (await repairDocument(store, doc)) !== undefined\n}\n\n/**\n * Load a document and make sure its cached triples can be read under the\n * current identity. The load itself is generation-checked: a response begun\n * under the previous identity can be recorded AFTER\n * `flagAuthorizationMetadata()` ran (the flag only marks response nodes that\n * already existed), which leaves a definitive-looking answer from the old\n * identity behind — so an overtaken load is repaired instead of being trusted.\n *\n * Returns whether the document can be consumed (see\n * ensureDocumentAuthorization). Load errors propagate, as a plain `load()`\n * would.\n */\nexport async function loadAuthorizedDocument (\n store: AuthorizationStore,\n doc: unknown\n): Promise<boolean> {\n const state = storeState(store)\n const generation = state.generation\n const load = store.fetcher?.load\n if (typeof load !== 'function') {\n // A plain load() would fail on a store with no fetcher: this call loads\n // `doc`, so it must not answer \"consumed\" after skipping the load.\n throw new Error('fetcher.load is unavailable')\n }\n await load.call(store.fetcher, doc)\n if (generation !== state.generation) {\n return (await repairDocument(store, doc)) !== undefined\n }\n return ensureDocumentAuthorization(store, doc)\n}\n"],"mappings":";;;AAiDA,SAAS,EAAY,GAAoC;CACvD,IAAI;EACF,IAAM,IAA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CAAM,sBAAsB,EAAM,SAAS,WAAW,CAAG,MAAM,KAAA,IAC3D,KAED,MAAM,EAAe,GAAO,CAAG,MAAO,KAAA;AAChD;AAcA,eAAsB,EACpB,GACA,GACkB;CAClB,IAAM,IAAQ,EAAW,CAAK,GACxB,IAAa,EAAM,YACnB,IAAO,EAAM,SAAS;CAC5B,IAAI,OAAO,KAAS,YAGlB,MAAU,MAAM,6BAA6B;CAM/C,OAJA,MAAM,EAAK,KAAK,EAAM,SAAS,CAAG,GAC9B,MAAe,EAAM,aAGlB,EAA4B,GAAO,CAAG,IAFnC,MAAM,EAAe,GAAO,CAAG,MAAO,KAAA;AAGlD"}
@@ -0,0 +1,2 @@
1
+ function e(e,t){return e.isActive===t.isActive?t.webId===e.webId?null:`sessionChange`:t.isActive?`sessionChange`:`logout`}function t(e,t){return e.webId===void 0||!e.isActive?!1:t.webId!==e.webId||!t.isActive}var n=e=>e.isActive===!0||e.isActive===void 0&&!!e.webId,r=2e3,i=new WeakMap,a=new WeakMap,o=e=>{if(typeof e!=`object`||!e)return;let t=i.get(e);return t||(t={session:e,raw:{isActive:!1},cleared:!1,cookieWebId:null,version:0,attemptId:0,subscribers:new Set,listenerAttached:!1,watchingTokenUpdates:!1},t.raw=u(t),i.set(e,t)),t};function s(e){return typeof e!=`object`||!e?!1:i.get(e)?.cleared===!0}function c(e){return s(e)?!0:e?.isActive===!1||e?.info?.isLoggedIn===!1}function l(e){return!c(e)&&n(e)}var u=e=>e.cleared?{isActive:!1}:{isActive:n(e.session),webId:e.session.webId};function d(e){let t=o(e);return t?l(e)?e.webId===void 0?{source:`none`}:{webId:e.webId,source:`session`}:t.cookieWebId===null?{source:`none`}:{webId:t.cookieWebId,source:`cookie`}:{source:`none`}}function f(e){return s(e)?{webId:void 0,isLoggedIn:!1}:{webId:e.webId,isLoggedIn:n(e)}}function p(e){let t=e?.restore;if(typeof t!=`function`||typeof e!=`object`||!e)return;let n=e,r=a.get(n);if(r)return r;let i=Promise.resolve().then(()=>t.call(e)).finally(()=>{a.delete(n)});return a.set(n,i),i}var m=(e,t)=>{e.subscribers.forEach(e=>e.onTransition?.(t)),e.subscribers.forEach(e=>{t.forEach(t=>e.onEvent?.(t))})};function h(r){r.cleared&&n(r.session)&&(r.cleared=!1),l(r.session)&&(r.cookieWebId=null);let i=u(r),a=e(r.raw,i),o=t(r.raw,i),s=a!==null||o;if(r.raw=i,!s)return;r.version+=1;let c=[];a&&c.push(a),o&&c.push(`identityReplaced`),m(r,c)}function g(e){if(e.cleared)return;let t=e.raw.isActive,n=e.raw.webId!==void 0;if(!t||!n){e.raw=u(e),t&&(e.version+=1,m(e,[`logout`]));return}e.cleared=!0,e.raw=u(e),e.version+=1,m(e,[`logout`,`identityReplaced`])}function _(e,t){if(e.attempt)return e.attempt;let r={id:++e.attemptId,version:e.version,raw:{isActive:n(e.session),webId:e.session.webId},promise:Promise.resolve().then(t).finally(()=>{e.attempt===r&&(e.attempt=void 0)})};return e.attempt=r,r}async function v(e){let t=y(e);if(typeof t!=`function`){h(e);return}let i=t,a=_(e,()=>i()),o=()=>a.id!==e.attemptId||e.version!==a.version,s=()=>n(e.session)===a.raw.isActive&&e.session.webId===a.raw.webId,c,l=!1,u=a.promise.then(e=>{c=e,l=!0},()=>{l=!0}),d=()=>{if(!o()){if(c===`cleared`){s()&&g(e);return}h(e)}},f,p=new Promise(e=>{f=setTimeout(e,r)});try{await Promise.race([u,p])}finally{f!==void 0&&clearTimeout(f)}if(l){d();return}h(e),u.then(d)}function y(e){let t;for(let n of e.subscribers)n.resync&&(t=n.resync);return t}function b(e){let t=e.session,n=t.setTokenDetails;typeof n!=`function`||e.watchingTokenUpdates||(e.watchingTokenUpdates=!0,t.setTokenDetails=(...r)=>{let i=u(e),a=()=>{let t=u(e);return t.webId!==i.webId||t.isActive!==i.isActive},o;try{o=n.apply(t,r)}catch(t){throw a()&&h(e),t}return o&&typeof o.then==`function`?o.then(t=>(a()&&h(e),t),t=>{throw a()&&h(e),t}):(a()&&h(e),o)})}function x(e,t={}){let n=o(e);if(!n)return{reportCookieIdentity:()=>void 0,unsubscribe:()=>void 0};let r={...t};n.subscribers.add(r),n.listenerAttached||(n.listenerAttached=!0,typeof e.addEventListener==`function`&&e.addEventListener(`sessionStateChange`,()=>h(n)),b(n));let i=typeof document>`u`?void 0:document;if(n.subscribers.size===1&&i&&typeof i.addEventListener==`function`){let e=()=>{i.visibilityState===`visible`&&(v(n),n.subscribers.forEach(e=>{e.onRefocus?.()}))};i.addEventListener(`visibilitychange`,e),n.detachDocument=()=>i.removeEventListener?.(`visibilitychange`,e)}let a=!1;return{reportCookieIdentity:e=>{a||S(n,e)},unsubscribe:()=>{a||(a=!0,n.subscribers.delete(r),n.subscribers.size===0&&(n.detachDocument?.(),n.detachDocument=void 0))}}}function S(e,t){if(e.cookieWebId===t||l(e.session))return;let n=e.cookieWebId!==null;e.cookieWebId=t;let r=[`sessionChange`];n&&r.push(`identityReplaced`),m(e,r)}function C(e,t=()=>{typeof window<`u`&&window.location.reload()}){!e||typeof e.on!=`function`||e.on(`identityReplaced`,t)}exports.classifyTransition=e,exports.effectiveIdentity=d,exports.identityReplaced=t,exports.legacySessionInfo=f,exports.reloadOnIdentityReplaced=C,exports.restoreSession=p,exports.sessionExplicitlyInactive=c,exports.sessionIsActive=n,exports.sessionOwnsIdentity=l,exports.sessionWasCleared=s,exports.subscribeIdentity=x;
2
+ //# sourceMappingURL=identityState.cjs.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"identityState.cjs.js","names":[],"sources":["../../src/authSession/identityState.ts"],"sourcesContent":["/**\n * One identity state per session.\n *\n * The session's identity is assembled from two sources — the OIDC session\n * itself and (on NSS localhost setups) a cookie-backed fallback — and is\n * observed by consumers that must invalidate what the previous identity\n * fetched. Doing that with independent flags and predicates per call site let\n * each new async path (a slow restore, a probe answering late, a refocus)\n * reintroduce the same class of bug, so the identity lives here, once:\n *\n * TEMPORARY, pending the uvdsl change: two mechanisms here exist only because\n * `@uvdsl/solid-oidc-client-browser` announces `sessionStateChange` when\n * `isActive` changes and nothing else — it does not report a WebID change that\n * keeps the session active, and it does not push a login/logout made in\n * another tab. Until it does (issue drafted), the cookie fallback is the only\n * way to see an NSS cookie identity change at all (see\n * `reportCookieIdentity`) and `watchTokenUpdates()` is the only way to see an\n * A -> B switch. Both are isolated here so they become a small deletion, not\n * a hunt, when uvdsl reports identity changes itself.\n *\n * - `sessionIsActive()` is the single activity rule (`isActive` is\n * authoritative, an explicit `false` wins over a cached WebID);\n * - every observation (session event, token update, refocus resync, cookie\n * probe result) is applied to ONE record, so a change is detected and\n * reported once, whichever path noticed it;\n * - the record carries a `version` (bumped when a transition is applied) and\n * the newest refresh attempt, so an answer that belongs to an identity the\n * session has since left — a restore started under Alice answering after\n * Bob logged in — is dropped instead of being applied;\n * - the transition is derived from the previous/next snapshots\n * (`classifyTransition`, `identityReplaced`), not from flags: there is\n * nothing to keep in sync, and an unchanged identity costs no event.\n *\n * Reported events (same vocabulary as before):\n * 'logout' — the session went from active to inactive;\n * 'sessionChange' — any other change of active state or WebID;\n * 'identityReplaced' — an identity that WAS actively established is gone or\n * replaced, so data fetched under it must be dropped.\n * Start-up (none -> A) and a token refresh for the same identity are not\n * replacements.\n *\n * A session whose backing store no longer holds it (a cross-tab logout) is\n * marked `cleared` here: the local session object keeps reporting the previous\n * identity, so the mark is what makes the derived reads report logged out\n * until the session reports an identity again.\n *\n * DO NOT keep identity state anywhere else: `SolidAuthnLogic` reads it,\n * `authSession` publishes it (`info`, events) and `solidLogicSingleton`\n * decides from it whose credentials a request would carry.\n */\n\nexport type SessionLike = {\n isActive?: boolean\n webId?: string\n info?: { isLoggedIn?: boolean, webId?: string }\n addEventListener?: (type: string, listener: () => void) => void\n setTokenDetails?: (...args: unknown[]) => unknown\n restore?: () => Promise<unknown>\n}\n\nexport type IdentityEvent = 'logout' | 'sessionChange' | 'identityReplaced'\n\n/** The session's own view: what the raw session reports, cleared-aware. */\nexport type IdentitySnapshot = { isActive: boolean, webId?: string }\n\nexport type DocumentLike = {\n visibilityState?: string\n addEventListener?: (type: string, listener: () => void) => void\n removeEventListener?: (type: string, listener: () => void) => void\n}\n\n/**\n * Which legacy event a session transition should emit:\n * 'logout' — the session went from active to inactive;\n * 'sessionChange' — any other change of active state or WebID (a login here\n * is also announced as 'login' by SolidAuthnLogic; the\n * duplicate is harmless — consumers only invalidate);\n * null — nothing changed, so a refocused tab with the same\n * identity costs no event and no invalidation.\n */\nexport function classifyTransition (\n prev: IdentitySnapshot,\n next: IdentitySnapshot\n): 'logout' | 'sessionChange' | null {\n if (prev.isActive !== next.isActive) return next.isActive ? 'sessionChange' : 'logout'\n return next.webId !== prev.webId ? 'sessionChange' : null\n}\n\n/**\n * Whether an established identity was replaced or cleared — a session that had\n * a WebID no longer reports the same one (A -> B), or no longer reports being\n * active (A -> logged out, A -> none). Data fetched under the previous\n * identity cannot be re-validated document by document, so this is the signal\n * to discard it.\n *\n * Only the transition OUT of an ACTIVELY established identity counts: once the\n * session has gone inactive (webId possibly retained), the replacement was\n * already reported — clearing the WebID afterwards or logging in as someone\n * else is not a second replacement.\n */\nexport function identityReplaced (prev: IdentitySnapshot, next: IdentitySnapshot): boolean {\n if (prev.webId === undefined) return false\n if (!prev.isActive) return false\n return next.webId !== prev.webId || !next.isActive\n}\n\n/**\n * Whether the session counts as active. `isActive` is authoritative — an\n * explicit `false` wins even when a WebID is still cached (a logout that has\n * not cleared it yet); the WebID only fills in an undefined state.\n */\nexport const sessionIsActive = (session: SessionLike): boolean =>\n session.isActive === true || (session.isActive === undefined && Boolean(session.webId))\n\n/**\n * How long a refocus resync may delay the snapshot comparison.\n */\nconst RESYNC_TIMEOUT_MS = 2000\n\ntype Subscriber = {\n onEvent?: (event: IdentityEvent) => void\n /** The whole transition, once — for consumers that only invalidate. */\n onTransition?: (events: IdentityEvent[]) => void\n onRefocus?: () => void | Promise<void>\n resync?: () => unknown\n}\n\ntype Attempt = {\n id: number\n /** The record version the attempt started from. */\n version: number\n /** The raw identity the attempt started from. */\n raw: { isActive: boolean, webId?: string }\n promise: Promise<unknown>\n}\n\ntype Record = {\n session: SessionLike\n /** The last applied view of the session, cleared-aware. */\n raw: IdentitySnapshot\n /** The backing store no longer holds the session (a cross-tab logout). */\n cleared: boolean\n /** The cookie-probed identity, when the session does not own one. */\n cookieWebId: string | null\n /** Bumped whenever a session transition is applied. */\n version: number\n /** The newest resync attempt, or undefined when none is running. */\n attempt?: Attempt\n attemptId: number\n subscribers: Set<Subscriber>\n /** Whether the session state listener is attached (once per session). */\n listenerAttached: boolean\n /** Detaches the document listener when the last subscriber leaves. */\n detachDocument?: () => void\n /** Wrapped once per session, see watchTokenUpdates(). */\n watchingTokenUpdates: boolean\n}\n\nconst records = new WeakMap<object, Record>()\n\n// One restore at a time per session: `restore()` can mutate the session before\n// it resolves, so two overlapping restores could write an older identity back\n// over a newer one. Every caller (the refocus resync and `checkUser()`) goes\n// through this lock, and one that arrives while a restore is in flight joins\n// it instead of starting another.\nconst restoresInFlight = new WeakMap<object, Promise<unknown>>()\n\nconst recordOf = (session: SessionLike): Record | undefined => {\n if (typeof session !== 'object' || session === null) return undefined\n let record = records.get(session as object)\n if (!record) {\n record = {\n session,\n raw: { isActive: false },\n cleared: false,\n cookieWebId: null,\n version: 0,\n attemptId: 0,\n subscribers: new Set(),\n listenerAttached: false,\n watchingTokenUpdates: false\n }\n record.raw = snapshotOf(record)\n records.set(session as object, record)\n }\n return record\n}\n\n/**\n * Whether a session was reported cleared: its backing store lost the session\n * while this tab still had one, so its identity no longer holds here.\n */\nexport function sessionWasCleared (session: unknown): boolean {\n if (typeof session !== 'object' || session === null) return false\n return records.get(session as object)?.cleared === true\n}\n\n/**\n * Whether the session explicitly reports itself inactive. An explicit `false`\n * — `isActive` on the session or `isLoggedIn` on the legacy `info` shape —\n * wins over a retained WebID: a partial logout that has not cleared the cached\n * WebID must not keep identifying the previous user. Consumers that would\n * otherwise act on the WebID alone (authenticated fetch, currentUser) use this\n * to stand down.\n */\nexport function sessionExplicitlyInactive (session: SessionLike): boolean {\n if (sessionWasCleared(session)) return true\n return session?.isActive === false || session?.info?.isLoggedIn === false\n}\n\n/**\n * Whether the OIDC session currently owns the identity. A session that was\n * reported cleared does not, and neither does one that explicitly reports\n * itself logged out (a legacy shape that still carries a WebID would otherwise\n * pass `sessionIsActive()` alone).\n */\nexport function sessionOwnsIdentity (session: SessionLike): boolean {\n return !sessionExplicitlyInactive(session) && sessionIsActive(session)\n}\n\n/** The WebID the raw session publishes, or undefined when it owns none. */\nexport function sessionIdentityWebId (session: SessionLike): string | undefined {\n return sessionOwnsIdentity(session) ? session.webId : undefined\n}\n\nconst snapshotOf = (record: Record): IdentitySnapshot => {\n // A cleared session answers as logged out until it reports an identity\n // again: the local session object may still carry the previous WebID.\n if (record.cleared) return { isActive: false }\n return { isActive: sessionIsActive(record.session), webId: record.session.webId }\n}\n\n/**\n * The identity a caller should act as: the session's own when it owns one, the\n * cookie-probed one when the session is inactive (or cleared) and a probe\n * established it, and undefined when neither does. This is the last word for\n * `currentUser()`, `info` consumers and the fetch bridge.\n */\nexport function effectiveIdentity (session: SessionLike): { webId?: string, source: 'none' | 'session' | 'cookie' } {\n const record = recordOf(session)\n if (!record) return { source: 'none' }\n if (sessionOwnsIdentity(session)) {\n return session.webId === undefined ? { source: 'none' } : { webId: session.webId, source: 'session' }\n }\n if (record.cookieWebId !== null) return { webId: record.cookieWebId, source: 'cookie' }\n // A session that only reports a logout keeps no identity — the retained\n // WebID must not be used (see sessionExplicitlyInactive).\n return { source: 'none' }\n}\n\n/**\n * The legacy `info` shape is session-derived and stays derived: callers\n * snapshot and restore it, so a retained value must never answer for the\n * session. `isLoggedIn` follows `sessionIsActive` — an explicit `isActive:\n * false` reports logged out even when a WebID is still cached, or the fetch\n * bridge would keep routing anonymous requests through the authenticated\n * fetch.\n */\nexport function legacySessionInfo (session: SessionLike): { webId?: string, isLoggedIn?: boolean } {\n if (sessionWasCleared(session)) return { webId: undefined, isLoggedIn: false }\n return { webId: session.webId, isLoggedIn: sessionIsActive(session) }\n}\n\n/**\n * Runs `session.restore()`, sharing an attempt that is already in flight.\n *\n * @returns the shared promise, or undefined when the session has no restore.\n */\nexport function restoreSession (session: SessionLike | undefined): Promise<unknown> | undefined {\n const restore = session?.restore\n if (typeof restore !== 'function' || typeof session !== 'object' || session === null) {\n return undefined\n }\n const key = session as object\n const inFlight = restoresInFlight.get(key)\n if (inFlight) return inFlight\n const started = Promise.resolve()\n .then(() => restore.call(session))\n .finally(() => { restoresInFlight.delete(key) })\n restoresInFlight.set(key, started)\n return started\n}\n\n/**\n * Reports one applied transition. `onEvent` receives each event separately\n * (the legacy vocabulary); `onTransition` receives the whole transition once,\n * so a consumer that only invalidates does not do its work twice when a\n * transition carries two events (a logout that also replaces the identity).\n *\n * Every subscriber's `onTransition` runs BEFORE any subscriber's `onEvent`:\n * a consumer that hears the event can rely on the transition having been\n * applied everywhere else (the store is already invalidated when the legacy\n * listeners run), instead of depending on the order subscriptions happened to\n * be created in.\n */\nconst deliver = (record: Record, events: IdentityEvent[]): void => {\n record.subscribers.forEach(subscriber => subscriber.onTransition?.(events))\n record.subscribers.forEach(subscriber => {\n events.forEach(event => subscriber.onEvent?.(event))\n })\n}\n\n/**\n * Re-reads the session and reports what changed since the last observation.\n * The cleared mark is dropped first when the session reports an identity\n * again, otherwise it would mask the new identity forever.\n */\nfunction note (record: Record): void {\n if (record.cleared && sessionIsActive(record.session)) {\n record.cleared = false\n }\n // The session owns the identity again: a cookie identity remembered from\n // before it activated is stale — the probe only runs while the session is\n // inactive, and after a session logout the remembered cookie value must not\n // answer as if it had just been probed. Silent on purpose: the session\n // transition is what is reported, not this book-keeping.\n if (sessionOwnsIdentity(record.session)) record.cookieWebId = null\n const next = snapshotOf(record)\n const event = classifyTransition(record.raw, next)\n const replaced = identityReplaced(record.raw, next)\n const moved = event !== null || replaced\n record.raw = next\n if (!moved) return\n // The session moved on: an attempt that started before this transition is\n // answering about a state that no longer holds.\n record.version += 1\n const events: IdentityEvent[] = []\n if (event) events.push(event)\n if (replaced) events.push('identityReplaced')\n deliver(record, events)\n}\n\n/**\n * The backing store has no session while this tab still believes it is signed\n * in: report the logout and the replacement for the identity that was active,\n * once — a later refocus that still finds no session must not repeat it.\n */\nfunction reportCleared (record: Record): void {\n if (record.cleared) return\n const wasActive = record.raw.isActive\n const wasEstablished = record.raw.webId !== undefined\n // Only a session that was actually in use has to be invalidated: an\n // anonymous tab is cleared already, and marking it would make snapshotOf()\n // report the cleared state — masking a later login until some other\n // observation happens to run.\n if (!wasActive || !wasEstablished) {\n record.raw = snapshotOf(record)\n if (wasActive) {\n record.version += 1\n deliver(record, ['logout'])\n }\n return\n }\n // The local session object still reports the old identity: the mark is what\n // makes the derived reads stop answering for it, and the cleared snapshot is\n // the baseline — a later activation is a new login, and a still-cleared\n // session cannot report the logout twice.\n record.cleared = true\n record.raw = snapshotOf(record)\n record.version += 1\n deliver(record, ['logout', 'identityReplaced'])\n}\n\n/**\n * Starts (or joins) the newest resync attempt. A caller that joins an attempt\n * in flight must judge its answer against the identity the ATTEMPT started\n * from, not the one it sees now — hence the baseline is stored with the\n * attempt.\n */\nfunction startAttempt (record: Record, action: () => unknown): Attempt {\n if (record.attempt) return record.attempt\n const attempt: Attempt = {\n id: ++record.attemptId,\n version: record.version,\n raw: { isActive: sessionIsActive(record.session), webId: record.session.webId },\n promise: Promise.resolve()\n .then(action)\n .finally(() => { if (record.attempt === attempt) record.attempt = undefined })\n }\n record.attempt = attempt\n return attempt\n}\n\n/**\n * Re-reads the session through `resync` (when given) and reports the\n * transition, bounded by RESYNC_TIMEOUT_MS so a hung restore cannot stall a\n * refocus — but keeping the outcome: a restore that only finishes later can\n * still report the session gone, and dropping it would leave this tab on the\n * old identity until some other event.\n */\nasync function resyncThenNote (record: Record): Promise<void> {\n const resync = resyncActionOf(record)\n if (typeof resync !== 'function') {\n note(record)\n return\n }\n const runResync = resync\n const started = startAttempt(record, () => runResync())\n // This attempt's outcome only applies while it is still the newest one and no\n // transition was applied since the attempt (not this caller) started.\n const stale = (): boolean => started.id !== record.attemptId || record.version !== started.version\n // A `'cleared'` answer only applies while the session still reports the\n // identity the attempt started from: `restore()` rejects with \"no session\"\n // for the identity it was started for, so if the session reports a different\n // identity now, the answer is about the previous one and must not log the new\n // one out.\n const sameRawIdentity = (): boolean =>\n sessionIsActive(record.session) === started.raw.isActive && record.session.webId === started.raw.webId\n let outcome: unknown\n let done = false\n const attempt = started.promise.then(\n (value) => { outcome = value; done = true },\n () => { done = true } // compared as it stands\n )\n const apply = (): void => {\n if (stale()) return\n if (outcome === 'cleared') {\n if (sameRawIdentity()) reportCleared(record)\n return\n }\n // Any other result may have updated the session (a cross-tab login):\n // comparing again is what turns that into `sessionChange` /\n // `identityReplaced` instead of leaving this tab on the old identity.\n note(record)\n }\n let timer: ReturnType<typeof setTimeout> | undefined\n const timeout = new Promise<void>((resolve) => { timer = setTimeout(resolve, RESYNC_TIMEOUT_MS) })\n try {\n await Promise.race([attempt, timeout])\n } finally {\n if (timer !== undefined) clearTimeout(timer)\n }\n if (done) {\n apply()\n return\n }\n note(record)\n void attempt.then(apply)\n}\n\n/**\n * The resync action lives with the subscriber that knows how to run it\n * (`authSession` maps a restore rejection to `'cleared'`); the module keeps\n * the newest one so a refocus started from any subscriber re-reads the\n * session.\n */\nfunction resyncActionOf (record: Record): (() => unknown) | undefined {\n // Subscribers iterate in insertion order, so the last match is the newest.\n let newest: (() => unknown) | undefined\n for (const subscriber of record.subscribers) {\n if (subscriber.resync) newest = subscriber.resync\n }\n return newest\n}\n\n// uvdsl's session announces only changes of `isActive`; a WebID can change\n// while both states stay active and would go unseen. Every token update goes\n// through `setTokenDetails`, so compare the identity around it. Wrapped once\n// per session.\n//\n// TEMPORARY, pending the uvdsl change: delete this wrapper when the library\n// dispatches `sessionStateChange` for an active -> active WebID change too\n// (see the module header). The state model does not depend on it: any\n// observation path reports the same transition.\nfunction watchTokenUpdates (record: Record): void {\n const session = record.session\n const original = session.setTokenDetails\n if (typeof original !== 'function' || record.watchingTokenUpdates) return\n record.watchingTokenUpdates = true\n session.setTokenDetails = (...args: unknown[]): unknown => {\n const before = snapshotOf(record)\n const changed = (): boolean => {\n const after = snapshotOf(record)\n return after.webId !== before.webId || after.isActive !== before.isActive\n }\n // Whatever the outcome — a token update can apply the new identity and\n // then fail (a failed persistence, for one) — the identity around the call\n // is what matters, so the change is reported and the failure passes on.\n let result: unknown\n try {\n result = original.apply(session, args)\n } catch (error) {\n if (changed()) note(record)\n throw error\n }\n if (result && typeof (result as Promise<unknown>).then === 'function') {\n return (result as Promise<unknown>).then(\n (value: unknown) => {\n if (changed()) note(record)\n return value\n },\n (error: unknown) => {\n if (changed()) note(record)\n throw error\n }\n )\n }\n if (changed()) note(record)\n return result\n }\n}\n\nexport type IdentitySubscription = {\n /**\n * Applies a cookie-probe result. Ignored once the subscription is released,\n * so a probe that answers after its owner was replaced cannot resurrect an\n * identity — and while the session owns the identity it must not be replaced\n * by a cookie one at all.\n */\n reportCookieIdentity: (webId: string | null) => void\n unsubscribe: () => void\n}\n\n/**\n * Observes the session for identity transitions, and for refocuses (one\n * document listener per session, removed when the last subscription is\n * released, so a replaced logic instance adds no second listener).\n *\n * `onEvent` receives the derived events; `onRefocus` runs on a refocus (the\n * cookie revalidation, in SolidAuthnLogic); `resync` re-reads the session\n * before the comparison (authSession owns it, because it knows that a restore\n * rejection means \"no session\").\n */\nexport function subscribeIdentity (\n session: SessionLike,\n options: Subscriber = {}\n): IdentitySubscription {\n const record = recordOf(session)\n if (!record) {\n return { reportCookieIdentity: () => undefined, unsubscribe: () => undefined }\n }\n const subscriber: Subscriber = { ...options }\n record.subscribers.add(subscriber)\n if (!record.listenerAttached) {\n record.listenerAttached = true\n if (typeof session.addEventListener === 'function') {\n session.addEventListener('sessionStateChange', () => note(record))\n }\n watchTokenUpdates(record)\n }\n const doc: DocumentLike | undefined = typeof document === 'undefined' ? undefined : document\n if (record.subscribers.size === 1 && doc && typeof doc.addEventListener === 'function') {\n const handler = (): void => {\n if (doc.visibilityState !== 'visible') return\n // Wake up the session first; the cookie identity is invisible to it and\n // is revalidated in parallel by the subscriber that owns the probe.\n void resyncThenNote(record)\n record.subscribers.forEach(sub => { void sub.onRefocus?.() })\n }\n doc.addEventListener('visibilitychange', handler)\n record.detachDocument = () => doc.removeEventListener?.('visibilitychange', handler)\n }\n let released = false\n return {\n reportCookieIdentity: (webId: string | null): void => {\n if (released) return\n applyCookieIdentity(record, webId)\n },\n unsubscribe: (): void => {\n if (released) return\n released = true\n record.subscribers.delete(subscriber)\n if (record.subscribers.size === 0) {\n record.detachDocument?.()\n record.detachDocument = undefined\n }\n }\n }\n}\n\n/**\n * Applies a cookie-probe result to the record. Only cookie-backed changes are\n * reported: an OIDC identity change is already emitted by `note()`, and\n * reporting it again would duplicate the events — a reload consumer would\n * reload twice. While the session owns the identity a cookie one must not\n * replace it, and `sessionChange` is emitted only when it does not (an active\n * session already reported its own transition).\n */\nfunction applyCookieIdentity (record: Record, webId: string | null): void {\n if (record.cookieWebId === webId) return\n // While the session owns the identity a cookie one must not replace it — a\n // probe only runs while the session is inactive for exactly that reason.\n if (sessionOwnsIdentity(record.session)) return\n const previousCookieBacked = record.cookieWebId !== null\n record.cookieWebId = webId\n // The replacement is owed whenever the identity being REPLACED was\n // cookie-backed — the session watcher could not see it. Adopting one is not\n // a replacement: there was nothing of a previous user to drop.\n const events: IdentityEvent[] = ['sessionChange']\n if (previousCookieBacked) events.push('identityReplaced')\n deliver(record, events)\n}\n\n/**\n * Reload the page when the identity that was active in this tab is replaced or\n * cleared — the pragmatic way to drop everything fetched under the previous\n * identity (store, panes, editability), instead of repairing every read path.\n *\n * Consumer-side on purpose: navigation is an application decision (solid-ui,\n * mashlib), and tests inject their own action.\n */\nexport function reloadOnIdentityReplaced (\n events: { on?: (event: 'identityReplaced', handler: () => void) => void } | undefined,\n reload: () => void = () => {\n if (typeof window !== 'undefined') window.location.reload()\n }\n): void {\n if (!events || typeof events.on !== 'function') return\n events.on('identityReplaced', reload)\n}\n\n/**\n * Re-reads the session and reports the transition, without a resync action\n * (a plain observation, used by tests and by callers that already know the\n * session was refreshed).\n */\nexport function observeSession (session: SessionLike): void {\n const record = recordOf(session)\n if (record) note(record)\n}\n"],"mappings":"AAgFA,SAAgB,EACd,EACA,EACmC,CAEnC,OADI,EAAK,WAAa,EAAK,SACpB,EAAK,QAAU,EAAK,MAA0B,KAAlB,gBADS,EAAK,SAAW,gBAAkB,QAEhF,CAcA,SAAgB,EAAkB,EAAwB,EAAiC,CAGzF,OAFI,EAAK,QAAU,IAAA,IACf,CAAC,EAAK,SAAiB,GACpB,EAAK,QAAU,EAAK,OAAS,CAAC,EAAK,QAC5C,CAOA,IAAa,EAAmB,GAC9B,EAAQ,WAAa,IAAS,EAAQ,WAAa,IAAA,IAAa,EAAQ,EAAQ,MAK5E,EAAoB,IAyCpB,EAAU,IAAI,QAOd,EAAmB,IAAI,QAEvB,EAAY,GAA6C,CAC7D,GAAI,OAAO,GAAY,WAAY,EAAkB,OACrD,IAAI,EAAS,EAAQ,IAAI,CAAiB,EAgB1C,OAfK,IACH,EAAS,CACP,UACA,IAAK,CAAE,SAAU,EAAM,EACvB,QAAS,GACT,YAAa,KACb,QAAS,EACT,UAAW,EACX,YAAa,IAAI,IACjB,iBAAkB,GAClB,qBAAsB,EACxB,EACA,EAAO,IAAM,EAAW,CAAM,EAC9B,EAAQ,IAAI,EAAmB,CAAM,GAEhC,CACT,EAMA,SAAgB,EAAmB,EAA2B,CAE5D,OADI,OAAO,GAAY,WAAY,EAAyB,GACrD,EAAQ,IAAI,CAAiB,CAAC,EAAE,UAAY,EACrD,CAUA,SAAgB,EAA2B,EAA+B,CAExE,OADI,EAAkB,CAAO,EAAU,GAChC,GAAS,WAAa,IAAS,GAAS,MAAM,aAAe,EACtE,CAQA,SAAgB,EAAqB,EAA+B,CAClE,MAAO,CAAC,EAA0B,CAAO,GAAK,EAAgB,CAAO,CACvE,CAOA,IAAM,EAAc,GAGd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pD,EAAO,YAAc,EAIrB,IAAM,EAA0B,CAAC,eAAe,EAC5C,GAAsB,EAAO,KAAK,kBAAkB,EACxD,EAAQ,EAAQ,CAAM,CACxB,CAUA,SAAgB,EACd,EACA,MAA2B,CACrB,OAAO,OAAW,KAAa,OAAO,SAAS,OAAO,CAC5D,EACM,CACF,CAAC,GAAU,OAAO,EAAO,IAAO,YACpC,EAAO,GAAG,mBAAoB,CAAM,CACtC"}
@@ -0,0 +1,198 @@
1
+ //#region src/authSession/identityState.ts
2
+ function e(e, t) {
3
+ return e.isActive === t.isActive ? t.webId === e.webId ? null : "sessionChange" : t.isActive ? "sessionChange" : "logout";
4
+ }
5
+ function t(e, t) {
6
+ return e.webId === void 0 || !e.isActive ? !1 : t.webId !== e.webId || !t.isActive;
7
+ }
8
+ var n = (e) => e.isActive === !0 || e.isActive === void 0 && !!e.webId, r = 2e3, i = /* @__PURE__ */ new WeakMap(), a = /* @__PURE__ */ new WeakMap(), o = (e) => {
9
+ if (typeof e != "object" || !e) return;
10
+ let t = i.get(e);
11
+ return t || (t = {
12
+ session: e,
13
+ raw: { isActive: !1 },
14
+ cleared: !1,
15
+ cookieWebId: null,
16
+ version: 0,
17
+ attemptId: 0,
18
+ subscribers: /* @__PURE__ */ new Set(),
19
+ listenerAttached: !1,
20
+ watchingTokenUpdates: !1
21
+ }, t.raw = u(t), i.set(e, t)), t;
22
+ };
23
+ function s(e) {
24
+ return typeof e != "object" || !e ? !1 : i.get(e)?.cleared === !0;
25
+ }
26
+ function c(e) {
27
+ return s(e) ? !0 : e?.isActive === !1 || e?.info?.isLoggedIn === !1;
28
+ }
29
+ function l(e) {
30
+ return !c(e) && n(e);
31
+ }
32
+ var u = (e) => e.cleared ? { isActive: !1 } : {
33
+ isActive: n(e.session),
34
+ webId: e.session.webId
35
+ };
36
+ function d(e) {
37
+ let t = o(e);
38
+ return t ? l(e) ? e.webId === void 0 ? { source: "none" } : {
39
+ webId: e.webId,
40
+ source: "session"
41
+ } : t.cookieWebId === null ? { source: "none" } : {
42
+ webId: t.cookieWebId,
43
+ source: "cookie"
44
+ } : { source: "none" };
45
+ }
46
+ function f(e) {
47
+ return s(e) ? {
48
+ webId: void 0,
49
+ isLoggedIn: !1
50
+ } : {
51
+ webId: e.webId,
52
+ isLoggedIn: n(e)
53
+ };
54
+ }
55
+ function p(e) {
56
+ let t = e?.restore;
57
+ if (typeof t != "function" || typeof e != "object" || !e) return;
58
+ let n = e, r = a.get(n);
59
+ if (r) return r;
60
+ let i = Promise.resolve().then(() => t.call(e)).finally(() => {
61
+ a.delete(n);
62
+ });
63
+ return a.set(n, i), i;
64
+ }
65
+ var m = (e, t) => {
66
+ e.subscribers.forEach((e) => e.onTransition?.(t)), e.subscribers.forEach((e) => {
67
+ t.forEach((t) => e.onEvent?.(t));
68
+ });
69
+ };
70
+ function h(r) {
71
+ r.cleared && n(r.session) && (r.cleared = !1), l(r.session) && (r.cookieWebId = null);
72
+ let i = u(r), a = e(r.raw, i), o = t(r.raw, i), s = a !== null || o;
73
+ if (r.raw = i, !s) return;
74
+ r.version += 1;
75
+ let c = [];
76
+ a && c.push(a), o && c.push("identityReplaced"), m(r, c);
77
+ }
78
+ function g(e) {
79
+ if (e.cleared) return;
80
+ let t = e.raw.isActive, n = e.raw.webId !== void 0;
81
+ if (!t || !n) {
82
+ e.raw = u(e), t && (e.version += 1, m(e, ["logout"]));
83
+ return;
84
+ }
85
+ e.cleared = !0, e.raw = u(e), e.version += 1, m(e, ["logout", "identityReplaced"]);
86
+ }
87
+ function _(e, t) {
88
+ if (e.attempt) return e.attempt;
89
+ let r = {
90
+ id: ++e.attemptId,
91
+ version: e.version,
92
+ raw: {
93
+ isActive: n(e.session),
94
+ webId: e.session.webId
95
+ },
96
+ promise: Promise.resolve().then(t).finally(() => {
97
+ e.attempt === r && (e.attempt = void 0);
98
+ })
99
+ };
100
+ return e.attempt = r, r;
101
+ }
102
+ async function v(e) {
103
+ let t = y(e);
104
+ if (typeof t != "function") {
105
+ h(e);
106
+ return;
107
+ }
108
+ let i = t, a = _(e, () => i()), o = () => a.id !== e.attemptId || e.version !== a.version, s = () => n(e.session) === a.raw.isActive && e.session.webId === a.raw.webId, c, l = !1, u = a.promise.then((e) => {
109
+ c = e, l = !0;
110
+ }, () => {
111
+ l = !0;
112
+ }), d = () => {
113
+ if (!o()) {
114
+ if (c === "cleared") {
115
+ s() && g(e);
116
+ return;
117
+ }
118
+ h(e);
119
+ }
120
+ }, f, p = new Promise((e) => {
121
+ f = setTimeout(e, r);
122
+ });
123
+ try {
124
+ await Promise.race([u, p]);
125
+ } finally {
126
+ f !== void 0 && clearTimeout(f);
127
+ }
128
+ if (l) {
129
+ d();
130
+ return;
131
+ }
132
+ h(e), u.then(d);
133
+ }
134
+ function y(e) {
135
+ let t;
136
+ for (let n of e.subscribers) n.resync && (t = n.resync);
137
+ return t;
138
+ }
139
+ function b(e) {
140
+ let t = e.session, n = t.setTokenDetails;
141
+ typeof n != "function" || e.watchingTokenUpdates || (e.watchingTokenUpdates = !0, t.setTokenDetails = (...r) => {
142
+ let i = u(e), a = () => {
143
+ let t = u(e);
144
+ return t.webId !== i.webId || t.isActive !== i.isActive;
145
+ }, o;
146
+ try {
147
+ o = n.apply(t, r);
148
+ } catch (t) {
149
+ throw a() && h(e), t;
150
+ }
151
+ return o && typeof o.then == "function" ? o.then((t) => (a() && h(e), t), (t) => {
152
+ throw a() && h(e), t;
153
+ }) : (a() && h(e), o);
154
+ });
155
+ }
156
+ function x(e, t = {}) {
157
+ let n = o(e);
158
+ if (!n) return {
159
+ reportCookieIdentity: () => void 0,
160
+ unsubscribe: () => void 0
161
+ };
162
+ let r = { ...t };
163
+ n.subscribers.add(r), n.listenerAttached || (n.listenerAttached = !0, typeof e.addEventListener == "function" && e.addEventListener("sessionStateChange", () => h(n)), b(n));
164
+ let i = typeof document > "u" ? void 0 : document;
165
+ if (n.subscribers.size === 1 && i && typeof i.addEventListener == "function") {
166
+ let e = () => {
167
+ i.visibilityState === "visible" && (v(n), n.subscribers.forEach((e) => {
168
+ e.onRefocus?.();
169
+ }));
170
+ };
171
+ i.addEventListener("visibilitychange", e), n.detachDocument = () => i.removeEventListener?.("visibilitychange", e);
172
+ }
173
+ let a = !1;
174
+ return {
175
+ reportCookieIdentity: (e) => {
176
+ a || S(n, e);
177
+ },
178
+ unsubscribe: () => {
179
+ a || (a = !0, n.subscribers.delete(r), n.subscribers.size === 0 && (n.detachDocument?.(), n.detachDocument = void 0));
180
+ }
181
+ };
182
+ }
183
+ function S(e, t) {
184
+ if (e.cookieWebId === t || l(e.session)) return;
185
+ let n = e.cookieWebId !== null;
186
+ e.cookieWebId = t;
187
+ let r = ["sessionChange"];
188
+ n && r.push("identityReplaced"), m(e, r);
189
+ }
190
+ function C(e, t = () => {
191
+ typeof window < "u" && window.location.reload();
192
+ }) {
193
+ !e || typeof e.on != "function" || e.on("identityReplaced", t);
194
+ }
195
+ //#endregion
196
+ export { e as classifyTransition, d as effectiveIdentity, t as identityReplaced, f as legacySessionInfo, C as reloadOnIdentityReplaced, p as restoreSession, c as sessionExplicitlyInactive, n as sessionIsActive, l as sessionOwnsIdentity, s as sessionWasCleared, x as subscribeIdentity };
197
+
198
+ //# sourceMappingURL=identityState.esm.js.map