@rise-x/apps-sdk 0.19.0 → 0.20.1

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 (40) hide show
  1. package/API.md +145 -0
  2. package/README.md +177 -10
  3. package/build/accessors.d.ts +2 -1
  4. package/build/accessors.js +10 -0
  5. package/build/connectors/assets.d.ts +5 -2
  6. package/build/connectors/assets.js +22 -6
  7. package/build/connectors/index.d.ts +1 -1
  8. package/build/connectors/types.d.ts +8 -0
  9. package/build/connectors/types.js +36 -4
  10. package/build/connectors/work.d.ts +1 -0
  11. package/build/connectors/work.js +66 -3
  12. package/build/dependencies/bound.d.ts +2 -2
  13. package/build/index.d.ts +2 -1
  14. package/build/index.js +4 -1
  15. package/build/live/index.d.ts +43 -0
  16. package/build/live/index.js +183 -0
  17. package/build/liveChannel.d.ts +32 -0
  18. package/build/liveChannel.js +60 -0
  19. package/build/mockShell.d.ts +2 -0
  20. package/build/mockShell.js +1 -0
  21. package/build/query/assets.d.ts +4 -4
  22. package/build/query/assets.js +13 -7
  23. package/build/query/index.d.ts +1 -0
  24. package/build/query/index.js +4 -2
  25. package/build/query/live.d.ts +14 -0
  26. package/build/query/live.js +115 -0
  27. package/build/shell/index.d.ts +2 -1
  28. package/build/shell/installShellBridge.d.ts +15 -1
  29. package/build/shell/installShellBridge.js +7 -1
  30. package/build/shell/liveHub.d.ts +25 -0
  31. package/build/shell/liveHub.js +201 -0
  32. package/build/shellBridge.d.ts +116 -1
  33. package/build/shellBridge.js +5 -1
  34. package/build/ui/demo.html +199 -197
  35. package/build/ui/standalone.js +60 -60
  36. package/build/ui/styles.css +1 -1
  37. package/build/ui/theme.css +9 -5
  38. package/live/package.json +8 -0
  39. package/package.json +7 -1
  40. package/template/AGENTS.md +6 -0
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.work = exports.resolveFlowRef = void 0;
4
4
  exports.buildAdditionalProperties = buildAdditionalProperties;
5
+ exports.readWorkBack = readWorkBack;
5
6
  exports.createWorkConnector = createWorkConnector;
6
7
  const _internal_1 = require("../_internal");
7
8
  const errors_1 = require("./errors");
@@ -39,22 +40,53 @@ function buildAdditionalProperties(properties) {
39
40
  isExpandedProperty: false,
40
41
  }));
41
42
  }
