@almateam/app-sdk 0.6.0 → 0.8.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.6.0
11
+ npm install --save-dev @alma/app-sdk@npm:@almateam/app-sdk@^0.8.0
12
12
  ```
13
13
 
14
14
  Alma builds an app's source with its own current copy of the SDK, whatever
@@ -36,8 +36,9 @@ const receipt = await alma.setTopicField(topicId, "stage", "Signed");
36
36
 
37
37
  Every call names an Alma `/v1` operation by its OpenAPI operationId
38
38
  (`listTopics`, `createTopic`, `listTopicTypes`, `getTopicRecord`,
39
- `getTopicFactDiscussion`, `downloadTopicFactAttachment`, `setTopicField`,
40
- `runWorkflow`, `listWorkflowExecutions`, `getExecution`, …); the typed helpers
39
+ `getTopicSummary`, `getTopicFactDiscussion`, `downloadTopicFactAttachment`,
40
+ `setTopicField`, `runWorkflow`, `listWorkflowExecutions`, `getExecution`, …);
41
+ the typed helpers
41
42
  wrap `alma.call(operationId, { params, query, body })`. These are the same
42
43
  public routes an API key calls, so an app built on them could run off-platform.
43
44
  The host refuses an unknown operation, a path parameter that is not a UUID (or,
@@ -46,10 +47,11 @@ for a field, a field key), and any operation outside the manifest's `scopes`
46
47
  forwards only the query keys an operation declares.
47
48
 
48
49
  A call resolves once it is done, within 30 seconds, or rejects. A change
49
- (`setTopicField`, `createWorkflowLesson`, `updateLesson`) is the viewer's own
50
- act: it saves as them where they may edit that record and is refused where they
51
- cannot. Nobody is asked and no dialog appears: the promise resolves with the
52
- result, or rejects with the refusal's words.
50
+ (`setTopicField`, `deleteTopic`, `restoreTopic`, `createWorkflowLesson`,
51
+ `updateLesson`) is the viewer's own act: it saves as them where they may edit
52
+ that record and is refused where they cannot. Nobody is asked and no dialog
53
+ appears: the promise resolves with the result, or rejects with the refusal's
54
+ words.
53
55
 
54
56
  A lesson added by a viewer who decides the workflow's lessons (its editors and
55
57
  the workspace's owners) is live at once: `createWorkflowLesson` resolves with
@@ -111,20 +113,142 @@ const filter = await alma.state.get<{ stage: string }>("filter"); // or undefine
111
113
  await alma.state.delete("filter");
112
114
  ```
113
115
 
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
+ If a workflow or Alma needs to see or act on something, or the workspace should
117
+ keep it for other people to find, it is a record. If everyone with the app open
118
+ sees it together, it is shared state (below). If only this app's screen for
119
+ this person needs it, it is app state.
116
120
 
117
121
  State is a small key/value store per installed app and per person: a filter, a
118
122
  collapsed column, a half-written draft. Only that person's sessions of that app
119
123
  read or write it. It needs no scope and no owner's approval, and declaring
