@dovetail-ts/integrations 0.0.0-stage → 1.0.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.
- package/CHANGELOG.md +30 -0
- package/LICENSE +21 -0
- package/README.md +228 -2
- package/dist/benchdog.d.ts +98 -0
- package/dist/benchdog.js +124 -0
- package/dist/benchdog.js.map +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +6 -0
- package/dist/index.js.map +1 -0
- package/dist/lattice.d.ts +154 -0
- package/dist/lattice.js +172 -0
- package/dist/lattice.js.map +1 -0
- package/dist/millwork.d.ts +24 -0
- package/dist/millwork.js +45 -0
- package/dist/millwork.js.map +1 -0
- package/dist/switchyard.d.ts +46 -0
- package/dist/switchyard.js +46 -0
- package/dist/switchyard.js.map +1 -0
- package/package.json +88 -3
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
# @dovetail-ts/integrations
|
|
2
|
+
|
|
3
|
+
## 1.0.1
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- 21b3dbf: Publish through OIDC trusted publishing only, with the Ember Workbench release kit. Each version from this release on has npm provenance.
|
|
8
|
+
- Updated dependencies [21b3dbf]
|
|
9
|
+
- @dovetail-ts/core@1.0.1
|
|
10
|
+
- @dovetail-ts/protocol@1.0.1
|
|
11
|
+
|
|
12
|
+
## 1.0.0
|
|
13
|
+
|
|
14
|
+
### Major Changes
|
|
15
|
+
|
|
16
|
+
- 480744b: First release of Dovetail: real-time and offline sync for Ember.
|
|
17
|
+
|
|
18
|
+
- `@dovetail-ts/core`: the connection life cycle, live store subscriptions, the optimistic ledger with rebase and rollback, the offline write queue in IndexedDB with a leader tab and dead letters, `DocSession` and `PresenceRoom`.
|
|
19
|
+
- `@dovetail-ts/warp-drive`: the store feed into WarpDrive.
|
|
20
|
+
- `@dovetail-ts/crdt`, `crdt-yjs`, `crdt-loro` and `crdt-automerge`: one `DocEngine` interface with three engines.
|
|
21
|
+
- `@dovetail-ts/tiptap`: co-editing in Tiptap 3 with carets, per-user undo, versions and comment threads.
|
|
22
|
+
- `@dovetail-ts/ember`, `notifications` and `inspector`: presence and status components, the inbox, toasts and activity feeds, and a dev panel.
|
|
23
|
+
- `@dovetail-ts/server`, the transports (`transport-ws`, `transport-sse`, `transport-cable`) and `conformance`: a Node server and one wire protocol that the Rails gems also pass.
|
|
24
|
+
- Adapters for Hocuspocus, Liveblocks, PartyKit and Supabase, and integrations for Switchyard, Millwork, Benchdog and Lattice. The Neon adapter is not in 1.0: it waits for a stable Neon Realtime client (1.1).
|
|
25
|
+
|
|
26
|
+
### Patch Changes
|
|
27
|
+
|
|
28
|
+
- Updated dependencies [480744b]
|
|
29
|
+
- @dovetail-ts/core@1.0.0
|
|
30
|
+
- @dovetail-ts/protocol@1.0.0
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Joe Gaudet
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,229 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @dovetail-ts/integrations
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Bindings between Dovetail and the other Workbench libraries: Switchyard, Millwork, Benchdog and
|
|
4
|
+
Lattice. Each library has its own entry point. Each library is an optional peer dependency, so
|
|
5
|
+
install only the libraries that you use.
|
|
6
|
+
|
|
7
|
+
Part of [Dovetail](https://joegaudet.com/dovetail/). Not released yet.
|
|
8
|
+
|
|
9
|
+
| Entry | Library |
|
|
10
|
+
| -------------------------------------- | ------------------------------------------ |
|
|
11
|
+
| `@dovetail-ts/integrations/switchyard` | `@switchyard-ts/core` |
|
|
12
|
+
| `@dovetail-ts/integrations/millwork` | `@millwork-ts/core` |
|
|
13
|
+
| `@dovetail-ts/integrations/benchdog` | `@benchdog-ts/client`, `@benchdog-ts/core` |
|
|
14
|
+
| `@dovetail-ts/integrations/lattice` | `@ember-lattice/*` (not on npm yet) |
|
|
15
|
+
|
|
16
|
+
## Switchyard
|
|
17
|
+
|
|
18
|
+
The life cycle of a `Connection` is a Switchyard statechart (`ConnectionMachine`), and
|
|
19
|
+
`connection.machine` is a Switchyard `Machine`. So the Switchyard tools take it as it is:
|
|
20
|
+
|
|
21
|
+
```ts
|
|
22
|
+
import { toMermaid } from '@switchyard-ts/graph'
|
|
23
|
+
import { connectInspector } from '@switchyard-ts/inspector'
|
|
24
|
+
import { createBrowserInspector } from '@statelyai/inspect'
|
|
25
|
+
import { ConnectionMachine } from '@dovetail-ts/core'
|
|
26
|
+
|
|
27
|
+
toMermaid(ConnectionMachine) // The diagram of the states.
|
|
28
|
+
connectInspector(connection.machine, createBrowserInspector()) // The Stately inspector.
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
In Ember, `<SwitchyardDebug @machine={{connection.machine}} />` of `@switchyard-ts/ember/debug`
|
|
32
|
+
shows the live chart. The Dovetail inspector panel (`@dovetail-ts/inspector`) shows the state and the transitions.
|
|
33
|
+
|
|
34
|
+
The entry adds two functions:
|
|
35
|
+
|
|
36
|
+
- `readConnection(connection)` gives the state of the connection as plain data: `state`,
|
|
37
|
+
`attempt`, `isOnline`, `session`, `version`, `user`, `error` and `rooms`.
|
|
38
|
+
- `transitionLog(connection, { limit, now })` records each transition from now on. Each entry
|
|
39
|
+
has `event` (for example `dropped`), `from`, `to` and `at`. The log keeps the last `limit`
|
|
40
|
+
entries (default 100). It has `entries`, `subscribe(listener)` and `stop()`.
|
|
41
|
+
|
|
42
|
+
```ts
|
|
43
|
+
import { transitionLog } from '@dovetail-ts/integrations/switchyard'
|
|
44
|
+
|
|
45
|
+
const log = transitionLog(connection)
|
|
46
|
+
log.subscribe(() => console.table(log.entries))
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
## Millwork
|
|
50
|
+
|
|
51
|
+
`millworkCodec(map)` is a `DocumentCodec` for `storeSink(store, { codec })` of
|
|
52
|
+
`@dovetail-ts/warp-drive`. For each listed attribute of each pushed resource, it runs
|
|
53
|
+
`serialize(hydrate(raw))` of the Millwork codec. The store then gets one wire form. A value
|
|
54
|
+
that is not valid becomes `null`, and Millwork reports it to `onInvalid`.
|
|
55
|
+
|
|
56
|
+
```ts
|
|
57
|
+
import { money, uuid } from '@millwork-ts/core'
|
|
58
|
+
import { millworkCodec } from '@dovetail-ts/integrations/millwork'
|
|
59
|
+
import { storeSink } from '@dovetail-ts/warp-drive'
|
|
60
|
+
|
|
61
|
+
const codec = millworkCodec({
|
|
62
|
+
invoice: { total: [money, { wire: 'decimal' }], payer: uuid },
|
|
63
|
+
})
|
|
64
|
+
const sink = storeSink(store, { codec })
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
The codec gives the same document when it runs on its own output. This is necessary, because
|
|
68
|
+
the ledger pushes a rollback through the sink again.
|
|
69
|
+
|
|
70
|
+
`rollbackShapes(ledger, shapesOf)` rolls back the Millwork shapes of a record when the server
|
|
71
|
+
rejects a write to it. The ledger puts the server state back in the store, but a shape keeps the
|
|
72
|
+
local edit of the user over that state. `shapesOf(ref)` gives the shapes or shape arrays of the
|
|
73
|
+
record that the app shows, for example the shape fields of a `checkout` copy.
|
|
74
|
+
|
|
75
|
+
```ts
|
|
76
|
+
import { rollbackShapes } from '@dovetail-ts/integrations/millwork'
|
|
77
|
+
|
|
78
|
+
const stop = rollbackShapes(sync.ledger, ref =>
|
|
79
|
+
ref.type === 'order' && ref.id === draft.id ? [draft.shipTo, draft.items] : [],
|
|
80
|
+
)
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
## Benchdog
|
|
84
|
+
|
|
85
|
+
### In the browser
|
|
86
|
+
|
|
87
|
+
`liveFlags(client, connection, environment)` joins the room of the environment
|
|
88
|
+
(`benchdogRoom(environment)`). For each change in the room, it calls `client.refresh()`. After a
|
|
89
|
+
reconnect, it calls `refresh()` again, because a change can come while the client is offline.
|
|
90
|
+
The client then needs no `live: true` and no `/stream` EventSource.
|
|
91
|
+
|
|
92
|
+
```ts
|
|
93
|
+
import { createClient, readPayload } from '@benchdog-ts/client'
|
|
94
|
+
import { liveFlags } from '@dovetail-ts/integrations/benchdog'
|
|
95
|
+
|
|
96
|
+
const benchdog = createClient({ flags, payload: readPayload() })
|
|
97
|
+
const stop = liveFlags(benchdog, connection, 'production')
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
### On the server
|
|
101
|
+
|
|
102
|
+
`dovetailChangeFeed(server)` is a Benchdog `ChangeFeed`. Each `publish(environment)` calls the
|
|
103
|
+
listeners of the process and sends a `benchdog-change` document to the room of the environment.
|
|
104
|
+
|
|
105
|
+
Two wrappers send notifications with `server.notify(user, payload)` of `@dovetail-ts/server`:
|
|
106
|
+
|
|
107
|
+
- `notifyApprovals(approvalStore, { notify, approvers })`: a new approval request sends
|
|
108
|
+
`benchdog.approval-requested` to each approver, but not to the person who asked. A decision
|
|
109
|
+
sends `benchdog.approval-approved` or `benchdog.approval-rejected` to the person who asked.
|
|
110
|
+
- `notifySchedules(flagStore, { notify, recipients })`: a write with the audit action
|
|
111
|
+
`schedule.apply` (from `applyDueSchedules` or `startScheduler`) sends
|
|
112
|
+
`benchdog.schedule-applied` to the recipients.
|
|
113
|
+
|
|
114
|
+
Benchdog has no list of users, so `approvers(environment)` and `recipients(environment, flag)`
|
|
115
|
+
come from the host. A failed notification goes to `onError` (default `console.error`). The
|
|
116
|
+
approval or the change stays.
|
|
117
|
+
|
|
118
|
+
```ts
|
|
119
|
+
import { MemoryApprovalStore, startScheduler } from '@benchdog-ts/core'
|
|
120
|
+
import { createAdminApi } from '@benchdog-ts/admin-api'
|
|
121
|
+
import {
|
|
122
|
+
dovetailChangeFeed,
|
|
123
|
+
notifyApprovals,
|
|
124
|
+
notifySchedules,
|
|
125
|
+
} from '@dovetail-ts/integrations/benchdog'
|
|
126
|
+
|
|
127
|
+
const notify = (user, payload) => dovetail.notify(user, payload)
|
|
128
|
+
const store = notifySchedules(flagStore, { notify, recipients: () => ['ops-lead'] })
|
|
129
|
+
const api = createAdminApi({
|
|
130
|
+
store,
|
|
131
|
+
feed: dovetailChangeFeed(dovetail),
|
|
132
|
+
approvals: notifyApprovals(new MemoryApprovalStore(), {
|
|
133
|
+
notify,
|
|
134
|
+
approvers: environment => approversOf(environment),
|
|
135
|
+
}),
|
|
136
|
+
// …
|
|
137
|
+
})
|
|
138
|
+
startScheduler({ store, environments: ['production'] })
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
## Lattice
|
|
142
|
+
|
|
143
|
+
Lattice is not on npm yet. The entry types against local interfaces, and the Lattice classes fit
|
|
144
|
+
them (ADR 0010, ADR 0019).
|
|
145
|
+
|
|
146
|
+
### Live rows
|
|
147
|
+
|
|
148
|
+
`liveRows(source, { connection, room, type, rowOf })` adds live updates to a Lattice
|
|
149
|
+
`DataSource`, for example of `warpDriveDataSource`. Each upsert of `type` in the store feed of
|
|
150
|
+
`room` is an `update` of a row that the grid loaded, or else an `add`. Each delete is a
|
|
151
|
+
`remove`. Also put the feed in the WarpDrive store (`sync.subscribe(room)`), so the rows that
|
|
152
|
+
the grid loads again are new.
|
|
153
|
+
|
|
154
|
+
```ts
|
|
155
|
+
import { warpDriveDataSource } from '@ember-lattice/data-warp-drive'
|
|
156
|
+
import { liveRows } from '@dovetail-ts/integrations/lattice'
|
|
157
|
+
|
|
158
|
+
const source = liveRows(warpDriveDataSource({ store, buildRequest }), {
|
|
159
|
+
connection,
|
|
160
|
+
room: 'notes',
|
|
161
|
+
type: 'note',
|
|
162
|
+
rowOf: resource => store.peekRecord(resource.type, resource.id),
|
|
163
|
+
})
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
### Presence on cells
|
|
167
|
+
|
|
168
|
+
- `setCell(presenceRoom, { row, col })` sets the cell that the local user edits. Give `null`
|
|
169
|
+
when the user stops. A sheet cell also has `sheet`.
|
|
170
|
+
- `cellPresence(state.peers)` gives the peers on each cell, by `cellKey(cell)`. Show a dot for
|
|
171
|
+
each peer on the cell. A `cell` field that is not valid is ignored, because remote states are
|
|
172
|
+
not trusted.
|
|
173
|
+
|
|
174
|
+
### The transport bridge
|
|
175
|
+
|
|
176
|
+
The bridge sends the Lattice collab messages through Dovetail, so the host has one connection,
|
|
177
|
+
one auth hook and one offline state. Each Lattice client has its own room,
|
|
178
|
+
`latticeRoom(docId, clientId)`, because the Lattice server sends some messages to one client
|
|
179
|
+
only.
|
|
180
|
+
|
|
181
|
+
```ts
|
|
182
|
+
import { CollabSession } from '@ember-lattice/collab'
|
|
183
|
+
import { latticeBridge, latticeRoom } from '@dovetail-ts/integrations/lattice'
|
|
184
|
+
|
|
185
|
+
const clientId = crypto.randomUUID()
|
|
186
|
+
const bridge = latticeBridge(connection, latticeRoom('sheet-1', clientId))
|
|
187
|
+
const session = new CollabSession({ doc, transport: bridge, docId: 'sheet-1', clientId })
|
|
188
|
+
const stop = bridge.attach(session)
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
`attach` opens the session after each join of the room, and closes it when the connection is
|
|
192
|
+
not open. The messages do not go through the write queue, because the session sends its pending
|
|
193
|
+
ops again on each `open()`.
|
|
194
|
+
|
|
195
|
+
On the server, `latticeServerBridge({ docServer, server, next })` gives the `handleWrite` hook.
|
|
196
|
+
A Lattice message goes to the Lattice doc server, and the other writes go to `next`.
|
|
197
|
+
|
|
198
|
+
```ts
|
|
199
|
+
import { createDocServer } from '@ember-lattice/server'
|
|
200
|
+
import { createDovetailServer } from '@dovetail-ts/server'
|
|
201
|
+
import { latticeServerBridge, parseLatticeRoom } from '@dovetail-ts/integrations/lattice'
|
|
202
|
+
|
|
203
|
+
const bridge = latticeServerBridge({
|
|
204
|
+
docServer: createDocServer({ store, engine }),
|
|
205
|
+
server: { publish: (room, document) => dovetail.publish(room, document) },
|
|
206
|
+
next: write => applyWrite(write),
|
|
207
|
+
})
|
|
208
|
+
const dovetail = createDovetailServer({
|
|
209
|
+
handleWrite: write => bridge.handleWrite(write),
|
|
210
|
+
onSessionEnd: session => bridge.onSessionEnd(session),
|
|
211
|
+
authorize: (user, room) => {
|
|
212
|
+
if (!room.startsWith('lattice:')) return canAccess(user, room)
|
|
213
|
+
const parsed = parseLatticeRoom(room) // { docId, clientId } or null
|
|
214
|
+
return parsed !== null && canOpen(user, parsed.docId)
|
|
215
|
+
},
|
|
216
|
+
})
|
|
217
|
+
```
|
|
218
|
+
|
|
219
|
+
- The `authorize` hook must let a user join and write only the `lattice:` rooms of the docs
|
|
220
|
+
that the user can open. Read the doc id with `parseLatticeRoom(room)`. It gives null for a
|
|
221
|
+
room name that is not `lattice:<docId>:<clientId>`. `latticeRoom(docId, clientId)` throws when
|
|
222
|
+
an id has a `:`, so a room name has one meaning only.
|
|
223
|
+
- `onSessionEnd: session => bridge.onSessionEnd(session)` is necessary. When a connection
|
|
224
|
+
closes, the bridge closes the Lattice connection of each client room of that session, as the
|
|
225
|
+
Lattice socket server does. It does not close a connection that a newer session uses. A
|
|
226
|
+
reconnect then makes a new Lattice connection, and the client joins again with its seq.
|
|
227
|
+
`bridge.close(room)` closes one client room.
|
|
228
|
+
- A message is one Dovetail message, so a snapshot must be smaller than `maxMessageBytes`
|
|
229
|
+
(default 1 MB).
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import type { Connection } from '@dovetail-ts/core';
|
|
2
|
+
import type { JsonApiDocument, JsonObject, ResourceIdentifier } from '@dovetail-ts/protocol';
|
|
3
|
+
/** The room of the flag changes of one Benchdog environment. */
|
|
4
|
+
export declare function benchdogRoom(environment: string): string;
|
|
5
|
+
/** The part of the Benchdog browser client that the binding uses. */
|
|
6
|
+
export interface FlagClientLike {
|
|
7
|
+
refresh(): Promise<void>;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Joins the room of `environment`, and fetches the flags again (`client.refresh()`) for each
|
|
11
|
+
* change in it. After a reconnect, it fetches them again too, because a change can come while
|
|
12
|
+
* the client is offline. Returns a function that stops it and releases the room.
|
|
13
|
+
*/
|
|
14
|
+
export declare function liveFlags(client: FlagClientLike, connection: Connection, environment: string): () => void;
|
|
15
|
+
/** The part of the Dovetail server that the binding uses. */
|
|
16
|
+
export interface DovetailServerLike {
|
|
17
|
+
publish(room: string, document: JsonApiDocument): unknown;
|
|
18
|
+
}
|
|
19
|
+
/** A Benchdog `ChangeFeed`: `subscribe` and `publish` for each environment. */
|
|
20
|
+
export interface ChangeFeedLike {
|
|
21
|
+
subscribe(environment: string, listener: () => void): () => void;
|
|
22
|
+
publish(environment: string): Promise<void>;
|
|
23
|
+
}
|
|
24
|
+
/** The record type of the documents that `dovetailChangeFeed` sends. */
|
|
25
|
+
export declare const CHANGE_TYPE = "benchdog-change";
|
|
26
|
+
/**
|
|
27
|
+
* A Benchdog `ChangeFeed` for `createAdminApi({ feed })` and `createBenchdog({ feed })`. Each
|
|
28
|
+
* `publish` calls the listeners of this process and sends a `benchdog-change` document to the
|
|
29
|
+
* room of the environment. The browser clients get it with `liveFlags`.
|
|
30
|
+
*/
|
|
31
|
+
export declare function dovetailChangeFeed(server: DovetailServerLike): ChangeFeedLike;
|
|
32
|
+
/** The payload of `server.notify(user, payload)` of `@dovetail-ts/server`. */
|
|
33
|
+
export interface BenchdogNotification {
|
|
34
|
+
verb: string;
|
|
35
|
+
actor: ResourceIdentifier;
|
|
36
|
+
target: ResourceIdentifier;
|
|
37
|
+
attributes: JsonObject;
|
|
38
|
+
}
|
|
39
|
+
/** Sends one notification, for example `(user, payload) => server.notify(user, payload)`. */
|
|
40
|
+
export type Notify = (userId: string, payload: BenchdogNotification) => unknown;
|
|
41
|
+
/** The fields of a Benchdog `Approval` that the binding reads. */
|
|
42
|
+
export interface ApprovalLike {
|
|
43
|
+
id: string;
|
|
44
|
+
environment: string;
|
|
45
|
+
requestedBy: string;
|
|
46
|
+
reason: string;
|
|
47
|
+
decidedBy: string | null;
|
|
48
|
+
decisionReason?: string;
|
|
49
|
+
state: string;
|
|
50
|
+
}
|
|
51
|
+
/** The methods of a Benchdog `ApprovalStore` that the binding wraps. */
|
|
52
|
+
export interface ApprovalStoreLike {
|
|
53
|
+
create(approval: ApprovalLike): Promise<void>;
|
|
54
|
+
decide(environment: string, id: string, next: {
|
|
55
|
+
state: string;
|
|
56
|
+
decidedBy: string | null;
|
|
57
|
+
decisionReason?: string;
|
|
58
|
+
}): Promise<ApprovalLike | undefined>;
|
|
59
|
+
}
|
|
60
|
+
export interface NotifyApprovalsOptions {
|
|
61
|
+
notify: Notify;
|
|
62
|
+
/** The users who can approve a change in `environment`. Benchdog has no list of users. */
|
|
63
|
+
approvers(environment: string): readonly string[] | Promise<readonly string[]>;
|
|
64
|
+
/** Gets each error of `notify`. The approval stays. Default `console.error`. */
|
|
65
|
+
onError?(error: unknown): void;
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Wraps a Benchdog `ApprovalStore` (for `createAdminApi({ approvals })`). A new request sends
|
|
69
|
+
* `benchdog.approval-requested` to each approver except the person who asked. A decision sends
|
|
70
|
+
* `benchdog.approval-approved` or `benchdog.approval-rejected` to the person who asked.
|
|
71
|
+
*/
|
|
72
|
+
export declare function notifyApprovals<S extends ApprovalStoreLike>(store: S, options: NotifyApprovalsOptions): S;
|
|
73
|
+
/** The fields of a Benchdog `AuditEntry` that the binding reads. */
|
|
74
|
+
export interface AuditEntryLike {
|
|
75
|
+
environment: string;
|
|
76
|
+
flag?: string;
|
|
77
|
+
action: string;
|
|
78
|
+
actor: {
|
|
79
|
+
id: string;
|
|
80
|
+
};
|
|
81
|
+
reason?: string;
|
|
82
|
+
}
|
|
83
|
+
/** The method of a Benchdog `FlagStore` that the binding wraps. */
|
|
84
|
+
export interface FlagStoreLike {
|
|
85
|
+
write(environment: string, change: never, audit: never): Promise<AuditEntryLike>;
|
|
86
|
+
}
|
|
87
|
+
export interface NotifySchedulesOptions {
|
|
88
|
+
notify: Notify;
|
|
89
|
+
/** The users to tell about an applied scheduled change of `flag`. */
|
|
90
|
+
recipients(environment: string, flag: string): readonly string[] | Promise<readonly string[]>;
|
|
91
|
+
/** Gets each error of `notify`. The change stays. Default `console.error`. */
|
|
92
|
+
onError?(error: unknown): void;
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Wraps a Benchdog `FlagStore`. Each write with the audit action `schedule.apply` (from
|
|
96
|
+
* `applyDueSchedules` or `startScheduler`) sends `benchdog.schedule-applied` to the recipients.
|
|
97
|
+
*/
|
|
98
|
+
export declare function notifySchedules<S extends FlagStoreLike>(store: S, options: NotifySchedulesOptions): S;
|
package/dist/benchdog.js
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
// src/benchdog.ts
|
|
2
|
+
function benchdogRoom(environment) {
|
|
3
|
+
return `benchdog:${environment}`;
|
|
4
|
+
}
|
|
5
|
+
function liveFlags(client, connection, environment) {
|
|
6
|
+
const room = benchdogRoom(environment);
|
|
7
|
+
const refresh = () => void client.refresh().catch(() => void 0);
|
|
8
|
+
let joined = false;
|
|
9
|
+
const stopJoin = connection.onJoin(room, () => {
|
|
10
|
+
if (joined) refresh();
|
|
11
|
+
joined = true;
|
|
12
|
+
});
|
|
13
|
+
const stopFeed = connection.onFeed(room, refresh);
|
|
14
|
+
const release = connection.retain(room);
|
|
15
|
+
return () => {
|
|
16
|
+
stopJoin();
|
|
17
|
+
stopFeed();
|
|
18
|
+
release();
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
var CHANGE_TYPE = "benchdog-change";
|
|
22
|
+
function dovetailChangeFeed(server) {
|
|
23
|
+
const listeners = /* @__PURE__ */ new Map();
|
|
24
|
+
return {
|
|
25
|
+
subscribe(environment, listener) {
|
|
26
|
+
const set = listeners.get(environment) ?? /* @__PURE__ */ new Set();
|
|
27
|
+
set.add(listener);
|
|
28
|
+
listeners.set(environment, set);
|
|
29
|
+
return () => void set.delete(listener);
|
|
30
|
+
},
|
|
31
|
+
async publish(environment) {
|
|
32
|
+
for (const listener of [...listeners.get(environment) ?? []]) listener();
|
|
33
|
+
server.publish(benchdogRoom(environment), {
|
|
34
|
+
data: { type: CHANGE_TYPE, id: crypto.randomUUID(), attributes: { environment } }
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
function wrap(inner, overrides) {
|
|
40
|
+
return new Proxy(inner, {
|
|
41
|
+
get(target, key) {
|
|
42
|
+
if (Object.hasOwn(overrides, key)) return overrides[key];
|
|
43
|
+
const value = Reflect.get(target, key, target);
|
|
44
|
+
return typeof value === "function" ? value.bind(target) : value;
|
|
45
|
+
}
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
async function send(notify, users, payload, onError) {
|
|
49
|
+
for (const user of users) {
|
|
50
|
+
try {
|
|
51
|
+
await notify(user, payload);
|
|
52
|
+
} catch (error) {
|
|
53
|
+
onError(error);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
function notifyApprovals(store, options) {
|
|
58
|
+
const { notify, approvers, onError = console.error } = options;
|
|
59
|
+
const target = (approval) => ({ type: "benchdog-approval", id: approval.id });
|
|
60
|
+
return wrap(store, {
|
|
61
|
+
async create(approval) {
|
|
62
|
+
await store.create(approval);
|
|
63
|
+
const users = (await approvers(approval.environment)).filter(
|
|
64
|
+
(user) => user !== approval.requestedBy
|
|
65
|
+
);
|
|
66
|
+
await send(
|
|
67
|
+
notify,
|
|
68
|
+
users,
|
|
69
|
+
{
|
|
70
|
+
verb: "benchdog.approval-requested",
|
|
71
|
+
actor: { type: "user", id: approval.requestedBy },
|
|
72
|
+
target: target(approval),
|
|
73
|
+
attributes: { environment: approval.environment, body: approval.reason }
|
|
74
|
+
},
|
|
75
|
+
onError
|
|
76
|
+
);
|
|
77
|
+
},
|
|
78
|
+
async decide(environment, id, next) {
|
|
79
|
+
const decided = await store.decide(environment, id, next);
|
|
80
|
+
if (!decided) return decided;
|
|
81
|
+
await send(
|
|
82
|
+
notify,
|
|
83
|
+
[decided.requestedBy],
|
|
84
|
+
{
|
|
85
|
+
verb: `benchdog.approval-${decided.state}`,
|
|
86
|
+
actor: { type: "user", id: decided.decidedBy ?? "benchdog" },
|
|
87
|
+
target: target(decided),
|
|
88
|
+
attributes: {
|
|
89
|
+
environment,
|
|
90
|
+
...decided.decisionReason ? { body: decided.decisionReason } : {}
|
|
91
|
+
}
|
|
92
|
+
},
|
|
93
|
+
onError
|
|
94
|
+
);
|
|
95
|
+
return decided;
|
|
96
|
+
}
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
function notifySchedules(store, options) {
|
|
100
|
+
const { notify, recipients, onError = console.error } = options;
|
|
101
|
+
return wrap(store, {
|
|
102
|
+
async write(environment, change, audit) {
|
|
103
|
+
const entry = await store.write(environment, change, audit);
|
|
104
|
+
if (entry.action === "schedule.apply" && entry.flag !== void 0) {
|
|
105
|
+
await send(
|
|
106
|
+
notify,
|
|
107
|
+
await recipients(environment, entry.flag),
|
|
108
|
+
{
|
|
109
|
+
verb: "benchdog.schedule-applied",
|
|
110
|
+
actor: { type: "user", id: entry.actor.id },
|
|
111
|
+
target: { type: "benchdog-flag", id: entry.flag },
|
|
112
|
+
attributes: { environment, ...entry.reason ? { body: entry.reason } : {} }
|
|
113
|
+
},
|
|
114
|
+
onError
|
|
115
|
+
);
|
|
116
|
+
}
|
|
117
|
+
return entry;
|
|
118
|
+
}
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export { CHANGE_TYPE, benchdogRoom, dovetailChangeFeed, liveFlags, notifyApprovals, notifySchedules };
|
|
123
|
+
//# sourceMappingURL=benchdog.js.map
|
|
124
|
+
//# sourceMappingURL=benchdog.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/benchdog.ts"],"names":[],"mappings":";AASO,SAAS,aAAa,WAAA,EAA6B;AACxD,EAAA,OAAO,YAAY,WAAW,CAAA,CAAA;AAChC;AAYO,SAAS,SAAA,CACd,MAAA,EACA,UAAA,EACA,WAAA,EACY;AACZ,EAAA,MAAM,IAAA,GAAO,aAAa,WAAW,CAAA;AAErC,EAAA,MAAM,OAAA,GAAU,MAAM,KAAK,MAAA,CAAO,SAAQ,CAAE,KAAA,CAAM,MAAM,MAAS,CAAA;AACjE,EAAA,IAAI,MAAA,GAAS,KAAA;AACb,EAAA,MAAM,QAAA,GAAW,UAAA,CAAW,MAAA,CAAO,IAAA,EAAM,MAAM;AAC7C,IAAA,IAAI,QAAQ,OAAA,EAAQ;AACpB,IAAA,MAAA,GAAS,IAAA;AAAA,EACX,CAAC,CAAA;AACD,EAAA,MAAM,QAAA,GAAW,UAAA,CAAW,MAAA,CAAO,IAAA,EAAM,OAAO,CAAA;AAChD,EAAA,MAAM,OAAA,GAAU,UAAA,CAAW,MAAA,CAAO,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AA,CAAW,WAAA,EAAa,KAAA,CAAM,IAAI,CAAA;AAAA,UACxC;AAAA,YACE,IAAA,EAAM,2BAAA;AAAA,YACN,OAAO,EAAE,IAAA,EAAM,QAAQ,EAAA,EAAI,KAAA,CAAM,MAAM,EAAA,EAAG;AAAA,YAC1C,QAAQ,EAAE,IAAA,EAAM,eAAA,EAAiB,EAAA,EAAI,MAAM,IAAA,EAAK;AAAA,YAChD,UAAA,EAAY,EAAE,WAAA,EAAa,GAAI,KAAA,CAAM,MAAA,GAAS,EAAE,IAAA,EAAM,KAAA,CAAM,MAAA,EAAO,GAAI,EAAC;AAAG,WAC7E;AAAA,UACA;AAAA,SACF;AAAA,MACF;AACA,MAAA,OAAO,KAAA;AAAA,IACT;AAAA,GACD,CAAA;AACH","file":"benchdog.js","sourcesContent":["// The Benchdog binding. In the browser, flag changes arrive through a Dovetail room, so the\n// Benchdog client needs no `/stream` EventSource. On the server, a Benchdog `ChangeFeed` sends\n// each change to that room, and wrappers of the Benchdog stores send notifications for approval\n// requests, their decisions and applied scheduled changes. The types here are structural, so a\n// host can use them with `@benchdog-ts/core` and `@benchdog-ts/admin-api`.\nimport type { Connection } from '@dovetail-ts/core'\nimport type { JsonApiDocument, JsonObject, ResourceIdentifier } from '@dovetail-ts/protocol'\n\n/** The room of the flag changes of one Benchdog environment. */\nexport function benchdogRoom(environment: string): string {\n return `benchdog:${environment}`\n}\n\n/** The part of the Benchdog browser client that the binding uses. */\nexport interface FlagClientLike {\n refresh(): Promise<void>\n}\n\n/**\n * Joins the room of `environment`, and fetches the flags again (`client.refresh()`) for each\n * change in it. After a reconnect, it fetches them again too, because a change can come while\n * the client is offline. Returns a function that stops it and releases the room.\n */\nexport function liveFlags(\n client: FlagClientLike,\n connection: Connection,\n environment: string,\n): () => void {\n const room = benchdogRoom(environment)\n // A failed fetch keeps the last values. The next change or reconnect tries again.\n const refresh = () => void client.refresh().catch(() => undefined)\n let joined = false\n const stopJoin = connection.onJoin(room, () => {\n if (joined) refresh()\n joined = true\n })\n const stopFeed = connection.onFeed(room, refresh)\n const release = connection.retain(room)\n return () => {\n stopJoin()\n stopFeed()\n release()\n }\n}\n\n/** The part of the Dovetail server that the binding uses. */\nexport interface DovetailServerLike {\n publish(room: string, document: JsonApiDocument): unknown\n}\n\n/** A Benchdog `ChangeFeed`: `subscribe` and `publish` for each environment. */\nexport interface ChangeFeedLike {\n subscribe(environment: string, listener: () => void): () => void\n publish(environment: string): Promise<void>\n}\n\n/** The record type of the documents that `dovetailChangeFeed` sends. */\nexport const CHANGE_TYPE = 'benchdog-change'\n\n/**\n * A Benchdog `ChangeFeed` for `createAdminApi({ feed })` and `createBenchdog({ feed })`. Each\n * `publish` calls the listeners of this process and sends a `benchdog-change` document to the\n * room of the environment. The browser clients get it with `liveFlags`.\n */\nexport function dovetailChangeFeed(server: DovetailServerLike): ChangeFeedLike {\n const listeners = new Map<string, Set<() => void>>()\n return {\n subscribe(environment, listener) {\n const set = listeners.get(environment) ?? new Set()\n set.add(listener)\n listeners.set(environment, set)\n return () => void set.delete(listener)\n },\n async publish(environment) {\n for (const listener of [...(listeners.get(environment) ?? [])]) listener()\n server.publish(benchdogRoom(environment), {\n data: { type: CHANGE_TYPE, id: crypto.randomUUID(), attributes: { environment } },\n })\n },\n }\n}\n\n/** The payload of `server.notify(user, payload)` of `@dovetail-ts/server`. */\nexport interface BenchdogNotification {\n verb: string\n actor: ResourceIdentifier\n target: ResourceIdentifier\n attributes: JsonObject\n}\n\n/** Sends one notification, for example `(user, payload) => server.notify(user, payload)`. */\nexport type Notify = (userId: string, payload: BenchdogNotification) => unknown\n\n/** The fields of a Benchdog `Approval` that the binding reads. */\nexport interface ApprovalLike {\n id: string\n environment: string\n requestedBy: string\n reason: string\n decidedBy: string | null\n decisionReason?: string\n state: string\n}\n\n/** The methods of a Benchdog `ApprovalStore` that the binding wraps. */\nexport interface ApprovalStoreLike {\n create(approval: ApprovalLike): Promise<void>\n decide(\n environment: string,\n id: string,\n next: { state: string; decidedBy: string | null; decisionReason?: string },\n ): Promise<ApprovalLike | undefined>\n}\n\nexport interface NotifyApprovalsOptions {\n notify: Notify\n /** The users who can approve a change in `environment`. Benchdog has no list of users. */\n approvers(environment: string): readonly string[] | Promise<readonly string[]>\n /** Gets each error of `notify`. The approval stays. Default `console.error`. */\n onError?(error: unknown): void\n}\n\n/** Calls `inner` with the arguments, but `overrides` in place of some methods. */\nfunction wrap<T extends object>(inner: T, overrides: Partial<T>): T {\n return new Proxy(inner, {\n get(target, key) {\n if (Object.hasOwn(overrides, key)) return overrides[key as keyof T]\n const value: unknown = Reflect.get(target, key, target)\n return typeof value === 'function' ? value.bind(target) : value\n },\n })\n}\n\nasync function send(\n notify: Notify,\n users: readonly string[],\n payload: BenchdogNotification,\n onError: (error: unknown) => void,\n): Promise<void> {\n for (const user of users) {\n try {\n await notify(user, payload)\n } catch (error) {\n onError(error)\n }\n }\n}\n\n/**\n * Wraps a Benchdog `ApprovalStore` (for `createAdminApi({ approvals })`). A new request sends\n * `benchdog.approval-requested` to each approver except the person who asked. A decision sends\n * `benchdog.approval-approved` or `benchdog.approval-rejected` to the person who asked.\n */\nexport function notifyApprovals<S extends ApprovalStoreLike>(\n store: S,\n options: NotifyApprovalsOptions,\n): S {\n const { notify, approvers, onError = console.error } = options\n const target = (approval: ApprovalLike) => ({ type: 'benchdog-approval', id: approval.id })\n return wrap<ApprovalStoreLike>(store, {\n async create(approval) {\n await store.create(approval)\n const users = (await approvers(approval.environment)).filter(\n user => user !== approval.requestedBy,\n )\n await send(\n notify,\n users,\n {\n verb: 'benchdog.approval-requested',\n actor: { type: 'user', id: approval.requestedBy },\n target: target(approval),\n attributes: { environment: approval.environment, body: approval.reason },\n },\n onError,\n )\n },\n async decide(environment, id, next) {\n const decided = await store.decide(environment, id, next)\n if (!decided) return decided\n await send(\n notify,\n [decided.requestedBy],\n {\n verb: `benchdog.approval-${decided.state}`,\n actor: { type: 'user', id: decided.decidedBy ?? 'benchdog' },\n target: target(decided),\n attributes: {\n environment,\n ...(decided.decisionReason ? { body: decided.decisionReason } : {}),\n },\n },\n onError,\n )\n return decided\n },\n }) as S\n}\n\n/** The fields of a Benchdog `AuditEntry` that the binding reads. */\nexport interface AuditEntryLike {\n environment: string\n flag?: string\n action: string\n actor: { id: string }\n reason?: string\n}\n\n/** The method of a Benchdog `FlagStore` that the binding wraps. */\nexport interface FlagStoreLike {\n write(environment: string, change: never, audit: never): Promise<AuditEntryLike>\n}\n\nexport interface NotifySchedulesOptions {\n notify: Notify\n /** The users to tell about an applied scheduled change of `flag`. */\n recipients(environment: string, flag: string): readonly string[] | Promise<readonly string[]>\n /** Gets each error of `notify`. The change stays. Default `console.error`. */\n onError?(error: unknown): void\n}\n\n/**\n * Wraps a Benchdog `FlagStore`. Each write with the audit action `schedule.apply` (from\n * `applyDueSchedules` or `startScheduler`) sends `benchdog.schedule-applied` to the recipients.\n */\nexport function notifySchedules<S extends FlagStoreLike>(\n store: S,\n options: NotifySchedulesOptions,\n): S {\n const { notify, recipients, onError = console.error } = options\n return wrap<FlagStoreLike>(store, {\n async write(environment, change, audit) {\n const entry = await store.write(environment, change, audit)\n if (entry.action === 'schedule.apply' && entry.flag !== undefined) {\n await send(\n notify,\n await recipients(environment, entry.flag),\n {\n verb: 'benchdog.schedule-applied',\n actor: { type: 'user', id: entry.actor.id },\n target: { type: 'benchdog-flag', id: entry.flag },\n attributes: { environment, ...(entry.reason ? { body: entry.reason } : {}) },\n },\n onError,\n )\n }\n return entry\n },\n }) as S\n}\n"]}
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/index.ts"],"names":[],"mappings":";AACO,IAAM,YAAA,GAAe","file":"index.js","sourcesContent":["/** The name of this package. The real exports come in a later milestone. */\nexport const PACKAGE_NAME = '@dovetail-ts/integrations'\n"]}
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
import type { Connection, PresencePeer } from '@dovetail-ts/core';
|
|
2
|
+
import type { JsonApiDocument, JsonObject, Resource, StoreOp } from '@dovetail-ts/protocol';
|
|
3
|
+
/** The request of `DataSource.getRows` of `@ember-lattice/data`. The binding does not read it. */
|
|
4
|
+
export type RowsRequestLike = object;
|
|
5
|
+
/** A live update of `DataSource.subscribe` of `@ember-lattice/data`. */
|
|
6
|
+
export interface LatticeTransaction<Row> {
|
|
7
|
+
v: 1;
|
|
8
|
+
add?: Row[];
|
|
9
|
+
update?: Row[];
|
|
10
|
+
/** Row ids. */
|
|
11
|
+
remove?: string[];
|
|
12
|
+
}
|
|
13
|
+
/** The parts of a Lattice `DataSource` that the binding uses, as `warpDriveDataSource` makes it. */
|
|
14
|
+
export interface LatticeDataSource<Row> {
|
|
15
|
+
readonly capabilities: {
|
|
16
|
+
readonly push: boolean;
|
|
17
|
+
};
|
|
18
|
+
getRows(request: RowsRequestLike, signal: AbortSignal): Promise<{
|
|
19
|
+
rows: Row[];
|
|
20
|
+
}>;
|
|
21
|
+
subscribe?(onChange: (tx: LatticeTransaction<Row>) => void): () => void;
|
|
22
|
+
getRowId(row: Row): string;
|
|
23
|
+
}
|
|
24
|
+
export interface LiveRowsOptions<Row> {
|
|
25
|
+
connection: Connection;
|
|
26
|
+
/** The room of the store feed of the rows. */
|
|
27
|
+
room: string;
|
|
28
|
+
/** The record type of the rows. The feed of other types does not change the grid. */
|
|
29
|
+
type: string;
|
|
30
|
+
/**
|
|
31
|
+
* The row of a resource of the feed. For WarpDrive rows, the record:
|
|
32
|
+
* `resource => store.peekRecord(resource.type, resource.id)`.
|
|
33
|
+
*/
|
|
34
|
+
rowOf(resource: Resource): Row;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Adds live updates to a Lattice `DataSource` (for example of `warpDriveDataSource`). Each
|
|
38
|
+
* upsert of `type` in the store feed of `room` is an update of a row that the grid loaded, or
|
|
39
|
+
* else an add. Each delete is a remove. Put the feed in the WarpDrive store too
|
|
40
|
+
* (`sync.subscribe(room)`), so the rows that the grid loads again are new.
|
|
41
|
+
*/
|
|
42
|
+
export declare function liveRows<Row, S extends LatticeDataSource<Row>>(source: S & LatticeDataSource<Row>, options: LiveRowsOptions<Row>): S & Required<Pick<LatticeDataSource<Row>, 'subscribe'>>;
|
|
43
|
+
/** A cell of a grid (a row id and a column id), or of a sheet (with `sheet`). */
|
|
44
|
+
export interface LatticeCell {
|
|
45
|
+
sheet?: string;
|
|
46
|
+
row: string;
|
|
47
|
+
col: string;
|
|
48
|
+
}
|
|
49
|
+
/** The key of a cell in the map of `cellPresence`. */
|
|
50
|
+
export declare function cellKey(cell: LatticeCell): string;
|
|
51
|
+
/**
|
|
52
|
+
* The peers on each cell, by `cellKey`: the presence dots of a grid. A peer is on a cell when its
|
|
53
|
+
* presence state has a valid `cell` field (see `setCell`).
|
|
54
|
+
*/
|
|
55
|
+
export declare function cellPresence(peers: readonly PresencePeer[]): Map<string, PresencePeer[]>;
|
|
56
|
+
/** Sets the cell that the local user edits, or null. `presence` is a `PresenceRoom`. */
|
|
57
|
+
export declare function setCell(presence: {
|
|
58
|
+
set(fields: JsonObject): void;
|
|
59
|
+
}, cell: LatticeCell | null): void;
|
|
60
|
+
/** The record type of a Lattice collab message in the store feed of a Dovetail room. */
|
|
61
|
+
export declare const MESSAGE_TYPE = "lattice-message";
|
|
62
|
+
/**
|
|
63
|
+
* The room of one Lattice client. The server sends some messages (the snapshot, an ack, a
|
|
64
|
+
* reject) to one client only, and Dovetail sends a feed to each member of a room. So each
|
|
65
|
+
* client has its own room. The client id of a Lattice session is a random id. The doc id and
|
|
66
|
+
* the client id must not have a `:`, so a room name has one meaning only.
|
|
67
|
+
*/
|
|
68
|
+
export declare function latticeRoom(docId: string, clientId: string): string;
|
|
69
|
+
/**
|
|
70
|
+
* The doc id and the client id of a client room, or null for another room. Use it in the host
|
|
71
|
+
* `authorize` hook: allow a `lattice:` room only when the user can open its doc.
|
|
72
|
+
*/
|
|
73
|
+
export declare function parseLatticeRoom(room: string): {
|
|
74
|
+
docId: string;
|
|
75
|
+
clientId: string;
|
|
76
|
+
} | null;
|
|
77
|
+
/** The calls of a Lattice `CollabSession` that the bridge makes. */
|
|
78
|
+
export interface CollabSessionLike {
|
|
79
|
+
receive(message: unknown): void;
|
|
80
|
+
open(): void;
|
|
81
|
+
close(): void;
|
|
82
|
+
}
|
|
83
|
+
export interface LatticeBridge {
|
|
84
|
+
/** The Lattice `Transport`: give the bridge as `transport` to `new CollabSession`. */
|
|
85
|
+
send(message: unknown): void;
|
|
86
|
+
/**
|
|
87
|
+
* Connects the session: it opens after each join of the room, and closes when the connection
|
|
88
|
+
* is not open. Returns a function that stops it and releases the room.
|
|
89
|
+
*/
|
|
90
|
+
attach(session: CollabSessionLike): () => void;
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* The client side of the transport bridge: a Lattice `Transport` over the Dovetail connection,
|
|
94
|
+
* in the room `latticeRoom(docId, clientId)`. The messages do not go through the write queue:
|
|
95
|
+
* a Lattice session keeps its own pending ops and sends them again on `open()`.
|
|
96
|
+
*/
|
|
97
|
+
export declare function latticeBridge(connection: Connection, room: string): LatticeBridge;
|
|
98
|
+
/** The answer of a `handleWrite` hook of `@dovetail-ts/server`. */
|
|
99
|
+
export type WriteResultLike = {
|
|
100
|
+
ok: true;
|
|
101
|
+
document?: JsonApiDocument;
|
|
102
|
+
} | {
|
|
103
|
+
ok: false;
|
|
104
|
+
status: number;
|
|
105
|
+
errors: {
|
|
106
|
+
status?: string;
|
|
107
|
+
title?: string;
|
|
108
|
+
}[];
|
|
109
|
+
};
|
|
110
|
+
/** The write of a `handleWrite` hook of `@dovetail-ts/server`. */
|
|
111
|
+
export interface WriteLike {
|
|
112
|
+
/** The id of the session that sent the write. */
|
|
113
|
+
session: string;
|
|
114
|
+
room: string;
|
|
115
|
+
op: StoreOp;
|
|
116
|
+
}
|
|
117
|
+
/** The Lattice doc server (`createDocServer` of `@ember-lattice/server`). */
|
|
118
|
+
export interface DocServerLike {
|
|
119
|
+
connect(send: (message: unknown) => void): {
|
|
120
|
+
receive(input: unknown): Promise<void>;
|
|
121
|
+
close(): void;
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
export interface LatticeServerBridgeOptions<W extends WriteLike> {
|
|
125
|
+
docServer: DocServerLike;
|
|
126
|
+
/** The Dovetail server: the bridge sends the Lattice messages to the room of each client. */
|
|
127
|
+
server: {
|
|
128
|
+
publish(room: string, document: JsonApiDocument): unknown;
|
|
129
|
+
};
|
|
130
|
+
/** Handles the writes that are not Lattice messages. Default: an ack. */
|
|
131
|
+
next?(write: W): WriteResultLike | Promise<WriteResultLike>;
|
|
132
|
+
}
|
|
133
|
+
export interface LatticeServerBridge<W extends WriteLike> {
|
|
134
|
+
/** The `handleWrite` hook of the Dovetail server. */
|
|
135
|
+
handleWrite(write: W): Promise<WriteResultLike>;
|
|
136
|
+
/**
|
|
137
|
+
* The `onSessionEnd` hook of the Dovetail server. It closes the Lattice connection of each
|
|
138
|
+
* client room of the session, as the Lattice socket server does when a socket closes. It does
|
|
139
|
+
* not close a connection that a newer session uses (a reconnect can write first).
|
|
140
|
+
*/
|
|
141
|
+
onSessionEnd(session: {
|
|
142
|
+
id: string;
|
|
143
|
+
rooms: readonly string[];
|
|
144
|
+
}): void;
|
|
145
|
+
/** Closes the Lattice connection of a client room. */
|
|
146
|
+
close(room: string): void;
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* The server side of the transport bridge. Each client room has one Lattice connection, also
|
|
150
|
+
* after a reconnect, so the session goes on with its seq. The Lattice server parses each
|
|
151
|
+
* message (its trust boundary). The host `authorize` hook must let a user join and write only
|
|
152
|
+
* the `lattice:` rooms of the docs that the user can open.
|
|
153
|
+
*/
|
|
154
|
+
export declare function latticeServerBridge<W extends WriteLike>(options: LatticeServerBridgeOptions<W>): LatticeServerBridge<W>;
|
package/dist/lattice.js
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
// src/lattice.ts
|
|
2
|
+
function liveRows(source, options) {
|
|
3
|
+
const { connection, room, type, rowOf } = options;
|
|
4
|
+
const loaded = /* @__PURE__ */ new Set();
|
|
5
|
+
const transaction = (op) => {
|
|
6
|
+
if (op.op === "delete") return op.ref.type === type ? { v: 1, remove: [op.ref.id] } : void 0;
|
|
7
|
+
const data = op.document.data;
|
|
8
|
+
const resources = (Array.isArray(data) ? data : data ? [data] : []).filter(
|
|
9
|
+
(resource) => resource.type === type
|
|
10
|
+
);
|
|
11
|
+
if (resources.length === 0) return void 0;
|
|
12
|
+
const tx = { v: 1 };
|
|
13
|
+
for (const resource of resources) {
|
|
14
|
+
const kind = loaded.has(resource.id) ? "update" : "add";
|
|
15
|
+
loaded.add(resource.id);
|
|
16
|
+
(tx[kind] ??= []).push(rowOf(resource));
|
|
17
|
+
}
|
|
18
|
+
return tx;
|
|
19
|
+
};
|
|
20
|
+
return {
|
|
21
|
+
...source,
|
|
22
|
+
capabilities: { ...source.capabilities, push: true },
|
|
23
|
+
async getRows(request, signal) {
|
|
24
|
+
const response = await source.getRows(request, signal);
|
|
25
|
+
for (const row of response.rows) loaded.add(source.getRowId(row));
|
|
26
|
+
return response;
|
|
27
|
+
},
|
|
28
|
+
subscribe(onChange) {
|
|
29
|
+
const stopFeed = connection.onFeed(room, (message) => {
|
|
30
|
+
queueMicrotask(() => {
|
|
31
|
+
for (const op of message.ops) {
|
|
32
|
+
const tx = transaction(op);
|
|
33
|
+
if (tx) onChange(tx);
|
|
34
|
+
}
|
|
35
|
+
});
|
|
36
|
+
});
|
|
37
|
+
const release = connection.retain(room);
|
|
38
|
+
return () => {
|
|
39
|
+
stopFeed();
|
|
40
|
+
release();
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
function cellKey(cell) {
|
|
46
|
+
return `${cell.sheet ?? ""}\0${cell.row}\0${cell.col}`;
|
|
47
|
+
}
|
|
48
|
+
function readCell(value) {
|
|
49
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
|
|
50
|
+
const { sheet, row, col } = value;
|
|
51
|
+
if (typeof row !== "string" || typeof col !== "string") return void 0;
|
|
52
|
+
if (sheet !== void 0 && typeof sheet !== "string") return void 0;
|
|
53
|
+
return sheet === void 0 ? { row, col } : { sheet, row, col };
|
|
54
|
+
}
|
|
55
|
+
function cellPresence(peers) {
|
|
56
|
+
const cells = /* @__PURE__ */ new Map();
|
|
57
|
+
for (const peer of peers) {
|
|
58
|
+
const cell = readCell(peer.extra["cell"]);
|
|
59
|
+
if (!cell) continue;
|
|
60
|
+
const key = cellKey(cell);
|
|
61
|
+
cells.set(key, [...cells.get(key) ?? [], peer]);
|
|
62
|
+
}
|
|
63
|
+
return cells;
|
|
64
|
+
}
|
|
65
|
+
function setCell(presence, cell) {
|
|
66
|
+
presence.set({ cell: cell ? { ...cell } : null });
|
|
67
|
+
}
|
|
68
|
+
var MESSAGE_TYPE = "lattice-message";
|
|
69
|
+
var ROOM_PREFIX = "lattice:";
|
|
70
|
+
function latticeRoom(docId, clientId) {
|
|
71
|
+
if (docId.includes(":") || clientId.includes(":"))
|
|
72
|
+
throw new Error("latticeRoom: a doc id or a client id must not have a `:`");
|
|
73
|
+
return `${ROOM_PREFIX}${docId}:${clientId}`;
|
|
74
|
+
}
|
|
75
|
+
function parseLatticeRoom(room) {
|
|
76
|
+
if (!room.startsWith(ROOM_PREFIX)) return null;
|
|
77
|
+
const parts = room.slice(ROOM_PREFIX.length).split(":");
|
|
78
|
+
if (parts.length !== 2 || !parts[0] || !parts[1]) return null;
|
|
79
|
+
return { docId: parts[0], clientId: parts[1] };
|
|
80
|
+
}
|
|
81
|
+
var envelope = (message) => ({
|
|
82
|
+
data: {
|
|
83
|
+
type: MESSAGE_TYPE,
|
|
84
|
+
id: crypto.randomUUID(),
|
|
85
|
+
attributes: { message }
|
|
86
|
+
}
|
|
87
|
+
});
|
|
88
|
+
function latticeBridge(connection, room) {
|
|
89
|
+
return {
|
|
90
|
+
send(message) {
|
|
91
|
+
if (!connection.isOpen) return;
|
|
92
|
+
const op = { op: "upsert", document: envelope(message) };
|
|
93
|
+
connection.write(crypto.randomUUID(), room, op).catch(() => void 0);
|
|
94
|
+
},
|
|
95
|
+
attach(session) {
|
|
96
|
+
let open = false;
|
|
97
|
+
const stopJoin = connection.onJoin(room, () => {
|
|
98
|
+
open = true;
|
|
99
|
+
session.open();
|
|
100
|
+
});
|
|
101
|
+
const stopState = connection.onStateChange(() => {
|
|
102
|
+
if (!open || connection.isOpen) return;
|
|
103
|
+
open = false;
|
|
104
|
+
session.close();
|
|
105
|
+
});
|
|
106
|
+
const stopFeed = connection.onFeed(room, (feed) => {
|
|
107
|
+
for (const op of feed.ops) {
|
|
108
|
+
if (op.op !== "upsert") continue;
|
|
109
|
+
const data = op.document.data;
|
|
110
|
+
if (data && !Array.isArray(data) && data.type === MESSAGE_TYPE)
|
|
111
|
+
session.receive(data.attributes?.["message"]);
|
|
112
|
+
}
|
|
113
|
+
});
|
|
114
|
+
const release = connection.retain(room);
|
|
115
|
+
return () => {
|
|
116
|
+
stopJoin();
|
|
117
|
+
stopState();
|
|
118
|
+
stopFeed();
|
|
119
|
+
release();
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
function belongsTo(message, room) {
|
|
125
|
+
if (typeof message !== "object" || message === null || Array.isArray(message)) return false;
|
|
126
|
+
const { docId, clientId } = message;
|
|
127
|
+
const parsed = parseLatticeRoom(room);
|
|
128
|
+
if (!parsed || docId !== parsed.docId) return false;
|
|
129
|
+
return clientId === void 0 || clientId === parsed.clientId;
|
|
130
|
+
}
|
|
131
|
+
function latticeServerBridge(options) {
|
|
132
|
+
const { docServer, server, next = () => ({ ok: true }) } = options;
|
|
133
|
+
const conns = /* @__PURE__ */ new Map();
|
|
134
|
+
const refuse = (status, title) => ({
|
|
135
|
+
ok: false,
|
|
136
|
+
status,
|
|
137
|
+
errors: [{ status: String(status), title }]
|
|
138
|
+
});
|
|
139
|
+
const close = (room) => {
|
|
140
|
+
conns.get(room)?.conn.close();
|
|
141
|
+
conns.delete(room);
|
|
142
|
+
};
|
|
143
|
+
return {
|
|
144
|
+
async handleWrite(write) {
|
|
145
|
+
const { op, room } = write;
|
|
146
|
+
const data = op.op === "upsert" ? op.document.data : null;
|
|
147
|
+
const isMessage = data && !Array.isArray(data) && data.type === MESSAGE_TYPE;
|
|
148
|
+
if (!isMessage) return next(write);
|
|
149
|
+
if (!room.startsWith(ROOM_PREFIX))
|
|
150
|
+
return refuse(403, "A Lattice message goes only to a lattice: room.");
|
|
151
|
+
const message = data.attributes?.["message"];
|
|
152
|
+
if (!belongsTo(message, room))
|
|
153
|
+
return refuse(403, "A Lattice message must have the doc and the client of its room.");
|
|
154
|
+
let entry = conns.get(room);
|
|
155
|
+
if (!entry) {
|
|
156
|
+
const conn = docServer.connect((message2) => void server.publish(room, envelope(message2)));
|
|
157
|
+
conns.set(room, entry = { conn, session: write.session });
|
|
158
|
+
}
|
|
159
|
+
entry.session = write.session;
|
|
160
|
+
await entry.conn.receive(message);
|
|
161
|
+
return { ok: true };
|
|
162
|
+
},
|
|
163
|
+
onSessionEnd({ id, rooms }) {
|
|
164
|
+
for (const room of rooms) if (conns.get(room)?.session === id) close(room);
|
|
165
|
+
},
|
|
166
|
+
close
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
export { MESSAGE_TYPE, cellKey, cellPresence, latticeBridge, latticeRoom, latticeServerBridge, liveRows, parseLatticeRoom, setCell };
|
|
171
|
+
//# sourceMappingURL=lattice.js.map
|
|
172
|
+
//# sourceMappingURL=lattice.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/lattice.ts"],"names":["message"],"mappings":";AAqDO,SAAS,QAAA,CACd,QACA,OAAA,EACyD;AACzD,EAAA,MAAM,EAAE,UAAA,EAAY,IAAA,EAAM,IAAA,EAAM,OAAM,GAAI,OAAA;AAG1C,EAAA,MAAM,MAAA,uBAAa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A,IAAI,CAAC,KAAA,EAAO;AACV,QAAA,MAAM,IAAA,GAAO,SAAA,CAAU,OAAA,CAAQ,CAAAA,QAAAA,KAAW,KAAK,MAAA,CAAO,OAAA,CAAQ,IAAA,EAAM,QAAA,CAASA,QAAO,CAAC,CAAC,CAAA;AACtF,QAAA,KAAA,CAAM,GAAA,CAAI,MAAO,KAAA,GAAQ,EAAE,MAAM,OAAA,EAAS,KAAA,CAAM,SAAU,CAAA;AAAA,MAC5D;AACA,MAAA,KAAA,CAAM,UAAU,KAAA,CAAM,OAAA;AACtB,MAAA,MAAM,KAAA,CAAM,IAAA,CAAK,OAAA,CAAQ,OAAO,CAAA;AAChC,MAAA,OAAO,EAAE,IAAI,IAAA,EAAK;AAAA,IACpB,CAAA;AAAA,IACA,YAAA,CAAa,EAAE,EAAA,EAAI,KAAA,EAAM,EAAG;AAC1B,MAAA,KAAA,MAAW,IAAA,IAAQ,KAAA,EAAO,IAAI,KAAA,CAAM,GAAA,CAAI,IAAI,CAAA,EAAG,OAAA,KAAY,EAAA,EAAI,KAAA,CAAM,IAAI,CAAA;AAAA,IAC3E,CAAA;AAAA,IACA;AAAA,GACF;AACF","file":"lattice.js","sourcesContent":["// The Lattice binding (ADR 0010, ADR 0019): live rows, presence on cells, and a transport\n// bridge for the Lattice collab layer. `@ember-lattice/*` is not on npm yet, so the binding\n// types against local interfaces that the Lattice classes fit structurally.\nimport type { Connection, PresencePeer } from '@dovetail-ts/core'\nimport type {\n JsonApiDocument,\n JsonObject,\n JsonValue,\n Resource,\n StoreOp,\n} from '@dovetail-ts/protocol'\n\n// Live rows.\n\n/** The request of `DataSource.getRows` of `@ember-lattice/data`. The binding does not read it. */\nexport type RowsRequestLike = object\n\n/** A live update of `DataSource.subscribe` of `@ember-lattice/data`. */\nexport interface LatticeTransaction<Row> {\n v: 1\n add?: Row[]\n update?: Row[]\n /** Row ids. */\n remove?: string[]\n}\n\n/** The parts of a Lattice `DataSource` that the binding uses, as `warpDriveDataSource` makes it. */\nexport interface LatticeDataSource<Row> {\n readonly capabilities: { readonly push: boolean }\n getRows(request: RowsRequestLike, signal: AbortSignal): Promise<{ rows: Row[] }>\n subscribe?(onChange: (tx: LatticeTransaction<Row>) => void): () => void\n getRowId(row: Row): string\n}\n\nexport interface LiveRowsOptions<Row> {\n connection: Connection\n /** The room of the store feed of the rows. */\n room: string\n /** The record type of the rows. The feed of other types does not change the grid. */\n type: string\n /**\n * The row of a resource of the feed. For WarpDrive rows, the record:\n * `resource => store.peekRecord(resource.type, resource.id)`.\n */\n rowOf(resource: Resource): Row\n}\n\n/**\n * Adds live updates to a Lattice `DataSource` (for example of `warpDriveDataSource`). Each\n * upsert of `type` in the store feed of `room` is an update of a row that the grid loaded, or\n * else an add. Each delete is a remove. Put the feed in the WarpDrive store too\n * (`sync.subscribe(room)`), so the rows that the grid loads again are new.\n */\nexport function liveRows<Row, S extends LatticeDataSource<Row>>(\n source: S & LatticeDataSource<Row>,\n options: LiveRowsOptions<Row>,\n): S & Required<Pick<LatticeDataSource<Row>, 'subscribe'>> {\n const { connection, room, type, rowOf } = options\n // shortcut: the ids of all loaded rows stay in memory until the grid is gone; upgrade to a\n // count per block when a grid loads very many rows.\n const loaded = new Set<string>()\n const transaction = (op: StoreOp): LatticeTransaction<Row> | undefined => {\n if (op.op === 'delete') return op.ref.type === type ? { v: 1, remove: [op.ref.id] } : undefined\n const data = op.document.data\n const resources = (Array.isArray(data) ? data : data ? [data] : []).filter(\n resource => resource.type === type,\n )\n if (resources.length === 0) return undefined\n const tx: LatticeTransaction<Row> = { v: 1 }\n for (const resource of resources) {\n const kind = loaded.has(resource.id) ? 'update' : 'add'\n loaded.add(resource.id)\n ;(tx[kind] ??= []).push(rowOf(resource))\n }\n return tx\n }\n return {\n ...source,\n capabilities: { ...source.capabilities, push: true },\n async getRows(request: RowsRequestLike, signal: AbortSignal) {\n const response = await source.getRows(request, signal)\n for (const row of response.rows) loaded.add(source.getRowId(row))\n return response\n },\n subscribe(onChange: (tx: LatticeTransaction<Row>) => void) {\n const stopFeed = connection.onFeed(room, message => {\n // After the other feed listeners, so `rowOf` reads the record that the store has now.\n queueMicrotask(() => {\n for (const op of message.ops) {\n const tx = transaction(op)\n if (tx) onChange(tx)\n }\n })\n })\n const release = connection.retain(room)\n return () => {\n stopFeed()\n release()\n }\n },\n }\n}\n\n// Presence on cells.\n\n/** A cell of a grid (a row id and a column id), or of a sheet (with `sheet`). */\nexport interface LatticeCell {\n sheet?: string\n row: string\n col: string\n}\n\n/** The key of a cell in the map of `cellPresence`. */\nexport function cellKey(cell: LatticeCell): string {\n return `${cell.sheet ?? ''}\\u0000${cell.row}\\u0000${cell.col}`\n}\n\n/** The `cell` field of a presence state. Remote states are not trusted, so it checks each one. */\nfunction readCell(value: JsonValue | undefined): LatticeCell | undefined {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return undefined\n const { sheet, row, col } = value\n if (typeof row !== 'string' || typeof col !== 'string') return undefined\n if (sheet !== undefined && typeof sheet !== 'string') return undefined\n return sheet === undefined ? { row, col } : { sheet, row, col }\n}\n\n/**\n * The peers on each cell, by `cellKey`: the presence dots of a grid. A peer is on a cell when its\n * presence state has a valid `cell` field (see `setCell`).\n */\nexport function cellPresence(peers: readonly PresencePeer[]): Map<string, PresencePeer[]> {\n const cells = new Map<string, PresencePeer[]>()\n for (const peer of peers) {\n const cell = readCell(peer.extra['cell'])\n if (!cell) continue\n const key = cellKey(cell)\n cells.set(key, [...(cells.get(key) ?? []), peer])\n }\n return cells\n}\n\n/** Sets the cell that the local user edits, or null. `presence` is a `PresenceRoom`. */\nexport function setCell(\n presence: { set(fields: JsonObject): void },\n cell: LatticeCell | null,\n): void {\n presence.set({ cell: cell ? { ...cell } : null })\n}\n\n// The transport bridge.\n\n/** The record type of a Lattice collab message in the store feed of a Dovetail room. */\nexport const MESSAGE_TYPE = 'lattice-message'\n\nconst ROOM_PREFIX = 'lattice:'\n\n/**\n * The room of one Lattice client. The server sends some messages (the snapshot, an ack, a\n * reject) to one client only, and Dovetail sends a feed to each member of a room. So each\n * client has its own room. The client id of a Lattice session is a random id. The doc id and\n * the client id must not have a `:`, so a room name has one meaning only.\n */\nexport function latticeRoom(docId: string, clientId: string): string {\n if (docId.includes(':') || clientId.includes(':'))\n throw new Error('latticeRoom: a doc id or a client id must not have a `:`')\n return `${ROOM_PREFIX}${docId}:${clientId}`\n}\n\n/**\n * The doc id and the client id of a client room, or null for another room. Use it in the host\n * `authorize` hook: allow a `lattice:` room only when the user can open its doc.\n */\nexport function parseLatticeRoom(room: string): { docId: string; clientId: string } | null {\n if (!room.startsWith(ROOM_PREFIX)) return null\n const parts = room.slice(ROOM_PREFIX.length).split(':')\n if (parts.length !== 2 || !parts[0] || !parts[1]) return null\n return { docId: parts[0], clientId: parts[1] }\n}\n\nconst envelope = (message: unknown): JsonApiDocument => ({\n data: {\n type: MESSAGE_TYPE,\n id: crypto.randomUUID(),\n attributes: { message: message as JsonValue },\n },\n})\n\n/** The calls of a Lattice `CollabSession` that the bridge makes. */\nexport interface CollabSessionLike {\n receive(message: unknown): void\n open(): void\n close(): void\n}\n\nexport interface LatticeBridge {\n /** The Lattice `Transport`: give the bridge as `transport` to `new CollabSession`. */\n send(message: unknown): void\n /**\n * Connects the session: it opens after each join of the room, and closes when the connection\n * is not open. Returns a function that stops it and releases the room.\n */\n attach(session: CollabSessionLike): () => void\n}\n\n/**\n * The client side of the transport bridge: a Lattice `Transport` over the Dovetail connection,\n * in the room `latticeRoom(docId, clientId)`. The messages do not go through the write queue:\n * a Lattice session keeps its own pending ops and sends them again on `open()`.\n */\nexport function latticeBridge(connection: Connection, room: string): LatticeBridge {\n return {\n send(message) {\n if (!connection.isOpen) return\n const op: StoreOp = { op: 'upsert', document: envelope(message) }\n // A lost message comes again: the session sends its pending ops on the next `open()`.\n connection.write(crypto.randomUUID(), room, op).catch(() => undefined)\n },\n attach(session) {\n let open = false\n const stopJoin = connection.onJoin(room, () => {\n open = true\n session.open()\n })\n const stopState = connection.onStateChange(() => {\n if (!open || connection.isOpen) return\n open = false\n session.close()\n })\n const stopFeed = connection.onFeed(room, feed => {\n for (const op of feed.ops) {\n if (op.op !== 'upsert') continue\n const data = op.document.data\n if (data && !Array.isArray(data) && data.type === MESSAGE_TYPE)\n session.receive(data.attributes?.['message'])\n }\n })\n const release = connection.retain(room)\n return () => {\n stopJoin()\n stopState()\n stopFeed()\n release()\n }\n },\n }\n}\n\n/** The answer of a `handleWrite` hook of `@dovetail-ts/server`. */\nexport type WriteResultLike =\n | { ok: true; document?: JsonApiDocument }\n | { ok: false; status: number; errors: { status?: string; title?: string }[] }\n\n/** The write of a `handleWrite` hook of `@dovetail-ts/server`. */\nexport interface WriteLike {\n /** The id of the session that sent the write. */\n session: string\n room: string\n op: StoreOp\n}\n\n/** The Lattice doc server (`createDocServer` of `@ember-lattice/server`). */\nexport interface DocServerLike {\n connect(send: (message: unknown) => void): {\n receive(input: unknown): Promise<void>\n close(): void\n }\n}\n\nexport interface LatticeServerBridgeOptions<W extends WriteLike> {\n docServer: DocServerLike\n /** The Dovetail server: the bridge sends the Lattice messages to the room of each client. */\n server: { publish(room: string, document: JsonApiDocument): unknown }\n /** Handles the writes that are not Lattice messages. Default: an ack. */\n next?(write: W): WriteResultLike | Promise<WriteResultLike>\n}\n\nexport interface LatticeServerBridge<W extends WriteLike> {\n /** The `handleWrite` hook of the Dovetail server. */\n handleWrite(write: W): Promise<WriteResultLike>\n /**\n * The `onSessionEnd` hook of the Dovetail server. It closes the Lattice connection of each\n * client room of the session, as the Lattice socket server does when a socket closes. It does\n * not close a connection that a newer session uses (a reconnect can write first).\n */\n onSessionEnd(session: { id: string; rooms: readonly string[] }): void\n /** Closes the Lattice connection of a client room. */\n close(room: string): void\n}\n\n/**\n * True when the doc and the client of `message` are the ones of `room`. The host `authorize` hook\n * sees only the room, so a message for another doc or with the id of another client is refused.\n * A presence message has no client id: the Lattice server uses the client of the connection.\n */\nfunction belongsTo(message: JsonValue | undefined, room: string): boolean {\n if (typeof message !== 'object' || message === null || Array.isArray(message)) return false\n const { docId, clientId } = message\n const parsed = parseLatticeRoom(room)\n if (!parsed || docId !== parsed.docId) return false\n return clientId === undefined || clientId === parsed.clientId\n}\n\n/**\n * The server side of the transport bridge. Each client room has one Lattice connection, also\n * after a reconnect, so the session goes on with its seq. The Lattice server parses each\n * message (its trust boundary). The host `authorize` hook must let a user join and write only\n * the `lattice:` rooms of the docs that the user can open.\n */\nexport function latticeServerBridge<W extends WriteLike>(\n options: LatticeServerBridgeOptions<W>,\n): LatticeServerBridge<W> {\n const { docServer, server, next = () => ({ ok: true }) } = options\n // Each client room has one Lattice connection, and the last session that used it.\n const conns = new Map<string, { conn: ReturnType<DocServerLike['connect']>; session: string }>()\n const refuse = (status: number, title: string): WriteResultLike => ({\n ok: false,\n status,\n errors: [{ status: String(status), title }],\n })\n // A function, not a method: the server calls the hooks with no receiver.\n const close = (room: string) => {\n conns.get(room)?.conn.close()\n conns.delete(room)\n }\n return {\n async handleWrite(write) {\n const { op, room } = write\n const data = op.op === 'upsert' ? op.document.data : null\n const isMessage = data && !Array.isArray(data) && data.type === MESSAGE_TYPE\n if (!isMessage) return next(write)\n if (!room.startsWith(ROOM_PREFIX))\n return refuse(403, 'A Lattice message goes only to a lattice: room.')\n const message = data.attributes?.['message']\n if (!belongsTo(message, room))\n return refuse(403, 'A Lattice message must have the doc and the client of its room.')\n let entry = conns.get(room)\n if (!entry) {\n const conn = docServer.connect(message => void server.publish(room, envelope(message)))\n conns.set(room, (entry = { conn, session: write.session }))\n }\n entry.session = write.session\n await entry.conn.receive(message)\n return { ok: true }\n },\n onSessionEnd({ id, rooms }) {\n for (const room of rooms) if (conns.get(room)?.session === id) close(room)\n },\n close,\n }\n}\n"]}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { OptimisticLedger } from '@dovetail-ts/core';
|
|
2
|
+
import type { JsonApiDocument, ResourceIdentifier } from '@dovetail-ts/protocol';
|
|
3
|
+
import type { AnyCodec, Tracked } from '@millwork-ts/core';
|
|
4
|
+
/** The `codec` option of `storeSink` of `@dovetail-ts/warp-drive`. */
|
|
5
|
+
export type DocumentCodec = (document: JsonApiDocument) => JsonApiDocument;
|
|
6
|
+
/** A Millwork codec, or a codec with its options: `[money, { wire: 'decimal' }]`. */
|
|
7
|
+
export type FieldCodec = AnyCodec | readonly [AnyCodec, unknown];
|
|
8
|
+
/** The codecs of the attributes, by record type and attribute name. */
|
|
9
|
+
export type CodecMap = Readonly<Record<string, Readonly<Record<string, FieldCodec>>>>;
|
|
10
|
+
/**
|
|
11
|
+
* A `DocumentCodec` that runs `codec.serialize(codec.hydrate(raw))` on each listed attribute of
|
|
12
|
+
* each resource (data and included). The store then gets one wire form. A value that is not
|
|
13
|
+
* valid becomes null, and Millwork reports it to `onInvalid`. The result does not change when
|
|
14
|
+
* the codec runs on it again, so the ledger can push a rollback through it.
|
|
15
|
+
*/
|
|
16
|
+
export declare function millworkCodec(map: CodecMap): DocumentCodec;
|
|
17
|
+
/**
|
|
18
|
+
* Rolls back the Millwork shapes of each record of a write that the server rejects. The ledger
|
|
19
|
+
* puts the server state back in the store, but a shape keeps the local edit of the user over
|
|
20
|
+
* it. `shapesOf(ref)` gives the shapes (or shape arrays) of a record that the app shows, for
|
|
21
|
+
* example the shape fields of a `checkout` copy. Give it `sync.ledger`. Returns a function that
|
|
22
|
+
* stops it.
|
|
23
|
+
*/
|
|
24
|
+
export declare function rollbackShapes(ledger: Pick<OptimisticLedger, 'errors' | 'onChange'>, shapesOf: (ref: ResourceIdentifier) => Iterable<Pick<Tracked, 'rollback'>>): () => void;
|
package/dist/millwork.js
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
// src/millwork.ts
|
|
2
|
+
function millworkCodec(map) {
|
|
3
|
+
const resource = (r) => {
|
|
4
|
+
const fields = map[r.type];
|
|
5
|
+
if (!fields || !r.attributes) return r;
|
|
6
|
+
const attributes = { ...r.attributes };
|
|
7
|
+
for (const [name, spec] of Object.entries(fields)) {
|
|
8
|
+
if (!(name in attributes)) continue;
|
|
9
|
+
const [codec, options] = Array.isArray(spec) ? spec : [spec, void 0];
|
|
10
|
+
attributes[name] = codec.serialize(
|
|
11
|
+
codec.hydrate(attributes[name], options),
|
|
12
|
+
options
|
|
13
|
+
);
|
|
14
|
+
}
|
|
15
|
+
return { ...r, attributes };
|
|
16
|
+
};
|
|
17
|
+
return (document) => {
|
|
18
|
+
const data = document.data;
|
|
19
|
+
return {
|
|
20
|
+
...document,
|
|
21
|
+
data: Array.isArray(data) ? data.map(resource) : data ? resource(data) : data,
|
|
22
|
+
...document.included ? { included: document.included.map(resource) } : {}
|
|
23
|
+
};
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
function refsOf(op) {
|
|
27
|
+
if (op.op === "delete") return [op.ref];
|
|
28
|
+
const data = op.document.data;
|
|
29
|
+
return [...Array.isArray(data) ? data : data ? [data] : [], ...op.document.included ?? []];
|
|
30
|
+
}
|
|
31
|
+
function rollbackShapes(ledger, shapesOf) {
|
|
32
|
+
let seen = new Set(ledger.errors.map((error) => error.id));
|
|
33
|
+
return ledger.onChange(() => {
|
|
34
|
+
const errors = ledger.errors;
|
|
35
|
+
for (const error of errors) {
|
|
36
|
+
if (seen.has(error.id)) continue;
|
|
37
|
+
for (const ref of refsOf(error.op)) for (const shape of shapesOf(ref)) shape.rollback();
|
|
38
|
+
}
|
|
39
|
+
seen = new Set(errors.map((error) => error.id));
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export { millworkCodec, rollbackShapes };
|
|
44
|
+
//# sourceMappingURL=millwork.js.map
|
|
45
|
+
//# sourceMappingURL=millwork.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/millwork.ts"],"names":[],"mappings":";AA8BO,SAAS,cAAc,GAAA,EAA8B;AAC1D,EAAA,MAAM,QAAA,GAAW,CAAC,CAAA,KAA0B;AAC1C,IAAA,MAAM,MAAA,GAAS,GAAA,CAAI,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,EAAA,MAAM,IAAA,GAAO,GAAG,QAAA,CAAS,IAAA;AACzB,EAAA,OAAO,CAAC,GAAI,KAAA,CAAM,QAAQ,IAAI,CAAA,GAAI,OAAO,IAAA,GAAO,CAAC,IAAI,CAAA,GAAI,EAAC,EAAI,GAAI,GAAG,QAAA,CAAS,QAAA,IAAY,EAAG,CAAA;AAC/F;AASO,SAAS,cAAA,CACd,QACA,QAAA,EACY;AAEZ,EAAA,IAAI,IAAA,GAAO,IAAI,GAAA,CAAI,MAAA,CAAO,OAAO,GAAA,CAAI,CAAA,KAAA,KAAS,KAAA,CAAM,EAAE,CAAC,CAAA;AACvD,EAAA,OAAO,MAAA,CAAO,SAAS,MAAM;AAC3B,IAAA,MAAM,SAAS,MAAA,CAAO,MAAA;AACtB,IAAA,KAAA,MAAW,SAAS,MAAA,EAAQ;AAC1B,MAAA,IAAI,IAAA,CAAK,GAAA,CAAI,KAAA,CAAM,EAAE,CAAA,EAAG;AACxB,MAAA,KAAA,MAAW,GAAA,IAAO,MAAA,CAAO,KAAA,CAAM,EAAE,CAAA,EAAG,KAAA,MAAW,KAAA,IAAS,QAAA,CAAS,GAAG,CAAA,EAAG,KAAA,CAAM,QAAA,EAAS;AAAA,IACxF;AACA,IAAA,IAAA,GAAO,IAAI,GAAA,CAAI,MAAA,CAAO,IAAI,CAAA,KAAA,KAAS,KAAA,CAAM,EAAE,CAAC,CAAA;AAAA,EAC9C,CAAC,CAAA;AACH","file":"millwork.js","sourcesContent":["// The Millwork binding (ADR 0004). `millworkCodec` is a `DocumentCodec` for\n// `storeSink(store, { codec })`: it runs Millwork codecs on the attributes of each pushed\n// document, so the store gets valid raw values in one wire form. `rollbackShapes` rolls back\n// the Millwork shapes of a record when the server rejects a write to it.\nimport type { OptimisticLedger } from '@dovetail-ts/core'\nimport type {\n JsonApiDocument,\n JsonObject,\n JsonValue,\n Resource,\n ResourceIdentifier,\n StoreOp,\n} from '@dovetail-ts/protocol'\nimport type { AnyCodec, Tracked } from '@millwork-ts/core'\n\n/** The `codec` option of `storeSink` of `@dovetail-ts/warp-drive`. */\nexport type DocumentCodec = (document: JsonApiDocument) => JsonApiDocument\n\n/** A Millwork codec, or a codec with its options: `[money, { wire: 'decimal' }]`. */\nexport type FieldCodec = AnyCodec | readonly [AnyCodec, unknown]\n\n/** The codecs of the attributes, by record type and attribute name. */\nexport type CodecMap = Readonly<Record<string, Readonly<Record<string, FieldCodec>>>>\n\n/**\n * A `DocumentCodec` that runs `codec.serialize(codec.hydrate(raw))` on each listed attribute of\n * each resource (data and included). The store then gets one wire form. A value that is not\n * valid becomes null, and Millwork reports it to `onInvalid`. The result does not change when\n * the codec runs on it again, so the ledger can push a rollback through it.\n */\nexport function millworkCodec(map: CodecMap): DocumentCodec {\n const resource = (r: Resource): Resource => {\n const fields = map[r.type]\n if (!fields || !r.attributes) return r\n const attributes: JsonObject = { ...r.attributes }\n for (const [name, spec] of Object.entries(fields)) {\n if (!(name in attributes)) continue\n const [codec, options] = Array.isArray(spec) ? spec : [spec as AnyCodec, undefined]\n // A codec gives JSON from `serialize`: that is its wire form.\n attributes[name] = codec.serialize(\n codec.hydrate(attributes[name], options),\n options,\n ) as JsonValue\n }\n return { ...r, attributes }\n }\n return document => {\n const data = document.data\n return {\n ...document,\n data: Array.isArray(data) ? data.map(resource) : data ? resource(data) : data,\n ...(document.included ? { included: document.included.map(resource) } : {}),\n }\n }\n}\n\n/** The records that an op changes. */\nfunction refsOf(op: StoreOp): ResourceIdentifier[] {\n if (op.op === 'delete') return [op.ref]\n const data = op.document.data\n return [...(Array.isArray(data) ? data : data ? [data] : []), ...(op.document.included ?? [])]\n}\n\n/**\n * Rolls back the Millwork shapes of each record of a write that the server rejects. The ledger\n * puts the server state back in the store, but a shape keeps the local edit of the user over\n * it. `shapesOf(ref)` gives the shapes (or shape arrays) of a record that the app shows, for\n * example the shape fields of a `checkout` copy. Give it `sync.ledger`. Returns a function that\n * stops it.\n */\nexport function rollbackShapes(\n ledger: Pick<OptimisticLedger, 'errors' | 'onChange'>,\n shapesOf: (ref: ResourceIdentifier) => Iterable<Pick<Tracked, 'rollback'>>,\n): () => void {\n // The ids of the errors now. A retry dismisses an error and can get one with the same id.\n let seen = new Set(ledger.errors.map(error => error.id))\n return ledger.onChange(() => {\n const errors = ledger.errors\n for (const error of errors) {\n if (seen.has(error.id)) continue\n for (const ref of refsOf(error.op)) for (const shape of shapesOf(ref)) shape.rollback()\n }\n seen = new Set(errors.map(error => error.id))\n })\n}\n"]}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import type { Connection } from '@dovetail-ts/core';
|
|
2
|
+
/** One transition of the connection statechart. */
|
|
3
|
+
export interface ConnectionTransition {
|
|
4
|
+
/** The event that caused the transition, for example `dropped` or `retry`. */
|
|
5
|
+
event: string;
|
|
6
|
+
from: string;
|
|
7
|
+
to: string;
|
|
8
|
+
/** The time of the transition, from the `now` option. */
|
|
9
|
+
at: number;
|
|
10
|
+
}
|
|
11
|
+
/** The state of a connection, as plain data. */
|
|
12
|
+
export interface ConnectionSnapshot {
|
|
13
|
+
state: string;
|
|
14
|
+
/** The number of failed attempts since the last open. */
|
|
15
|
+
attempt: number;
|
|
16
|
+
isOnline: boolean;
|
|
17
|
+
session: string | undefined;
|
|
18
|
+
version: number | undefined;
|
|
19
|
+
user: {
|
|
20
|
+
id: string;
|
|
21
|
+
} | undefined;
|
|
22
|
+
error: {
|
|
23
|
+
code: string;
|
|
24
|
+
message: string;
|
|
25
|
+
} | undefined;
|
|
26
|
+
/** The rooms that the connection joins, also after a reconnect. */
|
|
27
|
+
rooms: string[];
|
|
28
|
+
}
|
|
29
|
+
/** Reads the state of `connection` as plain data. */
|
|
30
|
+
export declare function readConnection(connection: Connection): ConnectionSnapshot;
|
|
31
|
+
export interface TransitionLogOptions {
|
|
32
|
+
/** The number of entries to keep. The oldest entry goes first. Default 100. */
|
|
33
|
+
limit?: number;
|
|
34
|
+
/** The clock of the entries. Default `Date.now`. */
|
|
35
|
+
now?: () => number;
|
|
36
|
+
}
|
|
37
|
+
export interface TransitionLog {
|
|
38
|
+
/** The transitions, oldest first. Each change makes a new array. */
|
|
39
|
+
readonly entries: readonly ConnectionTransition[];
|
|
40
|
+
/** Calls `listener` after each new entry. Returns a function that stops it. */
|
|
41
|
+
subscribe(listener: () => void): () => void;
|
|
42
|
+
/** Stops the log. The entries stay. */
|
|
43
|
+
stop(): void;
|
|
44
|
+
}
|
|
45
|
+
/** Records each transition of the statechart of `connection` from now on. */
|
|
46
|
+
export declare function transitionLog(connection: Connection, options?: TransitionLogOptions): TransitionLog;
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
// src/switchyard.ts
|
|
2
|
+
function readConnection(connection) {
|
|
3
|
+
return {
|
|
4
|
+
state: connection.state.value,
|
|
5
|
+
attempt: connection.attempt,
|
|
6
|
+
isOnline: connection.isOnline,
|
|
7
|
+
session: connection.session,
|
|
8
|
+
version: connection.version,
|
|
9
|
+
user: connection.user,
|
|
10
|
+
error: connection.error,
|
|
11
|
+
rooms: connection.rooms
|
|
12
|
+
};
|
|
13
|
+
}
|
|
14
|
+
function transitionLog(connection, options = {}) {
|
|
15
|
+
const { limit = 100, now = Date.now } = options;
|
|
16
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
17
|
+
let entries = [];
|
|
18
|
+
let state = connection.state.value;
|
|
19
|
+
const stop = connection.machine.inspect((event) => {
|
|
20
|
+
if (event.type !== "@xstate.microstep") return;
|
|
21
|
+
const added = [];
|
|
22
|
+
for (const { targets } of event.transitions) {
|
|
23
|
+
for (const to of targets) {
|
|
24
|
+
added.push({ event: event.event.type, from: state, to, at: now() });
|
|
25
|
+
state = to;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
if (added.length === 0) return;
|
|
29
|
+
entries = [...entries, ...added].slice(-limit);
|
|
30
|
+
for (const listener of [...listeners]) listener();
|
|
31
|
+
});
|
|
32
|
+
return {
|
|
33
|
+
get entries() {
|
|
34
|
+
return entries;
|
|
35
|
+
},
|
|
36
|
+
subscribe(listener) {
|
|
37
|
+
listeners.add(listener);
|
|
38
|
+
return () => listeners.delete(listener);
|
|
39
|
+
},
|
|
40
|
+
stop
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export { readConnection, transitionLog };
|
|
45
|
+
//# sourceMappingURL=switchyard.js.map
|
|
46
|
+
//# sourceMappingURL=switchyard.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/switchyard.ts"],"names":[],"mappings":";AA+BO,SAAS,eAAe,UAAA,EAA4C;AACzE,EAAA,OAAO;AAAA,IACL,KAAA,EAAO,WAAW,KAAA,CAAM,KAAA;AAAA,IACxB,SAAS,UAAA,CAAW,OAAA;AAAA,IACpB,UAAU,UAAA,CAAW,QAAA;AAAA,IACrB,SAAS,UAAA,CAAW,OAAA;AAAA,IACpB,SAAS,UAAA,CAAW,OAAA;AAAA,IACpB,MAAM,UAAA,CAAW,IAAA;AAAA,IACjB,OAAO,UAAA,CAAW,KAAA;AAAA,IAClB,OAAO,UAAA,CAAW;AAAA,GACpB;AACF;AAmBO,SAAS,aAAA,CACd,UAAA,EACA,OAAA,GAAgC,EAAC,EAClB;AACf,EAAA,MAAM,EAAE,KAAA,GAAQ,GAAA,EAAK,GAAA,GAAM,IAAA,CAAK,KAAI,GAAI,OAAA;AACxC,EAAA,MAAM,SAAA,uBAAgB,GAAA,EAAgB;AACtC,EAAA,IAAI,UAA2C,EAAC;AAEhD,EAAA,IAAI,KAAA,GAAQ,WAAW,KAAA,CAAM,KAAA;AAC7B,EAAA,MAAM,IAAA,GAAO,UAAA,CAAW,OAAA,CAAQ,OAAA,CAAQ,CAAA,KAAA,KAAS;AAC/C,IAAA,IAAI,KAAA,CAAM,SAAS,mBAAA,EAAqB;AACxC,IAAA,MAAM,QAAgC,EAAC;AACvC,IAAA,KAAA,MAAW,EAAE,OAAA,EAAQ,IAAK,KAAA,CAAM,WAAA,EAAa;AAC3C,MAAA,KAAA,MAAW,MAAM,OAAA,EAAS;AACxB,QAAA,KAAA,CAAM,IAAA,CAAK,EAAE,KAAA,EAAO,KAAA,CAAM,KAAA,CAAM,IAAA,EAAM,IAAA,EAAM,KAAA,EAAO,EAAA,EAAI,EAAA,EAAI,GAAA,EAAI,EAAG,CAAA;AAClE,QAAA,KAAA,GAAQ,EAAA;AAAA,MACV;AAAA,IACF;AACA,IAAA,IAAI,KAAA,CAAM,WAAW,CAAA,EAAG;AACxB,IAAA,OAAA,GAAU,CAAC,GAAG,OAAA,EAAS,GAAG,KAAK,CAAA,CAAE,KAAA,CAAM,CAAC,KAAK,CAAA;AAC7C,IAAA,KAAA,MAAW,QAAA,IAAY,CAAC,GAAG,SAAS,GAAG,QAAA,EAAS;AAAA,EAClD,CAAC,CAAA;AACD,EAAA,OAAO;AAAA,IACL,IAAI,OAAA,GAAU;AACZ,MAAA,OAAO,OAAA;AAAA,IACT,CAAA;AAAA,IACA,UAAU,QAAA,EAAU;AAClB,MAAA,SAAA,CAAU,IAAI,QAAQ,CAAA;AACtB,MAAA,OAAO,MAAM,SAAA,CAAU,MAAA,CAAO,QAAQ,CAAA;AAAA,IACxC,CAAA;AAAA,IACA;AAAA,GACF;AACF","file":"switchyard.js","sourcesContent":["// The Switchyard binding: the statechart of a Dovetail connection (`ConnectionMachine`) for the\n// Switchyard tools. `connection.machine` is a Switchyard `Machine`, so `<SwitchyardDebug>`,\n// `mountDiagram` and `connectInspector` take it as it is. This entry adds a log of the\n// transitions and a plain read of the connection, for an inspector panel.\nimport type { Connection } from '@dovetail-ts/core'\n\n/** One transition of the connection statechart. */\nexport interface ConnectionTransition {\n /** The event that caused the transition, for example `dropped` or `retry`. */\n event: string\n from: string\n to: string\n /** The time of the transition, from the `now` option. */\n at: number\n}\n\n/** The state of a connection, as plain data. */\nexport interface ConnectionSnapshot {\n state: string\n /** The number of failed attempts since the last open. */\n attempt: number\n isOnline: boolean\n session: string | undefined\n version: number | undefined\n user: { id: string } | undefined\n error: { code: string; message: string } | undefined\n /** The rooms that the connection joins, also after a reconnect. */\n rooms: string[]\n}\n\n/** Reads the state of `connection` as plain data. */\nexport function readConnection(connection: Connection): ConnectionSnapshot {\n return {\n state: connection.state.value,\n attempt: connection.attempt,\n isOnline: connection.isOnline,\n session: connection.session,\n version: connection.version,\n user: connection.user,\n error: connection.error,\n rooms: connection.rooms,\n }\n}\n\nexport interface TransitionLogOptions {\n /** The number of entries to keep. The oldest entry goes first. Default 100. */\n limit?: number\n /** The clock of the entries. Default `Date.now`. */\n now?: () => number\n}\n\nexport interface TransitionLog {\n /** The transitions, oldest first. Each change makes a new array. */\n readonly entries: readonly ConnectionTransition[]\n /** Calls `listener` after each new entry. Returns a function that stops it. */\n subscribe(listener: () => void): () => void\n /** Stops the log. The entries stay. */\n stop(): void\n}\n\n/** Records each transition of the statechart of `connection` from now on. */\nexport function transitionLog(\n connection: Connection,\n options: TransitionLogOptions = {},\n): TransitionLog {\n const { limit = 100, now = Date.now } = options\n const listeners = new Set<() => void>()\n let entries: readonly ConnectionTransition[] = []\n // A transition of the root (for example `close`) has no source, so the log keeps the state.\n let state = connection.state.value\n const stop = connection.machine.inspect(event => {\n if (event.type !== '@xstate.microstep') return\n const added: ConnectionTransition[] = []\n for (const { targets } of event.transitions) {\n for (const to of targets) {\n added.push({ event: event.event.type, from: state, to, at: now() })\n state = to\n }\n }\n if (added.length === 0) return\n entries = [...entries, ...added].slice(-limit)\n for (const listener of [...listeners]) listener()\n })\n return {\n get entries() {\n return entries\n },\n subscribe(listener) {\n listeners.add(listener)\n return () => listeners.delete(listener)\n },\n stop,\n }\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,91 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dovetail-ts/integrations",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "1.0.1",
|
|
4
|
+
"description": "Switchyard, Millwork, Benchdog and Lattice bindings for Dovetail (subpath exports).",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"author": "Joe Gaudet <joe@joegaudet.com>",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/joegaudet/dovetail.git",
|
|
10
|
+
"directory": "packages/integrations"
|
|
11
|
+
},
|
|
12
|
+
"homepage": "https://joegaudet.com/dovetail/",
|
|
13
|
+
"bugs": "https://github.com/joegaudet/dovetail/issues",
|
|
14
|
+
"keywords": [
|
|
15
|
+
"realtime",
|
|
16
|
+
"offline",
|
|
17
|
+
"sync",
|
|
18
|
+
"crdt"
|
|
19
|
+
],
|
|
20
|
+
"type": "module",
|
|
21
|
+
"types": "./dist/index.d.ts",
|
|
22
|
+
"exports": {
|
|
23
|
+
".": {
|
|
24
|
+
"types": "./dist/index.d.ts",
|
|
25
|
+
"default": "./dist/index.js"
|
|
26
|
+
},
|
|
27
|
+
"./switchyard": {
|
|
28
|
+
"types": "./dist/switchyard.d.ts",
|
|
29
|
+
"default": "./dist/switchyard.js"
|
|
30
|
+
},
|
|
31
|
+
"./millwork": {
|
|
32
|
+
"types": "./dist/millwork.d.ts",
|
|
33
|
+
"default": "./dist/millwork.js"
|
|
34
|
+
},
|
|
35
|
+
"./benchdog": {
|
|
36
|
+
"types": "./dist/benchdog.d.ts",
|
|
37
|
+
"default": "./dist/benchdog.js"
|
|
38
|
+
},
|
|
39
|
+
"./lattice": {
|
|
40
|
+
"types": "./dist/lattice.d.ts",
|
|
41
|
+
"default": "./dist/lattice.js"
|
|
42
|
+
},
|
|
43
|
+
"./package.json": "./package.json"
|
|
44
|
+
},
|
|
45
|
+
"files": [
|
|
46
|
+
"dist",
|
|
47
|
+
"CHANGELOG.md",
|
|
48
|
+
"README.md",
|
|
49
|
+
"LICENSE"
|
|
50
|
+
],
|
|
51
|
+
"sideEffects": false,
|
|
52
|
+
"dependencies": {
|
|
53
|
+
"@dovetail-ts/core": "1.0.1",
|
|
54
|
+
"@dovetail-ts/protocol": "1.0.1"
|
|
55
|
+
},
|
|
56
|
+
"peerDependencies": {
|
|
57
|
+
"@benchdog-ts/client": "^0.4.0",
|
|
58
|
+
"@millwork-ts/core": "^1.0.0",
|
|
59
|
+
"@switchyard-ts/core": ">=0.5.0"
|
|
60
|
+
},
|
|
61
|
+
"peerDependenciesMeta": {
|
|
62
|
+
"@benchdog-ts/client": {
|
|
63
|
+
"optional": true
|
|
64
|
+
},
|
|
65
|
+
"@millwork-ts/core": {
|
|
66
|
+
"optional": true
|
|
67
|
+
},
|
|
68
|
+
"@switchyard-ts/core": {
|
|
69
|
+
"optional": true
|
|
70
|
+
}
|
|
71
|
+
},
|
|
72
|
+
"devDependencies": {
|
|
73
|
+
"@benchdog-ts/client": "^0.4.0",
|
|
74
|
+
"@benchdog-ts/core": "^0.4.0",
|
|
75
|
+
"@millwork-ts/core": "^1.0.0",
|
|
76
|
+
"@millwork-ts/warp-drive": "^1.0.0",
|
|
77
|
+
"@switchyard-ts/core": "0.5.0",
|
|
78
|
+
"@warp-drive/core": "^5.9.1",
|
|
79
|
+
"@warp-drive/json-api": "^5.9.1",
|
|
80
|
+
"tsup": "^8.5.1"
|
|
81
|
+
},
|
|
82
|
+
"publishConfig": {
|
|
83
|
+
"access": "public"
|
|
84
|
+
},
|
|
85
|
+
"engines": {
|
|
86
|
+
"node": ">=22.12.0"
|
|
87
|
+
},
|
|
88
|
+
"scripts": {
|
|
89
|
+
"build": "tsc --build --force && tsup"
|
|
90
|
+
}
|
|
6
91
|
}
|