@rise-x/apps-sdk 0.11.1 → 0.15.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 (86) hide show
  1. package/README.md +915 -19
  2. package/build/_internal.d.ts +4 -1
  3. package/build/_internal.js +67 -0
  4. package/build/cli/index.d.ts +7 -1
  5. package/build/cli/index.js +68 -14
  6. package/build/cli/scan.d.ts +60 -0
  7. package/build/cli/scan.js +725 -0
  8. package/build/cli/validate.d.ts +33 -0
  9. package/build/cli/validate.js +169 -0
  10. package/build/connectors/agents.d.ts +10 -6
  11. package/build/connectors/agents.js +59 -44
  12. package/build/connectors/attachments.d.ts +51 -0
  13. package/build/connectors/attachments.js +76 -0
  14. package/build/connectors/errors.js +24 -0
  15. package/build/connectors/flows.d.ts +13 -2
  16. package/build/connectors/flows.js +64 -19
  17. package/build/connectors/index.d.ts +5 -1
  18. package/build/connectors/index.js +14 -2
  19. package/build/connectors/integrations.d.ts +29 -0
  20. package/build/connectors/integrations.js +32 -0
  21. package/build/connectors/offline.d.ts +34 -0
  22. package/build/connectors/offline.js +135 -0
  23. package/build/connectors/readPolicy.d.ts +29 -0
  24. package/build/connectors/readPolicy.js +105 -0
  25. package/build/connectors/types.d.ts +75 -0
  26. package/build/connectors/types.js +128 -0
  27. package/build/connectors/vectorStores.d.ts +45 -0
  28. package/build/connectors/vectorStores.js +199 -0
  29. package/build/connectors/work.d.ts +14 -2
  30. package/build/connectors/work.js +43 -19
  31. package/build/dependencies/bound.d.ts +87 -0
  32. package/build/dependencies/bound.js +207 -0
  33. package/build/dependencies/index.d.ts +2 -0
  34. package/build/dependencies/index.js +13 -0
  35. package/build/dependencyRegistry.d.ts +15 -0
  36. package/build/dependencyRegistry.js +28 -0
  37. package/build/index.d.ts +2 -1
  38. package/build/index.js +12 -1
  39. package/build/lifecycle.d.ts +10 -1
  40. package/build/manifest.d.ts +69 -0
  41. package/build/manifest.js +229 -0
  42. package/build/manifestSource.d.ts +27 -0
  43. package/build/manifestSource.js +99 -0
  44. package/build/mockShell.d.ts +2 -0
  45. package/build/mockShell.js +13 -0
  46. package/build/query/client.js +9 -1
  47. package/build/query/dependencies.d.ts +22 -0
  48. package/build/query/dependencies.js +73 -0
  49. package/build/query/flows.d.ts +8 -8
  50. package/build/query/index.d.ts +1 -0
  51. package/build/query/index.js +4 -2
  52. package/build/query/layer.d.ts +9 -9
  53. package/build/query/shared.js +10 -0
  54. package/build/query/work.d.ts +4 -4
  55. package/build/rsbuild/index.d.ts +3 -1
  56. package/build/rsbuild/index.js +35 -1
  57. package/build/rsbuild/riseAppManifestPlugin.d.ts +19 -0
  58. package/build/rsbuild/riseAppManifestPlugin.js +79 -0
  59. package/build/shell/installShellBridge.d.ts +2 -0
  60. package/build/shell/installShellBridge.js +3 -1
  61. package/build/shellBridge.d.ts +233 -1
  62. package/build/shellBridge.js +8 -7
  63. package/build/ui/classes.json +2 -2
  64. package/build/ui/components/app-frame.d.ts +1 -1
  65. package/build/ui/components/data-table.d.ts +39 -4
  66. package/build/ui/components/statistic.d.ts +1 -1
  67. package/build/ui/demo.html +671 -543
  68. package/build/ui/shadcn.css +629 -0
  69. package/build/ui/standalone.js +45 -44
  70. package/build/ui/styles.css +1 -1
  71. package/build/ui/tailwind.css +12 -0
  72. package/build/ui/theme.css +412 -0
  73. package/build/ui/tw-animate.css +1 -0
  74. package/build/webpack/index.d.ts +1 -0
  75. package/build/webpack/index.js +7 -0
  76. package/build/webpack/riseAppManifestPlugin.d.ts +61 -0
  77. package/build/webpack/riseAppManifestPlugin.js +103 -0
  78. package/dependencies/package.json +8 -0
  79. package/package.json +17 -4
  80. package/template/AGENTS.md +34 -4
  81. package/template/README.md +85 -2
  82. package/template/package.json +4 -0
  83. package/template/rise-x-app.json +4 -0
  84. package/template/src/App.tsx +7 -17
  85. package/template/src/styles.css +5 -0
  86. package/webpack/package.json +8 -0