120
124
  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`.
125
+ search or anything Alma knows. App state survives a reload and a new version of
126
+ the app, and goes when the app is removed from the workspace or the person
127
+ leaves it. Keys are letters, digits, `_` and `-` (up to 128 characters). A
128
+ value is any JSON up to 16 KB, and one person holds at most 64 keys and 256 KB
129
+ in one installation; a `set` past a limit rejects with a refusal whose `code` is
130
+ `app_state.value_too_large` or `app_state.quota_exceeded`.
131
+
132
+ ## Shared state: what everyone with the app open sees
133
+
134
+ ```ts
135
+ const stop = alma.shared.watch((entry) => {
136
+ // { key, exists, value, revision }: every key once, then each change
137
+ });
138
+ const mine = "player-" + viewer.person_id;
139
+ const joined = await alma.shared.set(mine, { score: 0 }, { ifRevision: 0 });
140
+ try {
141
+ await alma.shared.set(mine, { score: 1 }, { ifRevision: joined.revision });
142
+ } catch (error) {
143
+ if (!isSharedStateConflict(error)) throw error;
144
+ // error.current is the key as it stands: apply the change to it, write again
145
+ }
146
+ ```
147
+
148
+ Shared state is one small key/value store per installed app that everyone who
149
+ can open it reads and writes: a leaderboard's scores, a board's column order, a
150
+ vote, whose turn it is. It survives a reload and needs the `shared_state:write`
151
+ scope. `get(key)` answers `{ key, exists, value, revision }`, with revision 0
152
+ for a key that holds nothing; `list()` answers every key, `set(key, value)` the
153
+ key as written, and `delete(key)` removes it. `watch(listener)` calls its
154
+ listener with every key, then with each key as it changes, whoever changed it,
155
+ within a second or two, and with `exists: false` for a key deleted; it returns
156
+ the unsubscribe. An app never polls: where the host cannot tell (an Alma tab
157
+ from before it, the check Alma runs on a new version, or a channel the server
158
+ refuses), `watch` reads by itself, every 5 seconds and less often while nothing
159
+ changes.
160
+
161
+ Keep what each person changes under a key of their own, so two people writing
162
+ at once never write over each other, and keep that key the same between visits
163
+ (an id kept in `alma.state` the first time). Send one write at a time and fold
164
+ changes made meanwhile into the next. With `{ ifRevision }`, a `set` writes only
165
+ over that revision (0: only where the key holds nothing) and otherwise rejects
166
+ with an error `isSharedStateConflict` recognizes, whose `current` is the key as
167
+ it stands.
168
+
169
+ Keys are letters, digits, `_` and `-` (up to 128 characters). A value is any
170
+ JSON up to 16 KB; one installation holds at most 128 keys and 256 KB, and
171
+ everyone using it together may write 60 times at once, then 10 a second (a
172
+ `delete` counts as a write, and so does a write refused for a conflict or the
173
+ quota). A write past a limit rejects with a refusal whose `code` is
174
+ `app_shared_state.value_too_large`, `app_shared_state.quota_exceeded` or
175
+ `app_shared_state.rate_limited`. `alma_get_app_builder_guide` hands out a
176
+ multiplayer leaderboard built this way, with presence and quick messages, as
177
+ `live.sample`.
178
+
179
+ ## The viewer: which person is looking
180
+
181
+ ```ts
182
+ const viewer = await alma.viewer(); // { person_id } or null
183
+ const isMine = (owner: { topic_id: string } | null) =>
184
+ viewer !== null && owner?.topic_id === viewer.person_id;
185
+ ```
186
+
187
+ `viewer()` names the viewer's own `person` record: the one the workspace's
188
+ directory links to their Alma account. The host answers it from the session the
189
+ server opened for the signed-in person, so nothing an app sends can change it.
190
+ An app is told only when its manifest declares the `viewer:read` scope, which an
191
+ owner sees when the app is shared like every other scope; Alma's own apps are
192
+ told under `topics:read`. Read the record itself with `getTopicRecord`, which
193
+ needs `topics:read`. `viewer()` is `null` for an app without the scope, and also
194
+ when no directory entry is linked to the viewer's account, they cannot open that
195
+ record, or the app is open in an Alma tab from before the question. `null` is an
196
+ answer, not a failure; an app that needs to know asks the person then (and can
197
+ keep the answer in state). The host answers from its latest session, so the
198
+ answer can change when the app is reopened.
199
+
200
+ What everyone using the app sees of each person while they use it (a
201
+ leaderboard that names its players) goes in shared state, under a key per
202
+ person. What the workspace keeps of each person after the app closes is written
203
+ as records with a relationship to the `person` type: a record is the viewer's
204
+ own where that relationship holds their `person_id`.
205
+
206
+ ## Who else is here
207
+
208
+ ```ts
209
+ const stop = alma.presence.watch(({ count, people }) => {
210
+ // people: [{ person_id }] with viewer:read, null without it
211
+ });
212
+ ```
213
+
214
+ `presence.watch` tells the app who has this installation open right now: once
215
+ the host knows, and again within a second or two of anyone opening or closing
216
+ it. `count` includes the viewer while they are shown. `people` names each
217
+ person once by their `person` record, and only to an app that declares
218
+ `viewer:read`, so `count` can be more than `people` holds when a copy open
219
+ elsewhere names no one; without it, `people` is `null` and `count` counts open
220
+ copies, so one person with two tabs counts twice. Someone is present only
221
+ while their "Show when I'm viewing a task" switch is on and they are not in Do
222
+ not disturb, and they still see who else is. Where the host cannot tell (an
223
+ Alma tab from before the question, or no live connection), the listener is
224
+ never called: no answer means not known, not nobody. It needs no scope.
225
+
226
+ ## Quick messages to everyone viewing
227
+
228
+ ```ts
229
+ await alma.broadcast("cursor", { x: 120, y: 48 });
230
+ const stop = alma.onBroadcast("cursor", (payload) => {
231
+ // another viewer's cursor moved
232
+ });
233
+ ```
234
+
235
+ `broadcast` sends a quick message to everyone who has this installation open
236
+ right now, and `onBroadcast` calls its listener with the payload of each one
237
+ sent under that event name, within about a second. The sender's own listeners
238
+ are not called unless it passes `{ self: true }` as the third argument. Nothing
239
+ is kept: someone who opens the app later, or whose connection drops for a
240
+ moment, never hears it, so what a late viewer needs goes in shared state. An
241
+ event name is letters, digits, `_`, `.`, `:` and `-` (up to 128 characters),
242
+ and a payload is any JSON up to 8 KB. One viewer may send 20 at once in one
243
+ installation, then 10 a second. A send past a limit rejects with a refusal
244
+ whose `code` is `app_broadcast.payload_too_large` or
245
+ `app_broadcast.rate_limited`. Where the workspace's IP allowlist is in force,
246
+ no message is sent, because it cannot be checked against each listener's
247
+ address: a viewer on an approved network is refused with
248
+ `app_broadcast.ip_allowlist_in_force`, and one outside it is refused like any
249
+ other call. Both need the `shared_state:write` scope; without it, the listener
250
+ is never called.
251
+ `onBroadcast` returns the unsubscribe.
128
252
 
129
253
  ## Records: the workspace's typed topics
130
254
 
@@ -136,13 +260,53 @@ and its `relationships` (a `label`, the key of the type it points at, such as
136
260
  app, the workspace's type of that key is reused, gaining what it lacks, or
137
261
  created. `listTopics({ type, filter, sort })` reads them as the viewer,
138
262
  `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.
