@flipstream/sdk 0.9.0 → 0.10.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 (87) hide show
  1. package/CHANGELOG.md +73 -0
  2. package/README.md +534 -487
  3. package/dist/api/backend.d.ts +182 -0
  4. package/dist/api/backend.js +314 -0
  5. package/dist/api/backend.js.map +1 -0
  6. package/dist/api/created.d.ts +5 -0
  7. package/dist/api/created.js +15 -0
  8. package/dist/api/created.js.map +1 -0
  9. package/dist/api/credentials.d.ts +36 -0
  10. package/dist/api/credentials.js +94 -0
  11. package/dist/api/credentials.js.map +1 -0
  12. package/dist/api/datasets.d.ts +94 -0
  13. package/dist/api/datasets.js +212 -0
  14. package/dist/api/datasets.js.map +1 -0
  15. package/dist/api/handoff.d.ts +34 -0
  16. package/dist/api/handoff.js +52 -0
  17. package/dist/api/handoff.js.map +1 -0
  18. package/dist/api/ids.d.ts +7 -0
  19. package/dist/api/ids.js +27 -0
  20. package/dist/api/ids.js.map +1 -0
  21. package/dist/api/index.d.ts +9 -1
  22. package/dist/api/log.d.ts +95 -0
  23. package/dist/api/log.js +213 -0
  24. package/dist/api/log.js.map +1 -0
  25. package/dist/api/me.d.ts +58 -0
  26. package/dist/api/me.js +64 -0
  27. package/dist/api/me.js.map +1 -0
  28. package/dist/api/members.d.ts +48 -0
  29. package/dist/api/members.js +102 -0
  30. package/dist/api/members.js.map +1 -0
  31. package/dist/api/organization.d.ts +11 -0
  32. package/dist/api/organization.js +15 -0
  33. package/dist/api/organization.js.map +1 -0
  34. package/dist/api/page.d.ts +33 -0
  35. package/dist/api/page.js +38 -0
  36. package/dist/api/page.js.map +1 -0
  37. package/dist/api/time.d.ts +3 -0
  38. package/dist/api/time.js +49 -0
  39. package/dist/api/time.js.map +1 -0
  40. package/dist/api/unsent.d.ts +6 -0
  41. package/dist/api/unsent.js +9 -0
  42. package/dist/api/unsent.js.map +1 -0
  43. package/dist/api/wallet.d.ts +45 -0
  44. package/dist/api/wallet.js +102 -0
  45. package/dist/api/wallet.js.map +1 -0
  46. package/dist/api/workspaces.d.ts +70 -0
  47. package/dist/api/workspaces.js +108 -0
  48. package/dist/api/workspaces.js.map +1 -0
  49. package/dist/core/body.js +23 -5
  50. package/dist/core/body.js.map +1 -1
  51. package/dist/core/call.d.ts +6 -0
  52. package/dist/core/call.js +1 -1
  53. package/dist/core/call.js.map +1 -1
  54. package/dist/core/fetch.js +4 -1
  55. package/dist/core/fetch.js.map +1 -1
  56. package/dist/core/names.d.ts +39 -0
  57. package/dist/core/names.js +41 -0
  58. package/dist/core/names.js.map +1 -1
  59. package/dist/core/read.d.ts +1 -1
  60. package/dist/core/read.js +7 -4
  61. package/dist/core/read.js.map +1 -1
  62. package/dist/core/result.d.ts +41 -3
  63. package/dist/core/result.js +18 -4
  64. package/dist/core/result.js.map +1 -1
  65. package/dist/core/secrets.d.ts +2 -0
  66. package/dist/core/secrets.js +33 -0
  67. package/dist/core/secrets.js.map +1 -0
  68. package/dist/core/transport.d.ts +6 -2
  69. package/dist/flipstream.d.ts +296 -4
  70. package/dist/flipstream.js +172 -23
  71. package/dist/flipstream.js.map +1 -1
  72. package/dist/index.d.ts +1 -1
  73. package/dist/node/clientSecret.js +1 -0
  74. package/dist/node/clientSecret.js.map +1 -1
  75. package/dist/node/fileLock.d.ts +20 -2
  76. package/dist/node/fileLock.js +22 -13
  77. package/dist/node/fileLock.js.map +1 -1
  78. package/dist/node/keychainStore.d.ts +10 -0
  79. package/dist/node/keychainStore.js +33 -13
  80. package/dist/node/keychainStore.js.map +1 -1
  81. package/dist/node/session.d.ts +1 -2
  82. package/dist/node/session.js +22 -14
  83. package/dist/node/session.js.map +1 -1
  84. package/dist/version.gen.js +1 -1
  85. package/dist/version.gen.js.map +1 -1
  86. package/docs/node-sign-in.md +503 -0
  87. package/package.json +3 -2
package/README.md CHANGED
@@ -83,537 +83,500 @@ function shownAs(format: Format): string {
83
83
  }
84
84
  ```
85
85
 
86
- ## Signing in from Node and the CLI
86
+ ## Who you are
87
87
 
88
- For an app that runs on the person's own machine, or in their terminal: a CLI, a script, a local
89
- tool. `@flipstream/sdk/node` signs them in through their browser, with OAuth 2.0's authorisation
90
- code and PKCE. Signing in stores nothing: the tokens are the app's to keep, and the SDK has stores
91
- ready for them (see "Keeping the person signed in"). A web app signs in on its server instead (see
92
- "In a browser").
88
+ `flipstream.me()` answers your organisation, and you in it:
93
89
 
94
- In a TypeScript project, add `@types/node` (`npm install --save-dev @types/node`): this entry's
95
- types use Node's own.
90
+ ```ts
91
+ import { createFlipstream, orThrow } from '@flipstream/sdk'
96
92
 
97
- **Against an auth server on your own machine,** while developing it, pass `allowLocalhostHttp: true`
98
- to `discover`, `signInWithLoopback`, `finishSignIn` and `createSession`, as `createFlipstream` takes
99
- it. Plain http is then accepted for `localhost`, `127.0.0.1` and `[::1]` only, and every endpoint
100
- such a server names must be on its own origin. It's off unless your code sets it: the SDK never
101
- reads it from the environment. Never set it in production.
93
+ const flipstream = createFlipstream({ app: { name: 'my-app', version: '1.0.0' }, token: async () => '<your token>' })
102
94
 
103
- ### With a browser on the same machine
95
+ const { organization, user } = orThrow(await flipstream.me())
96
+ console.log(organization.name, user.email, user.role)
97
+ ```
104
98
 
105
- `signInWithLoopback` opens a one-time server on `127.0.0.1`, on a port the system chooses, and
106
- waits for the browser to come back to it.
99
+ - **`organization`** is `{ id, name, slug, access }`. The slug is its short name, as the console's
100
+ addresses spell it.
101
+ - `access` says whether the organisation may use Flipstream, read from its billing settings by
102
+ the console's rules, in the service's own words:
103
+ - `{ status: 'trial', trial_ends_on }`: in trial, with `trial_ends_on` the trial's last day as
104
+ `YYYY-MM-DD`;
105
+ - `{ status: 'active' }`;
106
+ - `{ status: 'expired', trial_ends_on }`: the service's `expired`, which doesn't say why. Today
107
+ it only ever follows a trial. `trial_ends_on` is the trial's end, not necessarily the day
108
+ access ended;
109
+ - `{ status: 'unknown' }`: settings that can't be read, or a status this version doesn't know.
110
+ It's never read as active, and it never fails `me()`.
111
+ - The status is the truth. A trial past its last day stays `trial` until the service says
112
+ otherwise: the SDK never reads the clock for it. A day that isn't a real `YYYY-MM-DD` is `null`.
113
+ - Every role reads the same access, a viewer limited to some workspaces and Flipstream's own
114
+ staff included.
115
+ - **`user`** is `{ id, email, first_name, last_name, role, active, workspace_ids }`: a `Member`, as
116
+ `flipstream.members` answers each person (see "Your organisation's members").
117
+ - `me()` reads the token's own person and doesn't apply `members`' people-only rule. An API key's
118
+ token isn't tested with it yet: service accounts come with pulse-admin#93.
119
+ - `role` is the highest you hold: `'owner'`, `'admin'`, `'editor'` or `'viewer'`. It's `null`
120
+ when you hold none of them, and for Flipstream's own staff (`godmode`, `swapper`), whatever
121
+ else they hold. There's no guest role yet. A role this version doesn't know counts as none of
122
+ ours: it never fails the answer, a known role beside it still wins, and its name is never shown.
123
+ - `active` says whether your account is switched on.
124
+ - `workspace_ids` are the workspaces your account names. For a viewer, they're the workspaces
125
+ you may open, and a viewer with none opens every workspace of the organisation. No other role
126
+ is limited by them.
127
+ - **Nothing else** from the services' answers is in it.
128
+ - **Three reads:** your organisation, and who your token belongs to, then that person. They share
129
+ one deadline, 30 s unless the call sets its own, and the first failure, in that order, is the
130
+ answer.
131
+ - **Renaming your organisation is a person's to do, in the console.**
132
+ `flipstream.organization.rename({ name })` never writes. It reads your organisation, then
133
+ answers `needs_person` with `why`. Where a console can be named (your own `hosts.console`), the
134
+ organisation's settings page is the `url`, with what it shows as `sees`, as `workspaces.rename`
135
+ does. There, Owners and Admins change the name and the short name. The `name` you give is never
136
+ echoed.
137
+
138
+ ## Your organisation's members
139
+
140
+ `flipstream.members` reads the people of your organisation, one page at a time, each as `me()`
141
+ answers you. People, not keys: an API user, a service account, is never listed, counted or
142
+ answered, as the console's People has it. (`me()` doesn't apply that rule: see "Who you are".)
107
143
 
108
144
  ```ts
109
- import { createFlipstream, discover } from '@flipstream/sdk'
110
- import { signInWithLoopback } from '@flipstream/sdk/node'
145
+ import { createFlipstream, orThrow } from '@flipstream/sdk'
111
146
 
112
- const server = await discover('https://auth.flipstream.io')
113
- if (!server.ok) throw new Error(`sign-in is unavailable: ${server.error.kind}`)
147
+ const flipstream = createFlipstream({ app: { name: 'my-app', version: '1.0.0' }, token: async () => '<your token>' })
114
148
 