@@ -0,0 +1,33 @@
1
+ import { type ResolvedAppDependency } from "../manifest";
2
+ import { type ScanResult } from "./scan";
3
+ import type { CliFlags } from "./index";
4
+ export interface ValidateArgs {
5
+ positional: string[];
6
+ flags: CliFlags;
7
+ }
8
+ export interface ValidatedEnvironment {
9
+ environment: string;
10
+ ok: boolean;
11
+ dependencies?: Record<string, ResolvedAppDependency>;
12
+ error?: string;
13
+ }
14
+ export interface ValidateResult {
15
+ ok: boolean;
16
+ manifest: string | null;
17
+ environments: ValidatedEnvironment[];
18
+ scan?: ScanResult;
19
+ }
20
+ /**
21
+ * Validates an app's `rise-x-app.json` against EVERY environment it declares,
22
+ * which is what a build cannot do: a build resolves the one environment it
23
+ * targets, so `pnpm build` says nothing about whether the prod ids are intact.
24
+ *
25
+ * Structural only — it never contacts the API, so it cannot tell you an id has
26
+ * been deleted from the target ecosystem. Neither does the deploy, which checks
27
+ * the manifest's shape and never looks the ids up: a stale id surfaces in the
28
+ * running app.
29
+ *
30
+ * Also scans app source for hardcoded ids and reports them as warnings, since a
31
+ * manifest can be perfectly valid and still be bypassed by a GUID literal.
32
+ */
33
+ export declare function validate(args: ValidateArgs): Promise<ValidateResult>;
@@ -0,0 +1,169 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.validate = validate;
37
+ const path = __importStar(require("node:path"));
38
+ const manifest_1 = require("../manifest");
39
+ const manifestSource_1 = require("../manifestSource");
40
+ const scan_1 = require("./scan");
41
+ /**
42
+ * The environments to check. `environments` is untrusted here — it has not been
43
+ * through the resolver yet — so anything malformed falls back to a single pass
44
+ * that lets the resolver report the malformed list itself.
45
+ */
46
+ function environmentsToCheck(source, explicit) {
47
+ if (explicit)
48
+ return [explicit];
49
+ const declared = (0, manifest_1.isRecord)(source) ? source.environments : undefined;
50
+ if (!Array.isArray(declared) ||
51
+ declared.length === 0 ||
52
+ !declared.every((name) => typeof name === "string")) {
53
+ return [manifest_1.DEFAULT_APP_ENVIRONMENT];
54
+ }
55
+ return declared;
56
+ }
57
+ function idOf(dependency) {
58
+ switch (dependency.kind) {
59
+ case "agent":
60
+ return dependency.agentId;
61
+ case "integration":
62
+ return `${dependency.integrationId}/${dependency.endpointId}`;
63
+ case "flow":
64
+ case "assetType":
65
+ return dependency.flowOriginId;
66
+ }
67
+ }
68
+ function report(result, showDismissed) {
69
+ if (!result.manifest) {
70
+ console.log("");
71
+ console.log(` No ${manifest_1.APP_MANIFEST_FILENAME}: the app declares no dependencies, and the build emits none.`);
72
+ console.log("");
73
+ // An app with no manifest is the case where the scan matters most: the ids
74
+ // it needs are somewhere, and nowhere is the manifest.
75
+ if (result.scan)
76
+ (0, scan_1.reportScan)(result.scan, showDismissed);
77
+ return;
78
+ }
79
+ console.log("");
80
+ console.log(` ${result.manifest}`);
81
+ console.log("");
82
+ for (const env of result.environments) {
83
+ if (!env.ok) {
84
+ console.log(` FAIL ${env.environment}`);
85
+ for (const line of (env.error ?? "").split("\n")) {
86
+ console.log(` ${line}`);
87
+ }
88
+ console.log("");
89
+ continue;
90
+ }
91
+ const entries = Object.entries(env.dependencies ?? {});
92
+ const count = entries.length === 1 ? "1 dependency" : `${entries.length} dependencies`;
93
+ console.log(` OK ${env.environment} — ${count}`);
94
+ const width = Math.max(0, ...entries.map(([alias]) => alias.length));
95
+ for (const [alias, dependency] of entries) {
96
+ console.log(` ${alias.padEnd(width)} ${dependency.kind.padEnd(11)} ${idOf(dependency)}`);
97
+ }
98
+ console.log("");
99
+ }
100
+ if (result.scan)
101
+ (0, scan_1.reportScan)(result.scan, showDismissed);
102
+ const failed = result.environments.filter((env) => !env.ok).length;
103
+ if (failed > 0) {
104
+ console.log(` ${failed} of ${result.environments.length} environments failed. Fix them before you deploy.`);
105
+ console.log("");
106
+ }
107
+ }
108
+ /**
109
+ * Validates an app's `rise-x-app.json` against EVERY environment it declares,
110
+ * which is what a build cannot do: a build resolves the one environment it
111
+ * targets, so `pnpm build` says nothing about whether the prod ids are intact.
112
+ *
113
+ * Structural only — it never contacts the API, so it cannot tell you an id has
114
+ * been deleted from the target ecosystem. Neither does the deploy, which checks
115
+ * the manifest's shape and never looks the ids up: a stale id surfaces in the
116
+ * running app.
117
+ *
118
+ * Also scans app source for hardcoded ids and reports them as warnings, since a
119
+ * manifest can be perfectly valid and still be bypassed by a GUID literal.
120
+ */
121
+ async function validate(args) {
122
+ const dir = path.resolve(process.cwd(), args.positional[0] ?? ".");
123
+ const sourcePath = (0, manifestSource_1.appManifestPath)(dir);
124
+ const jsonOutput = args.flags.json === true;
125
+ // The flag is parsed globally, so honour it here too rather than accepting it
126
+ // and doing nothing.
127
+ const showDismissed = args.flags["show-ignored"] === true;
128
+ // Read first: invalid JSON throws, and walking the whole source tree before
129
+ // finding that out is work nobody gets to see.
130
+ const read = (0, manifestSource_1.readAppManifestSource)(sourcePath);
131
+ const scan = args.flags["no-scan"] === true ? undefined : (0, scan_1.runScan)(dir);
132
+ if (!read) {
133
+ const result = {
134
+ ok: true,
135
+ manifest: null,
136
+ environments: [],
137
+ scan,
138
+ };
139
+ if (jsonOutput)
140
+ process.stdout.write(JSON.stringify(result) + "\n");
141
+ else
142
+ report(result, showDismissed);
143
+ return result;
144
+ }
145
+ const environments = environmentsToCheck(read.source, args.flags.env);
146
+ const checked = environments.map((environment) => {
147
+ try {
148
+ return {
149
+ environment,
150
+ ok: true,
151
+ dependencies: (0, manifest_1.resolveAppManifest)(read.source, environment).dependencies,
152
+ };
153
+ }
154
+ catch (err) {
155
+ return { environment, ok: false, error: err.message };
156
+ }
157
+ });
158
+ const result = {
159
+ ok: checked.every((env) => env.ok),
160
+ manifest: sourcePath,
161
+ environments: checked,
162
+ scan,
163
+ };
164
+ if (jsonOutput)
165
+ process.stdout.write(JSON.stringify(result) + "\n");
166
+ else
167
+ report(result, showDismissed);
168
+ return result;
169
+ }
@@ -10,13 +10,16 @@ export interface RunAgentArgs {
10
10
  agentId: string;
11
11
  message: string;
12
12
  chatId?: string;
13
- useHistory?: boolean;
14
13
  sessionId?: string;
15
14
  context?: Record<string, unknown>;
15
+ attachments?: readonly File[];
16
+ vectorStoreIds?: readonly string[];
16
17
  signal?: AbortSignal;
17
18
  }
