@rise-x/apps-sdk 0.19.0 → 0.20.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.
@@ -0,0 +1,183 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.LOCK_REFRESH_MS = void 0;
4
+ exports.useLiveStatus = useLiveStatus;
5
+ exports.useLiveEvents = useLiveEvents;
6
+ exports.useComponentLock = useComponentLock;
7
+ exports.useWorkLocks = useWorkLocks;
8
+ // @rise-x/apps-sdk/live: live platform events and editor presence, over the host's own
9
+ // connection.
10
+ //
11
+ // The host owns the connection and turns what it hears into `LiveEvent`s; these hooks subscribe
12
+ // an app to them. Nothing here opens a connection or polls. On a host that offers no live
13
+ // events every hook is inert, so an app keeps working from its own reads. To keep this SDK's query
14
+ // cache current from the same events, use `useLiveInvalidation` from `@rise-x/apps-sdk/query`.
15
+ //
16
+ // Not re-exported from the package root: the root barrel stays free of anything that reads the
17
+ // connectors.
18
+ const react_1 = require("react");
19
+ const accessors_1 = require("../accessors");
20
+ const work_1 = require("../connectors/work");
21
+ const NOOP = () => { };
22
+ // Module-level so the subscription is stable across renders. The bridge is read on each call,
23
+ // because it can finish wiring after the first render.
24
+ const subscribeToStatus = (onChange) => (0, accessors_1.getShellLive)()?.subscribeStatus(onChange) ?? NOOP;
25
+ const readStatus = () => (0, accessors_1.getShellLive)()?.getStatus() ?? "unavailable";
26
+ /**
27
+ * The host's live connection state. Re-renders on a change. `unavailable` means the host offers
28
+ * no live events at all, so keep whatever fallback you have; `connected` is the only state in
29
+ * which events arrive.
30
+ */
31
+ function useLiveStatus() {
32
+ return (0, react_1.useSyncExternalStore)(subscribeToStatus, readStatus, readStatus);
33
+ }
34
+ /**
35
+ * Calls `handler` with each live event while the component is mounted. The latest `handler` is
36
+ * always the one called, so an inline function does not subscribe again. Events arrive for every
37
+ * work item and asset the user can see, across their ecosystems, and are best-effort: a `resync`
38
+ * event says some were missed.
39
+ */
40
+ function useLiveEvents(handler, options = {}) {
41
+ const latest = (0, react_1.useRef)(handler);
42
+ // Updated after commit, so a render React throws away never replaces the live handler.
43
+ (0, react_1.useEffect)(() => {
44
+ latest.current = handler;
45
+ });
46
+ const enabled = options.enabled ?? true;
47
+ (0, react_1.useEffect)(() => {
48
+ if (!enabled)
49
+ return;
50
+ return (0, accessors_1.getShellLive)()?.subscribe((event) => latest.current(event));
51
+ }, [enabled]);
52
+ }
53
+ // The platform keeps one lock per user per work, so a second editor's lock replaces the first and
54
+ // releasing either would clear both. Holds on the same work therefore stack: the most recent one
55
+ // is the lock the platform sees, and releasing it takes the one beneath again.
56
+ const holds = new Map();
57
+ const last = (stack) => stack ? stack[stack.length - 1] : undefined;
58
+ const topHold = (workId) => last(holds.get(workId));
59
+ /** How often an open editor says its lock again, so the platform can tell a lock is still held. */
60
+ exports.LOCK_REFRESH_MS = 60000;
61
+ // Presence is advisory: a read-only user, or a connection that dropped, simply has none.
62
+ function send(live, workId, hold, locked) {
63
+ live
64
+ .setComponentLock({
65
+ workId,
66
+ componentId: hold.componentId,
67
+ dataPath: hold.dataPath,
68
+ locked,
69
+ })
70
+ .catch(NOOP);
71
+ }
72
+ function release(live, workId, hold) {
73
+ const wasTop = topHold(workId) === hold;
74
+ const rest = (holds.get(workId) ?? []).filter((h) => h !== hold);
75
+ if (rest.length)
76
+ holds.set(workId, rest);
77
+ else
78
+ holds.delete(workId);
79
+ // A hold beneath the top is not what the platform shows, so releasing it changes nothing there.
80
+ if (!wasTop)
81
+ return;
82
+ const next = last(rest);
83
+ if (next)
84
+ send(live, workId, next, true);
85
+ else
86
+ send(live, workId, hold, false);
87
+ }
88
+ /**
89
+ * Shows that the user is editing: takes a component lock on `workId` while `active`, says it again
90
+ * every {@link LOCK_REFRESH_MS} and after a reconnect, and releases it when `active` ends or the
91
+ * component unmounts. Others see it through `useWorkLocks`.
92
+ *
93
+ * `componentId` identifies the editor and must be a GUID. Use the same one for the same editor in
94
+ * every session, so other users' screens can tell which editor is open. The platform keeps one
95
+ * lock per user per work, so this lock and one the host's own editor takes for the same user
96
+ * replace each other. Several holds in one app are fine: the most recent shows, and releasing it
97
+ * takes the previous one again.
98
+ *
99
+ * Advisory only: it never gates a write, and it does nothing on a host without live events.
100
+ * Without a connection the lock is not sent, and the app keeps working.
101
+ */
102
+ function useComponentLock(workId, componentId, active, dataPath) {
103
+ (0, react_1.useEffect)(() => {
104
+ const live = (0, accessors_1.getShellLive)();
105
+ if (!live || !workId || !active)
106
+ return;
107
+ const hold = { componentId, dataPath };
108
+ holds.set(workId, [...(holds.get(workId) ?? []), hold]);
109
+ const say = () => {
110
+ if (topHold(workId) === hold)
111
+ send(live, workId, hold, true);
112
+ };
113
+ say();
114
+ // Locks live in the platform's memory and are not replayed after a reconnect: say it again.
115
+ const off = live.subscribe((event) => {
116
+ if (event.type === "resync")
117
+ say();
118
+ });
119
+ const refresh = setInterval(say, exports.LOCK_REFRESH_MS);
120
+ return () => {
121
+ clearInterval(refresh);
122
+ off();
123
+ release(live, workId, hold);
124
+ };
125
+ }, [workId, componentId, active, dataPath]);
126
+ }
127
+ /**
128
+ * Who has an editor open on this work right now: every user's lock, yours included. Starts from
129
+ * the locks on a fresh read of the work and follows `lock` events, so it stays current without
130
+ * polling. Empty on a host without live events. A lock from a closed browser can linger on
131
+ * the platform, so compare `at` with the age you are willing to believe.
132
+ */
133
+ function useWorkLocks(workId) {
134
+ const [locks, setLocks] = (0, react_1.useState)([]);
135
+ (0, react_1.useEffect)(() => {
136
+ setLocks([]);
137
+ const live = (0, accessors_1.getShellLive)();
138
+ if (!live || !workId)
139
+ return;
140
+ // The read in flight. A newer read (after a resync) or unmount aborts it, so an older answer
141
+ // never lands over a newer one, and no read outlives the component.
142
+ let reading = null;
143
+ // Users whose lock an event has already reported: the event is newer than the read.
144
+ const reported = new Set();
145
+ const seed = async () => {
146
+ reading?.abort();
147
+ const controller = (reading = new AbortController());
148
+ try {
149
+ const detail = await work_1.work.get(workId, { signal: controller.signal });
150
+ if (controller.signal.aborted || !detail)
151
+ return;
152
+ setLocks((current) => [
153
+ ...detail.activeLocks.filter((l) => !reported.has(l.userId)),
154
+ ...current.filter((l) => reported.has(l.userId)),
155
+ ]);
156
+ }
157
+ catch {
158
+ // Presence is advisory: without the read, only new lock events show.
159
+ }
160
+ };
161
+ const off = live.subscribe((event) => {
162
+ if (event.type === "resync") {
163
+ reported.clear();
164
+ void seed();
165
+ return;
166
+ }
167
+ if (event.type !== "lock" || event.workId !== workId)
168
+ return;
169
+ reported.add(event.userId);
170
+ const { type: _type, locked, ...lock } = event;
171
+ setLocks((current) => {
172
+ const others = current.filter((l) => l.userId !== lock.userId);
173
+ return locked ? [...others, lock] : others;
174
+ });
175
+ });
176
+ void seed();
177
+ return () => {
178
+ reading?.abort();
179
+ off();
180
+ };
181
+ }, [workId]);
182
+ return locks;
183
+ }
@@ -0,0 +1,32 @@
1
+ import type { LiveApi, LiveEvent, LiveStatus, SetComponentLockArgs } from "./shellBridge";
2
+ export type ComponentLockHandler = (args: SetComponentLockArgs) => Promise<void>;
3
+ export interface CreateLiveChannelOptions {
4
+ /** The starting status. Default `connecting`. */
5
+ status?: LiveStatus;
6
+ /** How a lock reaches the platform. Without one, `setComponentLock` rejects. */
7
+ setComponentLock?: ComponentLockHandler;
8
+ }
9
+ /**
10
+ * A {@link LiveApi} plus the controls that feed it: `emit` an event to every subscriber,
11
+ * `setStatus` as the connection moves.
12
+ *
13
+ * Hosts get one from the bridge, driven by their connection. For standalone development, build
14
+ * one, pass it to `createMockShell({ live })`, and `emit` events by hand.
15
+ */
16
+ export interface LiveChannel {
17
+ readonly api: LiveApi;
18
+ /** Deliver an event to every subscriber. A listener that throws does not stop the rest. */
19
+ emit(event: LiveEvent): void;
20
+ /**
21
+ * Report the connection state. Listeners fire on a change only. Moving to `connected` after an
22
+ * earlier connection also emits `{ type: "resync" }`, because events sent in between were lost;
23
+ * the first connection does not.
24
+ */
25
+ setStatus(status: LiveStatus): void;
26
+ }
27
+ export declare function callSafely<T>(listener: (value: T) => void, value: T): void;
28
+ /**
29
+ * Router-free and connector-free on purpose: the mock shell builds one for standalone dev, and
30
+ * the mock shell rides the root barrel.
31
+ */
32
+ export declare function createLiveChannel(options?: CreateLiveChannelOptions): LiveChannel;
@@ -0,0 +1,60 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.callSafely = callSafely;
4
+ exports.createLiveChannel = createLiveChannel;
5
+ // Every app in the shell listens on the same channel, so one app's listener that throws must
6
+ // neither stop the listeners after it nor reach the host's connection handling.
7
+ function callSafely(listener, value) {
8
+ try {
9
+ listener(value);
10
+ }
11
+ catch (error) {
12
+ console.error("[@rise-x/apps-sdk] a live listener threw; other listeners still run.", error);
13
+ }
14
+ }
15
+ /**
16
+ * Router-free and connector-free on purpose: the mock shell builds one for standalone dev, and
17
+ * the mock shell rides the root barrel.
18
+ */
19
+ function createLiveChannel(options = {}) {
20
+ let status = options.status ?? "connecting";
21
+ // A channel created `connected` has had its connection from the start.
22
+ let hasConnected = status === "connected";
23
+ const lockHandler = options.setComponentLock ?? null;
24
+ const eventListeners = new Set();
25
+ const statusListeners = new Set();
26
+ // A copy: a listener that unsubscribes while being called must not skip its neighbour.
27
+ const notify = (listeners, value) => {
28
+ for (const listener of [...listeners])
29
+ callSafely(listener, value);
30
+ };
31
+ const subscribe = (listeners, listener) => {
32
+ listeners.add(listener);
33
+ return () => {
34
+ listeners.delete(listener);
35
+ };
36
+ };
37
+ const emit = (event) => notify(eventListeners, event);
38
+ return {
39
+ api: {
40
+ getStatus: () => status,
41
+ subscribeStatus: (listener) => subscribe(statusListeners, listener),
42
+ subscribe: (listener) => subscribe(eventListeners, listener),
43
+ setComponentLock: (args) => lockHandler
44
+ ? lockHandler(args)
45
+ : Promise.reject(new Error("[@rise-x/apps-sdk] component locks are not available on this live channel")),
46
+ },
47
+ emit,
48
+ setStatus(next) {
49
+ if (next === status)
50
+ return;
51
+ status = next;
52
+ notify(statusListeners, next);
53
+ if (next !== "connected")
54
+ return;
55
+ if (hasConnected)
56
+ emit({ type: "resync" });
57
+ hasConnected = true;
58
+ },
59
+ };
60
+ }
@@ -1,3 +1,4 @@
1
+ import type { LiveChannel } from "./liveChannel";
1
2
  import { type ResolvedAppManifest } from "./manifest";
