@almateam/app-sdk 0.3.1 → 0.5.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.
package/README.md CHANGED
@@ -8,7 +8,7 @@ An app imports the SDK as `@alma/app-sdk`. Install the published package under
8
8
  that name, for its types:
9
9
 
10
10
  ```sh
11
- npm install --save-dev @alma/app-sdk@npm:@almateam/app-sdk@^0.3.1
11
+ npm install --save-dev @alma/app-sdk@npm:@almateam/app-sdk@^0.5.0
12
12
  ```
13
13
 
14
14
  Alma builds an app's source with its own current copy of the SDK, whatever
@@ -51,6 +51,14 @@ act: it saves as them where they may edit that record and is refused where they
51
51
  cannot. Nobody is asked and no dialog appears: the promise resolves with the
52
52
  result, or rejects with the refusal's words.
53
53
 
54
+ A lesson added by a viewer who decides the workflow's lessons (its editors and
55
+ the workspace's owners) is live at once: `createWorkflowLesson` resolves with
56
+ `active: true` and the lesson is on the card's `lessons`. From any other viewer
57
+ it is a proposal: it resolves with `active: false`, is sent to the people who do
58
+ decide, and runs follow it only once one of them approves it in Tasks. Until
59
+ then it is on the card's `proposed_lessons`, for its author and for those
60
+ deciders.
61
+
54
62
  The app talks to its host on one channel that belongs to the document the Space
55
63
  loaded; the SDK finds it there. A document the frame navigates to has no
56
64
  channel, and the host closes the Space when the frame leaves or reloads its
@@ -64,33 +72,90 @@ topic the viewer can edit, and is parsed against its field — a date that is no
64
72
  one, or a choice outside the field's options, is refused. Setting a value the
65
73
  field already holds confirms it as the viewer's.
66
74
 
75
+ A write says what the app read. Every read (`listTopics`, `getTopicRecord`)
76
+ carries each field's `revisions`, the SDK remembers them, and `setTopicField`
77
+ sends the one for the field it writes. If someone changed that field after the
78
+ app read it, nothing is written and the call rejects with a `field.changed`
79
+ error carrying what the field holds now:
80
+
81
+ ```ts
82
+ import { isFieldChanged } from "@alma/app-sdk";
83
+
84
+ try {
85
+ await alma.setTopicField(topicId, "stage", "Signed");
86
+ } catch (error) {
87
+ if (!isFieldChanged(error)) throw error;
88
+ // "This changed since you opened it": show error.current.values, let the
89
+ // viewer decide again, then write against what they were shown.
90
+ await alma.setTopicField(topicId, "stage", "Signed", undefined, {
91
+ ifRevision: error.current.revision,
92
+ });
93
+ }
94
+ ```
95
+
96
+ Read the record before writing it, so the SDK has something to send: a write
97
+ that says nothing about what it read is refused (`precondition.required`) and
98
+ writes nothing. To say it yourself, pass `{ ifRevision }` (a revision from a
99
+ read, a receipt's `revision` or a conflict's `current.revision`) or
100
+ `{ ifValue }` (a value the field held, as its `text` was read, or `null` if it
101
+ held nothing). The receipt names how the write ended in `outcome` (`applied`,
102
+ `confirmed` or `unchanged`). To make a write safe to send twice, pass
103
+ `{ idempotencyKey }`: the same key and request again answers with the first
104
+ receipt and writes nothing, marked `superseded` if the field has changed since.
105
+
106
+ ## State: what only this person's screen needs
107
+
108
+ ```ts
109
+ await alma.state.set("filter", { stage: "Live" });
110
+ const filter = await alma.state.get<{ stage: string }>("filter"); // or undefined
111
+ await alma.state.delete("filter");
112
+ ```
113
+
114
+ If another person, a workflow or Alma needs to see or act on something, it is a
115
+ record. If only this app's screen for this person needs it, it is app state.
116
+
117
+ State is a small key/value store per installed app and per person: a filter, a
118
+ collapsed column, a half-written draft. Only that person's sessions of that app
119
+ read or write it. It needs no scope and no owner's approval, and declaring
120
+ nothing for it does not widen a version. Nothing in it reaches a workflow run,
121
+ search or anything Alma knows; there is no store an app's people share. It
122
+ survives a reload and a new version of the app, and goes when the app is removed
123
+ from the workspace or the person leaves it. Keys are letters, digits, `_` and
124
+ `-` (up to 128 characters). A value is any JSON up to 16 KB, and one person
125
+ holds at most 64 keys and 256 KB in one app; a `set` past a limit rejects with a
126
+ refusal whose `code` is `app_state.value_too_large` or
127
+ `app_state.quota_exceeded`.
128
+
67
129
  ## Records: the workspace's typed topics