18
19
  export interface SendChatArgs {
19
20
  context?: Record<string, unknown>;
21
+ attachments?: readonly File[];
22
+ vectorStoreIds?: readonly string[];
20
23
  signal?: AbortSignal;
21
24
  }
22
25
  export interface AgentChatSession {
@@ -25,6 +28,11 @@ export interface AgentChatSession {
25
28
  send(message: string, opts?: SendChatArgs): AsyncIterable<AgentRunEvent>;
26
29
  reset(): void;
27
30
  }
31
+ export interface CreateAgentChatArgs {
32
+ agentId: string;
33
+ chatId?: string;
34
+ sessionId?: string;
35
+ }
28
36
  export interface ListChatsArgs {
29
37
  agentId?: string;
30
38
  page?: number;
@@ -51,11 +59,7 @@ export interface AgentsConnector {
51
59
  signal?: AbortSignal;
52
60
  }): Promise<void>;
53
61
  run(args: RunAgentArgs): AsyncIterable<AgentRunEvent>;
54
- createChat(args: {
55
- agentId: string;
56
- chatId?: string;
57
- sessionId?: string;
58
- }): AgentChatSession;
62
+ createChat(args: CreateAgentChatArgs): AgentChatSession;
59
63
  listChats(args?: ListChatsArgs): Promise<AgentChatPage>;
60
64
  getChat(id: string, opts?: {
61
65
  signal?: AbortSignal;
@@ -153,19 +153,54 @@ async function collectAgentReply(events) {
153
153
  }
154
154
  return last;
155
155
  }
156
+ // Content-Type is ours to decide on either path, so a host's own is dropped
157
+ // rather than merged: JSON needs the exact value, and multipart needs the
158
+ // boundary the browser derives from the FormData body. A host that returned one
159
+ // would win the spread and produce a body the gateway cannot parse, with no
160
+ // client-side symptom.
161
+ function runHeaders(fromShell, withFiles) {
162
+ const headers = (0, _internal_1.stripContentType)(fromShell);
163
+ if (!withFiles)
164
+ headers["Content-Type"] = "application/json";
165
+ headers.Accept = "text/event-stream";
166
+ return headers;
167
+ }
168
+ // Gateway is FastAPI — snake_case wire contract.
169
+ function runJsonBody(args) {
170
+ return JSON.stringify({
171
+ agent_id: args.agentId,
172
+ message: args.message,
173
+ chat_id: args.chatId,
174
+ session_id: args.sessionId,
175
+ context: args.context,
176
+ ...(args.vectorStoreIds?.length && {
177
+ vector_store_ids: args.vectorStoreIds,
178
+ }),
179
+ });
180
+ }
181
+ // The multipart shape of the same request. Form fields are flat, so `context`
182
+ // rides as a JSON object string; every file goes under the `attachments` key.
183
+ function runFormBody(args) {
184
+ const form = new FormData();
185
+ form.append("agent_id", args.agentId);
186
+ form.append("message", args.message);
187
+ if (args.chatId)
188
+ form.append("chat_id", args.chatId);
189
+ if (args.sessionId)
190
+ form.append("session_id", args.sessionId);
191
+ if (args.context)
192
+ form.append("context", JSON.stringify(args.context));
193
+ for (const id of args.vectorStoreIds ?? []) {
194
+ form.append("vector_store_ids", id);
195
+ }
196
+ for (const file of args.attachments ?? []) {
197
+ form.append("attachments", file, file.name);
198
+ }
199
+ return form;
200
+ }
156
201
  function createAgentsConnector(deps = { shell: _internal_1.requireShell }) {
157
202
  const configApi = () => deps.shell().getApiV4("config");
158
- const resolveAi = () => {
159
- const shell = deps.shell();
160
- if (typeof shell.getAi !== "function") {
161
- throw new errors_1.ConnectorError("SHELL_TOO_OLD", "agents.run requires shell bridge v3 (getAi) — update the Rise-X shell");
162
- }
163
- const ai = shell.getAi();
164
- if (!ai) {
165
- throw new errors_1.ConnectorError("AI_UNAVAILABLE", "no AI gateway is configured for this deployment");
166
- }
167
- return ai;
168
- };
203
+ const resolveAi = () => (0, _internal_1.resolveAi)(deps.shell(), "agents.run");
169
204
  const list = async (args = {}) => {
170
205
  try {
171
206
  const page = args.page ?? 1;
@@ -222,52 +257,30 @@ function createAgentsConnector(deps = { shell: _internal_1.requireShell }) {
222
257
  }
223
258
  };
224
259
  const run = async function* (args) {
225
- // Mirror the gateway's 400: continuing a chat requires history.
226
- if (args.chatId && args.useHistory === false) {
227
- throw new errors_1.ConnectorError("INVALID_ARG", "agents.run: chatId cannot be combined with useHistory:false");
260
+ // The multipart parser drops an empty-valued part, so an unset stored id
261
+ // would run the turn with no file_search and still answer 200 — the JSON
262
+ // path rejects the same id as a validation error (422).
263
+ if (args.vectorStoreIds?.some((id) => !id)) {
264
+ throw new errors_1.ConnectorError("INVALID_ARG", "agents.run: vectorStoreIds must not contain empty ids");
228
265
  }
229
266
  const ai = resolveAi();
267
+ // A JSON body cannot carry a file, so a turn with attachments goes as
268
+ // multipart. Same route, same fields — only the encoding differs.
269
+ const withFiles = (args.attachments?.length ?? 0) > 0;
230
270
  let response;
231
271
  try {
232
272
  // fetch, not axios: the response is an SSE stream read incrementally.
233
273
  response = await fetch(`${ai.baseUrl}/api/v1/agent/run`, {
234
274
  method: "POST",
235
- headers: {
236
- ...ai.getHeaders(),
237
- "Content-Type": "application/json",
238
- Accept: "text/event-stream",
239
- },
240
- // Gateway is FastAPI — snake_case wire contract. use_history defaults to
241
- // true server-side, so omit it unless the caller opts out.
242
- body: JSON.stringify({
243
- agent_id: args.agentId,
244
- message: args.message,
245
- chat_id: args.chatId,
246
- ...(args.useHistory === false && { use_history: false }),
247
- session_id: args.sessionId,
248
- context: args.context,
249
- }),
275
+ headers: runHeaders(ai.getHeaders(), withFiles),
276
+ body: withFiles ? runFormBody(args) : runJsonBody(args),
250
277
  signal: args.signal,
251
278
  });
252
279
  }
253
280
  catch (e) {
254
281
  throw (0, errors_1.toConnectorError)(e);
255
282
  }
256
- if (!response.ok) {
257
- let message = `agent run failed with status ${response.status}`;
258
- try {
259
- const body = (await response.json());
260
- const detail = body?.detail ?? body?.message;
261
- if (typeof detail === "string" && detail)
262
- message = detail;
263
- }
264
- catch {
265
- // non-JSON error body — keep the generic message
266
- }
267
- throw new errors_1.ConnectorError(response.status === 404 ? "NOT_FOUND" : "HTTP_ERROR", message, {
268
- status: response.status,
269
- });
270
- }
283
+ await (0, _internal_1.ensureOk)(response, "agent run");
271
284
  if (!response.body) {
272
285
  throw new errors_1.ConnectorError("NETWORK_ERROR", "agent run response has no body");
273
286
  }
@@ -295,6 +308,8 @@ function createAgentsConnector(deps = { shell: _internal_1.requireShell }) {
295
308
  chatId: chatIdForTurn,
296
309
  sessionId,
297
310
  context: opts.context,
311
+ attachments: opts.attachments,
312
+ vectorStoreIds: opts.vectorStoreIds,
298
313
  signal: opts.signal,
299
314
  })) {
300
315
  // The first turn's end_of_stream reports the freshly-created chat id;
@@ -0,0 +1,51 @@
1
+ import type { ConnectorDeps } from "./deps";
2
+ export interface GetAttachmentBlobArgs {
3
+ id: string;
4
+ /**
5
+ * The resource the attachment hangs off. Needed by the cache side, which can also resolve a
6
+ * still-pending offline upload — those are found by their resource, not by an id the server has
7
+ * never seen. The network read is keyed by attachment id alone.
8
+ */
9
+ resourceId: string;
10
+ /** Read the thumbnail rather than the full attachment. */
11
+ thumb?: boolean;
12
+ /**
13
+ * The attachment's current version. Sent as `?v=` and part of the cache key, so a replace upload
14
+ * that reuses the id does not serve the previous bytes.
15
+ */
16
+ version?: number;
17
+ signal?: AbortSignal;
18
+ }
19
+ export interface UploadAttachmentArgs {
20
+ /** The work the attachment hangs off. */
21
+ workId: string;
22
+ files: File[];
23
+ /**
24
+ * Freeform grouping key. Attachments upsert on resourceId+folder+filename, so re-uploading the
25
+ * same filename into the same folder replaces the earlier one rather than adding a second.
26
+ */
27
+ folder: string;
28
+ /** How it renders when the work is printed. Cosmetic; no effect on the upload. */
29
+ reportSize?: "small" | "large" | "custom";
30
+ signal?: AbortSignal;
31
+ }
32
+ export interface AttachmentsConnector {
33
+ /**
34
+ * The attachment's bytes. `null` when the attachment does not exist and when nothing was
35
+ * downloaded for it — never for a server that could not be reached, which throws.
36
+ */
37
+ getBlob(args: GetAttachmentBlobArgs): Promise<Blob | null>;
38
+ /**
39
+ * Uploads to the server. Network only — offline, queue it with
40
+ * `offline.queueWorkAttachmentUpload` instead, which is the deliberate act this deliberately
41
+ * is not.
42
+ */
43
+ upload(args: UploadAttachmentArgs): Promise<void>;
44
+ /** Deletes on the server. Network only, same reasoning as `upload`. */
45
+ delete(args: {
46
+ id: string;
47
+ signal?: AbortSignal;
48
+ }): Promise<void>;
49
+ }
50
+ export declare function createAttachmentsConnector(deps?: ConnectorDeps): AttachmentsConnector;
51
+ export declare const attachments: AttachmentsConnector;
@@ -0,0 +1,76 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.attachments = void 0;
4
+ exports.createAttachmentsConnector = createAttachmentsConnector;
5
+ /**
6
+ * Attachment bytes, resolved the same way every other read is.
7
+ *
8
+ * Reads only for now — `upload` and `delete` are writes, and writes stay explicit under the
9
+ * `offline.*` queue tools rather than deciding for themselves.
10
+ */
11
+ const _internal_1 = require("../_internal");
12
+ const errors_1 = require("./errors");
13
+ const readPolicy_1 = require("./readPolicy");
14
+ function createAttachmentsConnector(deps = { shell: _internal_1.requireShell }) {
15
+ const getBlob = (args) => {
16
+ const { id, resourceId, thumb = false, version, signal } = args;
17
+ return (0, readPolicy_1.resolveRead)({
18
+ shell: deps.shell,
19
+ signal,
20
+ network: async (requestSignal) => {
21
+ try {
22
+ const { data } = await deps
23
+ .shell()
24
+ .getApiV4("attachment")
25
+ .get(
26
+ // `/thumb`, matching the shell's own attachment queries — a thumbnail request sent
27
+ // to the full-size route would quietly return multi-megabyte bytes instead.
28
+ thumb
29
+ ? `/api/v4/attachments/${id}/thumb`
30
+ : `/api/v4/attachments/${id}`, {
31
+ responseType: "blob",
32
+ params: version != null ? { v: version } : undefined,
33
+ signal: requestSignal,
34
+ });
35
+ return data ?? null;
36
+ }
37
+ catch (e) {
38
+ throw (0, errors_1.toConnectorError)(e);
39
+ }
40
+ },
41
+ // The one asynchronous cache read in the surface: the bytes may live in IndexedDB, which has
42
+ // no synchronous API. `resolveRead` awaits this branch for exactly that reason.
43
+ cache: (api) => api.readAttachmentBlob({ id, resourceId, thumb, version }),
44
+ });
45
+ };
46
+ const upload = async (args) => {
47
+ const { workId, files, folder, reportSize, signal } = args;
48
+ try {
49
+ const body = new FormData();
50
+ files.forEach((file) => body.append("files", file));
51
+ await deps
52
+ .shell()
53
+ .getApiV4("attachment")
54
+ .post(`/api/v4/attachments/work/${workId}/${folder}`, body, {
55
+ params: reportSize ? { reportSize } : undefined,
56
+ signal,
57
+ });
58
+ }
59
+ catch (e) {
60
+ throw (0, errors_1.toConnectorError)(e);
61
+ }
62
+ };
63
+ const del = async ({ id, signal }) => {
64
+ try {
65
+ await deps
66
+ .shell()
67
+ .getApiV4("attachment")
68
+ .delete(`/api/v4/attachments/${id}`, { signal });
69
+ }
70
+ catch (e) {
71
+ throw (0, errors_1.toConnectorError)(e);
72
+ }
73
+ };
74
+ return { getBlob, upload, delete: del };
75
+ }
76
+ exports.attachments = createAttachmentsConnector();
@@ -36,12 +36,36 @@ function httpMessage(e) {
36
36
  e.message ||
37
37
  `request failed with status ${e.response?.status}`);
38
38
  }
39
+ // A ConnectorError raised by a DIFFERENT module instance of this file: identical shape, failing
40
+ // `instanceof`. Duck-typed for exactly the reason axios is above — identity is not reliable here.
41
+ //
42
+ // Two copies of this module in one page is ordinary, not pathological: an app bundles the SDK and
43
+ // so does whatever built its shell, and `createMockShell`'s `getApi` thrower is constructed in one
44
+ // while `toConnectorError` runs in the other. Without this check such an error missed the
45
+ // pass-through, fell to the catch-all at the bottom, and had its **code rewritten** while keeping
46
+ // its message — a permanent `SHELL_UNAVAILABLE` came out as `NETWORK_ERROR`. Apps classify
47
+ // retryability from `code`, so every one of them read "the link dropped, try again" for "this host
48
+ // has no backend", and retried forever instead of surfacing it.
49
+ function isConnectorErrorLike(e) {
50
+ return (typeof e === "object" &&
51
+ e !== null &&
52
+ e.name === "ConnectorError" &&
53
+ typeof e.code === "string");
54
+ }
39
55
  // Normalize anything thrown while talking to the platform into a ConnectorError.
40
56
  // ConnectorError instances pass through unchanged; the original error is always
41
57
  // preserved on `cause`.
42
58
  function toConnectorError(e) {
43
59
  if (e instanceof ConnectorError)
44
60
  return e;
61
+ // Re-raised through THIS module's class so that downstream `instanceof` — in here and in every
62
+ // caller — holds from now on. Code, message and status carry over verbatim.
63
+ if (isConnectorErrorLike(e)) {
64
+ return new ConnectorError(e.code, e.message, {
65
+ status: e.status,
66
+ cause: e.cause ?? e,
67
+ });
68
+ }
45
69
  if (isAxiosErrorLike(e)) {
46
70
  if (e.code === "ERR_CANCELED" || isAbortLike(e)) {
47
71
  return new ConnectorError("ABORTED", "request aborted", { cause: e });
@@ -24,12 +24,23 @@ export interface FlowsConnector {
24
24
  findTask(args: FindTaskArgs): Promise<FindTaskResult | null>;
25
25
  findTaskIn(flow: Flow, taskRef: string): FindTaskResult | null;
26
26
  flattenLayoutFields(layout: Layout): LayoutField[];
27
+ /**
28
+ * v4 step/task/layout config, grouped per step with a display-name map. Accepts a concrete flow
29
+ * id or a flowOriginId; resolved to the latest published version. `null` only when the flow does
30
+ * not exist (a 404); an unreachable server with nothing cached throws. Where the bytes come from
31
+ * is decided for you (see readPolicy.ts).
32
+ */
27
33
  getConfig(flowId: string, opts?: {
28
34
  signal?: AbortSignal;
29
- }): Promise<FlowConfig>;
35
+ }): Promise<FlowConfig | null>;
36
+ /**
37
+ * The layout's component list, flat and exactly as stored — mapped identically from either source.
38
+ * `null` only when the layout does not exist (a 404); an unreachable server with nothing cached
39
+ * throws. Where the bytes come from is decided for you (see readPolicy.ts).
40
+ */
30
41
  getLayout(layoutId: string, opts?: {
31
42
  signal?: AbortSignal;
32
- }): Promise<Layout>;
43
+ }): Promise<Layout | null>;
33
44
  }
34
45
  export declare function findTaskIn(flow: Flow, taskRef: string): FindTaskResult | null;
35
46
  export declare function flattenLayoutFields(layout: Layout): LayoutField[];