autosolutions-os 0.2.3 → 0.2.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,196 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.5 - 2026-10-15
4
+
5
+ Single sign-on fix. Signed in at the Hub, people opening an app were asked to
6
+ sign in with Google again (reported on 2026-10-14 for Artificial Design
7
+ Studio), and the Hub itself was often signed out an hour later.
8
+
9
+ - **The newest session wins.** `adoptSharedSession` copied the shared session
10
+ in only when the app had none of its own; when both existed it wrote the
11
+ app's own copy over the shared cookie. Supabase rotates refresh tokens and
12
+ accepts a retired one only one step behind or within 10 seconds; anything
13
+ older ends the session for every app (`refresh_token_already_used`). An app
14
+ opened again after the Hub had refreshed twice therefore wrote its old copy
15
+ over the Hub's, refreshed with a retired token and was signed out, and the
16
+ Hub with it. Now, wherever the two copies meet, the one that expires later is
17
+ kept (on a tie, the shared one): on load, and with `followSharedSession`
18
+ (below) when a tab becomes visible or gets focus and whenever supabase-js
19
+ reads its session, which it does before every refresh. An auth event no
20
+ longer writes over a newer shared copy.
21
+ - **A refresh on the wire keeps its result.** supabase-js (2.112 and later)
22
+ reads its stored session before and after a token request and throws the
23
+ rotated tokens away when the copy changed in between. While the page's own
24
+ refresh is in flight, a newer copy of the same person shared by another app
25
+ therefore waits for the next read; taken at once, it made supabase-js
26
+ discard a valid refresh (on supabase-js 2.112.3 a `getSession()` that
27
+ refreshed answered once with no session, and an explicit `refreshSession()`
28
+ reported "Refresh result discarded"). A different person signing in
29
+ elsewhere is still taken at once (the page reloads), so the refreshing
30
+ page's copy of the previous person cannot replace that sign-in.
31
+ - **Only an explicit sign-out clears the shared session, and it clears it
32
+ everywhere.** `client.auth.signOut()` (any scope but `"others"`) now leaves
33
+ a note, `sb-<ref>-auth-token-signed-out`, then clears the cookie and signs
34
+ out as before. The note holds the expiry of the newest copy it knew and the
35
+ `session_id` of each session the sign-out ended (`<expiry>|<id>.<id>`, the
36
+ last 8), a claim every refresh of one sign-in keeps. Every app drops a copy
37
+ that expires at or before the note, or of a session it names, instead of
38
+ sharing it again; until now an app still holding a copy put it back, and the
39
+ Hub took it on its next load. A failed refresh, another tab's `SIGNED_OUT`,
40
+ a missing local copy or blocked storage no longer clear anything.
41
+ - **A sign-out after an idle hour, or during a refresh, stays signed out.**
42
+ supabase-js refreshes an expired copy inside `signOut`, and waits for a
43
+ refresh already in flight, so a rotated copy can be saved and announced
44
+ after the note. It expires later than the note, so without more the Hub and
45
+ every app would load a session the server had just ended (its access token
46
+ stays valid for about an hour). The note's session ids keep such a copy
47
+ out, and `client.auth.signOut()` also leaves the note and clears the cookie
48
+ again once supabase-js has finished, so the note covers it by its expiry as
49
+ well, including a copy whose access token names no session.
50
+ - **A sign-out that does not happen changes nothing.** When supabase-js
51
+ reports a failed sign-out and still holds the session,
52
+ `client.auth.signOut()` puts the note back as it was before (none, or an
53
+ earlier sign-out's) and shares this page's copy again, so the person stays
54
+ signed in everywhere and can sign out again. Left in place, the note made
55
+ the next focus drop this page's copy and every other app's without a
56
+ logout, a second sign-out found no session and called nothing, and the
57
+ session stayed live on the server. supabase-js 2.106 (Smart LeadGen CRM's)
58
+ keeps the session when the server's logout fails (a 500 or a network error;
59
+ a 401, 403 or 404 still signs out), and every version keeps it when the
60
+ refresh it makes first fails on the network. supabase-js 2.112 and later
61
+ remove the session even when the logout fails: that is a sign-out on this
62
+ device, and it stays one everywhere. Two sign-outs at once (a double click)
63
+ count as one: the note goes back only when neither signed out.
64
+ - **Someone else signing in elsewhere replaces the session.** An open page
65
+ that was showing another person reloads, and so does a page on its sign-in
66
+ screen when a session arrives, so it shows that person: when the window
67
+ only gets focus (a click back into a window already in view, with no tab
68
+ switch) nothing tells supabase-js, and such a page would keep asking for
69
+ Google with a valid session stored. A page that has had no auth event yet
70
+ takes the session without reloading (its own first read shows it), and a
71
+ page on its sign-in screen does not reload when a copy that a sign-out
72
+ ended is dropped.
73
+ - **Storage and cookie errors never break sign-in.** The auth callback is now
74
+ guarded too: with cookies blocked, signing in threw a `SecurityError` to the
75
+ caller. A shared cookie read halfway through another app's write is left
76
+ alone instead of being taken for no session.
77
+ - **New: `followSharedSession(client, projectRef)`.** `createOsClient` calls
78
+ it; an app that builds its own client calls it once, right after
79
+ `publishSessionChanges`. It listens for the tab coming back, guards the
80
+ client's session reads (`client.auth.storage`, an internal of supabase-js:
81
+ feature-detected, and the tests fail if a supabase-js update moves it) and
82
+ makes `client.auth.signOut()` the explicit sign-out. `adoptSharedSession`
83
+ and `publishSessionChanges` keep their signatures.
84
+
85
+ ### Upgrading
86
+
87
+ - An app on `createOsClient` (the Hub) takes 0.2.5 and changes nothing else.
88
+ From 0.2.4 nothing else is needed: the design-system peer range stays
89
+ `>=6.4.0 <7`.
90
+ - An app with its own copy of the session code replaces it with the 0.2.5
91
+ copy and adds the one `followSharedSession` call where it creates its
92
+ client. Until then it can still sign everyone out with a stale refresh, so
93
+ every app on the core needs one or the other.
94
+ - The Hub takes 0.2.5 before, or together with, the first app that takes the
95
+ copy: a Hub on an older version still lets its own copy win, and its
96
+ sign-out leaves no note.
97
+
98
+ ## 0.2.4 - 2026-10-14
99
+
100
+ Released with `autosolutions-design-system` 6.4.0: the workspace frame in the
101
+ final design, with 6.3.5's fixes (wide pages scroll sideways again, a phone's
102
+ menu closes on every pick, no search box without a search) and the fixes of
103
+ the full review. The design-system peer range is now `>=6.4.0 <7`: the frame
104
+ passes the bar 6.4.0's `companyPending`, which an older design system would
105
+ put on the bar's element, and it relies on 6.4.0 for links on tabs, refused
106
+ navigations and the rest below.
107
+
108
+ - **A company switch to a company that does not hold this app goes to the
109
+ Hub again.** When `switch_company_for_app` answers with no `appUrl` (the
110
+ new company does not have the app), `useCompanySwitch`, and so
111
+ `OsCompanySwitcher` and `OsWorkspaceFrame`'s plate with `companySwitch`
112
+ `"os"`, reloaded the page in place, where the app showed its "not
113
+ entitled" state. It now goes to the Hub (`HUB_URL`) in the same tab, as
114
+ the apps' own company switchers did before they took this package, and as
115
+ this package's own doc comments already said. The Hub still reloads in
116
+ place, and a returned `appUrl` still reloads when it is this origin and
117
+ navigates otherwise. The decision is `companySwitchLanding` in
118
+ `src/url.ts` (internal), tested in `test/switch.test.ts`.
119
+ - **This app's own rows and tabs are links.** The frame's tabs and this
120
+ app's own rows were buttons, so a Cmd, Ctrl, Shift or middle click did
121
+ nothing useful and there was no link to copy, where the apps' own menus
122
+ were links. They now carry their path as `href` (`hrefFor`, default the
123
+ path itself): a plain click still goes through `onNavigate`, the rest is
124
+ the browser's. A hash router passes `hrefFor={(path) => "#" + path}`; an
125
+ app whose places never reach the address bar (Label Maker's views)
126
+ passes `hrefFor={null}` and keeps buttons.
127
+ - **A navigation the app does not make leaves the frame where the URL is.**
128
+ The frame shows a click at once; when the app's router then refused the
129
+ navigation (an unsaved-changes prompt the person stays on), the frame
130
+ stayed on what was clicked. When `onNavigate` returns a promise (TanStack
131
+ Router's `navigate`), the frame now waits for it and, if the address bar
132
+ did not move, goes back to where the URL is.
133
+ - **os_context() is the signed-in person's, and a failure is asked again.**
134
+ The cached answer was the page's, whoever was signed in: another person
135
+ signing in on the same browser without a reload (in this tab or another)
136
+ saw the last person's company and companies. It is now keyed on the person
137
+ in the stored session, dropped when another person's session arrives from
138
+ another tab, and followed through the app's auth client when the frame is
139
+ given one (`auth`, or `watchOsAuth(auth)`). A failed read was never asked
140
+ again in a mounted frame: the plate, the company switch and every link to
141
+ another app stayed missing until a reload. It is asked again 1, 3, 10, 30
142
+ and 60 seconds on, when the window comes back (focus, online, visible),
143
+ and when the app's location changes (`retryOsContext`); every mounted
144
+ reader gets the answer. `useOsContextState` says whether the answer is
145
+ still being read, read, or failed.
146
+ - **Until the catalogue answers, no tool claims it is not linked.** Other
147
+ apps' Live tools read "Live, not linked from the Hub yet" while
148
+ os_context() was pending or failing. `catalogueLinks(null)` now marks them
149
+ `HINTS.checking` ("Checking your access…").
150
+ - **An in-place switch moves the plate at once.** With `companySwitch` as a
151
+ function, the plate stayed on the old company when the read after the
152
+ switch failed, and a pick of that old company was then ignored, though the
153
+ session acted as the new one. The chosen company is now the acting one on
154
+ the plate, the menu's check and the links as soon as the switch resolves,
155
+ until the core is read again (asked up to three times).
156
+ - **The plate's place is kept while the company is read**
157
+ (`companyPending`), so an app's own bar controls do not jump when it
158
+ arrives; a company's name on the plate has the whole name as its tooltip;
159
+ and in the company menu a mark that does not load keeps its slot, so the
160
+ names stay lined up.
161
+ - **Where a location is.** A tool's tab now claims a location before the
162
+ tool's own row (Key Accounts: the list at `/` and a draft under Requests
163
+ are one place, so a menu the person closed stays closed between them); a
164
+ tab at `/` claims `/` only, not every page of the app (a member without
165
+ Trends on /trends is on no tab, not on the Dashboard); and paths compare
166
+ without regard to case, as the apps' routers serve them (/ops/Boards is the
167
+ Boards page).
168
+ - **`search` and `initialOpen`, as 6.4.0 draws them.** The bar draws a search
169
+ box only when `search.onChange` is given (a placeholder alone draws none).
170
+ A phone's screen needs no `initialOpen={false}`: at 767px and below the
171
+ menu is closed on every location and after every row or tab picked, once
172
+ the page is live; a server-rendered page shows it open until it hydrates.
173
+ The README's look-only frame example now passes a search handler.
174
+
175
+ ### Upgrading
176
+
177
+ - Take 0.2.4 and `autosolutions-design-system` 6.4.0 together, in one
178
+ commit: bump both in `package.json` and the lockfile. Nothing else is
179
+ required.
180
+ - An app whose router reads hashes passes `hrefFor={(path) => "#" + path}`;
181
+ one whose places are not addresses passes `hrefFor={null}`.
182
+ - An app whose navigations can be refused returns its router's promise from
183
+ `onNavigate` (TanStack Router: `onNavigate={(href) => navigate({ to: href })}`).
184
+ - An app that passes `auth={supabase.auth}` gets sign-in changes followed
185
+ live; others are covered through the stored session.
186
+ - An app whose top bar should keep a search box passes `search.onChange`.
187
+ One that passes no handler (or only a placeholder) loses the box, which
188
+ did nothing.
189
+ - `initialOpen={false}` passed for a narrow screen can go; kept, it does no
190
+ harm. Rows marked `menu: false` only so that a pick closes the menu on a
191
+ narrow screen (the Hub's) can drop that flag there: see the design
192
+ system's 6.4.0 notes.
193
+
3
194
  ## 0.2.3 - 2026-10-01
4
195
 
5
196
  With `autosolutions-design-system` 6.3.4, whose frame fixes this release
package/README.md CHANGED
@@ -29,16 +29,44 @@ export function App() {
29
29
  `supabase` is bound to your schema, so `.from("your_table")` works unchanged.
30
30
  `os` is the same connection bound to `public`, for the platform's own functions.
31
31
 
32
+ ## One sign-in across the apps
33
+
34
+ `createOsClient` keeps every app on one session: Supabase stores it in each
35
+ origin's localStorage, and the package mirrors it into a cookie on
36
+ `.autosolutions.app`. The newest copy always wins (on load, when a tab comes
37
+ back, and before supabase-js refreshes), only `supabase.auth.signOut()` clears
38
+ it, and it clears it in every app. A sign-out that does not happen (supabase-js
39
+ reports a failure and keeps the session) clears nothing, so the person can sign
40
+ out again. An app that builds its own Supabase client wires the same three calls
41
+ itself, in this order, at module scope:
42
+
43
+ ```ts
44
+ import { createClient } from "@supabase/supabase-js";
45
+ import { adoptSharedSession, followSharedSession, publishSessionChanges, coreProjectRef } from "autosolutions-os";
46
+
47
+ const ref = coreProjectRef();
48
+ adoptSharedSession(ref); // before the client reads its storage
49
+ const supabase = createClient(url, key, { auth: { persistSession: true, autoRefreshToken: true } });
50
+ publishSessionChanges(supabase, ref);
51
+ followSharedSession(supabase, ref);
52
+ ```
53
+
32
54
  ## The workspace frame
33
55
 
34
56
  `OsWorkspaceFrame` is the frame every app on the core renders around its pages:
35
57
  the top bar with the company's mark and switcher, the rail, the OS menu (the 53
36
58
  tools of the menu map: the handoff's 49 plus Shelf simulator, Key accounts, PM
37
59
  Copilot and Candidate hub), the footer with Admin for people who manage something, and the
38
- browser-tab icon. It needs `autosolutions-design-system` 6.3.4 or later
39
- (an optional peer: only this entry point uses it). Take this package's 0.2.3
40
- and the design system's 6.3.4 together, in one commit. An app that renders
41
- `OsWorkspaceFrame` changes nothing else. Code that calls `osFrame().targetFor`
60
+ browser-tab icon. It needs `autosolutions-design-system` 6.4.0 or later
61
+ (an optional peer: only this entry point uses it). Take this package's 0.2.4
62
+ and the design system's 6.4.0 together, in one commit: 0.2.4 sends a company
63
+ switch the app's new company does not hold to the Hub, reads os_context()
64
+ for the person signed in and asks again after a failure, and makes this
65
+ app's own rows and tabs links; 6.4.0 brings the final design and the frame's
66
+ own fixes (wide pages scroll sideways again, a phone's menu closes on every
67
+ pick, no search box without a search, and the rest in its CHANGELOG). An
68
+ app that renders `OsWorkspaceFrame` changes nothing else, but for the
69
+ options below (`hrefFor`, a navigation promise, `auth`). Code that calls `osFrame().targetFor`
42
70
  itself in the Hub (a test of the Hub's rows, say) and means Back to hub passes
43
71
  `back: true`: since 0.2.3 the hub function with no row and no flag is the
44
72
  rail's Hub (see below). The Hub's adoption of 0.2.3 updates its one test that
@@ -67,8 +95,14 @@ import { OsWorkspaceFrame } from "autosolutions-os/frame";
67
95
 
68
96
  It works with any router: it reads `location` and calls `onNavigate(href)` for
69
97
  paths inside the app, and opens other apps itself, in the same tab. The rows
70
- for other apps are links (`<a href>` with `?tenant=`), so a middle-click, a
71
- Cmd or Ctrl click and Copy link work as the browser does them. Browser Back
98
+ for other apps are links (`<a href>` with `?tenant=`), and so are this app's
99
+ own rows and tabs (`href` is the path; `hrefFor` writes it another way, as
100
+ `(path) => "#" + path` for a hash router, or `null` keeps buttons for an app
101
+ whose places never reach the address bar), so a middle-click, a Cmd or Ctrl
102
+ click and Copy link work as the browser does them. Return the router's
103
+ navigation promise from `onNavigate` (as above) and a navigation the app
104
+ refuses (an unsaved-changes prompt the person stays on, which leaves the
105
+ address bar where it was) puts the frame back where the URL is. Browser Back
72
106
  moves the menus because the frame follows `location`, and it calls
73
107
  `onNavigate` only when someone clicks, so there is no loop. Back from another
74
108
  app out of the browser's back/forward cache puts the frame where the URL is,
@@ -106,32 +140,49 @@ why).
106
140
  (`staticLinks()`). Tools with no app follow the map: Pricing researcher and
107
141
  Brand voice copywriter read "Live, not linked from the Hub yet", anything
108
142
  not Live shows its status.
143
+ - os_context() is read once per page and person: another person signing in
144
+ on the same browser, without a reload, reads their own (pass `auth`, the
145
+ app's `supabase.auth`, to have sign-ins followed live in this tab too). A
146
+ read that fails is asked again (1, 3, 10, 30 and 60 seconds on, when the
147
+ window comes back, and when the location changes), and until it answers
148
+ other apps' tools read "Checking your access…" and the plate's place is
149
+ kept, drawn as nothing.
109
150
  - The company plate is `markFor(tenant, "plain")`. A company with no artwork
110
151
  there (one outside the brand bucket's eight, with no stored logo), or whose
111
- artwork fails to load, has its name on the plate instead, and its row in
112
- the company menu drops the broken mark. The chevron appears only for
152
+ artwork fails to load, has its name on the plate instead (its whole name
153
+ in a tooltip), and its row in the company menu keeps the mark's slot,
154
+ empty. The chevron appears only for
113
155
  someone with more than one company, and then the plate and the chevron are
114
156
  one button that opens the company menu: a menu of the companies, the acting
115
157
  one checked, with arrow keys, and focus back on the button when it closes.
116
158
  `companySwitch` says what it does:
117
159
  - `"os"` (the default) switches exactly as `OsCompanySwitcher` does, since
118
160
  both use `useCompanySwitch(os, appKey)`: `switch_company_for_app`, then a
119
- reload or that company's deployment of this app.
161
+ reload or that company's deployment of this app, or the Hub when that
162
+ company does not hold the app (the core returns no `appUrl`).
120
163
  - `"none"` shows the acting company with no chevron, for an app whose
121
164
  company is fixed some other way (PM Copilot's assignment).
122
165
  - a function `(tenant) => Promise<void>` is the app's own in-place switch
123
166
  (e-sales: `switch_tenant`, invalidate, toast). The frame calls it, closes
124
- the menu and does not reload; when it resolves, `refreshOsContext(os)`
125
- brings the plate and the menu's links round to the new company. The
126
- function reports its own failures.
167
+ the menu and does not reload; when it resolves, the plate, the menu's
168
+ check and its links follow the new company at once, and
169
+ `refreshOsContext(os)` reads the core again (asking again if that fails).
170
+ The function reports its own failures.
127
171
  - `actions` go in the top bar before the plate (What's new, a notification
128
172
  bell). `panelFooter` renders in the panel under the open tool's tabs, in the
129
173
  panel's padding, scrolling with them (Create Studio's sessions).
130
174
  - Settings goes to `settingsPath` when the app has a settings page, and to the
131
175
  Hub's settings when it has none.
132
- - `initialOpen={false}` starts the menu closed on the first location (a narrow
133
- screen); after that the frame's own rule applies. `data-*` and `aria-*` props
134
- land on the frame's root.
176
+ - `search` is the top bar's field. It is drawn only when `search.onChange`
177
+ is given: an app with no search passes none and the bar has no box (a
178
+ placeholder alone draws none either).
179
+ - On a phone's screen (767px and below) the design system closes the menu on
180
+ every location and on every row or tab picked, so the page picked gets the
181
+ width, once the page is live (a server-rendered page shows it open until it
182
+ hydrates); a reselect still goes back to its own page. No prop is needed
183
+ for it. `initialOpen={false}` starts the menu closed on the first location,
184
+ which a phone no longer needs it for; after that the frame's own rule
185
+ applies. `data-*` and `aria-*` props land on the frame's root.
135
186
  - Admin appears when `my_admin_scope()` says the person manages something; pass
136
187
  `admin` to decide it yourself.
137
188
  - The Hub passes `hubItems`, its own rows. In any other app the rail's Hub, Back
@@ -165,7 +216,7 @@ const frame = osFrame({ appKey: "ops_hub", tools, links: staticLinks() });
165
216
  const here = pathname + search;
166
217
 
167
218
  <WorkspaceFrame
168
- topBar={<TopBar searchPlaceholder="Search" companySrc={companyMarkUrl("frankbody", "plain")} />}
219
+ topBar={<TopBar searchPlaceholder="Search" searchValue={query} onSearchChange={setQuery} companySrc={companyMarkUrl("frankbody", "plain")} />}
169
220
  functions={frame.functions}
170
221
  sections={frame.sections}
171
222
  footerItems={frame.footerItems}
package/dist/chrome.d.ts CHANGED
@@ -26,9 +26,12 @@ export declare function OsAppSwitcher({ os, appKey, variant, onOpen }: {
26
26
  *
27
27
  * `choose` runs `close` synchronously, and does nothing else, when there is
28
28
  * nothing to do: the company is already current or a switch is in flight.
29
+ * `status` says whether the context is still being read, read, or failed
30
+ * (and is being asked again).
29
31
  */
30
32
  export declare function useCompanySwitch(os: unknown, appKey: string): {
31
- context: import("./context.js").OsContext | null;
33
+ context: import("./contextCache.js").OsContext | null;
34
+ status: import("./contextCache.js").OsContextStatus;
32
35
  current: OsTenant | null;
33
36
  tenants: OsTenant[];
34
37
  busy: boolean;
package/dist/chrome.js CHANGED
@@ -12,7 +12,8 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
12
12
  */
13
13
  import { useEffect, useRef, useState } from "react";
14
14
  import { HUB_URL } from "./config.js";
15
- import { groupApps, invalidateOsContext, labelFor, markFor, useOsContext, withTenantHint, } from "./context.js";
15
+ import { companySwitchLanding } from "./url.js";
16
+ import { groupApps, invalidateOsContext, labelFor, markFor, useOsContext, useOsContextState, withTenantHint, } from "./context.js";
16
17
  function useDismiss(open, close, ref) {
17
18
  useEffect(() => {
18
19
  if (!open)
@@ -69,9 +70,11 @@ export function OsAppSwitcher({ os, appKey, variant = "menu", onOpen }) {
69
70
  *
70
71
  * `choose` runs `close` synchronously, and does nothing else, when there is
71
72
  * nothing to do: the company is already current or a switch is in flight.
73
+ * `status` says whether the context is still being read, read, or failed
74
+ * (and is being asked again).
72
75
  */
73
76
  export function useCompanySwitch(os, appKey) {
74
- const context = useOsContext(os);
77
+ const { context, status } = useOsContextState(os);
75
78
  const [busy, setBusy] = useState(false);
76
79
  const [error, setError] = useState(null);
77
80
  const current = context?.tenant ?? null;
@@ -97,24 +100,15 @@ export function useCompanySwitch(os, appKey) {
97
100
  }
98
101
  invalidateOsContext();
99
102
  const result = (data ?? {});
100
- if (appKey === "hub" || !result.appUrl) {
103
+ const destination = companySwitchLanding(appKey, result, window.location.origin);
104
+ if (destination === null)
101
105
  window.location.reload();
102
- return;
103
- }
104
- const destination = withTenantHint(result.appUrl, result.tenantSlug ?? null);
105
- try {
106
- if (new URL(destination).origin === window.location.origin) {
107
- window.location.reload();
108
- return;
109
- }
110
- }
111
- catch {
112
- /* malformed destination: fall through and let the browser report it */
113
- }
114
- window.location.assign(destination);
106
+ else
107
+ window.location.assign(destination);
115
108
  };
116
109
  return {
117
110
  context,
111
+ status,
118
112
  current,
119
113
  tenants: context?.tenants ?? [],
120
114
  busy,
package/dist/client.js CHANGED
@@ -7,7 +7,7 @@
7
7
  */
8
8
  import { createClient } from "@supabase/supabase-js";
9
9
  import { coreProjectRef, corePublishableKey, coreUrl } from "./config.js";
10
- import { adoptSharedSession, publishSessionChanges } from "./session.js";
10
+ import { adoptSharedSession, followSharedSession, publishSessionChanges } from "./session.js";
11
11
  let cached;
12
12
  export function createOsClient(options) {
13
13
  // One client per page. A second would keep its own session state and the two
@@ -24,6 +24,9 @@ export function createOsClient(options) {
24
24
  });
25
25
  // Signing in or out here carries to every other AutoSolutions app.
26
26
  publishSessionChanges(supabase, ref);
27
+ // While the page is open the newest session wins: when the tab comes back,
28
+ // and before supabase-js refreshes, so it never refreshes with an older token.
29
+ followSharedSession(supabase, ref);
27
30
  const client = {
28
31
  supabase,
29
32
  // Always take the explicit `public` view, so the type is the same whether or
package/dist/context.d.ts CHANGED
@@ -1,37 +1,10 @@
1
- export type OsTenant = {
2
- id: string;
3
- slug: string;
4
- name: string;
5
- logoUrl: string | null;
6
- logoPlainUrl: string | null;
7
- osRole?: string;
1
+ import { type OsApp, type OsContext, type OsContextStatus, type OsTenant } from "./contextCache.js";
2
+ export { loadOsContext, invalidateOsContext, refreshOsContext, retryOsContext, watchOsAuth, type OsApp, type OsContext, type OsContextStatus, type OsTenant, } from "./contextCache.js";
3
+ /** The context and where it stands, for a component that shows the difference. */
4
+ export declare function useOsContextState(os: unknown): {
5
+ context: OsContext | null;
6
+ status: OsContextStatus;
8
7
  };
9
- export type OsApp = {
10
- key: string;
11
- name: string;
12
- iconUrl: string | null;
13
- url: string | null;
14
- sortOrder: number;
15
- /** Switcher column, e.g. Marketing. Comes from the catalogue, not from code. */
16
- groupKey: string | null;
17
- /** Sub-heading inside the column; null means the untitled first block. */
18
- sectionKey: string | null;
19
- designKey: string | null;
20
- labelUrl: string | null;
21
- };
22
- export type OsContext = {
23
- tenant: OsTenant | null;
24
- tenants: OsTenant[];
25
- apps: OsApp[];
26
- };
27
- export declare function loadOsContext(os: unknown): Promise<OsContext | null>;
28
- /** Forget the cached answer, so the next read reflects a company switch. */
29
- export declare function invalidateOsContext(): void;
30
- /**
31
- * Ask again and hand the answer to every mounted reader: after a company
32
- * switch that does not reload the page. A failed call changes nothing.
33
- */
34
- export declare function refreshOsContext(os: unknown): Promise<OsContext | null>;
35
8
  export declare function useOsContext(os: unknown): OsContext | null;
36
9
  export declare function useTenant(os: unknown): OsTenant | null;
37
10
  export declare function useApps(os: unknown): OsApp[];
package/dist/context.js CHANGED
@@ -1,68 +1,41 @@
1
1
  /**
2
2
  * `os_context()` is the one call every app's chrome makes: who you are acting
3
3
  * as, which companies you can act as, and which apps you hold. One round trip,
4
- * cached for the page.
4
+ * cached for the page and for the person signed in (contextCache.ts).
5
5
  */
6
6
  import { useEffect, useState } from "react";
7
7
  import { appLabelUrl, companyMarkUrl } from "./config.js";
8
- /**
9
- * One fetch per page, but a FAILURE is never cached. A call that races a token
10
- * refresh would otherwise blank both switchers until a full reload.
11
- */
12
- let pending = null;
13
- export function loadOsContext(os) {
14
- if (!pending) {
15
- pending = Promise.resolve(os.rpc("os_context"))
16
- .then(({ data, error }) => {
17
- if (error || !data) {
18
- pending = null;
19
- return null;
20
- }
21
- return data;
22
- })
23
- .catch(() => {
24
- pending = null;
25
- return null;
26
- });
27
- }
28
- return pending;
29
- }
30
- /** Forget the cached answer, so the next read reflects a company switch. */
31
- export function invalidateOsContext() {
32
- pending = null;
33
- }
34
- /* Every mounted useOsContext, so an in-place switch reaches them all. */
35
- const readers = new Set();
36
- /**
37
- * Ask again and hand the answer to every mounted reader: after a company
38
- * switch that does not reload the page. A failed call changes nothing.
39
- */
40
- export async function refreshOsContext(os) {
41
- pending = null;
42
- const value = await loadOsContext(os);
43
- if (value)
44
- readers.forEach((read) => read(value));
45
- return value;
46
- }
47
- export function useOsContext(os) {
48
- const [context, setContext] = useState(null);
8
+ import { loadOsContext, scheduleOsContextRetry, subscribeOsContext, } from "./contextCache.js";
9
+ export { loadOsContext, invalidateOsContext, refreshOsContext, retryOsContext, watchOsAuth, } from "./contextCache.js";
10
+ /** The context and where it stands, for a component that shows the difference. */
11
+ export function useOsContextState(os) {
12
+ const [state, setState] = useState({ context: null, status: "loading" });
49
13
  useEffect(() => {
50
14
  let live = true;
51
- const read = (value) => {
15
+ const read = (context, status) => {
52
16
  if (live)
53
- setContext(value);
17
+ setState((was) => (was.context === context && was.status === status ? was : { context, status }));
54
18
  };
55
- readers.add(read);
19
+ const unsubscribe = subscribeOsContext(read);
56
20
  void loadOsContext(os).then((value) => {
57
- if (live)
58
- setContext(value);
21
+ if (!live)
22
+ return;
23
+ if (value) {
24
+ read(value, "ready");
25
+ return;
26
+ }
27
+ read(null, "failed");
28
+ scheduleOsContextRetry(os);
59
29
  });
60
30
  return () => {
61
31
  live = false;
62
- readers.delete(read);
32
+ unsubscribe();
63
33
  };
64
34
  }, [os]);
65
- return context;
35
+ return state;
36
+ }
37
+ export function useOsContext(os) {
38
+ return useOsContextState(os).context;
66
39
  }
67
40
  export function useTenant(os) {
68
41
  return useOsContext(os)?.tenant ?? null;
@@ -0,0 +1,50 @@
1
+ export type OsTenant = {
2
+ id: string;
3
+ slug: string;
4
+ name: string;
5
+ logoUrl: string | null;
6
+ logoPlainUrl: string | null;
7
+ osRole?: string;
8
+ };
9
+ export type OsApp = {
10
+ key: string;
11
+ name: string;
12
+ iconUrl: string | null;
13
+ url: string | null;
14
+ sortOrder: number;
15
+ /** Switcher column, e.g. Marketing. Comes from the catalogue, not from code. */
16
+ groupKey: string | null;
17
+ /** Sub-heading inside the column; null means the untitled first block. */
18
+ sectionKey: string | null;
19
+ designKey: string | null;
20
+ labelUrl: string | null;
21
+ };
22
+ export type OsContext = {
23
+ tenant: OsTenant | null;
24
+ tenants: OsTenant[];
25
+ apps: OsApp[];
26
+ };
27
+ /**
28
+ * Where a reader's context stands: still being read, read, or failed (and
29
+ * being asked again).
30
+ */
31
+ export type OsContextStatus = "loading" | "ready" | "failed";
32
+ export declare function loadOsContext(os: unknown): Promise<OsContext | null>;
33
+ /** Forget the cached answer, so the next read reflects a company switch. */
34
+ export declare function invalidateOsContext(): void;
35
+ /** Hear every new answer (and a change of person) until the returned function is called. */
36
+ export declare function subscribeOsContext(read: (context: OsContext | null, status: OsContextStatus) => void): () => void;
37
+ /**
38
+ * Ask again and hand the answer to every mounted reader: after a company
39
+ * switch that does not reload the page. A failed call changes nothing.
40
+ */
41
+ export declare function refreshOsContext(os: unknown): Promise<OsContext | null>;
42
+ /** After a failed read: ask again on a timer (1, 3, 10, 30, 60 seconds). */
43
+ export declare function scheduleOsContextRetry(os: unknown): void;
44
+ /**
45
+ * Ask again now if the last read failed (the frame calls it when the app's
46
+ * location changes); otherwise the cached answer. Every mounted reader gets a
47
+ * new answer.
48
+ */
49
+ export declare function retryOsContext(os: unknown): Promise<OsContext | null>;
50
+ export declare function watchOsAuth(auth: unknown): void;