115
- const signedIn = await signInWithLoopback({
116
- server: server.data,
117
- clientId: '<your client id>',
118
- scopes: ['<scope>'],
119
- // Show the person where to sign in: open their browser, or print the URL.
120
- open: (url) => {
121
- console.log(`Sign in at ${url}`)
122
- },
123
- })
124
- if (!signedIn.ok) throw new Error(`sign-in failed: ${signedIn.error.kind}`)
149
+ const page = orThrow(await flipstream.members.list({ limit: 50 }))
150
+ for (const member of page.items) console.log(member.email, member.role, member.active)
125
151
 
126
- const flipstream = createFlipstream({ app: { name: 'my-cli', version: '1.0.0' }, token: () => signedIn.data.accessToken })
152
+ const member = orThrow(await flipstream.members.get({ member_id: page.items[0]?.id ?? '<member id>' }))
153
+ console.log(member.first_name, member.workspace_ids.length)
127
154
  ```
128
155
 
129
- - **The SDK opens nothing and writes nothing to the terminal.** `open` does that, once the port is
130
- open.
131
- - **The port listens on `127.0.0.1` only,** and is closed on every path: signed in, refused, timed
132
- out (after 5 minutes, or `timeoutMs`), aborted (`signal`), or `open` or `readPasted` failing.
133
- - **The redirect is checked before its code is exchanged:** the sign-in's own state first, then the
134
- issuer.
135
- - **`page: { signedIn, failed }`** sets the HTML the browser shows afterwards.
136
- - **What comes back:** `accessToken`, `scope`, `expiresAt` (ms since the epoch) when the server
137
- says, and `refreshToken` when it issues one. Never log them.
138
-
139
- ### When the browser may not reach this machine
140
-
141
- **The way for a CLI, or any app that waits while the person signs in.** In a remote session
142
- nothing may say so (a tmux session started before the SSH login sets no `SSH_*` variable), and
143
- the person's browser, on their own device, then can't load the address it's sent back to. Give
144
- `signInWithLoopback` a `readPasted` as well: the person pastes that address back, and the same
145
- sign-in finishes. Where their browser can reach the port, it does, and the prompt stops.
156
+ - **A member** is `{ id, email, first_name, last_name, role, active, workspace_ids }`, and nothing
157
+ else, with `role` and `workspace_ids` by `me()`'s rules (see "Who you are"): the highest role
158
+ they hold, or `null` for none and for Flipstream's own staff. A role this version doesn't know
159
+ counts as none of ours, and its name is never shown.
160
+ - **An open invitation is in the list:** someone invited who hasn't joined yet has an empty
161
+ `first_name`, as the console tells them apart.
162
+ - **Keys are left out by the service itself,** so `total` counts people.
163
+ - **A list is one page:** `{ items, total, limit, offset }`, where `total` counts every member.
164
+ - The limit is 100 unless you set one, and at most 1,000.
165
+ - A limit or offset that isn't a whole number in range rejects, with nothing sent.
166
+ - **The order is the service's own:** by email. Pages read at different times can overlap, or skip
167
+ a person, when people are added or removed, or an email changes, in between. A changed `total`
168
+ shows some of that, but an unchanged one doesn't prove nothing moved. For a complete, stable
169
+ list, read it in one page: up to 1,000.
170
+ - **Each call reads your organisation beside the people,** under one deadline for both reads, and
171
+ its failure is the answer. In a list, a person of another organisation makes the answer
172
+ `invalid`; they're never shown or dropped.
173
+ - **What `get` answers,** for an id:
174
+ - **the person,** when they're one of your organisation's people;
175
+ - **`not_found`** when there's no such person for you: pulse-auth has none by that id, or your
176
+ role can't read them (it answers 404), or the id is one of your organisation's API keys, which
177
+ `get` answers as an id nobody has;
178
+ - **`forbidden`** when pulse-auth refuses the read (403);
179
+ - **`invalid`** when the answer is another organisation's person or API key, which only a staff
180
+ token reaches, such as Flipstream's staff acting through a swap token. The organisation is
181
+ checked before the key, so another organisation's key is `invalid` too. So is an answer that
182
+ is someone else than the person asked for.
183
+
184
+ ## Workspaces
185
+
186
+ `flipstream.workspaces` reads your organisation's workspaces, one page at a time:
146
187
 
147
188
  ```ts
148
- import { discover } from '@flipstream/sdk'
149
- import { signInWithLoopback } from '@flipstream/sdk/node'
150
- import { createInterface } from 'node:readline/promises'
189
+ import { createFlipstream, orThrow } from '@flipstream/sdk'
151
190
 
152
- const server = await discover('https://auth.flipstream.io')
153
- if (!server.ok) throw new Error(`sign-in is unavailable: ${server.error.kind}`)
191
+ const flipstream = createFlipstream({ app: { name: 'my-app', version: '1.0.0' }, token: async () => '<your token>' })
154
192
 
155
- const prompt = createInterface({ input: process.stdin, output: process.stdout })
156
- const signedIn = await signInWithLoopback({
157
- server: server.data,
158
- clientId: '<your client id>',
159
- scopes: ['<scope>'],
160
- open: (url) => {
161
- console.log(`Sign in at ${url}`)
162
- },
163
- // The signal fires once a paste can't be taken any more, and stops the prompt.
164
- readPasted: (signal) => prompt.question('If your browser fails to load the page after signing in, paste its address here: ', { signal }),
165
- })
166
- prompt.close()
167
- if (!signedIn.ok) throw new Error(`sign-in failed: ${signedIn.error.kind}`)
168
- ```
193
+ const page = orThrow(await flipstream.workspaces.list({ limit: 50 }))
194
+ console.log(page.total, page.items.map((workspace) => workspace.name))
169
195
 
170
- - **Whichever comes first is taken,** the port's redirect or the paste, and only its code is
171
- exchanged. Once one is taken, the port answers anything else with the failure page, and a later
172
- paste is dropped.
173
- - **A paste is checked before anything is sent,** as `parsePastedRedirect` checks one: this
174
- sign-in's own address, then its state. A paste that fails ends the sign-in with its reason, such
175
- as `wrong_state`, and nothing is exchanged.
176
- - **A reader that rejects** ends the sign-in as `paste_failed`. `readPasted` is called once, just
177
- after `open`.
196
+ const workspace = orThrow(await flipstream.workspaces.get({ workspace_id: page.items[0]?.id ?? '<workspace id>' }))
197
+ console.log(workspace.slug)
198
+ ```
178
199
 