68
130
 
69
- An app keeps no store of its own. Its records are the workspace's topics, of the
70
- types its manifest declares (`types`): each type's `key` and `name`, its
71
- `fields` (a key, a name, a value type of `text`, `date`, `number`, `money` or
72
- `choice`, and a choice's `options`) and its `relationships` (a `label`, the key
73
- of the type it points at, such as `person` or `contact`, and a `cardinality`).
74
- When an owner's share installs the app, the workspace's type of that key is
75
- reused, gaining what it lacks, or created. `listTopics({ type, filter, sort })`
76
- reads them as the viewer, `setTopicField` changes one as the viewer, and
77
- `createTopic(name, typeId)` (the id from `listTopicTypes()`) creates one: the
78
- host shows Alma's own access sheet, starting from the app's audience, and the
79
- viewer chooses who can see it. A relationship's values sit under
80
- `rel_<label>__<type key>` (`rel_csm__person`). A version declaring a type, field
81
- or relationship the shared version did not is wider and asks an owner; while the
82
- app is installed, the workspace's schema editor lists it under "Used by" and
83
- refuses to retype or remove what it declares.
131
+ An app's records are the workspace's topics, of the types its manifest declares
132
+ (`types`): each type's `key` and `name`, its `fields` (a key, a name, a value
133
+ type of `text`, `date`, `number`, `money` or `choice`, and a choice's `options`)
134
+ and its `relationships` (a `label`, the key of the type it points at, such as
135
+ `person` or `contact`, and a `cardinality`). When an owner's share installs the
136
+ app, the workspace's type of that key is reused, gaining what it lacks, or
137
+ created. `listTopics({ type, filter, sort })` reads them as the viewer,
138
+ `setTopicField` changes one as the viewer, and `createTopic(name, typeId)` (the
139
+ id from `listTopicTypes()`) creates one: the host shows Alma's own access sheet,
140
+ starting from the app's audience, and the viewer chooses who can see it. A
141
+ relationship's values sit under `rel_<label>__<type key>` (`rel_csm__person`). A
142
+ version declaring a type, field or relationship the shared version did not is
143
+ wider and asks an owner; while the app is installed, the workspace's schema
144
+ editor lists it under "Used by" and refuses to retype or remove what it
145
+ declares.
84
146
 
85
147
  ## Workflows: the app's backend
86
148
 
87
149
  An app's backend is the ordinary workflows its manifest names (`workflows`, by
88
150
  id, with the `workflows:run` scope): workflows of the workspace, edited by their
89
151
  managers and run as they stand. `listWorkflows()` marks them `runnable` where
90
- the viewer may start them; `runWorkflow(id, { topicId, input })` starts one as
91
- the viewer (`POST /v1/workflows/{id}/executions`), with nobody asked: the viewer
92
- must be in the app's audience and, on a record, able to edit it. The run acts as
93
- them. Follow it with `waitForExecution(run.id, { onUpdate })`, which polls
152
+ the viewer may start them, and where they may not gives the reason in
153
+ `not_runnable` (`{ code, reason }`, the sentence `runWorkflow` would refuse
154
+ with): show the control disabled with that reason.
155
+ `runWorkflow(id, { topicId, input })` starts one as the viewer
156
+ (`POST /v1/workflows/{id}/executions`), with nobody asked: the viewer must be in
157
+ the app's audience and, on a record, able to edit it. The run acts as them.
158
+ Follow it with `waitForExecution(run.id, { onUpdate })`, which polls
94
159
  `GET /v1/executions/{id}` with backoff: a run paused at an approval step reads