2
3
  import type { DianaShell, ShellAiApi, ShellEnvironment, ShellUser } from "./shellBridge";
3
4
  export interface MockShellFixtures {
@@ -17,6 +18,7 @@ export interface CreateMockShellOptions {
17
18
  apiV4?: DianaShell["getApiV4"];
18
19
  fixtures?: MockShellFixtures;
19
20
  ai?: ShellAiApi | null;
21
+ live?: LiveChannel;
20
22
  dependencies?: ResolvedAppManifest["dependencies"];
21
23
  }
22
24
  export declare function createMockShell(overrides?: CreateMockShellOptions): DianaShell;
@@ -211,6 +211,7 @@ function createMockShell(overrides = {}) {
211
211
  // Standalone dev has no cache, outbox or sync engine — null is the honest answer for both.
212
212
  getOffline: () => null,
213
213
  getCache: () => null,
214
+ getLive: () => overrides.live?.api ?? null,
214
215
  navigate,
215
216
  };
216
217
  // Untyped marker so SDK internals (e.g. the query layer's dev diagnostics)
@@ -5,6 +5,7 @@ export { AppQueryProvider, useAppQueryClient } from "./context";
5
5
  export { getLiveEnvId, invalidateAppSdkQueries, type SdkMutationOptions, type SdkQueryOptions, } from "./shared";
6
6
  export { createQueryLayer, type QueryLayer } from "./layer";
7
7
  export { prefetchAppDependencies } from "./dependencies";
8
+ export { useLiveInvalidation, type LiveInvalidationOptions } from "./live";
8
9
  export { createFlowQueries, flowQueries, useFlow, useFlowConfig, useFlowLayout, useFlows, useFlowTask, type FindTaskQueryArgs, type FlowQueries, type ListFlowsQueryArgs, } from "./flows";
9
10
  export { createWorkQueries, dedupeRows, useDeleteWork, usePatchWorkData, useRelatedWork, useStartWork, useSubmitWork, useWork, useWorkAudit, useWorkData, useWorkRows, useWorkSearch, workQueries, type DeleteWorkVariables, type ListRelatedWorkQueryArgs, type ListWorkRowsQueryArgs, type PatchWorkDataVariables, type SearchWorkQueryArgs, type StartWorkVariables, type SubmitWorkVariables, type WorkQueries, } from "./work";
10
11
  export { assetQueries, createAssetQueries, useAsset, useAssetQuickSearch, useAssetRows, useAssetSearch, useAssetTypes, useCloneAsset, useCreateAsset, useDeleteAsset, useRelatedAssets, useStartEditAsset, type AssetQueries, type CloneAssetVariables, type CreateAssetVariables, type DeleteAssetVariables, type ListAssetRowsQueryArgs, type ListRelatedAssetsQueryArgs, type QuickSearchAssetsQueryArgs, type SearchAssetsQueryArgs, type StartEditAssetVariables, } from "./assets";
@@ -21,8 +21,8 @@
21
21
  // Deliberately NOT re-exported from the package root: apps that don't import
22
22
  // this subpath never load react-query.
23
23
  Object.defineProperty(exports, "__esModule", { value: true });
24
- exports.useAgentChatMessages = exports.useAgentChat = exports.useAgent = exports.createAgentQueries = exports.agentQueries = exports.useStartEditAsset = exports.useRelatedAssets = exports.useDeleteAsset = exports.useCreateAsset = exports.useCloneAsset = exports.useAssetTypes = exports.useAssetSearch = exports.useAssetRows = exports.useAssetQuickSearch = exports.useAsset = exports.createAssetQueries = exports.assetQueries = exports.workQueries = exports.useWorkSearch = exports.useWorkRows = exports.useWorkData = exports.useWorkAudit = exports.useWork = exports.useSubmitWork = exports.useStartWork = exports.useRelatedWork = exports.usePatchWorkData = exports.useDeleteWork = exports.dedupeRows = exports.createWorkQueries = exports.useFlowTask = exports.useFlows = exports.useFlowLayout = exports.useFlowConfig = exports.useFlow = exports.flowQueries = exports.createFlowQueries = exports.prefetchAppDependencies = exports.createQueryLayer = exports.invalidateAppSdkQueries = exports.getLiveEnvId = exports.useAppQueryClient = exports.AppQueryProvider = exports.shouldRetryConnectorError = exports.getFallbackAppClient = exports.createAppQueryClient = exports.searchCacheShape = exports.QUERY_KEY_ROOT = exports.queryKeys = exports.normalizeArgs = void 0;
25
- exports.ConnectorError = exports.useUpdateAgent = exports.useRenameAgentChat = exports.useDeleteAgentChat = exports.useDeleteAgent = exports.useCreateAgent = exports.useAgents = exports.useAgentChats = void 0;
24
+ exports.useAgentChat = exports.useAgent = exports.createAgentQueries = exports.agentQueries = exports.useStartEditAsset = exports.useRelatedAssets = exports.useDeleteAsset = exports.useCreateAsset = exports.useCloneAsset = exports.useAssetTypes = exports.useAssetSearch = exports.useAssetRows = exports.useAssetQuickSearch = exports.useAsset = exports.createAssetQueries = exports.assetQueries = exports.workQueries = exports.useWorkSearch = exports.useWorkRows = exports.useWorkData = exports.useWorkAudit = exports.useWork = exports.useSubmitWork = exports.useStartWork = exports.useRelatedWork = exports.usePatchWorkData = exports.useDeleteWork = exports.dedupeRows = exports.createWorkQueries = exports.useFlowTask = exports.useFlows = exports.useFlowLayout = exports.useFlowConfig = exports.useFlow = exports.flowQueries = exports.createFlowQueries = exports.useLiveInvalidation = exports.prefetchAppDependencies = exports.createQueryLayer = exports.invalidateAppSdkQueries = exports.getLiveEnvId = exports.useAppQueryClient = exports.AppQueryProvider = exports.shouldRetryConnectorError = exports.getFallbackAppClient = exports.createAppQueryClient = exports.searchCacheShape = exports.QUERY_KEY_ROOT = exports.queryKeys = exports.normalizeArgs = void 0;
25
+ exports.ConnectorError = exports.useUpdateAgent = exports.useRenameAgentChat = exports.useDeleteAgentChat = exports.useDeleteAgent = exports.useCreateAgent = exports.useAgents = exports.useAgentChats = exports.useAgentChatMessages = void 0;
26
26
  var keys_1 = require("./keys");
27
27
  Object.defineProperty(exports, "normalizeArgs", { enumerable: true, get: function () { return keys_1.normalizeArgs; } });
28
28
  Object.defineProperty(exports, "queryKeys", { enumerable: true, get: function () { return keys_1.queryKeys; } });
@@ -46,6 +46,8 @@ var layer_1 = require("./layer");
46
46
  Object.defineProperty(exports, "createQueryLayer", { enumerable: true, get: function () { return layer_1.createQueryLayer; } });
47
47
  var dependencies_1 = require("./dependencies");
48
48
  Object.defineProperty(exports, "prefetchAppDependencies", { enumerable: true, get: function () { return dependencies_1.prefetchAppDependencies; } });
49
+ var live_1 = require("./live");
50
+ Object.defineProperty(exports, "useLiveInvalidation", { enumerable: true, get: function () { return live_1.useLiveInvalidation; } });
49
51
  var flows_1 = require("./flows");
50
52
  Object.defineProperty(exports, "createFlowQueries", { enumerable: true, get: function () { return flows_1.createFlowQueries; } });
51
53
  Object.defineProperty(exports, "flowQueries", { enumerable: true, get: function () { return flows_1.flowQueries; } });
@@ -0,0 +1,14 @@
1
+ export interface LiveInvalidationOptions {
2
+ /**
3
+ * Only data writes in these flows, by flow origin id, refresh queries. A change that names no
4
+ * flow (`workUpdated`, `workDeleted`, an asset change, a write that named none) always does.
5
+ */
6
+ flowOriginIds?: readonly string[];
7
+ }
8
+ /**
9
+ * Marks this SDK's queries stale when a live event says what they hold changed: the work item's
10
+ * or asset's own queries and the listings (only the ones on screen refetch). A delete drops the
11
+ * item's queries, and a `resync` marks every work and asset query stale. Call it once, near the
12
+ * root of the app.
13
+ */
14
+ export declare function useLiveInvalidation(options?: LiveInvalidationOptions): void;
@@ -0,0 +1,115 @@
1
+ "use strict";
2
+ // Keeps this SDK's query cache current from the host's live events, so an app hears about other
3
+ // people's changes instead of polling. Does nothing on a host without live events, so keep
4
+ // the app's own refresh for those hosts.
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.useLiveInvalidation = useLiveInvalidation;
7
+ const react_1 = require("react");
8
+ const accessors_1 = require("../accessors");
9
+ const context_1 = require("./context");
10
+ const keys_1 = require("./keys");
11
+ const shared_1 = require("./shared");
12
+ // A form saved one field at a time is one event per field: collect a burst, refresh once.
13
+ const BATCH_MS = 300;
14
+ /**
15
+ * Marks this SDK's queries stale when a live event says what they hold changed: the work item's
16
+ * or asset's own queries and the listings (only the ones on screen refetch). A delete drops the
17
+ * item's queries, and a `resync` marks every work and asset query stale. Call it once, near the
18
+ * root of the app.
19
+ */
20
+ function useLiveInvalidation(options = {}) {
21
+ const client = (0, context_1.useAppQueryClient)();
22
+ // A key rather than the array, so an inline `flowOriginIds: [...]` doesn't subscribe each render.
23
+ const flowsKey = options.flowOriginIds?.join("\n");
24
+ (0, react_1.useEffect)(() => {
25
+ const live = (0, accessors_1.getShellLive)();
26
+ if (!live)
27
+ return;
28
+ const flows = flowsKey === undefined ? undefined : new Set(flowsKey.split("\n"));
29
+ // Id → whether it was deleted. A delete sticks over a later change in the same burst.
30
+ let works = new Map();
31
+ let assets = new Map();
32
+ let timer = null;
33
+ const mark = (ids, id, deleted) => ids.set(id, ids.get(id) || deleted);
34
+ const flush = () => {
35
+ timer = null;
36
+ invalidateChanges(client, works, assets);
37
+ works = new Map();
38
+ assets = new Map();
39
+ };
40
+ const off = live.subscribe((event) => {
41
+ switch (event.type) {
42
+ case "resync": {
43
+ const envId = (0, shared_1.getLiveEnvId)();
44
+ void client.invalidateQueries({
45
+ queryKey: keys_1.queryKeys.work.all(envId),
46
+ });
47
+ void client.invalidateQueries({
48
+ queryKey: keys_1.queryKeys.assets.all(envId),
49
+ });
50
+ return;
51
+ }
52
+ case "workData":
53
+ if (flows && event.flowOriginId && !flows.has(event.flowOriginId)) {
54
+ return;
55
+ }
56
+ mark(works, event.workId, false);
57
+ break;
58
+ case "workUpdated":
59
+ case "workDeleted":
60
+ mark(works, event.workId, event.type === "workDeleted");
61
+ break;
62
+ case "assetUpdated":
63
+ case "assetDeleted":
64
+ mark(assets, event.assetId, event.type === "assetDeleted");
65
+ break;
66
+ default:
67
+ return;
68
+ }
69
+ timer ?? (timer = setTimeout(flush, BATCH_MS));
70
+ });
71
+ return () => {
72
+ off();
73
+ if (timer !== null)
74
+ clearTimeout(timer);
75
+ };
76
+ }, [client, flowsKey]);
77
+ }
78
+ // The same keys the mutation hooks invalidate after an app's own write.
79
+ function invalidateChanges(client, works, assets) {
80
+ const envId = (0, shared_1.getLiveEnvId)();
81
+ const refresh = (queryKey, deleted) => {
82
+ if (deleted)
83
+ client.removeQueries({ queryKey });
84
+ else
85
+ void client.invalidateQueries({ queryKey });
86
+ };
87
+ for (const [workId, deleted] of works) {
88
+ refresh(keys_1.queryKeys.work.detail(envId, workId), deleted);
89
+ refresh(keys_1.queryKeys.work.dataAll(envId, workId), deleted);
90
+ refresh(keys_1.queryKeys.work.audit(envId, workId), deleted);
91
+ }
92
+ for (const [assetId, deleted] of assets) {
93
+ refresh(keys_1.queryKeys.assets.detail(envId, assetId), deleted);
94
+ }
95
+ // Listings project data, and a new or deleted item changes which rows they hold.
96
+ const listings = [
97
+ ...(works.size
98
+ ? [
99
+ keys_1.queryKeys.work.allRows(envId),
100
+ keys_1.queryKeys.work.searchAll(envId),
101
+ keys_1.queryKeys.work.relatedAll(envId),
102
+ ]
103
+ : []),
104
+ ...(assets.size
105
+ ? [
106
+ keys_1.queryKeys.assets.allRows(envId),
107
+ keys_1.queryKeys.assets.searchAll(envId),
108
+ keys_1.queryKeys.assets.quickSearchAll(envId),
109
+ keys_1.queryKeys.assets.relatedAll(envId),
110
+ ]
111
+ : []),
112
+ ];
113
+ for (const queryKey of listings)
114
+ void client.invalidateQueries({ queryKey });
115
+ }
@@ -1 +1,2 @@
1
- export { installShellBridge, getMutableShell, type InstallShellBridgeOptions, type MutableShell, } from './installShellBridge';
1
+ export { installShellBridge, getMutableShell, type InstallShellBridgeOptions, type MutableShell, } from "./installShellBridge";
2
+ export type { LiveHubConnection } from "./liveHub";
@@ -1,13 +1,27 @@
1
- import type { DianaShell, ShellEnvironment, ShellNavigate, ShellUser } from "../shellBridge";
1
+ import type { DianaShell, LiveStatus, ShellEnvironment, ShellNavigate, ShellUser } from "../shellBridge";
2
+ import { type LiveHubConnection } from "./liveHub";
2
3
  export interface MutableShell extends DianaShell {
3
4
  _setUser(user: ShellUser | null): void;
4
5
  _setEnvironment(env: ShellEnvironment | null): void;
5
6
  _setNavigate(fn: ShellNavigate): void;
7
+ /**
8
+ * Report the host's hub connection, or null while there is none, and the state it is in. Call
9
+ * it again whenever either changes. The bridge maps the hub's events for apps, moves their
10
+ * subscriptions to a new connection, and turns the state into the status every host reports.
11
+ */
12
+ _setLiveConnection(connection: LiveHubConnection | null, state: LiveStatus): void;
6
13
  }
7
14
  export type InstallShellBridgeOptions = Pick<DianaShell, "getApi" | "getApiV4"> & {
8
15
  getAi?: DianaShell["getAi"];
9
16
  getOffline?: DianaShell["getOffline"];
10
17
  getCache?: DianaShell["getCache"];
18
+ /**
19
+ * Whether this host has a hub connection to wire (through `_setLiveConnection`). Defaults to
20
+ * true: `getLive()` then answers a channel whose status is `connecting` until the host wires a
21
+ * connection. A host with no hub passes false, and `getLive()` answers null, so an app keeps
22
+ * its own reads rather than wait for a connection that never comes.
23
+ */
24
+ live?: boolean;
11
25
  };
12
26
  export declare function installShellBridge(options: InstallShellBridgeOptions): void;
13
27
  export declare function getMutableShell(): MutableShell | null;
@@ -4,6 +4,7 @@ exports.installShellBridge = installShellBridge;
4
4
  exports.getMutableShell = getMutableShell;
5
5
  const react_router_dom_1 = require("react-router-dom");
6
6
  const shellBridge_1 = require("../shellBridge");
7
+ const liveHub_1 = require("./liveHub");
7
8
  function createSubscribers() {
8
9
  const listeners = new Set();
9
10
  return {
@@ -56,12 +57,13 @@ function isEqualEnvironment(a, b) {
56
57
  function installShellBridge(options) {
57
58
  if (window.__DIANA_SHELL__)
58
59
  return;
59
- const { getApi, getApiV4, getAi = () => null, getOffline = () => null, getCache = () => null, } = options;
60
+ const { getApi, getApiV4, getAi = () => null, getOffline = () => null, getCache = () => null, live = true, } = options;
60
61
  let currentUser = null;
61
62
  let currentEnvironment = null;
62
63
  let navigate = defaultNavigate;
63
64
  const userSubs = createSubscribers();
64
65
  const envSubs = createSubscribers();
66
+ const liveHub = live ? (0, liveHub_1.createLiveHub)() : null;
65
67
  // Stable shim so apps can hold onto shell.navigate across re-renders —
66
68
  // internally delegates to whichever NavigateFunction the router currently owns.
67
69
  // Branch on typeof to pick the right overload instead of casting.
@@ -82,6 +84,7 @@ function installShellBridge(options) {
82
84
  getAi,
83
85
  getOffline,
84
86
  getCache,
87
+ getLive: () => liveHub?.api ?? null,
85
88
  navigate: navigateShim,
86
89
  _setUser(user) {
87
90
  if (isEqualUser(currentUser, user))
@@ -98,6 +101,9 @@ function installShellBridge(options) {
98
101
  _setNavigate(fn) {
99
102
  navigate = fn;
100
103
  },
104
+ _setLiveConnection(connection, state) {
105
+ liveHub?.update(connection, state);
106
+ },
101
107
  };
102
108
  window.__DIANA_SHELL__ = shell;
103
109
  }
@@ -0,0 +1,25 @@
1
+ import type { LiveApi, LiveEvent, LiveStatus } from "../shellBridge";
2
+ /** The part of a SignalR hub connection the bridge uses. A `HubConnection` fits as it is. */
3
+ export interface LiveHubConnection {
4
+ on(method: string, handler: (...args: unknown[]) => void): void;
5
+ off(method: string, handler: (...args: unknown[]) => void): void;
6
+ invoke(method: string, ...args: unknown[]): Promise<unknown>;
7
+ }
8
+ /** The hub events apps see, by their wire names. Everything else on the connection is the host's. */
9
+ export declare const LIVE_HUB_EVENTS: readonly ["DataPatch", "DataObjectPatch", "WorkUpdated", "WorkDeleted", "EntityUpdated", "EntityDeleted", "ComponentLockUpdated"];
10
+ /**
11
+ * Turns one hub event into the event an app sees. Null for an event that is not for apps (a
12
+ * patch to a resource that is not a work item) or a payload that is not what the platform sends:
13
+ * a push from the server must never throw into the connection.
14
+ */
15
+ export declare function mapLiveEvent(name: string, payload: unknown): LiveEvent | null;
16
+ export interface LiveHub {
17
+ readonly api: LiveApi;
18
+ /**
19
+ * Report the connection the host holds now, or null while there is none, and the state it is
20
+ * in. Call it again whenever either changes.
21
+ */
22
+ update(connection: LiveHubConnection | null, state: LiveStatus): void;
23
+ }
24
+ /** The live channel a host's bridge offers, fed from whichever hub connection the host holds. */
25
+ export declare function createLiveHub(): LiveHub;