179
- ### Over SSH, in CI, or with no display
200
+ - **A workspace** is `{ id, name, slug }`. Nothing else the service sends is in it.
201
+ - **A page** is `{ items, total, limit, offset }`. `total` counts every workspace, and `limit` and
202
+ `offset` say what was read. `limit` is 100 when left out and at most 1,000, and a larger one is
203
+ read as 1,000. A limit or offset that isn't a whole number in range rejects with a `TypeError`,
204
+ with nothing sent.
205
+ - **The order is the service's own:** by name alone, for workspaces. Pages read at different times
206
+ can overlap, or skip a workspace, when workspaces are added, removed or renamed in between, or
207
+ when two have the same name. A changed `total` shows some of that, but an unchanged one doesn't
208
+ prove nothing moved. For a complete, stable list, read it in one page: up to 1,000.
209
+ - **Each call reads your organisation first,** under one deadline for both reads, and its failure
210
+ is the answer. A workspace of another organisation makes the answer `invalid`; it's never shown
211
+ or dropped.
212
+ - **Creating a workspace:** `flipstream.workspaces.create({ name })` makes one in your organisation
213
+ and answers it as a `Workspace`.
214
+
215
+ ```ts
216
+ import { createFlipstream, orThrow } from '@flipstream/sdk'
217
+
218
+ const flipstream = createFlipstream({ app: { name: 'my-app', version: '1.0.0' }, token: async () => '<your token>' })
219
+
220
+ const made = orThrow(await flipstream.workspaces.create({ name: 'Acme NL' }))
221
+ console.log(made.id, made.slug) // the short name the service chose, such as 'acme-nl-2'
222
+ ```
223
+
224
+ - It sends the name alone, with your organisation. The service makes the short name, unique in
225
+ your organisation, so read `slug` from the answer.
226
+ - **A request with any key but `name` is `refused`** (`reason: 'fields'`, naming them), with
227
+ nothing sent: a `slug` or an `organization_id` it dropped would look set. A `name` that isn't a
228
+ non-empty string, or is only spaces, rejects with a `TypeError`, with nothing sent.
229
+ - Who may create one is the service's rule, not the SDK's: Owners and Admins. pulse-admin#181
230
+ aligns the service with it; until then an Editor still succeeds. Anyone it refuses gets
231
+ `forbidden`.
232
+ - **It's never tried again.** Only a refusal (a 4xx kind such as `forbidden`), `refused` or
233
+ `no_token` shows nothing was made. After any other failure (`timeout`, `unavailable`,
234
+ `aborted`, `cancelled`, or `invalid`, which may be the service's answer that it made one) it may
235
+ have been made, so list the workspaces before you create it again. Names needn't be unique, so
236
+ compare that list with one from before you created it.
237
+ - **Renaming or deleting a workspace is a person's to do, in the console.**
238
+ `flipstream.workspaces.rename({ workspace_id, name })` and `delete({ workspace_id })` never write.
239
+ Each reads the workspace (one that isn't yours is `not_found`), then answers `needs_person`:
240
+
241
+ ```ts
242
+ import { createFlipstream } from '@flipstream/sdk'
243
+
244
+ const flipstream = createFlipstream({
245
+ app: { name: 'my-app', version: '1.0.0' },
246
+ token: async () => '<your token>',
247
+ hosts: { console: 'http://localhost:5173' },
248
+ })
180
249
 
181
- When no browser can come back to this machine, the person opens the URL on another device. The
182
- redirect then fails to load, and they paste back the address it ended on. If one process waits for
183
- them, `readPasted` above does this. The two halves below are for when the app can't wait, or
184
- won't open a port: it keeps `pending` until the paste comes, for instance in a second command.
185
- `isHeadless` tells you when no browser can come back.
250
+ const result = await flipstream.workspaces.rename({ workspace_id: '<workspace id>', name: 'New name' })
251
+ if (!result.ok && result.error.kind === 'needs_person') {
252
+ console.log(result.error.why) // tell the person what to do, and why
253
+ if (result.error.url !== undefined) console.log(result.error.url, result.error.sees)
254
+ }
255
+ ```
186
256
 
187
- ```ts
188
- import { discover, finishSignIn, startSignIn } from '@flipstream/sdk'
189
- import { isHeadless, parsePastedRedirect } from '@flipstream/sdk/node'
190
- import { createInterface } from 'node:readline/promises'
257
+ - `why` is the SDK's own words, never a value you gave, so it's safe to show.
258
+ - `url` and `sees` name the workspace's settings page, and are there only when a console can be
259
+ named: set `hosts.console` (for example `http://localhost:5173`, while developing). It must be
260
+ https, or http on this machine, with no query, fragment or credentials, or `createFlipstream`
261
+ throws a `TypeError`.
262
+ - `orThrow` throws it as an `ApiFailure` whose message gives `why`.
191
263
 
192
- const server = await discover('https://auth.flipstream.io')
193
- if (!server.ok) throw new Error(`sign-in is unavailable: ${server.error.kind}`)
264
+ ## A workspace's logbook
194
265
 
195
- if (isHeadless(process.env)) {
196
- const { url, pending } = await startSignIn({
197
- server: server.data,
198
- clientId: '<your client id>',
199
- redirectUri: 'http://127.0.0.1:8976/callback',
200
- scopes: ['<scope>'],
201
- })
202
- console.log(`Open this on any device and sign in:\n${url}`)
266
+ `flipstream.log` reads and writes a workspace's logbook: its notes on time ranges, such as a launch
267
+ or a site migration.
203
268
 
204
- const prompt = createInterface({ input: process.stdin, output: process.stdout })
205
- const pasted = parsePastedRedirect(await prompt.question('Paste the address your browser ended on: '), pending)
206
- prompt.close()
207
- if (!pasted.ok) throw new Error(`that isn't this sign-in's redirect: ${pasted.error.kind}`)
269
+ ```ts
270
+ import { createFlipstream, orThrow } from '@flipstream/sdk'
208
271
 
209
- const signedIn = await finishSignIn(pasted.callbackUrl, pending)
210
- if (!signedIn.ok) throw new Error(`sign-in failed: ${signedIn.error.kind}`)
211
- }
212
- ```
272
+ const flipstream = createFlipstream({ app: { name: 'my-app', version: '1.0.0' }, token: async () => '<your token>' })
213
273
 
214
- - **`isHeadless(env)`** is true in CI, in an SSH session, and on Linux without a display.
215
- - **`parsePastedRedirect`** checks the pasted address as the loopback checks a redirect, before
216
- anything is sent. Prompting for it is the app's.
217
- - **`pending` holds the PKCE verifier,** a secret. Keep it only until the sign-in finishes, and
218
- never log it.
274
+ const page = orThrow(await flipstream.log.list({ workspace_id: '<workspace id>', limit: 50 }))
275
+ for (const entry of page.items) console.log(entry.start_date, entry.end_date, entry.description)
276
+ console.log(`${page.items.length} of ${page.total}`)
219
277
 
220
- ### Keeping the person signed in
278
+ const entry = orThrow(await flipstream.log.get({ log_id: '<log entry id>' }))
279
+ ```
221
280
 
222
- `createSession` keeps an access token fresh from the tokens your store holds, and signs the person
223
- out. It holds a refresh token, so it belongs in a CLI or on a server, never in browser code. The
224
- SDK has two stores ready for it, which keep the store's rules for you.
281
+ - **An entry** is `{ id, description, start_date, end_date, workspace_id, created_on, created_by_id }`,
282
+ and nothing else.
283
+ - `start_date` and `end_date` are ISO 8601 instants in UTC, such as `2026-10-05T00:00:00.000Z`.
284
+ - A point in time starts and ends at once.
285
+ - `created_on` is when it was written, in the same form, and `created_by_id` the person who wrote
286
+ it. Either is `null` when the service holds none.
287
+ - `flipstream.members.get({ member_id: created_by_id })` names the writer. When it doesn't answer
288
+ ok (see "Your organisation's members"), show the writer as unknown, for example for an entry
289
+ Flipstream staff wrote through a swap token.
290
+ - **A list is one page:** `{ items, total, limit, offset }`, where `total` counts every entry.
291
+ - The limit is 100 unless you set one, and at most 1,000.
292
+ - A limit or offset that isn't a whole number in range rejects, with nothing sent.
293
+ - **The order is newest written first:** the logbook's own, since the SDK asks for no other.
294
+ - When an entry was written never changes, so editing an entry doesn't move it.
295
+ - Pages read at different times can still overlap or skip an entry, when one is written or
296
+ removed in between.
297
+ - Entries written at the same moment have no fixed order among themselves.
298
+ - A changed `total` shows that something was added or removed; an unchanged one doesn't prove
299
+ nothing was.
300
+ - **The workspace is read beside the list,** with your organisation, under one deadline: one
301
+ nobody has is `not_found`, and another organisation's is `invalid`, never an empty page. Their
302
+ failure, then the list's, is the answer.
303
+ - **An entry of another workspace or organisation** in the list makes the answer `invalid`; it's
304
+ never dropped.
305
+ - **A missing entry:** `get` answers `not_found`. `get` reads your organisation beside the entry, and
306
+ an answer that is another entry than the one asked for, or another organisation's, is `invalid`.
307
+
308
+ **Writing to it:** `add`, `update` and `remove`.
225
309
 
226
310
  ```ts
227
- import { createFlipstream, discover } from '@flipstream/sdk'
228
- import { createSession, fileStore, KeychainError, keychainStore, signInWithLoopback } from '@flipstream/sdk/node'
229
- import { homedir } from 'node:os'
230
- import { join } from 'node:path'
231
-
232
- const issuer = 'https://auth.flipstream.io'
233
-
234
- // The system's keychain by default. A file that only this user can read when the person asks for
235
- // one, for a machine with no keychain (Linux without a Secret Service, as on most servers). A real
236
- // app remembers that choice, in its config say, so every run uses the same store.
237
- const inFile = process.argv.includes('--tokens-in-file')
238
- const tokensFile = join(homedir(), '.config', 'example-cli', 'tokens.json')
239
- const store = inFile ? fileStore(tokensFile) : keychainStore({ service: 'io.example.cli', account: issuer })
240
- if (inFile) console.error(`Your sign-in is kept in ${tokensFile}, which only your user can read.`)
241
-
242
- // A store that can't be read is the person's to fix: never a quiet switch from the keychain to a file.
243
- const saved = await store.tokens().catch((error: unknown) => {
244
- const why = error instanceof Error ? error.message : String(error)
245
- if (inFile) throw new Error(`${tokensFile} can't be read (${why})`)
246
- const kind = error instanceof KeychainError ? error.failure.kind : undefined
247
- if (kind === 'unavailable') throw new Error('this machine has no keychain: run with --tokens-in-file')
248
- if (kind === 'locked') throw new Error('the keychain is locked: unlock it, or log in at this machine once')
249
- throw new Error(`the keychain can't be read (${why})`)
250
- })
311
+ import { createFlipstream, orThrow } from '@flipstream/sdk'
251
312
 
252
- // Sign in once, and save the tokens. Only signing in needs the server first.
253
- if (saved === null) {
254
- const server = await discover(issuer)
255
- if (!server.ok) throw new Error(`sign-in is unavailable: ${server.error.kind}`)
256
- const signedIn = await signInWithLoopback({
257
- server: server.data,
258
- clientId: '<your client id>',
259
- scopes: ['<scope>'],
260
- open: (url) => {
261
- console.log(`Sign in at ${url}`)
262
- },
263
- })
264
- if (!signedIn.ok) throw new Error(`sign-in failed: ${signedIn.error.kind}`)
265
- await store.save(signedIn.data)
266
- }
313
+ const flipstream = createFlipstream({ app: { name: 'my-app', version: '1.0.0' }, token: async () => '<your token>' })
267
314
 
268
- // The session discovers the server itself, only when a refresh or a sign-out needs it.
269
- const session = createSession({ issuer, clientId: '<your client id>', ...store })
270
- const flipstream = createFlipstream({ app: { name: 'my-cli', version: '1.0.0' }, token: session.token })
271
-
272
- // Signing out ends the session at the server, then clears the store through onTokens, and says
273
- // how each went.
274
- const signedOut = await session.revoke()
275
- console.log(signedOut.kind)
276
- if (signedOut.cleared === 'failed') {
277
- // Where the store failed (read, lock or clear), and its own error: a KeychainError says why.
278
- const { step, cause } = signedOut.failure
279
- console.error(`the tokens may still be stored: the ${step} failed (${cause instanceof Error ? cause.message : String(cause)})`)
280
- } else if (signedOut.cleared !== 'cleared' && signedOut.cleared !== 'kept') {
281
- console.error(`the tokens may still be stored (${signedOut.cleared}): sign out again`)
282
- }
315
+ const added = orThrow(
316
+ await flipstream.log.add({ workspace_id: '<workspace id>', description: 'Site migration', start_date: '2026-10-05T00:00:00Z', end_date: '2026-10-06T00:00:00Z' }),
317
+ )
318
+ orThrow(await flipstream.log.update({ log_id: added.id, description: 'Site migration, phase 1' }))
319
+ orThrow(await flipstream.log.remove({ log_id: added.id })) // null
283
320
  ```
284
321
 
285
- - **`issuer`,** as above, discovers the server itself, only when a refresh or a sign-out needs it,
286
- and keeps it. A command holding a token with time left then sends nothing to the auth host, and
287
- an outage there doesn't stop it. Give exactly one of `issuer` and `server`, from your own
288
- `discover` (as in "Writing your own store" below).
289
- - **Write the issuer exactly as its metadata names it,** with no slash at the end for
290
- `https://auth.flipstream.io`. Any other spelling fails every discovery.
291
- - **A discovery that gets no answer** (offline, a 5xx, a timeout) is `unavailable` from
292
- `token()`. **One answered outside the contract** (a 404, metadata naming another issuer) is
293
- `refresh_failed`, with the error: waiting won't mend it. From `revoke()`, either is
294
- `unconfirmed`. A failed discovery is tried again at the next need.
295
- - **What it guarantees:** with a store that shows only what it has saved and compares and sets on
296
- `replaces`, and one lock shared by every process, the session never sends a refresh token another
297
- refresh is spending, never hands out a token that wasn't saved, never overwrites a newer sign-in,
298
- and says `revoked` only when the server took the access token just before and refuses it just
299
- after. A lost answer or a failed save can still leave a spent token stored, and a server fault
300
- between the two checks reads as `revoked`.
301
- - **The ready-made stores keep both rules:** each shows only what it has saved, and saves a
302
- refresh's tokens only while it still holds the ones they replace, so a newer sign-in is kept.
303
- `save` is for a sign-in's tokens, and `clear` for an app that signs out without a session:
304
- `session.revoke()` clears the store itself.
305
- - **`fileStore(path)`** is for a machine with no keychain, chosen by the app or the person, never
306
- switched to quietly when the keychain fails: tell them where the file is. **The risk:** anyone
307
- who can read their files, as them or as an administrator, can use the tokens in it.
308
- It writes the whole file under a temporary name in its folder, flushes it to disk, renames it
309
- over the old one and flushes the folder: a reader, or a power cut, sees the old
310
- tokens or the new ones, never half. The file's mode is 0600, and a folder it makes is 0700. It
311
- refuses a file that is a link, isn't this user's or is open to others, and it won't read or
312
- save in a folder others can write to. On Windows the folder isn't flushed, and nothing checks
313
- who owns what. With `{ lock: true }` it also brings a lock for several processes (see
314
- "Several processes on one store").
315
- - **`keychainStore({ service, account })`** keeps the tokens in one item of the system's
316
- credential store: the macOS keychain, Windows' Credential Manager, or the Secret Service on
317
- Linux (GNOME Keyring, KWallet). It needs the optional package `@napi-rs/keyring`
318
- (`npm install @napi-rs/keyring`).
319
- - **Every failure of the keychain or its helper is a `KeychainError`,** which is also the
320
- `cause` of a session's `store_failed`. Three failures are the store's own, not the
321
- keychain's: `save` rejects tokens with no access token as a `TypeError` before any step; an
322
- item holding something other than tokens fails its read with a plain `Error` that never
323
- quotes it; and an update for tokens the item no longer holds is refused with a
324
- `StoreMovedOnError`, which a sign-out reads as `kept` and a refresh reports as `store_failed`
325
- (`save`). A `KeychainError`'s `failure.kind` says why:
326
- - `unavailable`: there's no keychain on this machine, as on Linux with no Secret Service or no
327
- D-Bus session (most servers and containers). It's the only kind after which a file may
328
- stand in, if your app or the person chooses it;
329
- - `locked`: the keychain is locked and can't ask to be unlocked, as on a Mac over SSH after a
330
- reboot;
331
- - `refused`: any other refusal, in the keychain's own words;
332
- - `timeout`: the step took longer than its `timeoutMs`;
333
- - `helper`: the helper process couldn't start, or ended before it answered (`exit` says how);
334
- - `missing`: `@napi-rs/keyring` isn't installed, and the message names it;
335
- - `too-long`: the tokens are over 2,560 bytes, so nothing was saved.
336
-
337
- `unavailable` and `locked` are read from the keychain library's words, which carry no code.
338
- Only words known for them match, and anything else is `refused`. The words for a locked
339
- macOS keychain, and any on Windows, haven't been seen yet, so those failures may read as
340
- `refused` for now.
341
- - Its steps run in one helper process, one at a time. The first step starts it, and it stays
342
- warm while your app runs (about 57 MB), so a step after that takes a keychain call, not a
343
- process start. A step that takes longer than 30 s (`timeoutMs`) ends it, so a keychain prompt
344
- that nobody answers can't hold up your app, and the next step starts another. A Ctrl-C in
345
- the terminal reaches the helper too, and it ignores it, from before its own code loads. Not
346
- during Node's own start-up, though, or any preload in `NODE_OPTIONS`: a Ctrl-C then still
347
- ends a helper that is just starting. When your app ends, the helper ends
348
- too: at once if it's idle or reading, or once it has finished the save or delete it's on, so
349
- a refresh's save isn't lost to a Ctrl-C. It gives that step 1 s more at most, less than the
350
- soonest `fileLock` lets another process take the lock your app held: at the soonest about
351
- 2 s after your app ends, for an app whose heartbeat was running (3 s after its last touch),
352
- when the clock has stepped or your app's clock runs behind. So a late save can't land over
353
- that process's. For a helper's first step, that 1 s counts from the helper's own start, so a
354
- helper slow to start (on a loaded machine, say) can't stretch it. A first step still going
355
- when your app ends may therefore be cut sooner. A save waiting on a keychain prompt is ended
356
- then. On macOS, the keychain's
357
- own dialog stays open after a Ctrl-C until someone answers it, even once your app and its
358
- helper have ended. A step whose helper died
359
- before it answered runs once more on a fresh one, within the same 30 s. The helper never
360
- keeps your app running. It's `process.execPath`, so it needs a Node that runs a script: not an Electron
361
- app (without `ELECTRON_RUN_AS_NODE`), a Node single-executable application, or a compiled
362
- Bun binary. A bundle must keep
363
- `keychainChild.js` beside the module, with `zod` and `@napi-rs/keyring` resolvable from
364
- there, and `import.meta.url` set. Where it doesn't (an esbuild CommonJS bundle, say), only the
365
- keychain's steps fail, as `store_failed`.
366
- - Through `session.token()`, a keychain read that takes longer than the caller's wait, 15 s
367
- unless you pass `createSession({ waitMs })`, is `unavailable`. On macOS a read can wait on
368
- an access dialog, every time, for an item another program saved: give `waitMs` as long as
369
- the person may take. Each keychain step still ends at its own `timeoutMs`.
370
- - Tokens over 2,560 bytes, Windows' limit, kept on every platform, fail the save with nothing
371
- written. A Flipstream sign-in's tokens take about 1.6 KB.
372
- - On Linux without a Secret Service, as on most servers, every step is `unavailable`: use
373
- `fileStore`.
374
- - Over SSH on a Mac it works too, unless the keychain is locked, as after a reboot with nobody
375
- logged in at the screen. Then every step fails, as `locked` or at the latest after its 30 s,
376
- until the person logs in at the machine once, or runs `security unlock-keychain`.
377
- - On macOS, a script run by the same Node can read the item without a prompt, much as with a
378
- file only the person can read.
379
- - It's tested on macOS. Windows and Linux aren't tested yet.
380
- - **One session per store,** shared by everything that uses it, or pass `lock`, a lock every
381
- process takes, which settles only once its work has settled. Two sessions on one store refresh as
382
- two processes would, and the server can end the session.
383
- - **In one process,** the ready-made stores take each save, update and clear of the same file or
384
- item in turn, so a sign-in saved while a refresh is saving is kept. A file counts as the same
385
- however its folder is spelt (through a link, or in another case on macOS), but not when its own
386
- name differs only in case.
387
- - **Across processes,** take the session's lock around `save` and `clear` too: a store's compare
388
- and its write are one step only among processes that take turns.
389
- - **`session.token()`** rejects with a `SessionError` when there's no token to give: `signed-out`,
390
- `unavailable`, `store_failed` or `refresh_failed`.
391
- - **`unavailable` comes at the caller's wait,** the store's read included: 15 s unless you pass
392
- `createSession({ waitMs })`. Give a store that can wait on a person, such as a keychain asking
393
- for access, as long as they may take: 120 s when interactive, say. Only this wait changes. A
394
- refresh still waits at most 60 s for its answer, and a sign-out sends nothing after its 10 s.
395
- - **Before your process exits, `await session.settled()`.** It resolves once the session has no
396
- refresh, save or sign-out in flight. `unavailable` comes while a refresh may still be saving the
397
- token it got, and an exit then loses it. It never rejects and starts nothing.
398
- - **It waits at most as long as the session's own limits.** A store that never answers a read or
399
- a save holds it, and so does a lock that ignores its signal. A sign-out's store call still
400
- running after 60 s isn't waited for.
401
- - **The SDK's own stores answer every call.** A `keychainStore` save or clear is two steps of up
402
- to its `timeoutMs` each, so keep `timeoutMs` at 30 s or under, or a sign-out's clear can be cut,
403
- which it reports as `cut`.
404
- - **Stop making calls before you await it:** calls that keep coming keep it waiting.
405
- - **`session.revoke()`** ends the session the store holds when its turn comes, then, whatever the
406
- server said, clears it through `onTokens` (`cleared`), once, in the same hold of the lock, so a
407
- refresh can't bring it back. A sign-in saved after that is kept. A refresh token the session holds
408
- only because saving it failed goes too, after the stored session, even once the store has moved
409
- on, and the session then lets it go.
410
- - **It answers once both are done:** `kind` is `revoked`, or `unconfirmed` with the reason, and
411
- `cleared` says what became of the store:
412
- - `cleared`: it was cleared;
413
- - `kept`: there was nothing to clear: nothing stored, or the store moved on meanwhile, to a
414
- newer sign-in, which is kept, or to another sign-out's clear;
415
- - `failed`: the store failed, and `failure` says where and how: its `step` is `read`, `lock`
416
- or `clear`, and its `cause` is what the store threw, such as a `KeychainError`, whose
417
- `failure.kind` and message say why. A clear or a lock that rejects with something other
418
- than an `Error` gives an `Error` carrying its text instead. A clear it refuses with anything
419
- but `StoreMovedOnError` counts as failed, at `clear`;
420
- - `cut`: the lock or a store call took longer than its 60 s;
421
- - `pending`: your `signal` answered first, and the clear goes on, unless the signal had already
422
- fired when you called, when nothing runs at all.
423
-
424
- After anything but `cleared` and `kept`, the tokens may still be stored: tell the person, so
425
- they can sign out again.
426
- - **It can take minutes on a stalled store, and longer behind one.** It sends nothing after its
427
- 10 s, but it waits for the clear. First it waits for any turn ahead of it, for as long as that
428
- takes: a refresh that is still saving, or a lock that ignores its signal. Then it waits at most
429
- 60 s for the lock and for each of its three store calls, so up to about four minutes. It used to
430
- answer within 10 s while the clear went on behind it. A lock held longer than its 60 s by
431
- another process, or a store call that doesn't answer within its 60 s, leaves the store as it
432
- was, unless that call finishes later on its own.
433
- - **Pass a `signal` to stop waiting:** it answers at once, with `cleared: 'pending'`, and the
434
- clear goes on. Await `session.settled()` before the process exits. A signal that has already
435
- fired when you call runs nothing at all, and answers `pending` too.
436
-
437
- **Writing your own store:** give `tokens` and `onTokens` instead, and keep the same two rules.
438
- `tokens()` returns only what `onTokens` has durably saved: write first, show second. `onTokens`
439
- writes only while the store's key is still `update.replaces`, and when it refuses, throws a
440
- `StoreMovedOnError`, as the ready-made stores do. A sign-out whose clear is refused that way says
441
- `kept`: the store holds a newer sign-in, or nothing. Any other throw is read as the store failing,
442
- and the sign-out says `failed`. The key is the stored refresh token, or the access token when it has
443
- none or an empty one (`refreshToken || accessToken`). Here in memory:
322
+ - **What each takes,** before anything is sent:
323
+ - a key it doesn't send is `refused` (`reason: 'fields'`, naming them);
324
+ - a description that isn't a non-blank string, a time not written as `2026-10-05T00:00:00Z`, or a
325
+ start after the end rejects with a `TypeError`. A fraction may follow the seconds, and an offset
326
+ such as `+02:00`, or none, may take the place of the `Z`. A time with no offset is read as UTC,
327
+ and every time is sent as a UTC instant.
328
+ - **Each write reads first.** `add` reads the workspace: one nobody has is `not_found`, and another
329
+ organisation's is `invalid`, with nothing written. `update` and `remove` read the entry, held to
330
+ your organisation the same way.
331
+ - **`update` changes what you give,** at least one of `description`, `start_date` and `end_date`,
332
+ and sends the rest back exactly as stored. When you give a time, a start after the stored end
333
+ (or an end before the stored start) rejects with a `TypeError`, with nothing written. Since the
334
+ whole entry goes back, a change someone else made between `update`'s read and its write is
335
+ overwritten.
336
+ - **`remove` answers `null`.** A log entry's remove is direct; it's not handed to a person.
337
+ - **Who may write is the service's rule, not the SDK's:** Owners, Admins and Editors add; an Editor
338
+ changes or removes only their own entries, and Owners and Admins any. Until the service enforces
339
+ it (pulse-admin#161, for Editors), a Viewer can also add, change and remove entries, and an Editor
340
+ can change anyone's. Anyone it refuses gets `forbidden`.
341
+ - **A write is never tried again.** Only a refusal (a 4xx kind such as `forbidden`), `refused` or
342
+ `no_token` shows nothing was written. After any other failure it may have been, so list the
343
+ logbook before you write again.
344
+
345
+ ## A workspace's datasets
346
+
347
+ `flipstream.datasets` reads a workspace's datasets, its uploads and connected accounts, and pauses
348
+ and resumes them. `flipstream.datasetTypes` lists the types of dataset this version knows.
444
349
 
445
350
  ```ts
446
- import { discover } from '@flipstream/sdk'
447
- import { createSession, StoreMovedOnError, type SessionTokens, type TokenUpdate } from '@flipstream/sdk/node'
351
+ import { createFlipstream, orThrow } from '@flipstream/sdk'
448
352
 
449
- const server = await discover('https://auth.flipstream.io')
450
- if (!server.ok) throw new Error(`sign-in is unavailable: ${server.error.kind}`)
353
+ const flipstream = createFlipstream({ app: { name: 'my-app', version: '1.0.0' }, token: async () => '<your token>' })
451
354
 
452
- let stored: SessionTokens | null = null
355
+ const page = orThrow(await flipstream.datasets.list({ workspace_id: '<workspace id>', limit: 50 }))
356
+ for (const dataset of page.items) console.log(dataset.name, dataset.type, dataset.active)
453
357
 
454
- const session = createSession({
455
- server: server.data,
456
- clientId: '<your client id>',
457
- tokens: () => stored,
458
- onTokens: (update: TokenUpdate) => {
459
- // Compare and set: only while the store's key is still the one this update replaces.
460
- if (stored === null || (stored.refreshToken || stored.accessToken) !== update.replaces) throw new StoreMovedOnError()
461
- if (update.kind === 'cleared') {
462
- stored = null
463
- return
464
- }
465
- const { accessToken, expiresAt } = update
466
- const refreshToken = update.kind === 'rotated' ? update.refreshToken : stored.refreshToken
467
- stored = { accessToken, ...(refreshToken === undefined ? {} : { refreshToken }), ...(expiresAt === undefined ? {} : { expiresAt }) }
468
- },
469
- })
358
+ const dataset = orThrow(await flipstream.datasets.get({ dataset_id: '<dataset id>' }))
359
+ const types = orThrow(await flipstream.datasetTypes.list())
360
+ console.log(dataset.name, types.length)
470
361
  ```
471
362
 
472
- ### Several processes on one store
473
-
474
- `fileLock(path)` is a ready-made `lock` for Node processes that share one store, such as a CLI
475
- run several times at once.
363
+ - **A dataset** is `{ id, name, workspace_id, type, active, created_on, created_by_id, history }`,
364
+ and nothing else: never a credential, a setting or its parameters. The service's answer embeds the dataset's
365
+ sign-in, so a body that isn't the service's JSON is never kept either: a failure of the dataset's
366
+ own read or write gives its kind and status, with no `text`. The reads of your organisation and
367
+ the workspace beside it keep theirs.
368
+ - `type` is one of the types `datasetTypes.list()` gives, such as `'google_search_console'`, or
369
+ a type this version doesn't know yet, kept as it came, so a new kind of dataset never makes the
370
+ list unreadable. It's `null` when the service holds no type for it.
371
+ - `active` says whether it's switched on.
372
+ - `created_on` is when it was made, an ISO 8601 instant in UTC, and `created_by_id` the person who
373
+ made it. Either is `null` when the service holds none.
374
+ - `flipstream.members.get({ member_id: created_by_id })` names the maker. When it doesn't answer
375
+ ok (see "Your organisation's members"), show the maker as unknown, for example for a dataset
376
+ Flipstream staff made through a swap token.
377
+ - `history` says how much of its history is in the warehouse, a `DatasetHistory`, in the
378
+ service's own values (the SDK renames fields, never values):
379
+ - `'not_available'`: no history is loaded for its kind of dataset;
380
+ - `'todo'`: its history hasn't started loading. Every new dataset starts here, and the
381
+ pipeline sets `'not_available'` only when it first runs for one, so `'todo'` may never start
382
+ for a type that loads no history;
383
+ - `'started'`: its history is loading, from the first load until it's in; a load that keeps
384
+ failing stays `'started'`;
385
+ - `'done'`: its history is in.
386
+
387
+ Merge them as your app needs: the console shows `'todo'` and `'started'` alike as "coming in".
388
+ It's `null` when it's unknown, because the service holds none or a value this version doesn't
389
+ know: show "Not available yet" then, never a value of your own.
390
+ - **A list is one page:** `{ items, total, limit, offset }`, where `total` counts every dataset.
391
+ - The limit is 100 unless you set one, and at most 1,000.
392
+ - A limit or offset that isn't a whole number in range rejects, with nothing sent.
393
+ - **The order is the service's own:** by name alone. Pages read at different times can overlap, or
394
+ skip a dataset, when datasets are added, removed or renamed in between, or when two have the same
395
+ name. A changed `total` shows some of that, but an unchanged one doesn't prove nothing moved. For
396
+ a complete, stable list, read it in one page: up to 1,000.
397
+ - **Each call reads your organisation beside the datasets,** and a list reads its workspace too,
398
+ under one deadline for every read. The organisation's failure, then the workspace's, is the
399
+ answer. A dataset of another organisation, or in the list one of another workspace, makes the
400
+ answer `invalid`; it's never shown or dropped.
401
+ - **A workspace nobody has** is `not_found`, and another organisation's is `invalid`: never an empty
402
+ page, which would say it has no datasets.
403
+ - **A missing dataset:** `get` answers `not_found`. An answer that is another dataset than the one
404
+ asked for is `invalid`.
405
+ - **`datasetTypes.list()`** sends nothing: the types are the SDK's own list, since the service has
406
+ no route for them yet. Each call gives you a list of your own.
407
+
408
+ **Pausing and resuming:** `pause` and `resume`.
476
409
 
477
410
  ```ts
478
- import { homedir } from 'node:os'
479
- import { join } from 'node:path'
480
- import { discover } from '@flipstream/sdk'
481
- import { createSession, fileLock, signInWithLoopback, type TokenStore } from '@flipstream/sdk/node'
482
-
483
- const issuer = 'https://auth.flipstream.io'
484
-
485
- // The store, chosen as above: the keychain, or the file the person asked for.
486
- declare const store: TokenStore
487
-
488
- // One lock file for every process on this machine.
489
- const lock = fileLock(join(homedir(), '.config', 'example-cli', 'session.lock'))
490
- const session = createSession({ issuer, clientId: '<your client id>', ...store, lock })
491
-
492
- // A sign-in's save takes the same lock. Give it longer than the 10 s a lock file left by a crash
493
- // can take to go stale.
494
- if ((await store.tokens()) === null) {
495
- const server = await discover(issuer)
496
- if (!server.ok) throw new Error(`sign-in is unavailable: ${server.error.kind}`)
497
- const signedIn = await signInWithLoopback({
498
- server: server.data,
499
- clientId: '<your client id>',
500
- scopes: ['<scope>'],
501
- open: (url) => {
502
- console.log(`Sign in at ${url}`)
503
- },
504
- })
505
- if (!signedIn.ok) throw new Error(`sign-in failed: ${signedIn.error.kind}`)
506
- await lock(() => store.save(signedIn.data), AbortSignal.timeout(30_000))
507
- }
411
+ import { createFlipstream, orThrow } from '@flipstream/sdk'
412
+
413
+ const flipstream = createFlipstream({ app: { name: 'my-app', version: '1.0.0' }, token: async () => '<your token>' })
508
414
 
509
- // Signing out takes the lock itself, and clears the store inside it.
510
- await session.revoke()
415
+ const paused = orThrow(await flipstream.datasets.pause({ dataset_id: '<dataset id>' }))
416
+ console.log(paused.active) // false
417
+ orThrow(await flipstream.datasets.resume({ dataset_id: '<dataset id>' })) // active: true
511
418
  ```
512
419
 
513
- - **Give every process the same absolute path,** on a local disk, for processes on this machine's
514
- clock. A holder whose clock is 10 s or more behind, in a virtual machine sharing the folder say,
515
- loses the lock after 2 to 3 s without a touch. The file exists only while a process holds the
516
- lock. Its folder is made when it isn't there (on macOS and Linux, for this user only).
517
- - **One refresh at a time:** the next process waits for it, reads the store again, and uses the
518
- token it saved. A process still waiting at the refresh's 60 s deadline gives up, and sends
519
- nothing.
520
- - **A process that dies holding it** holds the others off for about 10 s: a holder touches the file
521
- every second, and a waiter takes a file over once nobody has touched it for 10 s and it has
522
- watched it for 3 s. A sign-out, which sends nothing after its 10 s, takes over a file left 10 s or
523
- more before within about 3 s.
524
- - **On Ctrl-C,** Node ends the process without letting a held lock go, and the next process waits
525
- up to 10 s for it. An app that wants it gone sooner can handle SIGINT itself, and exit only once
526
- every hold of its lock has settled, as below: a hold still waiting for the file gives up at once,
527
- and one running its work finishes it. Waiting for the session's calls isn't enough: `token()` can
528
- answer before its hold ends, and so can `revoke()` at its `signal`. Await `session.settled()`
529
- too, so the session's own work has finished before the exit. The keychain store's own helper
530
- ignores the Ctrl-C and finishes the step it's on, within that step's 30 s and at most 1 s after
531
- the app has gone; the lock file goes when that work settles, as long as the app waits for it, as
532
- below.
420
+ - **Each answers the `Dataset`,** with `active` as asked. Pausing a paused dataset sends the same
421
+ write and answers the same, so calling either twice is the same as once.
422
+ - **What each takes,** before anything is sent: `dataset_id` alone. Any other key is `refused`
423
+ (`reason: 'fields'`, naming them), and an id that isn't a string rejects with a `TypeError`.
424
+ - **Each reads first:** the dataset, fresh, beside your organisation. One nobody has is
425
+ `not_found`, and another organisation's is `invalid`, with nothing written. Then `active` alone
426
+ is sent, so a rename made in between stays.
427
+ - **Each reads again after the write,** fresh, and answers that read. One whose `active` isn't the
428
+ one asked for is `invalid`, since the write may not have been stored, as is one of another
429
+ dataset, workspace or organisation. That read comes after the write was sent, so its failure
430
+ is never answered as a refusal: a 4xx kind, `refused` or `no_token` there is `invalid`, naming
431
+ its kind. A `timeout`, `aborted`, `cancelled`, `unavailable` or `invalid` there keeps its kind,
432
+ since it already says the write may have been made.
433
+ - **Who may is the service's rule:** Owners, Admins and Editors pause and resume, and a Viewer
434
+ doesn't. Anyone it refuses gets `forbidden`.
435
+ - **A write is never tried again.** Only a refusal (a 4xx kind such as `forbidden`), `refused` or
436
+ `no_token` shows nothing was written. After any other failure it may have been; calling it
437
+ again is safe, since it's the same write.
438
+
439
+ **Deleting a dataset is a person's to do, in the console.** It removes the dataset's data for good,
440
+ and the console can't delete a dataset yet. `flipstream.datasets.delete({ dataset_id })` never
441
+ writes. It reads the dataset first: one nobody has is `not_found`, and another organisation's is
442
+ `invalid`. Then it answers `needs_person` with `why`, and, where a console can be named (your own
443
+ `hosts.console`), the dataset's page as `url`, with what it shows as `sees`, as
444
+ `workspaces.delete` does.
445
+
446
+ ## Sign-ins to your sources
447
+
448
+ `flipstream.credentials` lists the provider sign-ins your organisation holds, such as a Google
449
+ account a dataset reads with, as metadata only. The SDK has no call that reads a sign-in's value.
533
450
 
534
451
  ```ts
535
- import { homedir } from 'node:os'
536
- import { join } from 'node:path'
537
- import { fileLock, type Session } from '@flipstream/sdk/node'
538
-
539
- // The lock for the session and the app's own saves, with every hold kept until it settles. Once
540
- // the app is stopping, a hold still waiting for the file gives up, and a new one creates nothing
541
- // (fileLock with a signal that has fired), so the wait below is only for work already running.
542
- const file = fileLock(join(homedir(), '.config', 'example-cli', 'session.lock'))
543
- const holds = new Set<Promise<unknown>>()
544
- const stop = new AbortController()
545
- const lock: typeof file = (work, signal) => {
546
- const hold = file(work, AbortSignal.any([signal, stop.signal]))
547
- holds.add(hold)
548
- const done = (): void => {
549
- holds.delete(hold)
550
- }
551
- hold.then(done, done)
552
- return hold
553
- }
452
+ import { createFlipstream, orThrow } from '@flipstream/sdk'
554
453
 
555
- declare const session: Session
454
+ const flipstream = createFlipstream({ app: { name: 'my-app', version: '1.0.0' }, token: async () => '<your token>' })
556
455
 
557
- // On Ctrl-C, exit once every hold has let its lock file go and the session's own work is done; a
558
- // second Ctrl-C exits at once.
559
- process.on('SIGINT', () => {
560
- if (stop.signal.aborted) process.exit(130)
561
- stop.abort(new Error('stopping'))
562
- void Promise.all([Promise.allSettled([...holds]), session.settled()]).then(() => process.exit(130))
563
- })
456
+ const page = orThrow(await flipstream.credentials.list({ limit: 50 }))
457
+ for (const credential of page.items) console.log(credential.name, credential.type, credential.datasource_types)
564
458
  ```
565
459
 
566
- - **A holder that can't touch its file for 10 s loses the lock,** and its work goes on beside the
567
- next holder's: a thread blocked by a synchronous store waiting for a person, or a process stopped
568
- by Ctrl-Z or a debugger. Keep your store asynchronous.
569
- - **Take the same lock for the store's other writes,** a sign-in's `save`, or a `clear` without a
570
- session, so they can't land between a refresh's compare and its set. `session.revoke()` takes it
571
- for its own clear. Never take it inside `onTokens`, which runs inside it already: the lock isn't
572
- reentrant.
573
- - **On Windows, `fileLock` hasn't been tried yet.** What may differ there:
574
- - the lock file and its folder take the folder's own permissions, so they aren't private to this
575
- user;
576
- - a lock file it isn't allowed to create, for the folder's permissions, reads as held by another
577
- process: a refresh then waits out its 60 s and is `unavailable`, not `store_failed`. A file
578
- antivirus still holds open reads as held only until it lets go;
579
- - taking over a crashed holder's file fails while antivirus or the indexer has it open, as
580
- `store_failed`;
581
- - a path such as `\my-app\session.lock` counts as absolute but names a file on whichever drive
582
- is current: give the drive as well (`C:\…`).
583
-
584
- **A file store can bring its own lock.** `fileStore(path, { lock: true })` also returns `lock`:
585
- `fileLock` on the file's path with `.lock` added, beside it. Every process, and every version of
586
- your app, that opens the same file then takes the same lock, with no path of its own to agree on.
460
+ - **A credential** is `{ id, name, type, datasource_types, created_on }`, and nothing else.
461
+ - `name` is the provider account it signs in as: for a Google sign-in, that account's email
462
+ address.
463
+ - `type` is what kind of sign-in it is, such as `'oauth2'` or `'service_account'`. A kind this
464
+ version doesn't know is kept as it came, and it's `null` when the service holds none.
465
+ - `datasource_types` lists the kinds of dataset it serves, such as `'google_search_console'`.
466
+ - `created_on` is an ISO 8601 instant in UTC.
467
+ - **Never a value.** The service doesn't mask a sign-in, so the SDK checks every answer itself. An
468
+ answer holding what may be a sign-in's value (a `data` that isn't empty, or a key such as
469
+ `refresh_token`, `apiKey`, `auth_values` or `password`, at any depth, however it's spelt) is
470
+ `invalid`. Its issues name the place, never the value, and nothing is answered at all. A body
471
+ that isn't the service's JSON is never kept either: a failure of the sign-ins' own reads gives
472
+ its kind and status, with no `text`. The read of your organisation beside them keeps its.
473
+ - **A list is one page:** `{ items, total, limit, offset }`, as every list is. The limit is 100
474
+ unless you set one, and at most 1,000.
475
+ - **It reads your organisation first,** for its id, and its failure is the answer. A sign-in of
476
+ another organisation makes the answer `invalid`.
477
+ - **Who may list them is the service's rule:** today Owners, Admins, Editors and Viewers. Anyone
478
+ it refuses gets `forbidden`.
479
+ - **Revoking or deleting a sign-in is a person's to do, in the console.** Either breaks every
480
+ dataset that reads with it. `flipstream.credentials.revoke({ credential_id })` and
481
+ `delete({ credential_id })` never write. Each reads the sign-in first: one nobody has is
482
+ `not_found`, and another organisation's is `invalid`. Then it answers `needs_person` with `why`.
483
+ There's no `url` yet: no console page names a sign-in.
484
+
485
+ ## Wallet
486
+
487
+ `flipstream.wallet` reads your organisation's prepaid wallet. It only reads: adding credit is done
488
+ by a person, in the console.
587
489
 
588
490
  ```ts
589
- import { homedir } from 'node:os'
590
- import { join } from 'node:path'
591
- import { createSession, fileStore, type SessionTokens } from '@flipstream/sdk/node'
491
+ import { createFlipstream, orThrow } from '@flipstream/sdk'
492
+
493
+ const flipstream = createFlipstream({ app: { name: 'my-app', version: '1.0.0' }, token: async () => '<your token>' })
592
494
 
593
- const store = fileStore(join(homedir(), '.config', 'example-cli', 'tokens.json'), { lock: true })
495
+ const balance = orThrow(await flipstream.wallet.balance())
496
+ if (balance !== null) console.log(balance.balance_micro / balance.micro_per_euro, 'euros')
497
+
498
+ const ledger = orThrow(await flipstream.wallet.transactions())
499
+ console.log(ledger.items.length, 'rows')
500
+ ```
594
501
 
595
- // Spread in, so the session takes store.lock for its refreshes and sign-outs.
596
- const session = createSession({ issuer: 'https://auth.flipstream.io', clientId: '<your client id>', ...store })
502
+ - **Amounts are whole numbers of micro,** and each answer says how many make a euro, in
503
+ `micro_per_euro`. Divide by it, never by a number of your own: the basis can change.
504
+ - **`balance()`** is `{ balance_micro, micro_per_euro }`, or `null` when your organisation has no
505
+ wallet. No wallet is a real state, so it's not an error, and it's never a zero balance: €0.00
506
+ would claim a wallet that holds nothing.
507
+ - **`transactions()`** is the whole ledger, in one answer, with no paging: `{ items, micro_per_euro }`.
508
+ The ledger's rows don't name their wallet, so the balance is read beside it, and the ledger is
509
+ answered only when that's your organisation's wallet. Each row
510
+ is `{ id, type, dataset_id, description, amount_micro, quantity, unit_price_micro, created_on }`.
511
+ A row that charged no dataset, such as a credit, has `dataset_id: null`, whether the wallet
512
+ wrote its `connection_id` empty or null. `created_on` is an
513
+ ISO 8601 instant in UTC, such as `2026-10-31T13:08:25.312Z`, as the logbook's times are. A type
514
+ this version doesn't know is kept as it came.
515
+ - **Who may read it is the wallet's rule, not the SDK's.** Today that's Owners and Admins, and
516
+ Editors too once pulse-wallet#15 lands. Anyone the wallet refuses gets `forbidden`, never an
517
+ empty ledger.
597
518
 
598
- // A sign-in's save takes it too, as does a clear of your own.
599
- declare const signedIn: SessionTokens
600
- await store.lock(() => store.save(signedIn), AbortSignal.timeout(30_000))
519
+ ## Signing in from Node and the CLI
520
+
521
+ For an app that runs on the person's own machine, or in their terminal: a CLI, a script, a local
522
+ tool. `@flipstream/sdk/node` signs them in through their browser, with OAuth 2.0's authorisation
523
+ code and PKCE. Signing in stores nothing: the tokens are the app's to keep, and the SDK has stores
524
+ ready for them (see "Keeping the person signed in" in [docs/node-sign-in.md](docs/node-sign-in.md)). A
525
+ web app signs in on its server instead (see "In a browser").
526
+
527
+ In a TypeScript project, add `@types/node` (`npm install --save-dev @types/node`): this entry's
528
+ types use Node's own.
529
+
530
+ **Against an auth server on your own machine,** while developing it, pass `allowLocalhostHttp: true`
531
+ to `discover`, `signInWithLoopback`, `finishSignIn` and `createSession`, as `createFlipstream` takes
532
+ it. Plain http is then accepted for `localhost`, `127.0.0.1` and `[::1]` only, and every endpoint
533
+ such a server names must be on its own origin. It's off unless your code sets it: the SDK never
534
+ reads it from the environment. Never set it in production.
535
+
536
+ ### With a browser on the same machine
537
+
538
+ `signInWithLoopback` opens a one-time server on `127.0.0.1`, on a port the system chooses, and
539
+ waits for the browser to come back to it.
601
540
 
602
- // Signing out takes it itself.
603
- await session.revoke()
541
+ ```ts
542
+ import { createFlipstream, discover } from '@flipstream/sdk'
543
+ import { signInWithLoopback } from '@flipstream/sdk/node'
544
+
545
+ const server = await discover('https://auth.flipstream.io')
546
+ if (!server.ok) throw new Error(`sign-in is unavailable: ${server.error.kind}`)
547
+
548
+ const signedIn = await signInWithLoopback({
549
+ server: server.data,
550
+ clientId: '<your client id>',
551
+ scopes: ['<scope>'],
552
+ // Show the person where to sign in: open their browser, or print the URL.
553
+ open: (url) => {
554
+ console.log(`Sign in at ${url}`)
555
+ },
556
+ })
557
+ if (!signedIn.ok) throw new Error(`sign-in failed: ${signedIn.error.kind}`)
558
+
559
+ const flipstream = createFlipstream({ app: { name: 'my-cli', version: '1.0.0' }, token: () => signedIn.data.accessToken })
604
560
  ```
605
561
 
606
- - **The store's own steps never take it,** so a `save` or `clear` inside it doesn't wait for itself,
607
- and a clear leaves the lock file alone. Without `{ lock: true }`, nothing changes.
608
- - **Don't pass a `lock` of your own as well:** `{ ...store, lock }` leaves the session on yours and
609
- your saves on `store.lock`, and `{ lock, ...store }` swaps yours out without a word. Either way a
610
- sign-in can land between a refresh's compare and its write.
611
- - **Never call the session inside `store.lock`:** the lock isn't reentrant, so the call waits for
612
- the hold it's in, and fails at its own limit (`token()` at its `waitMs`, `revoke()` once its turn
613
- gives up on the lock, 60 s on, with `cut`).
614
- - **Nor from your own `tokens` or `onTokens`,** if you wrap the store's: they run inside the
615
- session's own turn. A `revoke()` there waits for that turn for ever, answering only at its
616
- `signal`, and a `token()` answers only at its `waitMs`.
562
+ - **The SDK opens nothing and writes nothing to the terminal.** `open` does that, once the port is
563
+ open.
564
+ - **The port listens on `127.0.0.1` only,** and is closed on every path: signed in, refused, timed
565
+ out (after 5 minutes, or `timeoutMs`), aborted (`signal`), or `open` or `readPasted` failing
566
+ (`readPasted` reads a pasted address when the browser can't come back: see
567
+ [docs/node-sign-in.md](docs/node-sign-in.md)).
568
+ - **The redirect is checked before its code is exchanged:** the sign-in's own state first, then the
569
+ issuer.
570
+ - **`page: { signedIn, failed }`** sets the HTML the browser shows afterwards.
571
+ - **What comes back:** `accessToken`, `scope`, `expiresAt` (ms since the epoch) when the server
572
+ says, and `refreshToken` when it issues one. Never log them.
573
+
574
+ **The rest is in [docs/node-sign-in.md](docs/node-sign-in.md),** which ships in the package, at
575
+ `node_modules/@flipstream/sdk/docs/node-sign-in.md`:
576
+ - when the browser may not reach this machine;
577
+ - over SSH, in CI, or with no display;
578
+ - keeping the person signed in: `createSession`, `keychainStore` and `fileStore`;
579
+ - several processes on one store: `fileLock`.
617
580
 
618
581
  ## In a browser
619
582
 
@@ -627,7 +590,8 @@ The main entry, `@flipstream/sdk`, runs in browsers with no Node polyfills. Only
627
590
  - **A browser sends no identification yet.** `app`, `agent` and `conversationId` are still
628
591
  required and checked, but none of "Which app sent a request"'s headers go from a page until the
629
592
  hosts' CORS allows them (query-planner#48); a page can't set `User-Agent` anyway.
630
- - **Signing in from a page** uses the same two halves as the paste-back above:
593
+ - **Signing in from a page** uses the same two halves as the paste-back ("Over SSH, in CI, or
594
+ with no display" in [docs/node-sign-in.md](docs/node-sign-in.md)):
631
595
  - `startSignIn` gives the URL to send the person to, and a `pending` to keep, for instance in
632
596
  `sessionStorage`;
633
597
  - when they come back, `finishSignIn(location.href, pending)` checks the redirect and exchanges
@@ -678,7 +642,8 @@ if (!signedIn.ok) throw new Error(`sign-in failed: ${signedIn.error.kind}`)
678
642
  not the server's description or body (an empty `message` or `text`): a server or proxy that
679
643
  echoes the request would put the credentials there.
680
644
  - **Without `clientSecret`,** the sign-in is a public client's, with PKCE alone.
681
- - **Keep the person signed in with `createSession`** (see "Keeping the person signed in"), passing
645
+ - **Keep the person signed in with `createSession`** (see "Keeping the person signed in" in
646
+ [docs/node-sign-in.md](docs/node-sign-in.md)), passing
682
647
  the same `clientSecret`. Its refresh and its revocation then carry the header too, under the same
683
648
  rules.
684
649
  - **Browser code can't pass a secret:** the main entry's `startSignIn` and `finishSignIn` have no
@@ -688,10 +653,11 @@ if (!signedIn.ok) throw new Error(`sign-in failed: ${signedIn.error.kind}`)
688
653
 
689
654
  ## Results, not exceptions
690
655
 
691
- Every call settles into a result: `{ ok: true, data }` or `{ ok: false, error }`. A call rejects
692
- only on a programming error. For instance, a request that can't be sent as JSON (a `BigInt`, a
693
- cycle) rejects with the `TypeError`, and nothing is sent. `orThrow(result)` gives the data, or
694
- throws the failure as an `ApiFailure` carrying its `error`, for callers who'd rather catch.
656
+ Every call settles into a result: `{ ok: true, data }` or `{ ok: false, error }`, each with the
657
+ call's `traceId` when a request went out (see "Finding a request in Logs"). A call rejects only on a
658
+ programming error. For instance, a request that can't be sent as JSON (a `BigInt`, a cycle) rejects
659
+ with the `TypeError`, and nothing is sent. `orThrow(result)` gives the data, or throws the failure
660
+ as an `ApiFailure` carrying its `error`, for callers who'd rather catch.
695
661
 
696
662
  - **`flipstream.catalog.list()`** gives a `Catalog`.
697
663
  - **`flipstream.catalog.get({ source })`** gives a `CatalogSource`: a source plus `catalogVersion`.
@@ -709,10 +675,31 @@ throws the failure as an `ApiFailure` carrying its `error`, for callers who'd ra
709
675
  - **`flipstream.health()`** gives the planner's answer to `GET /health`, an object of strings
710
676
  (`{ status: 'ok' }` today). It works signed out: no token is asked for or sent, so it tells "the
711
677
  service is down" from "the sign-in is wrong".
678
+ - **`flipstream.me()`** gives a `Me`: your organisation and you in it, and
679
+ **`flipstream.organization.rename()`** answers `needs_person` (see "Who you are").
680
+ - **`flipstream.workspaces.list({ limit, offset })`** gives a `Page<Workspace>`, and
681
+ **`flipstream.workspaces.get({ workspace_id })`** and **`create({ name })`** a `Workspace` (see
682
+ "Workspaces").
683
+ - **`flipstream.log.list()`** gives a `Page<LogEntry>`, **`flipstream.log.get()`**, **`add()`** and
684
+ **`update()`** a `LogEntry`, and **`remove()`** `null` (see "A workspace's logbook").
685
+ - **`flipstream.datasets.list()`** gives a `Page<Dataset>`, **`flipstream.datasets.get()`**,
686
+ **`pause()`** and **`resume()`** a `Dataset`, **`delete()`** answers `needs_person`, and
687
+ **`flipstream.datasetTypes.list()`** gives the `DatasetType`s this version knows (see "A
688
+ workspace's datasets").
689
+ - **`flipstream.credentials.list({ limit, offset })`** gives a `Page<Credential>`, and
690
+ **`revoke()`** and **`delete()`** answer `needs_person` (see "Sign-ins to your sources").
691
+ - **`flipstream.wallet.balance()`** gives a `Balance` or `null`, and
692
+ **`flipstream.wallet.transactions()`** a `Ledger` (see "Wallet").
693
+ - **`flipstream.members.list({ limit, offset })`** gives a `Page<Member>`, and
694
+ **`flipstream.members.get({ member_id })`** a `Member` (see "Your organisation's members").
712
695
 
713
696
  **Every answer is checked against the API's spec.** An answer that doesn't match, with a missing
714
697
  field or a value of the wrong type, is an `invalid` failure that names the field. It never comes
715
- back as data. A field the SDK doesn't know yet is kept.
698
+ back as data. Some of a dataset's fields are read more leniently, so one new or missing backend
699
+ value never makes a workspace's datasets unreadable: a `type` this version doesn't know is kept as
700
+ it came, `created_on` and `created_by_id` are `null` when missing, and `history` is `null` when
701
+ missing or when it holds a value this version doesn't know (see "A workspace's datasets"). A field the SDK doesn't know yet is kept, except in the answers of `me()`,
702
+ `workspaces`, `log`, `datasets`, `wallet` and `members`, which hold only the fields their types name.
716
703
 
717
704
  ## Typed errors
718
705
 
@@ -728,10 +715,13 @@ back as data. A field the SDK doesn't know yet is kept.
728
715
  | `refused` | Nothing was sent, by rule, and `reason` says which (below) |
729
716
  | `no_token` | The token function failed, or gave no token. `cause` is what it threw |
730
717
  | `cancelled` | The app's own transport cancelled the call, because the session it was made for moved on |
718
+ | `needs_person` | A person does it, in the console: `action`, `why`, and `url` and `sees` where a console can be named. Nothing was changed |
731
719
 
732
720
  **A failure the API answered keeps its `status`.**
733
721
  - It keeps the API's `code` and `message` when the body is an error body, or its `text` when it
734
- isn't (a proxy's `Bad gateway`).
722
+ isn't (a proxy's `Bad gateway`). The sign-ins' and the datasets' own reads and writes keep no
723
+ `text`, since a body there may hold a sign-in's value (see "Sign-ins to your sources" and "A
724
+ workspace's datasets"). The reads of your organisation and a workspace beside them keep theirs.
735
725
  - `isPlannerCode(error.code)` narrows the code to the ones the query API documents
736
726
  (`PlannerErrorCode`), so a switch over them can be exhaustive. A code added since is kept as it
737
727
  came.
@@ -746,7 +736,7 @@ never the value:
746
736
  | `identification` | A value identifying the app, its agent or the conversation holds the access token (see "Which app sent a request") |
747
737
  | `path` | A `source` of `''`, `.` or `..`, which can't stay one path segment |
748
738
  | `conversation-id` | A call's own `conversationId` that breaks its rule |
749
- | `fields` | A query with keys it doesn't send, each named in `fields` |
739
+ | `fields` | A query, or a write (`workspaces.create`, `log.add`, `update` or `remove`, `datasets.pause` or `resume`), with keys it doesn't send, each named in `fields` |
750
740
  | `pending` | Sign-in: a `pending` that isn't one, wasn't started by this app at this server, or whose token endpoint breaks its issuer's rule |
751
741
  | `callback` | Sign-in: a callback URL that can't be read |
752
742
 
@@ -778,6 +768,8 @@ function explain(error: ApiError): string {
778
768
  return error.fields === undefined ? `Not sent: ${error.reason ?? 'refused'}.` : `Not sent: unknown field ${error.fields.join(', ')}`
779
769
  case 'no_token':
780
770
  return 'No token to send.'
771
+ case 'needs_person':
772
+ return error.url === undefined ? error.why : `${error.why} ${error.url}`
781
773
  default: {
782
774
  const unhandled: never = error
783
775
  return unhandled
@@ -814,7 +806,7 @@ const flipstream = createFlipstream({
814
806
  // Asked before every attempt; after a 401, asked once more with the token the API refused.
815
807
  token: ({ rejected }) => session.accessToken(rejected),
816
808
  fetch: globalThis.fetch, // optional: every request goes through it
817
- hosts: { query: 'https://query.flipstream.io' }, // optional: the default
809
+ hosts: { query: 'https://query.flipstream.io' }, // optional: the default; also auth, admin, wallet and console
818
810
  onWarning: (message) => process.stderr.write(`${message}\n`), // optional: console.warn by default
819
811
  })
820
812
 
@@ -831,14 +823,16 @@ await flipstream.catalog.list({ conversationId: 'c-456', traceparent: '00-4bf92f
831
823
  cookies are sent. Plain http to a loopback host needs `allowLocalhostHttp: true`, for development
832
824
  only.
833
825
  - **Retries:**
834
- - A read (`catalog`, `health`) is tried again after a 408, 429, 502, 503 or 504, or a
835
- connection that failed, at most twice. It waits as long as `Retry-After` asks, in seconds, or
826
+ - A read (`catalog`, `health`, each of `me`'s) is tried again after a 408, 429, 502, 503 or
827
+ 504, or a connection that failed, at most twice. It waits as long as `Retry-After` asks, in seconds, or
836
828
  500 ms, then 1 s.
837
829
  - `query` is never tried again: a timeout at the gateway may already have run on the warehouse.
830
+ - `workspaces.create` is never tried again either: it writes, and an answer that never came may
831
+ still have made the workspace.
838
832
  - `no_token` and `refused` are never tried again.
839
833
  - A wait that wouldn't end before the deadline isn't started.
840
- - **Deadlines:** 60 s for `query`, 10 s for `health` and 30 s for the rest, every attempt and
841
- wait included. `deadlineMs` sets one call's.
834
+ - **Deadlines:** 60 s for `query`, 10 s for `health` and 30 s for the rest (for `me`, its three
835
+ reads together), every attempt and wait included. `deadlineMs` sets one call's.
842
836
  - **Abort:** `signal` ends a call at once, also while it waits for a token or to try again.
843
837
  - **Warnings:** the SDK's warnings go to `onWarning`, or to `console.warn` without it; `() => {}`
844
838
  silences them. Today there is one kind: a catalogue format type this version doesn't know,
@@ -858,7 +852,7 @@ the SDK has no telemetry. In Node, each signed-in request to an API host carries
858
852
  | Header | Value | Standard |
859
853
  |---|---|---|
860
854
  | `User-Agent` | `<app>/<version> flipstream-sdk/<version> node/<version>` | RFC 9110 product tokens |
861
- | `traceparent` | one trace-id per call, kept across its retries, with a new parent-id for each request | W3C Trace Context |
855
+ | `traceparent` | one trace-id per call, kept across its retries and shared by all of a call's requests, with a new parent-id for each request | W3C Trace Context |
862
856
  | `baggage` | `gen_ai.agent.name`, `gen_ai.agent.version` and `gen_ai.conversation.id`, percent-encoded, only those given | W3C Baggage, with OpenTelemetry's GenAI names (not stable yet) |
863
857
 
864
858
  - **`app` is required;** `agent` and `conversationId` are optional, and a call's own
@@ -883,6 +877,59 @@ the SDK has no telemetry. In Node, each signed-in request to an API host carries
883
877
  revoke send none.
884
878
  - **Not from a browser yet:** see "In a browser".
885
879
 
880
+ ## Finding a request in Logs
881
+
882
+ Every result says which trace its call's requests carried, as `traceId`, so a person can find them
883
+ in Logs:
884
+
885
+ ```ts
886
+ import { createFlipstream } from '@flipstream/sdk'
887
+
888
+ const flipstream = createFlipstream({ app: { name: 'my-app', version: '1.0.0' }, token: async () => '<your token>' })
889
+
890
+ const result = await flipstream.catalog.list()
891
+ if (!result.ok) console.error(`${result.error.kind} (request ${result.traceId ?? 'not sent'})`)
892
+ ```
893
+
894
+ - **On both arms:** `{ ok: true, data, traceId }` and `{ ok: false, error, traceId }`. It's the
895
+ W3C trace-id the call's `traceparent` carried: 32 lowercase hex digits.
896
+ - **One call, one trace:** a call that makes several requests, such as `me()`'s reads or
897
+ `workspaces.list()`'s two, sends them all under one trace-id, each with its own parent-id. So
898
+ does a retry, and the resend after a 401.
899
+ - **Your trace:** a call given your own `traceparent` keeps it, and `traceId` is its trace-id.
900
+ - **Nothing sent, no `traceId`:** a call `refused` before anything is sent (a path, fields,
901
+ identification, the conversation's id, the destination) has none, and neither does a `no_token`
902
+ from the first ask for a token.
903
+ - **Once a request went out, the call has one,** whatever comes after: a `no_token` when the token
904
+ function fails after a 401 (the refused request is the one to look up), or a `timeout` while a
905
+ request is on its way. "Went out" means the SDK handed it to `fetch`: a host that was never
906
+ reached (refused, or not found by DNS) gives `unavailable` with a `traceId` that no host logged.
907
+ - **`orThrow`'s message ends with `(request <traceId>)`** when there is one, so a CLI or an app
908
+ that prints the error carries the id with no code of its own. The `ApiFailure` it throws has the
909
+ id as `traceId` too, for a log field or an error tracker's tag:
910
+
911
+ ```ts
912
+ import { ApiFailure, createFlipstream, orThrow } from '@flipstream/sdk'
913
+
914
+ const flipstream = createFlipstream({ app: { name: 'my-app', version: '1.0.0' }, token: async () => '<your token>' })
915
+
916
+ try {
917
+ orThrow(await flipstream.catalog.list())
918
+ } catch (error) {
919
+ if (error instanceof ApiFailure) console.error(error.error.kind, error.traceId ?? 'not sent')
920
+ }
921
+ ```
922
+
923
+ It's there only when the result had one, and only as a W3C trace-id.
924
+ - **Only what reaches the API hosts is in it:** the auth server gets no `traceparent`, so a read
925
+ made there, such as `me()`'s userinfo and person, isn't in the call's trace.
926
+ - **With your own transport,** the SDK can't see the request leave, so a result has `traceId` once
927
+ an answer came back.
928
+ - **Not from a browser yet:** a browser sends no `traceparent` (see "In a browser"), so its results
929
+ have no `traceId`.
930
+ - **The service's side:** finding the id needs the API hosts to log it, and Logs to index it. Until
931
+ then, the id is still the one to quote.
932
+
886
933
  ## Which version is running
887
934
 
888
935
  ```ts