263
+ id from `listTopicTypes()`) creates one with the app's audience: who can see it
264
+ is set in Alma, never by the app. `createTopic(name, typeId, { fields })` saves
265
+ the record and its first values in one request, as the viewer's own confirmed
266
+ word, each entry a `key`, a `value` and, for a relationship, a `refTopicId`.
267
+ It needs no scope beyond `facts:confirm`. Nothing is created if one value is
268
+ refused, and the refusal starts with the field's key. A request denied whole,
269
+ such as one with a credential in a value, names no field.
270
+ `deleteTopic(topicId)` deletes one of the app's own records (a type declared
271
+ `"scope": "app"`, which a type naming no scope gets) as the viewer, where they
272
+ can edit it, and Alma keeps it for 30 days; any other record rejects as not
273
+ found. Retried under the same `idempotencyKey`, it answers with the first result
274
+ while the record stays deleted, and deletes it again once it has been restored.
275
+ `restoreTopic(topicId)` is its Undo: the person who deleted one of the app's
276
+ records brings it back within those 30 days, while they can still edit it, and
277
+ it resolves with `{ id, name, cleared }`, where `cleared` lists the values that
278
+ did not come back because they no longer fit the record's type. A record
279
+ somebody else deleted rejects as not found. One past its 30 days rejects with
280
+ the refusal's words until Alma removes it for good, then as not found. Retried
281
+ under the same `idempotencyKey`, it answers with the latest result while the
282
+ record stays restored, and restores it again once it has been deleted again. Someone who
283
+ edits the app can also restore a record from its Data. A relationship's values
284
+ sit under `rel_<label>__<type key>` (`rel_csm__person`). A version declaring a
285
+ type, field or relationship the shared version did not is wider and asks an
286
+ owner; while the app is installed, the workspace's schema editor lists it under
287
+ "Used by" and refuses to retype or remove what it declares.
288
+
289
+ ## Views: a type's saved views
290
+
291
+ A type's saved views (the filters, search, sort, grouping and columns its grid
292
+ opens on) are the workspace's, saved in the grid or by Alma. `listViews(type)`
293
+ lists the ones the viewer can open, each `{ key, name, scope }`, and
294
+ `readView(type, key, { cursor, limit })` reads a page of one as the viewer:
295
+ `view`, the `columns` it shows, `data` with each record's values for them, and
296
+ `meta` with `next_cursor`, `total` and, for a grouped view, `groups` counting
297
+ each group. A type the manifest declares can declare its own `views`, made
298
+ shared on the type when the app is shared, so the app reads them by the keys it
299
+ chose.
300
+
301
+ ```ts
302
+ const page = await alma.readView("account", "renewals-this-quarter");
303
+ for (const column of page.columns) console.info(column.name, column.kind);
304
+ const next = page.meta.next_cursor
305
+ ? await alma.readView("account", "renewals-this-quarter", {
306
+ cursor: page.meta.next_cursor,
307
+ })
308
+ : null;
309
+ ```
146
310
 