95
160
  `waiting`, with the people it waits on in `approvers` (its Task is theirs, not
96
161
  the viewer's), and a failed run's `error` is safe to show.
@@ -37,6 +37,11 @@ export interface AppLesson {
37
37
  id: string;
38
38
  content: string;
39
39
  workflow_id: string | null;
40
+ /**
41
+ * False while the lesson waits for the workflow's editors to approve it;
42
+ * runs follow it only once it is true.
43
+ */
44
+ active: boolean;
40
45
  /** Pass it back as `expected_revision` on the next save. */
41
46
  edit_revision: string;
42
47
  }
@@ -61,10 +66,27 @@ export interface AppRunReceipt {
61
66
  status: string;
62
67
  created_at: string;
63
68
  }
69
+ /**
70
+ * One key of an app's own state for its viewer: what only that person's
71
+ * screen of that app needs between visits.
72
+ */
73
+ export interface AppStateEntry {
74
+ key: string;
75
+ /** Whether the key holds a value; one never set, or deleted, does not. */
76
+ exists: boolean;
77
+ /** The stored JSON; null when the key holds nothing. */
78
+ value: unknown;
79
+ }
64
80
  export interface AppTopicRecord {
65
81
  topic: TopicRef;
66
82
  record: KnowledgeRecord;
67
83
  facts: TopicFact[];
84
+ /**
85
+ * Each field's revision, by field key, for every field that holds a value.
86
+ * Send it back as `if_revision` when writing that field; a field absent
87
+ * here holds nothing (`if_value: null`).
88
+ */
89
+ revisions: Record<string, string>;
68
90
  }
69
91
  /**
70
92
  * A row of the member Workflows list: a workflow the viewer reads the card
@@ -75,6 +97,7 @@ export interface AppWorkflowSummary {
75
97
  name: string;
76
98
  /** The newest run, on the organization's calendar, and how it went. */
77
99
  last_run?: string;
100
+ needs_connection?: boolean;
78
101
  /** Paused only when the newest run waits on one of the viewer's own Tasks. */
79
102
  state: "proposed" | "draft" | "live" | "paused";
80
103
  /**
@@ -82,6 +105,16 @@ export interface AppWorkflowSummary {
82
105
  * `runWorkflow`.
83
106
  */
84
107
  runnable?: true;
108
+ /**
109
+ * A workflow the app's manifest names, which the viewer may not start now:
110
+ * why, as a stable `code` and the sentence `runWorkflow` would refuse
111
+ * with. Show the control disabled with `reason`. On a record, the viewer
112
+ * must also be able to edit that record (its `can_edit`).
113
+ */
114
+ not_runnable?: {
115
+ code: "workflow.off" | "app.not_in_audience";
116
+ reason: string;
117
+ };
85
118
  /** The facts the Workflows list sorts and filters by. */
86
119
  index?: {
87
120
  createdAt: string;
@@ -190,6 +223,11 @@ export interface RecordSection {
190
223
  value_type: "text" | "date" | "number" | "money" | "choice";
191
224
  currency?: string;
192
225
  options?: string[];
226
+ /**
227
+ * How many earlier values of this field the viewer can read with
228
+ * `getTopicFieldHistory`; absent when there are none.
229
+ */
230
+ earlier_values?: number;
193
231
  facts: RecordFact[];
194
232
  }
195
233
  export interface RecordUpdate {
@@ -247,8 +285,57 @@ export interface TopicFact {
247
285
  value: FactValue;
248
286
  verified_at: string | null;
249
287
  }
288
+ export interface TopicFieldHistory {
289
+ topic_id: string;
290
+ field_key: string;
291
+ entries: TopicFieldHistoryEntry[];
292
+ }
293
+ /** One earlier value of a field, as a reader of the record sees it. */
294
+ export interface TopicFieldHistoryEntry {
295
+ id: string;
296
+ value: string;
297
+ value_json: TypedValue | null;
298
+ /**
299
+ * Who or what a history line names: a person (named where the viewer can
300
+ * still resolve them), Alma, or a workflow's run.
301
+ */
302
+ written_by: {
303
+ kind: "person";
304
+ name: string | null;
305
+ } | {
306
+ kind: "alma";
307
+ } | {
308
+ kind: "workflow";
309
+ };
310
+ /** Who had confirmed the value while it stood. */
311
+ verified_by: {
312
+ name: string | null;
313
+ at: string;
314
+ } | null;
315
+ /** Why the value stopped standing. */
316
+ reason: "corrected" | "superseded" | "retracted" | "rejected" | "moved" | "unattributed";
317
+ /** The preset a person gave for removing it, when they gave one. */
318
+ rejection_reason: "wrong_entity" | "inaccurate" | "irrelevant" | "duplicate" | null;
319
+ /** Who or what made the change; null when no writer declared itself. */
320
+ changed_by: {
321
+ kind: "person";
322
+ name: string | null;
323
+ } | {
324
+ kind: "alma";
325
+ } | {
326
+ kind: "workflow";
327
+ } | null;
328
+ /** What took its place, when something did. */
329
+ replaced_by_value: string | null;
330
+ stood_from: string | null;
331
+ replaced_at: string;
332
+ }
250
333
  export interface TopicFieldReceipt {
251
- status: "saved" | "confirmed" | "unchanged";
334
+ /**
335
+ * `applied` wrote the value; `confirmed` marked a value the field already
336
+ * held as the caller's; `unchanged` found it already confirmed.
337
+ */
338
+ outcome: "applied" | "confirmed" | "unchanged";
252
339
  topic_id: string;
253
340
  field_key: string;
254
341
  fact_id: string;
@@ -256,6 +343,21 @@ export interface TopicFieldReceipt {
256
343
  text: string;
257
344
  typed: TypedValue | null;
258
345
  };
346
+ /**
347
+ * The field's revision once this write stood: the `if_revision` of the
348
+ * next write.
349
+ */
350
+ revision: string;
351
+ applied_at: string;
352
+ /** The call ledger row that records this write. */
353
+ call_id: string | null;
354
+ /**
355
+ * On a retry under the same Idempotency-Key: the field has changed since
356
+ * this write, and nothing was written again.
357
+ */
358
+ superseded?: true;
359
+ /** With `superseded`: the field's revision now. */
360
+ current_revision?: string;
259
361
  }
260
362
  export interface TopicRecord {
261
363
  id: string;
@@ -271,6 +373,12 @@ export interface TopicRecord {
271
373
  icon: string | null;
272
374
  } | null;
273
375
  values: Record<string, FactValue[]>;
376
+ /**
377
+ * Each field's revision, by field key, for every field that holds a value.
378
+ * Send it back as `if_revision` when writing that field; a field absent
379
+ * here holds nothing (`if_value: null`).
380
+ */
381
+ revisions: Record<string, string>;
274
382
  unverified_value_count: number;
275
383
  can_edit: boolean;
276
384
  created_at: string;
@@ -344,7 +452,21 @@ export interface WorkflowCard {
344
452
  /** Newest first. */
345
453
  runs: WorkflowRun[];
346
454
  lessons: WorkflowLesson[];
455
+ /**
456
+ * Lessons waiting for approval, which runs do not follow yet: all of them
457
+ * for a viewer who decides this workflow's lessons, the viewer's own
458
+ * otherwise.
459
+ */
460
+ proposed_lessons: WorkflowLesson[];
347
461
  can_edit_lessons: boolean;
462
+ connection_blocks?: {
463
+ step_id: string;
464
+ step_name: string;
465
+ provider: string;
466
+ owner_user_id: string | null;
467
+ account_name: string;
468
+ reason: "missing" | "expired" | "revoked" | "identity_unverified" | "account_unavailable" | "credential_missing" | "scope_missing" | "requester_required";
469
+ }[];
348
470
  /** Only topics the viewer can open. */
349
471
  topics: WorkflowTopic[];
350
472
  audience?: RecordAudience;
@@ -388,6 +510,8 @@ export interface AppOperationResults {
388
510
  listTopicTypes: TopicType[];
389
511
  /** Get a topic's record */
390
512
  getTopicRecord: AppTopicRecord;
513
+ /** Get a field's earlier values */
514
+ getTopicFieldHistory: TopicFieldHistory;
391
515
  /** Get the discussion about a value */
392
516
  getTopicFactDiscussion: AppFactDiscussion;
393
517
  /** Set a field's value */
@@ -413,4 +537,10 @@ export interface AppOperationResults {
413
537
  };
414
538
  /** Get the organization's defined aggregates */
415
539
  getOrganizationAnalytics: OrganizationAnalytics;
540
+ /** Read a key of the app's state */
541
+ getAppState: AppStateEntry;
542
+ /** Set a key of the app's state */
543
+ setAppState: AppStateEntry;
544
+ /** Delete a key of the app's state */
545
+ deleteAppState: AppStateEntry;
416
546
  }
package/index.d.ts CHANGED
@@ -43,6 +43,7 @@ declare const APP_OPERATIONS: {
43
43
  readonly listTopicTypes: "read";
44
44
  readonly getTopicRecord: "read";
45
45
  readonly getTopicFactDiscussion: "read";
46
+ readonly getTopicFieldHistory: "read";
46
47
  readonly downloadTopicFactAttachment: "read";
47
48
  readonly setTopicField: "change";
48
49
  readonly listWorkflows: "read";
@@ -54,6 +55,9 @@ declare const APP_OPERATIONS: {
54
55
  readonly getExecution: "read";
55
56
  readonly listOutcomes: "read";
56
57
  readonly getOrganizationAnalytics: "read";
58
+ readonly getAppState: "read";
59
+ readonly setAppState: "change";
60
+ readonly deleteAppState: "change";
57
61
  };
58
62
  export type AppOperationId = keyof typeof APP_OPERATIONS;
59
63
  export interface AppRequest {
@@ -62,6 +66,47 @@ export interface AppRequest {
62
66
  /** Only the query keys the operation declares reach the API. */
63
67
  query?: Record<string, string | number | string[] | undefined>;
64
68
  body?: Record<string, unknown>;
69
+ /** Names one request, so making it again (after an answer that never
70
+ * arrived) answers with what the first attempt did and changes nothing. */
71
+ idempotencyKey?: string;
72
+ }
73
+ /** A field as it stands: its revision and the values it holds. */
74
+ export interface FieldState {
75
+ revision: string;
76
+ values: {
77
+ text: string;
78
+ typed: Api.TypedValue | null;
79
+ }[];
80
+ }
81
+ /** A refused call. `message` is the refusal's words, to show as they are.
82
+ * A refusal a program can act on also carries its `code`; `field.changed`
83
+ * carries the field as it stands in `current`. */
84
+ export declare class AppCallError extends Error {
85
+ readonly code: string | undefined;
86
+ readonly current: FieldState | undefined;
87
+ constructor(message: string, detail?: {
88
+ code?: string;
89
+ current?: FieldState;
90
+ });
91
+ }
92
+ /** A field write refused because the field changed after the app read it.
93
+ * Nothing was written; `current` is what the field holds now. */
94
+ export type FieldChangedError = AppCallError & {
95
+ code: "field.changed";
96
+ current: FieldState;
97
+ };
98
+ export declare function isFieldChanged(error: unknown): error is FieldChangedError;
99
+ /** What a field write says the app read before writing. Left out, the SDK
100
+ * sends what its own last read of the record showed. A write to a record
101
+ * the app never read, with none of these, is refused. */
102
+ export interface FieldWriteOptions {
103
+ /** The field's revision, from a record's `revisions`, a receipt's
104
+ * `revision` or a conflict's `current.revision`. */
105
+ ifRevision?: string;
106
+ /** A value the field held, as its `text` was read; null if it held
107
+ * nothing. */
108
+ ifValue?: string | null;
109
+ idempotencyKey?: string;
65
110
  }
66
111
  export interface AppTransport {
67
112
  /** Resolves with the response's `data`, or `{ data, meta }` when the
@@ -80,6 +125,9 @@ export declare function createAppSdk(transport: AppTransport): {
80
125
  }>;
81
126
  getTopicRecord: (topicId: string) => Promise<Api.AppTopicRecord>;
82
127
  getTopicFactDiscussion: (topicId: string, factId: string) => Promise<Api.AppFactDiscussion>;
128
+ /** A field's earlier values, newest first, as the viewer may read
129
+ * them. A record section's `earlier_values` says how many there are. */
130
+ getTopicFieldHistory: (topicId: string, fieldKey: string) => Promise<Api.TopicFieldHistory>;
83
131
  /** The host downloads the file itself; the app receives only a receipt. */
84
132
  downloadTopicFactAttachment: (topicId: string, factId: string, turn: {
85
133
  kind: "message" | "queued";
@@ -88,8 +136,15 @@ export declare function createAppSdk(transport: AppTransport): {
88
136
  /** Sets one field as the viewer, where they may edit the topic;
89
137
  * rejects with the refusal's words where they may not. Nobody is asked.
90
138
  * Setting a value the field already holds confirms it as theirs. On a
91
- * relationship, `refTopicId` names the topic the value refers to. */
92
- setTopicField: (topicId: string, fieldKey: string, value: string, refTopicId?: string) => Promise<Api.TopicFieldReceipt>;
139
+ * relationship, `refTopicId` names the topic the value refers to.
140
+ *
141
+ * The write says what this app last read of the field (from
142
+ * `listTopics` or `getTopicRecord`). If the field changed since, nothing
143
+ * is written and it rejects with a `field.changed` error
144
+ * (`isFieldChanged`) carrying the field as it stands: show that, and
145
+ * write again against it by passing `ifRevision: error.current.revision`
146
+ * once the viewer has decided. */
147
+ setTopicField: (topicId: string, fieldKey: string, value: string, refTopicId?: string, options?: FieldWriteOptions) => Promise<Api.TopicFieldReceipt>;
93
148
  /** Creates a record as the viewer. Who can see it is the viewer's
94
149
  * choice in Alma's own access sheet, never the app's. */
95
150
  createTopic: (name: string, topicTypeId?: string) => Promise<Api.CreatedTopicRecord>;
@@ -117,12 +172,27 @@ export declare function createAppSdk(transport: AppTransport): {
117
172
  * `signal` to stop. */
118
173
  waitForExecution: (executionId: string, options?: PollOptions) => Promise<Api.AppExecution>;
119
174
  getWorkflowCard: (workflowId: string) => Promise<Api.WorkflowCard>;
120
- /** A lesson every later run of the workflow follows. Screened: wording
121
- * that reads as an instruction to Alma is refused with the reason. */
175
+ /** Propose a lesson for the workflow's later runs. It resolves with
176
+ * `active: false` and applies once someone who can edit the workflow
177
+ * approves it in Tasks. Screened: wording that reads as an instruction
178
+ * to Alma is refused with the reason. */
122
179
  createWorkflowLesson: (workflowId: string, content: string) => Promise<Api.AppLesson>;
123
180
  /** Pass the `edit_revision` the card gave; a save made meanwhile is
124
181
  * refused rather than overwritten. */
125
182
  updateLesson: (lessonId: string, content: string, editRevision: string) => Promise<Api.AppLesson>;
183
+ /** This app's own state for its viewer: a small store for what only
184
+ * this person's screen of this app needs between visits, such as a
185
+ * filter, a collapsed column or a half-written draft. It needs no scope
186
+ * and nobody else reads it. If another person, a workflow or Alma needs
187
+ * to see or act on something, keep it in a record instead. Keys are
188
+ * letters, digits, `_` and `-`; values are any JSON, within a size limit
189
+ * a `set` past it rejects with. */
190
+ state: {
191
+ /** The value a key holds, or `undefined` when it holds nothing. */
192
+ get: <T = unknown>(key: string) => Promise<T | undefined>;
193
+ set: (key: string, value: unknown) => Promise<void>;
194
+ delete: (key: string) => Promise<void>;
195
+ };
126
196
  listOutcomes: (page?: {
127
197
  limit?: number;
128
198
  offset?: number;
package/index.js CHANGED
@@ -83,33 +83,81 @@ var FINISHED = [
83
83
  "failed",
84
84
  "cancelled"
85
85
  ];
86
+ class AppCallError extends Error {
87
+ code;
88
+ current;
89
+ constructor(message, detail = {}) {
90
+ super(message);
91
+ this.name = "AppCallError";
92
+ this.code = detail.code;
93
+ this.current = detail.current;
94
+ }
95
+ }
96
+ function isFieldChanged(error) {
97
+ return error instanceof Error && error.code === "field.changed" && error.current !== undefined;
98
+ }
86
99
  function createAppSdk(transport) {
100
+ const read = new Map;
101
+ const precondition = (topicId, fieldKey, options) => {
102
+ if (options.ifRevision !== undefined || options.ifValue !== undefined)
103
+ return {
104
+ ...options.ifRevision === undefined ? {} : { if_revision: options.ifRevision },
105
+ ...options.ifValue === undefined ? {} : { if_value: options.ifValue }
106
+ };
107
+ const fields = read.get(topicId);
108
+ if (!fields)
109
+ return {};
110
+ const revision = fields[fieldKey];
111
+ return revision === undefined ? { if_value: null } : { if_revision: revision };
112
+ };
87
113
  const getExecution = (executionId) => transport.call("getExecution", {
88
114
  params: { id: executionId }
89
115
  });
90
116
  return {
91
117
  call: (operationId, request) => transport.call(operationId, request),
92
- listTopics: (query = {}) => transport.call("listTopics", {
93
- query: {
94
- type: query.type,
95
- filter: query.filter,
96
- sort: query.sort,
97
- cursor: query.cursor,
98
- limit: query.limit
99
- }
100
- }),
101
- getTopicRecord: (topicId) => transport.call("getTopicRecord", {
102
- params: { id: topicId }
103
- }),
118
+ listTopics: async (query = {}) => {
119
+ const page = await transport.call("listTopics", {
120
+ query: {
121
+ type: query.type,
122
+ filter: query.filter,
123
+ sort: query.sort,
124
+ cursor: query.cursor,
125
+ limit: query.limit
126
+ }
127
+ });
128
+ for (const topic of page.data)
129
+ if (topic.revisions)
130
+ read.set(topic.id, { ...topic.revisions });
131
+ return page;
132
+ },
133
+ getTopicRecord: async (topicId) => {
134
+ const record = await transport.call("getTopicRecord", { params: { id: topicId } });
135
+ if (record.revisions)
136
+ read.set(topicId, { ...record.revisions });
137
+ return record;
138
+ },
104
139
  getTopicFactDiscussion: (topicId, factId) => transport.call("getTopicFactDiscussion", { params: { id: topicId, factId } }),
140
+ getTopicFieldHistory: (topicId, fieldKey) => transport.call("getTopicFieldHistory", { params: { id: topicId, key: fieldKey } }),
105
141
  downloadTopicFactAttachment: (topicId, factId, turn, attachmentId) => transport.call("downloadTopicFactAttachment", {
106
142
  params: { id: topicId, factId, attachmentId },
107
143
  query: { turn_kind: turn.kind, turn_id: turn.id }
108
144
  }),
109
- setTopicField: (topicId, fieldKey, value, refTopicId) => transport.call("setTopicField", {
110
- params: { id: topicId, key: fieldKey },
111
- body: { value, ...refTopicId ? { ref_topic_id: refTopicId } : {} }
112
- }),
145
+ setTopicField: async (topicId, fieldKey, value, refTopicId, options = {}) => {
146
+ const receipt = await transport.call("setTopicField", {
147
+ params: { id: topicId, key: fieldKey },
148
+ body: {
149
+ value,
150
+ ...refTopicId ? { ref_topic_id: refTopicId } : {},
151
+ ...precondition(topicId, fieldKey, options)
152
+ },
153
+ ...options.idempotencyKey ? { idempotencyKey: options.idempotencyKey } : {}
154
+ });
155
+ const revision = receipt.current_revision ?? receipt.revision;
156
+ const fields = read.get(topicId);
157
+ if (fields && revision)
158
+ fields[fieldKey] = revision;
159
+ return receipt;
160
+ },
113
161
  createTopic: (name, topicTypeId) => transport.call("createTopic", {
114
162
  body: { name, ...topicTypeId ? { topic_type_id: topicTypeId } : {} }
115
163
  }),
@@ -156,6 +204,21 @@ function createAppSdk(transport) {
156
204
  params: { id: lessonId },
157
205
  body: { content, expected_revision: editRevision }
158
206
  }),
207
+ state: {
208
+ get: async (key) => {
209
+ const entry = await transport.call("getAppState", { params: { key } });
210
+ return entry.exists ? entry.value : undefined;
211
+ },
212
+ set: async (key, value) => {
213
+ await transport.call("setAppState", {
214
+ params: { key },
215
+ body: { value }
216
+ });
217
+ },
218
+ delete: async (key) => {
219
+ await transport.call("deleteAppState", { params: { key } });
220
+ }
221
+ },
159
222
  listOutcomes: (page = {}) => transport.call("listOutcomes", {
160
223
  query: { limit: page.limit, offset: page.offset }
161
224
  }),
@@ -177,7 +240,12 @@ function hostTransport() {
177
240
  clearTimeout(call.timer);
178
241
  pending.delete(message["id"]);
179
242
  if (typeof message["error"] === "string")
180
- call.reject(new Error(message["error"]));
243
+ call.reject(new AppCallError(message["error"], {
244
+ ...typeof message["code"] === "string" ? { code: message["code"] } : {},
245
+ ...typeof message["current"] === "object" && message["current"] !== null ? {
246
+ current: message["current"]
247
+ } : {}
248
+ }));
181
249
  else if (message["meta"] !== undefined)
182
250
  call.resolve({ data: message["data"], meta: message["meta"] });
183
251
  else
@@ -205,14 +273,17 @@ function hostTransport() {
205
273
  operation: operationId,
206
274
  params: request.params ?? {},
207
275
  query,
208
- ...request.body ? { body: request.body } : {}
276
+ ...request.body ? { body: request.body } : {},
277
+ ...request.idempotencyKey ? { idempotency_key: request.idempotencyKey } : {}
209
278
  });
210
279
  })
211
280
  };
212
281
  }
213
282
  export {
283
+ AppCallError,
214
284
  applicationPath,
215
285
  createAppSdk,
216
286
  hostNavigation,
217
- hostTransport
287
+ hostTransport,
288
+ isFieldChanged
218
289
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@almateam/app-sdk",
3
- "version": "0.3.1",
3
+ "version": "0.5.0",
4
4
  "description": "Types, host bridge and the alma-app dev command for apps that run in Alma. Alma builds every app with its own current copy of the SDK; install this for the types and the command.",
5
5
  "license": "MIT",
6
6
  "homepage": "https://docs.alma.team/developers/apps",