43
+ // v3 answers carry actions without event names and a step state as `status`, so writes that
44
+ // answer from v3 read the item from v4. The write already happened: a failed read must not hide
45
+ // it. Network only, since a cached copy predates the write.
46
+ async function readWorkBack(deps, workId, written, signal) {
47
+ let data;
48
+ try {
49
+ ({ data } = await deps
50
+ .shell()
51
+ .getApiV4("work")
52
+ .get(`/api/v4/work/${workId}`, {
53
+ signal,
54
+ timeout: readPolicy_1.READ_TIMEOUT_MS,
55
+ }));
56
+ }
57
+ catch {
58
+ // A host with no v4 work client counts as a failed read, not a failed write.
59
+ }
60
+ const detail = (0, types_1.mapWorkDetail)(data ?? {});
61
+ return detail.id
62
+ ? detail
63
+ : {
64
+ ...written,
65
+ id: workId,
66
+ displayName: written.displayName || workId,
67
+ status: undefined,
68
+ actions: [],
69
+ };
70
+ }
42
71
  function createWorkConnector(deps = { shell: _internal_1.requireShell }) {
43
72
  const workApi = () => deps.shell().getApiV4("work");
73
+ const readBack = (workId, written, signal) => readWorkBack(deps, workId, written, signal);
44
74
  // start/submit go through the v3 flow engine — the same endpoints the shell
45
75
  // uses. The v4 `work/submit/*` routes only ever existed on the unreleased
46
76
  // flow-engine branch and 404 on deployed APIs.
47
77
  const start = async (args) => {
78
+ let created;
48
79
  try {
49
80
  const { data } = await deps
50
81
  .shell()
51
82
  .getApi()
52
83
  .post(`/api/v3/flow/${args.flowId}/startAt`, args.data ?? {}, { params: { stepName: args.stepName }, signal: args.signal });
53
- return (0, types_1.mapWorkDetail)(data ?? {});
84
+ created = (0, types_1.mapWorkDetail)(data ?? {});
54
85
  }
55
86
  catch (e) {
56
87
  throw (0, errors_1.toConnectorError)(e);
57
88
  }
89
+ return readBack(created.id, created, args.signal);
58
90
  };
59
91
  const get = (workId, opts = {}) => (0, readPolicy_1.resolveRead)({
60
92
  shell: deps.shell,
@@ -119,17 +151,48 @@ function createWorkConnector(deps = { shell: _internal_1.requireShell }) {
119
151
  throw (0, errors_1.toConnectorError)(e);
120
152
  }
121
153
  };
154
+ // Without the action set's name, `Submit` matches the step's autosubmit event: a 200 that moves
155
+ // nothing. Any miss sends no name, as before, so a call that worked without one still does.
156
+ const resolveStepName = async (args) => {
157
+ try {
158
+ const detail = await get(args.workId, { signal: args.signal });
159
+ const actionSetIds = new Set((detail?.actions ?? [])
160
+ .filter((a) => (a.eventName ?? a.name) === args.actionName)
161
+ .map((a) => a.actionSetId));
162
+ const [actionSetId] = actionSetIds;
163
+ if (!detail?.flowId || actionSetIds.size !== 1 || !actionSetId) {
164
+ return undefined;
165
+ }
166
+ // The work's own flow version: the latest one may have renamed the action set.
167
+ const { data } = await deps
168
+ .shell()
169
+ .getApiV4("config")
170
+ .get(`/api/v4/config/flow/${detail.flowId}`, {
171
+ signal: args.signal,
172
+ });
173
+ return (0, types_1.mapFlowConfig)(detail.flowId, data ?? {})
174
+ .steps.flatMap((s) => s.tasks)
175
+ .flatMap((t) => t.actionSets ?? [])
176
+ .find((a) => a.id === actionSetId)?.name;
177
+ }
178
+ catch {
179
+ return undefined;
180
+ }
181
+ };
122
182
  const submit = async (args) => {
183
+ let submitted;
123
184
  try {
185
+ const stepName = args.stepName ?? (await resolveStepName(args));
124
186
  const { data } = await deps
125
187
  .shell()
126
188
  .getApi()
127
- .post(`/api/v3/flow/submit/${args.workId}`, { stepName: args.stepName }, { params: { eventName: args.actionName }, signal: args.signal });
128
- return (0, types_1.mapWorkDetail)(data ?? {});
189
+ .post(`/api/v3/flow/submit/${args.workId}`, { stepName }, { params: { eventName: args.actionName }, signal: args.signal });
190
+ submitted = (0, types_1.mapWorkDetail)(data ?? {});
129
191
  }
130
192
  catch (e) {
131
193
  throw (0, errors_1.toConnectorError)(e);
132
194
  }
195
+ return readBack(args.workId, submitted, args.signal);
133
196
  };
134
197
  const del = async (workId, opts = {}) => {
135
198
  try {
@@ -1,5 +1,5 @@
1
1
  import { type AgentChatSession, type AgentsConnector, type CreateAgentChatArgs, type ListChatsArgs, type RunAgentArgs } from "../connectors/agents";
2
- import { type AssetRowPage, type AssetSearchPage, type AssetsConnector, type CreateAssetArgs, type IterateAssetRowsArgs, type ListAssetRowsArgs, type QuickSearchAssetsArgs } from "../connectors/assets";
2
+ import { type AssetDraft, type AssetRowPage, type AssetSearchPage, type AssetsConnector, type CreateAssetArgs, type IterateAssetRowsArgs, type ListAssetRowsArgs, type QuickSearchAssetsArgs } from "../connectors/assets";
3
3
  import { type FlowsConnector } from "../connectors/flows";
4
4
  import { type IntegrationsConnector, type InvokeIntegrationEndpointArgs } from "../connectors/integrations";
5
5
  import type { SearchArgs } from "../connectors/search";
@@ -25,7 +25,7 @@ export interface BoundAssetsSurface {
25
25
  iterate(args?: Omit<IterateAssetRowsArgs, "type">): AsyncIterable<AssetSummary>;
26
26
  search(args?: SearchArgs): Promise<AssetSearchPage>;
27
27
  quickSearch(args?: Omit<QuickSearchAssetsArgs, "typeOriginId">): Promise<AssetSummary[]>;
28
- create(args?: Omit<CreateAssetArgs, "type">): Promise<WorkDetail>;
28
+ create(args?: Omit<CreateAssetArgs, "type">): Promise<AssetDraft>;
29
29
  }
30
30
  export interface BoundAgentSurface {
31
31
  get(opts?: {
package/build/index.d.ts CHANGED
@@ -1,7 +1,8 @@
1
1
  export * from "./shellBridge";
2
2
  export * from "./lifecycle";
3
3
  export { useShellUser, useShellEnvironment, useShellNavigate } from "./hooks";
4
- export { getShell, getShellAi, getShellApi, getShellApiV4, getShellEnvironment, getShellUser, } from "./accessors";
4
+ export { getShell, getShellAi, getShellApi, getShellApiV4, getShellEnvironment, getShellLive, getShellUser, } from "./accessors";
5
+ export { createLiveChannel, type ComponentLockHandler, type CreateLiveChannelOptions, type LiveChannel, } from "./liveChannel";
5
6
  export { createMockShell, isMockShell, type CreateMockShellOptions, type MockShellFixtures, } from "./mockShell";
6
7
  export { registerTopBarActions, type TopBarAction } from "./topBar";
7
8
  export { setShellBreadcrumb, useShellBreadcrumb, type ShellBreadcrumbBack, type ShellBreadcrumbBadge, type ShellBreadcrumbItem, } from "./breadcrumb";
package/build/index.js CHANGED
@@ -14,7 +14,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.resolveAppManifest = exports.DEFAULT_APP_ENVIRONMENT = exports.APP_MANIFEST_FILENAME = exports.APP_DEPENDENCY_KINDS = exports.useShellBreadcrumb = exports.setShellBreadcrumb = exports.registerTopBarActions = exports.isMockShell = exports.createMockShell = exports.getShellUser = exports.getShellEnvironment = exports.getShellApiV4 = exports.getShellApi = exports.getShellAi = exports.getShell = exports.useShellNavigate = exports.useShellEnvironment = exports.useShellUser = void 0;
17
+ exports.resolveAppManifest = exports.DEFAULT_APP_ENVIRONMENT = exports.APP_MANIFEST_FILENAME = exports.APP_DEPENDENCY_KINDS = exports.useShellBreadcrumb = exports.setShellBreadcrumb = exports.registerTopBarActions = exports.isMockShell = exports.createMockShell = exports.createLiveChannel = exports.getShellUser = exports.getShellLive = exports.getShellEnvironment = exports.getShellApiV4 = exports.getShellApi = exports.getShellAi = exports.getShell = exports.useShellNavigate = exports.useShellEnvironment = exports.useShellUser = void 0;
18
18
  __exportStar(require("./shellBridge"), exports);
19
19
  __exportStar(require("./lifecycle"), exports);
20
20
  var hooks_1 = require("./hooks");
@@ -27,7 +27,10 @@ Object.defineProperty(exports, "getShellAi", { enumerable: true, get: function (
27
27
  Object.defineProperty(exports, "getShellApi", { enumerable: true, get: function () { return accessors_1.getShellApi; } });
28
28
  Object.defineProperty(exports, "getShellApiV4", { enumerable: true, get: function () { return accessors_1.getShellApiV4; } });
29
29
  Object.defineProperty(exports, "getShellEnvironment", { enumerable: true, get: function () { return accessors_1.getShellEnvironment; } });
30
+ Object.defineProperty(exports, "getShellLive", { enumerable: true, get: function () { return accessors_1.getShellLive; } });
30
31
  Object.defineProperty(exports, "getShellUser", { enumerable: true, get: function () { return accessors_1.getShellUser; } });
32
+ var liveChannel_1 = require("./liveChannel");
33
+ Object.defineProperty(exports, "createLiveChannel", { enumerable: true, get: function () { return liveChannel_1.createLiveChannel; } });
31
34
  var mockShell_1 = require("./mockShell");
32
35
  Object.defineProperty(exports, "createMockShell", { enumerable: true, get: function () { return mockShell_1.createMockShell; } });
33
36
  Object.defineProperty(exports, "isMockShell", { enumerable: true, get: function () { return mockShell_1.isMockShell; } });
@@ -0,0 +1,43 @@
1
+ import type { LiveEvent, LiveStatus, WorkComponentLock } from "../shellBridge";
2
+ export type { LiveApi, LiveEvent, LiveStatus, SetComponentLockArgs, WorkComponentLock, } from "../shellBridge";
3
+ /** What `useLiveStatus` reports: the host's status, or `unavailable` when it offers no live events. */
4
+ export type LiveAvailability = LiveStatus | "unavailable";
5
+ /**
6
+ * The host's live connection state. Re-renders on a change. `unavailable` means the host offers
7
+ * no live events at all, so keep whatever fallback you have; `connected` is the only state in
8
+ * which events arrive.
9
+ */
10
+ export declare function useLiveStatus(): LiveAvailability;
11
+ /**
12
+ * Calls `handler` with each live event while the component is mounted. The latest `handler` is
13
+ * always the one called, so an inline function does not subscribe again. Events arrive for every
14
+ * work item and asset the user can see, across their ecosystems, and are best-effort: a `resync`
15
+ * event says some were missed.
16
+ */
17
+ export declare function useLiveEvents(handler: (event: LiveEvent) => void, options?: {
18
+ enabled?: boolean;
19
+ }): void;
20
+ /** How often an open editor says its lock again, so the platform can tell a lock is still held. */
21
+ export declare const LOCK_REFRESH_MS = 60000;
22
+ /**
23
+ * Shows that the user is editing: takes a component lock on `workId` while `active`, says it again
24
+ * every {@link LOCK_REFRESH_MS} and after a reconnect, and releases it when `active` ends or the
25
+ * component unmounts. Others see it through `useWorkLocks`.
26
+ *
27
+ * `componentId` identifies the editor and must be a GUID. Use the same one for the same editor in
28
+ * every session, so other users' screens can tell which editor is open. The platform keeps one
29
+ * lock per user per work, so this lock and one the host's own editor takes for the same user
30
+ * replace each other. Several holds in one app are fine: the most recent shows, and releasing it
31
+ * takes the previous one again.
32
+ *
33
+ * Advisory only: it never gates a write, and it does nothing on a host without live events.
34
+ * Without a connection the lock is not sent, and the app keeps working.
35
+ */
36
+ export declare function useComponentLock(workId: string | undefined, componentId: string, active: boolean, dataPath?: string): void;
37
+ /**
38
+ * Who has an editor open on this work right now: every user's lock, yours included. Starts from
39
+ * the locks on a fresh read of the work and follows `lock` events, so it stays current without
40
+ * polling. Empty on a host without live events. A lock from a closed browser can linger on
41
+ * the platform, so compare `at` with the age you are willing to believe.
42
+ */
43
+ export declare function useWorkLocks(workId: string | undefined): WorkComponentLock[];
@@ -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)
@@ -1,7 +1,7 @@
1
1
  import { type InfiniteData, type UseInfiniteQueryResult, type UseQueryResult } from "@tanstack/react-query";
2
- import { type AssetRowPage, type AssetSearchPage, type AssetsConnector, type CreateAssetArgs, type ListAssetRowsArgs, type ListRelatedAssetsArgs, type QuickSearchAssetsArgs, type SearchAssetsArgs, type StartEditAssetArgs } from "../connectors/assets";
2
+ import { type AssetDraft, type AssetRowPage, type AssetSearchPage, type AssetsConnector, type CreateAssetArgs, type ListAssetRowsArgs, type ListRelatedAssetsArgs, type QuickSearchAssetsArgs, type SearchAssetsArgs, type StartEditAssetArgs } from "../connectors/assets";
3
3
  import type { ConnectorError } from "../connectors/errors";
4
- import type { AssetDetail, AssetSummary, AssetType, WorkDetail } from "../connectors/types";
4
+ import type { AssetDetail, AssetSummary, AssetType } from "../connectors/types";
5
5
  import { type QueryEnvId } from "./keys";
6
6
  import { type SdkMutationOptions, type SdkQueryOptions } from "./shared";
7
7
  export type SearchAssetsQueryArgs = Omit<SearchAssetsArgs, "page" | "signal">;
@@ -73,9 +73,9 @@ export declare function useAssetQuickSearch(args: QuickSearchAssetsQueryArgs, op
73
73
  export declare function useAssetRows(args: ListAssetRowsQueryArgs, options?: SdkQueryOptions): UseInfiniteQueryResult<InfiniteData<AssetRowPage>, ConnectorError>;
74
74
  export declare function useRelatedAssets(args: ListRelatedAssetsQueryArgs, options?: SdkQueryOptions): UseQueryResult<AssetSummary[], ConnectorError>;
75
75
  export type CreateAssetVariables = Omit<CreateAssetArgs, "signal">;
76
- export declare function useCreateAsset(options?: SdkMutationOptions<WorkDetail, CreateAssetVariables>): import("@tanstack/react-query").UseMutationResult<WorkDetail, ConnectorError, CreateAssetVariables, unknown>;
76
+ export declare function useCreateAsset(options?: SdkMutationOptions<AssetDraft, CreateAssetVariables>): import("@tanstack/react-query").UseMutationResult<AssetDraft, ConnectorError, CreateAssetVariables, unknown>;
77
77
  export type StartEditAssetVariables = Omit<StartEditAssetArgs, "signal">;
78
- export declare function useStartEditAsset(options?: SdkMutationOptions<WorkDetail, StartEditAssetVariables>): import("@tanstack/react-query").UseMutationResult<WorkDetail, ConnectorError, StartEditAssetVariables, unknown>;
78
+ export declare function useStartEditAsset(options?: SdkMutationOptions<AssetDraft, StartEditAssetVariables>): import("@tanstack/react-query").UseMutationResult<AssetDraft, ConnectorError, StartEditAssetVariables, unknown>;
79
79
  export interface CloneAssetVariables {
80
80
  assetId: string;
81
81
  }
@@ -16,10 +16,11 @@ exports.useDeleteAsset = useDeleteAsset;
16
16
  // their cache-consistency rules. Built-in invalidation runs before the
17
17
  // caller's onSuccess — composed, never replaced.
18
18
  //
19
- // Note the platform's edit model: create/startEdit return a DRAFT WORK ITEM —
20
- // the asset only materializes when that draft is saved via work.submit
21
- // (useSubmitWork), which is why those mutations invalidate the WORK listings
22
- // here and useSubmitWork (query/work.ts) invalidates the assets scope.
19
+ // Note the platform's edit model: create/startEdit return a DRAFT WORK ITEM,
20
+ // saved via work.submit (useSubmitWork). Both mutations invalidate the WORK
21
+ // listings here. create also saves a draft asset at once and startEdit sets
22
+ // the asset's draftWorkId, so they invalidate asset caches too; useSubmitWork
23
+ // (query/work.ts) invalidates the assets scope when the draft is saved.
23
24
  const react_query_1 = require("@tanstack/react-query");
24
25
  const assets_1 = require("../connectors/assets");
25
26
  const search_1 = require("../connectors/search");
@@ -126,18 +127,19 @@ function useRelatedAssets(args, options) {
126
127
  function useCreateAsset(options) {
127
128
  return (0, shared_1.useSdkMutation)((vars) => assets_1.assets.create(vars), (client) => {
128
129
  const envId = (0, shared_1.getLiveEnvId)();
129
- // CROSS-DOMAIN: the draft shows up as a WORK item; the asset itself
130
- // only exists after submit.
130
+ // CROSS-DOMAIN: the draft shows up as a WORK item, and the platform
131
+ // saves the asset as a draft at once, so asset listings go stale too.
131
132
  void client.invalidateQueries({
132
133
  queryKey: keys_1.queryKeys.work.allRows(envId),
133
134
  });
134
135
  void client.invalidateQueries({
135
136
  queryKey: keys_1.queryKeys.work.searchAll(envId),
136
137
  });
138
+ void client.invalidateQueries({ queryKey: keys_1.queryKeys.assets.all(envId) });
137
139
  }, options);
138
140
  }
139
141
  function useStartEditAsset(options) {
140
- return (0, shared_1.useSdkMutation)((vars) => assets_1.assets.startEdit(vars), (client) => {
142
+ return (0, shared_1.useSdkMutation)((vars) => assets_1.assets.startEdit(vars), (client, _data, vars) => {
141
143
  const envId = (0, shared_1.getLiveEnvId)();
142
144
  // CROSS-DOMAIN: same draft-as-work-item model as useCreateAsset.
143
145
  void client.invalidateQueries({
@@ -146,6 +148,10 @@ function useStartEditAsset(options) {
146
148
  void client.invalidateQueries({
147
149
  queryKey: keys_1.queryKeys.work.searchAll(envId),
148
150
  });
151
+ // The asset's draftWorkId now names this draft.
152
+ void client.invalidateQueries({
153
+ queryKey: keys_1.queryKeys.assets.detail(envId, vars.assetId),
154
+ });
149
155
  }, options);
150
156
  }
151
157
  function useCloneAsset(options) {
@@ -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;