147
311
  ## Workflows: the app's backend
148
312
 
@@ -152,13 +316,21 @@ managers and run as they stand. `listWorkflows()` marks them `runnable` where
152
316
  the viewer may start them, and where they may not gives the reason in
153
317
  `not_runnable` (`{ code, reason }`, the sentence `runWorkflow` would refuse
154
318
  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
159
- `GET /v1/executions/{id}` with backoff: a run paused at an approval step reads
160
- `waiting`, with the people it waits on in `approvers` (its Task is theirs, not
161
- the viewer's), and a failed run's `error` is safe to show.
319
+ `runWorkflow(id, { topicId, input })` starts one
320
+ (`POST /v1/workflows/{id}/executions`), with nobody asked, where the workflow's
321
+ owner granted the app **Can run** on its access list or the viewer can run it
322
+ themselves, and on a record the viewer can see. Naming a workflow grants the app
323
+ nothing. The run acts as the workflow, on its own permissions and step accounts,
324
+ not as the viewer; only a step account set to whoever starts the run goes out
325
+ on the viewer's own connection. Follow it with `waitForExecution(run.id, { onUpdate })`,
326
+ which polls `GET /v1/executions/{id}` with backoff: a run paused at an approval
327
+ step reads `waiting`, with the people it waits on in `approvers` (its Task is
328
+ theirs, not the viewer's), and a failed run's `error` is safe to show. When the
329
+ workflow's last step runs as code and its program finishes it, the run's
330
+ `result` is the JSON the program returned (null otherwise, or past 64 KB);
331
+ `waitForExecution<T>(run.id)` and `listRuns<T>` type it as `T | null`. It is
332
+ read as `response_content` is: whoever started the run gets it unless the run
333
+ read something sensitive, and then gets neither.
162
334
 
163
335
  A run started on a record can set that record's fields itself, so an app does
164
336
  not write a run's outcome. Each run carries `field_writes`: one entry for each
@@ -185,6 +357,34 @@ An attachment download returns only a receipt (`attachment_id`, `filename`,
185
357
  `status`): the host fetches the file itself, and neither its URL nor the session
186
358
  token reaches the app.
187
359
 
360
+ ## Events: what the app tells workflows happened
361
+
362
+ An app can also say that something happened and let the workspace's workflows
363
+ decide what to do about it. The manifest declares each event the app raises
364
+ (`events: [{ name, description }]`, lowercase names such as `score.posted`), and
365
+ the owner approves them when sharing; adding one is a new version to approve.
366
+ `raiseEvent(name, payload)` (`POST /v1/app-events`, with the `events:raise`
367
+ scope) raises one for the viewer: every workflow whose trigger names this app
368
+ and this event starts, as the workflow, with `payload` (a JSON object of at most
369
+ 16 KB) as data it does not trust. The answer is the same whether or not a
370
+ workflow listens, so an app cannot tell. The trigger lives on the workflow, so
371
+ raising an event no workflow listens to is fine.
372
+
373
+ An event the shared version does not declare rejects with `event.undeclared`,
374
+ and a draft raises nothing (`app.draft`). Everyone using the app together can
375
+ raise 30 events an hour, after a burst of 10; past that a raise rejects with
376
+ `event.rate_limited`, and its message says how many seconds to wait. Raise an
377
+ event for something a person did, not on a timer.
378
+
379
+ ```ts
380
+ try {
381
+ await alma.raiseEvent("score.posted", { player: viewer.name, score });
382
+ } catch (error) {
383
+ if ((error as AppCallError).code === "event.rate_limited") showLater();
384
+ else throw error;
385
+ }
386
+ ```
387
+
188
388
  ## Developing an app
189
389
 
190
390
  The package carries the `alma-app` command, which runs under Node.