plsremind 0.0.0-stage → 0.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +277 -2
- package/dist/cache.d.ts +54 -0
- package/dist/cache.js +287 -0
- package/dist/client.d.ts +39 -0
- package/dist/client.js +199 -0
- package/dist/convert.d.ts +8 -0
- package/dist/convert.js +123 -0
- package/dist/duration.d.ts +4 -0
- package/dist/duration.js +35 -0
- package/dist/emitter.d.ts +10 -0
- package/dist/emitter.js +39 -0
- package/dist/errors.d.ts +21 -0
- package/dist/errors.js +31 -0
- package/dist/events.d.ts +152 -0
- package/dist/events.js +21 -0
- package/dist/gateway.d.ts +34 -0
- package/dist/gateway.js +283 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.js +4 -0
- package/dist/optimistic/index.d.ts +51 -0
- package/dist/optimistic/index.js +540 -0
- package/dist/rest.d.ts +212 -0
- package/dist/rest.js +394 -0
- package/dist/types.d.ts +307 -0
- package/dist/types.js +1 -0
- package/package.json +58 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026-present rayakame
|
|
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,278 @@
|
|
|
1
|
-
#
|
|
1
|
+
# plsremind for TypeScript and JavaScript
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A client for the [plsremind](https://github.com/rayakame/plsremind) hub. It connects to the gateway, keeps the
|
|
4
|
+
state it is sent in memory, reports every change as a typed event and offers each call of
|
|
5
|
+
the REST API as a method.
|
|
6
|
+
|
|
7
|
+
It runs in browsers and in Node 22 or newer, has no dependencies and works with plsremind
|
|
8
|
+
0.1 or newer.
|
|
9
|
+
|
|
10
|
+
```sh
|
|
11
|
+
npm install plsremind
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
```ts
|
|
15
|
+
import { Client } from "plsremind";
|
|
16
|
+
|
|
17
|
+
const client = new Client({
|
|
18
|
+
url: "https://todo.example.com",
|
|
19
|
+
token: process.env.PLSREMIND_TOKEN,
|
|
20
|
+
intents: ["items", "deliveries"],
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
client.on("item.created", (event) => {
|
|
24
|
+
console.log("new item:", event.data.title);
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
client.on("delivery.created", async (event) => {
|
|
28
|
+
await remind(event.data);
|
|
29
|
+
await client.rest.acknowledgeDelivery(event.data.id, { status: "delivered" });
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
await client.connect();
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
`connect()` returns once the state of every user the session covers is in the cache. From
|
|
36
|
+
then on the client reconnects and resumes on its own. If the very first attempt fails, for
|
|
37
|
+
example because the hub is down or the address is wrong, `connect()` rejects with a
|
|
38
|
+
`GatewayError` and the client does not try again; call `connect()` again when you want to.
|
|
39
|
+
|
|
40
|
+
## The rules
|
|
41
|
+
|
|
42
|
+
- **Nothing is confirmed for you.** A reminder counts as delivered only when you call
|
|
43
|
+
`client.rest.acknowledgeDelivery`. Until then the hub sends it again after every
|
|
44
|
+
reconnect, with a growing `attempt`, and the SDK hands you every one of them. If you
|
|
45
|
+
must not remind twice, remember the `id` yourself, as the
|
|
46
|
+
[example adapter](https://github.com/rayakame/plsremind/blob/main/sdk/ts/examples/remind.ts) does.
|
|
47
|
+
- **Objects are data.** What you receive has no methods and must not be changed. To change
|
|
48
|
+
something, call `client.rest`. The cache replaces objects instead of editing them, so
|
|
49
|
+
`before === after` tells you whether something changed.
|
|
50
|
+
- **Every HTTP call goes through `client.rest`**, and its answers do not touch the cache.
|
|
51
|
+
The cache changes only through the gateway events that follow.
|
|
52
|
+
|
|
53
|
+
## Names and types
|
|
54
|
+
|
|
55
|
+
The [gateway](https://github.com/rayakame/plsremind/blob/main/docs/gateway.md) and the [API reference](https://github.com/rayakame/plsremind/blob/main/docs/api/openapi.yaml)
|
|
56
|
+
describe what travels over the wire. The SDK keeps the names of events, operations and
|
|
57
|
+
schemas, and turns the rest into what is usual in TypeScript:
|
|
58
|
+
|
|
59
|
+
| In the API | In the SDK |
|
|
60
|
+
| ----------------------------------------- | ---------------------------------------------------------------------- |
|
|
61
|
+
| `snake_case` fields (`due_at`, `list_id`) | `camelCase` (`dueAt`, `listId`) |
|
|
62
|
+
| a moment as RFC 3339 text | `Date` |
|
|
63
|
+
| a duration as text (`1d12h`) | a number of milliseconds; `parseDuration` and `formatDuration` convert |
|
|
64
|
+
| a whole day (`due_date`) | text, `"2026-11-13"` |
|
|
65
|
+
| a time of day in quiet hours | text, `"22:00"` |
|
|
66
|
+
| fixed values (`status: "done"`) | the same text, narrowed by the type |
|
|
67
|
+
| `preferences` on the profile | passed through untouched |
|
|
68
|
+
|
|
69
|
+
The same holds in the other direction: methods of `client.rest` take `camelCase`, `Date`
|
|
70
|
+
and milliseconds. Field names in `ApiError.fields` are the SDK's.
|
|
71
|
+
|
|
72
|
+
## Events
|
|
73
|
+
|
|
74
|
+
`client.on(name, handler)` returns a function that unsubscribes. The name decides the type
|
|
75
|
+
of the event; every event type can also be imported by name, for example
|
|
76
|
+
`ItemCreatedEvent`.
|
|
77
|
+
|
|
78
|
+
Events of the hub keep their gateway names: `item.created`, `item.updated`,
|
|
79
|
+
`item.deleted`, `list.*`, `subitem.*`, `reminder.*`, `plan.updated`, `user.updated`,
|
|
80
|
+
`connection.updated`, `delivery.created`, `delivery.closed`, `delivery.test`, `user.sync`
|
|
81
|
+
and `user.gone`. `delivery.test` asks you to show the user that you reach them; answer it
|
|
82
|
+
with `client.rest.reportTest`. Names a later hub adds reach no handler and are dropped.
|
|
83
|
+
A change event carries:
|
|
84
|
+
|
|
85
|
+
| Field | Meaning |
|
|
86
|
+
| -------- | ------------------------------------------------------------------- |
|
|
87
|
+
| `userId` | the user it is about |
|
|
88
|
+
| `data` | the whole object after the change |
|
|
89
|
+
| `old` | the object as the cache held it before, if it held one |
|
|
90
|
+
| `actor` | who made the change; compare `actor?.id` with `client.principal.id` |
|
|
91
|
+
| `nonce` | the `nonce` option of the REST call that made the change, or `null` |
|
|
92
|
+
|
|
93
|
+
`actor` is `null` for what the hub does by itself, such as removing a manual reminder whose
|
|
94
|
+
time has passed.
|
|
95
|
+
|
|
96
|
+
`user.gone` also comes for a user the cache held whom a new session no longer names, for
|
|
97
|
+
example one who switched a connection off while it could not resume.
|
|
98
|
+
|
|
99
|
+
The cache is already up to date when a handler runs. Handlers run in the order of the
|
|
100
|
+
events; a handler that returns a promise is not waited for.
|
|
101
|
+
|
|
102
|
+
The client adds events of its own:
|
|
103
|
+
|
|
104
|
+
| Event | When |
|
|
105
|
+
| -------------- | ----------------------------------------------------------------------------------------- |
|
|
106
|
+
| `ready` | after every new login, once the state is complete |
|
|
107
|
+
| `user.ready` | one user's state is complete |
|
|
108
|
+
| `resumed` | a dropped connection was picked up again and missed nothing |
|
|
109
|
+
| `disconnected` | the connection is gone and is being opened again; once per outage |
|
|
110
|
+
| `closed` | the client gave up: the first connect failed, or the hub refuses the token or the intents |
|
|
111
|
+
| `error` | a handler threw or its promise rejected |
|
|
112
|
+
|
|
113
|
+
`client.status` is `idle`, `connecting`, `connected`, `reconnecting` or `closed`.
|
|
114
|
+
`client.close()` ends the session and every retry; the cache stays readable and
|
|
115
|
+
`connect()` starts over.
|
|
116
|
+
|
|
117
|
+
A failing handler never ends the connection. Without an `error` handler the failure is
|
|
118
|
+
written to the console.
|
|
119
|
+
|
|
120
|
+
## The cache
|
|
121
|
+
|
|
122
|
+
```ts
|
|
123
|
+
const me = client.cache.user(); // the user of a personal token or a login
|
|
124
|
+
if (!me) throw new Error("not connected yet");
|
|
125
|
+
me.profile;
|
|
126
|
+
me.lists();
|
|
127
|
+
me.items(); // every open item, with subitems and manual reminders
|
|
128
|
+
me.item(id);
|
|
129
|
+
me.history(); // completed items, newest first; needs the "history" intent
|
|
130
|
+
me.plans();
|
|
131
|
+
|
|
132
|
+
const off = client.cache.subscribe(({ userId, kinds }) => {
|
|
133
|
+
if (kinds.includes("items")) render(client.cache.user(userId)?.items());
|
|
134
|
+
});
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
- What the cache holds follows from the intents: `users` gives the profile, `lists`,
|
|
138
|
+
`items` and `plans` their parts, `history` the completed items.
|
|
139
|
+
- Reading is synchronous. An array stays the very same array until something of its kind
|
|
140
|
+
changes for that user, which makes it safe to use as a snapshot in UI frameworks.
|
|
141
|
+
- `user()` hands out one object per user for as long as the user is in the cache, so it
|
|
142
|
+
is not a snapshot itself: take the arrays or `profile`. After `user.gone`, ask for the
|
|
143
|
+
user again instead of keeping the old object.
|
|
144
|
+
- The listener of `subscribe` gets `{ userId, kinds, cause }`. `cause` names the event
|
|
145
|
+
behind the change (`name`, `nonce` and the object's `id`), or is undefined for a sync.
|
|
146
|
+
- The cache does not filter or sort beyond that. Build views like "overdue" on top.
|
|
147
|
+
- `history()` starts with the 1000 most recently completed items and grows with every
|
|
148
|
+
item completed while connected. `historyCursor` continues it over REST:
|
|
149
|
+
|
|
150
|
+
```ts
|
|
151
|
+
if (me.historyCursor !== null) {
|
|
152
|
+
const older = await client.rest.listItems({
|
|
153
|
+
status: "done",
|
|
154
|
+
sort: "completed",
|
|
155
|
+
order: "desc",
|
|
156
|
+
cursor: me.historyCursor,
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
`null` means there is nothing older. Pages loaded that way are yours to keep; they do
|
|
162
|
+
not enter the cache.
|
|
163
|
+
|
|
164
|
+
## Connections
|
|
165
|
+
|
|
166
|
+
A connection token covers many users. Ask the cache for a user by id and tell every REST
|
|
167
|
+
call whom it is for:
|
|
168
|
+
|
|
169
|
+
```ts
|
|
170
|
+
const bot = new Client({ url, token: "plsr_con_...", intents: ["users", "items"] });
|
|
171
|
+
await bot.connect();
|
|
172
|
+
|
|
173
|
+
for (const user of bot.cache.users()) {
|
|
174
|
+
console.log(user.profile?.displayName, user.items().length);
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
const { id } = await bot.rest.lookupUser(discordUserId);
|
|
178
|
+
await bot.rest.createItem({ title: "Hand in the report" }, { user: id });
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
Leaving `user` out with a connection token is refused before the hub is asked.
|
|
182
|
+
|
|
183
|
+
## REST without the gateway
|
|
184
|
+
|
|
185
|
+
`RestClient` works on its own. A script that runs every few minutes needs nothing else:
|
|
186
|
+
|
|
187
|
+
```ts
|
|
188
|
+
import { RestClient } from "plsremind";
|
|
189
|
+
|
|
190
|
+
const rest = new RestClient({ url, token });
|
|
191
|
+
for (const delivery of await rest.listDeliveries()) {
|
|
192
|
+
await remind(delivery);
|
|
193
|
+
await rest.acknowledgeDelivery(delivery.id, { status: "delivered" });
|
|
194
|
+
}
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
- Every operation of the API reference is a method of the same name: `createItem`,
|
|
198
|
+
`updateItem`, `listReminderPlans` and so on. Ids from the path come first, then the
|
|
199
|
+
body, then options.
|
|
200
|
+
- Options: `user` (the id of the user to act for; the caller by default), `signal` to abort, and on writes
|
|
201
|
+
`nonce`, which comes back in every event the call causes.
|
|
202
|
+
- Listings that page return `{ data, nextCursor }`. `rest.pages` walks them:
|
|
203
|
+
|
|
204
|
+
```ts
|
|
205
|
+
for await (const page of rest.pages((cursor) => rest.listItems({ status: "done", cursor }))) {
|
|
206
|
+
// ...
|
|
207
|
+
}
|
|
208
|
+
```
|
|
209
|
+
|
|
210
|
+
- An error answer is thrown as `ApiError` with `status`, `code`, `message` and `fields`.
|
|
211
|
+
No answer at all is a `NetworkError`. A `409` with the code `delivery_closed` on
|
|
212
|
+
`acknowledgeDelivery` means the hub withdrew the reminder: treat it as done.
|
|
213
|
+
- A `429` is waited out and tried again, up to three times, when the hub asks for less
|
|
214
|
+
than 30 seconds. `retry: false` turns that off.
|
|
215
|
+
- In the dashboard, `auth: "session"` uses the login cookie instead of a token, and `url`
|
|
216
|
+
may be left out.
|
|
217
|
+
|
|
218
|
+
## Showing changes before the hub confirmed them
|
|
219
|
+
|
|
220
|
+
`plsremind/optimistic` is a separate entry point, so an adapter that only reminds does not
|
|
221
|
+
load it.
|
|
222
|
+
|
|
223
|
+
```ts
|
|
224
|
+
import { optimistic } from "plsremind/optimistic";
|
|
225
|
+
|
|
226
|
+
const view = optimistic(client);
|
|
227
|
+
|
|
228
|
+
await view.apply(
|
|
229
|
+
[{ kind: "item", id, update: (item) => ({ ...item, status: "done", completedAt: new Date() }) }],
|
|
230
|
+
(nonce) => client.rest.updateItem(id, { status: "done" }, { nonce }),
|
|
231
|
+
);
|
|
232
|
+
```
|
|
233
|
+
|
|
234
|
+
- `view` reads like `client.cache` and has the same `subscribe`. It shows the confirmed
|
|
235
|
+
state with the pending changes on top. `client.cache` itself always stays confirmed.
|
|
236
|
+
- A change creates, updates or removes an `item` or a `list`, or updates a `plan` or the
|
|
237
|
+
`profile`. For a new object, take an id from `view.tempId()`; `view.resolveId(tempId)`
|
|
238
|
+
gives the real one once it is known.
|
|
239
|
+
It answers once the real object has taken the draft's place. `view.isPending(tempId)`
|
|
240
|
+
says whether a draft still waits for the hub; it is false once the draft is real or was
|
|
241
|
+
taken back. Pending items that name a draft list in `listId` follow the list to its
|
|
242
|
+
real id.
|
|
243
|
+
- When one `apply` creates several objects of one kind, send each create with a nonce of
|
|
244
|
+
its own, which the call gets as a second argument: `(nonce, nonceFor) =>
|
|
245
|
+
client.rest.createItem(body, { nonce: nonceFor(tempId) })`. Without it the view matches
|
|
246
|
+
each new object to the draft it resembles most, which cannot tell identical drafts apart.
|
|
247
|
+
- Read the view from `view.subscribe`, not from a listener on `client.cache`: only the
|
|
248
|
+
view's own listeners are called after it has taken a change in.
|
|
249
|
+
- `apply` is for the caller's own user unless you pass `{ user }` as the third argument.
|
|
250
|
+
A user the cache does not hold shows nothing; the call still runs.
|
|
251
|
+
- If the call rejects, exactly its changes are taken back and the error is rethrown.
|
|
252
|
+
- If it succeeds, a change stays until the event with its nonce arrived, or the confirmed
|
|
253
|
+
state already shows it, and for five seconds at most. Pass the nonce on to REST as in
|
|
254
|
+
the example; without it the view cannot tell your event from someone else's.
|
|
255
|
+
|
|
256
|
+
## The example
|
|
257
|
+
|
|
258
|
+
[`examples/remind.ts`](https://github.com/rayakame/plsremind/blob/main/sdk/ts/examples/remind.ts) is a complete reminder adapter. It imports the
|
|
259
|
+
built package, which `npm install` builds, and Node runs the TypeScript file directly
|
|
260
|
+
from version 22.18 on:
|
|
261
|
+
|
|
262
|
+
```sh
|
|
263
|
+
PLSREMIND_URL=https://todo.example.com PLSREMIND_TOKEN=plsr_pat_... node examples/remind.ts
|
|
264
|
+
```
|
|
265
|
+
|
|
266
|
+
The token must be a personal token marked for reminders, or a connection token. With
|
|
267
|
+
`PLSREMIND_ONCE=1` the adapter exits after the first reminder.
|
|
268
|
+
|
|
269
|
+
## Development
|
|
270
|
+
|
|
271
|
+
```sh
|
|
272
|
+
npm install # in the repository root; also builds the package
|
|
273
|
+
cd sdk/ts
|
|
274
|
+
npm run dev # rebuild on every change, for apps in the workspace
|
|
275
|
+
npm run check # types and formatting
|
|
276
|
+
npm test # unit tests
|
|
277
|
+
npm run test:hub # against a real hub; needs Docker and Go
|
|
278
|
+
```
|
package/dist/cache.d.ts
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import type { Intent, Item, List, Priority, Profile, ReminderPlan } from "./types.js";
|
|
2
|
+
export type CacheKind = "profile" | "lists" | "items" | "history" | "plans";
|
|
3
|
+
export interface CacheChange {
|
|
4
|
+
readonly userId: string;
|
|
5
|
+
/** What changed for this user. All five when the user was loaded anew or went away. */
|
|
6
|
+
readonly kinds: readonly CacheKind[];
|
|
7
|
+
/** The event behind the change, or undefined for a sync or a user going away. */
|
|
8
|
+
readonly cause: {
|
|
9
|
+
readonly name: string;
|
|
10
|
+
readonly nonce: string | null;
|
|
11
|
+
readonly id: string | undefined;
|
|
12
|
+
} | undefined;
|
|
13
|
+
}
|
|
14
|
+
/** What the cache holds about one user. Reading is synchronous and never changes anything. */
|
|
15
|
+
export interface UserState {
|
|
16
|
+
readonly userId: string;
|
|
17
|
+
readonly profile: Profile | undefined;
|
|
18
|
+
/** The lists in their order. The array stays the same until a list changes. */
|
|
19
|
+
lists(): readonly List[];
|
|
20
|
+
list(id: string): List | undefined;
|
|
21
|
+
/** Every open item. The array stays the same until an open item changes. */
|
|
22
|
+
items(): readonly Item[];
|
|
23
|
+
/** An open item, or a completed one from the history. */
|
|
24
|
+
item(id: string): Item | undefined;
|
|
25
|
+
/** Completed items, most recently completed first. Needs the `history` intent. */
|
|
26
|
+
history(): readonly Item[];
|
|
27
|
+
/** Where `listItems` continues after the history, or null if nothing older exists. */
|
|
28
|
+
readonly historyCursor: string | null;
|
|
29
|
+
plans(): readonly ReminderPlan[];
|
|
30
|
+
plan(priority: Priority): ReminderPlan | undefined;
|
|
31
|
+
}
|
|
32
|
+
export interface Cache {
|
|
33
|
+
/** The state of a user. Without an id: the user a personal token or a session belongs to. */
|
|
34
|
+
user(userId?: string): UserState | undefined;
|
|
35
|
+
users(): readonly UserState[];
|
|
36
|
+
/** Calls the listener after every change. Returns a function that unsubscribes. */
|
|
37
|
+
subscribe(listener: (change: CacheChange) => void): () => void;
|
|
38
|
+
}
|
|
39
|
+
export interface Applied {
|
|
40
|
+
/** The payload in the SDK's form. */
|
|
41
|
+
event: unknown;
|
|
42
|
+
change: CacheChange | undefined;
|
|
43
|
+
old: unknown;
|
|
44
|
+
/** The user whose state just became complete. */
|
|
45
|
+
synced: string | undefined;
|
|
46
|
+
}
|
|
47
|
+
/** The writing side of the cache. Only gateway events go in. */
|
|
48
|
+
export declare class CacheStore {
|
|
49
|
+
#private;
|
|
50
|
+
readonly cache: Cache;
|
|
51
|
+
/** Starts a new session: users it no longer names go and are returned, the others stay readable. */
|
|
52
|
+
begin(users: readonly string[], intents: readonly Intent[], self: string | undefined): string[];
|
|
53
|
+
apply(name: string, wire: unknown): Applied;
|
|
54
|
+
}
|
package/dist/cache.js
ADDED
|
@@ -0,0 +1,287 @@
|
|
|
1
|
+
import { fromWire, microsOf } from "./convert.js";
|
|
2
|
+
const allKinds = ["profile", "lists", "items", "history", "plans"];
|
|
3
|
+
function newerFirst(a, b) {
|
|
4
|
+
if (a.at !== b.at)
|
|
5
|
+
return a.at > b.at ? -1 : 1;
|
|
6
|
+
if (a.key !== b.key)
|
|
7
|
+
return a.key > b.key ? -1 : 1;
|
|
8
|
+
return 0;
|
|
9
|
+
}
|
|
10
|
+
class Slots {
|
|
11
|
+
profile;
|
|
12
|
+
lists = new Map();
|
|
13
|
+
items = new Map();
|
|
14
|
+
done = new Map();
|
|
15
|
+
history = [];
|
|
16
|
+
historyCursor = null;
|
|
17
|
+
plans = new Map();
|
|
18
|
+
insertDone(item, completedAt) {
|
|
19
|
+
let at = 0n;
|
|
20
|
+
try {
|
|
21
|
+
at = microsOf(completedAt);
|
|
22
|
+
}
|
|
23
|
+
catch {
|
|
24
|
+
// An unreadable time sorts last instead of keeping the item out.
|
|
25
|
+
}
|
|
26
|
+
const entry = { item, at, key: item.id.toLowerCase() };
|
|
27
|
+
let low = 0;
|
|
28
|
+
let high = this.history.length;
|
|
29
|
+
while (low < high) {
|
|
30
|
+
const middle = (low + high) >>> 1;
|
|
31
|
+
if (newerFirst(this.history[middle], entry) < 0)
|
|
32
|
+
low = middle + 1;
|
|
33
|
+
else
|
|
34
|
+
high = middle;
|
|
35
|
+
}
|
|
36
|
+
this.history.splice(low, 0, entry);
|
|
37
|
+
this.done.set(item.id, entry);
|
|
38
|
+
}
|
|
39
|
+
removeDone(id) {
|
|
40
|
+
const entry = this.done.get(id);
|
|
41
|
+
if (!entry)
|
|
42
|
+
return undefined;
|
|
43
|
+
this.done.delete(id);
|
|
44
|
+
this.history.splice(this.history.indexOf(entry), 1);
|
|
45
|
+
return entry.item;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
class UserData {
|
|
49
|
+
userId;
|
|
50
|
+
slots = new Slots();
|
|
51
|
+
#lists;
|
|
52
|
+
#items;
|
|
53
|
+
#history;
|
|
54
|
+
#plans;
|
|
55
|
+
constructor(userId) {
|
|
56
|
+
this.userId = userId;
|
|
57
|
+
}
|
|
58
|
+
touch(kinds) {
|
|
59
|
+
for (const kind of kinds) {
|
|
60
|
+
if (kind === "lists")
|
|
61
|
+
this.#lists = undefined;
|
|
62
|
+
else if (kind === "items")
|
|
63
|
+
this.#items = undefined;
|
|
64
|
+
else if (kind === "history")
|
|
65
|
+
this.#history = undefined;
|
|
66
|
+
else if (kind === "plans")
|
|
67
|
+
this.#plans = undefined;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
get profile() {
|
|
71
|
+
return this.slots.profile;
|
|
72
|
+
}
|
|
73
|
+
get historyCursor() {
|
|
74
|
+
return this.slots.historyCursor;
|
|
75
|
+
}
|
|
76
|
+
lists() {
|
|
77
|
+
return (this.#lists ??= Object.freeze([...this.slots.lists.values()].sort((a, b) => a.position - b.position)));
|
|
78
|
+
}
|
|
79
|
+
list(id) {
|
|
80
|
+
return this.slots.lists.get(id);
|
|
81
|
+
}
|
|
82
|
+
items() {
|
|
83
|
+
return (this.#items ??= Object.freeze([...this.slots.items.values()]));
|
|
84
|
+
}
|
|
85
|
+
item(id) {
|
|
86
|
+
return this.slots.items.get(id) ?? this.slots.done.get(id)?.item;
|
|
87
|
+
}
|
|
88
|
+
history() {
|
|
89
|
+
return (this.#history ??= Object.freeze(this.slots.history.map((entry) => entry.item)));
|
|
90
|
+
}
|
|
91
|
+
plans() {
|
|
92
|
+
return (this.#plans ??= Object.freeze([...this.slots.plans.values()]));
|
|
93
|
+
}
|
|
94
|
+
plan(priority) {
|
|
95
|
+
return this.slots.plans.get(priority);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
/** The writing side of the cache. Only gateway events go in. */
|
|
99
|
+
export class CacheStore {
|
|
100
|
+
#users = new Map();
|
|
101
|
+
#pending = new Map();
|
|
102
|
+
#listeners = new Set();
|
|
103
|
+
#list;
|
|
104
|
+
#self;
|
|
105
|
+
#history = false;
|
|
106
|
+
cache = {
|
|
107
|
+
user: (userId) => {
|
|
108
|
+
const id = userId ?? this.#self;
|
|
109
|
+
return id === undefined ? undefined : this.#users.get(id);
|
|
110
|
+
},
|
|
111
|
+
users: () => (this.#list ??= Object.freeze([...this.#users.values()])),
|
|
112
|
+
subscribe: (listener) => {
|
|
113
|
+
const own = (change) => listener(change);
|
|
114
|
+
this.#listeners.add(own);
|
|
115
|
+
return () => {
|
|
116
|
+
this.#listeners.delete(own);
|
|
117
|
+
};
|
|
118
|
+
},
|
|
119
|
+
};
|
|
120
|
+
/** Starts a new session: users it no longer names go and are returned, the others stay readable. */
|
|
121
|
+
begin(users, intents, self) {
|
|
122
|
+
this.#self = self;
|
|
123
|
+
this.#history = intents.includes("history");
|
|
124
|
+
this.#pending.clear();
|
|
125
|
+
const named = new Set(users);
|
|
126
|
+
const dropped = [...this.#users.keys()].filter((id) => !named.has(id));
|
|
127
|
+
for (const id of dropped)
|
|
128
|
+
this.#notify(this.#drop(id));
|
|
129
|
+
return dropped;
|
|
130
|
+
}
|
|
131
|
+
apply(name, wire) {
|
|
132
|
+
const event = fromWire(wire);
|
|
133
|
+
const applied = { event, change: undefined, old: undefined, synced: undefined };
|
|
134
|
+
if (wire === null || typeof wire !== "object")
|
|
135
|
+
return applied;
|
|
136
|
+
const userId = wire.user_id;
|
|
137
|
+
if (name === "user.sync") {
|
|
138
|
+
this.#sync(wire, event, applied);
|
|
139
|
+
}
|
|
140
|
+
else if (name === "user.gone") {
|
|
141
|
+
this.#pending.delete(userId);
|
|
142
|
+
if (this.#users.has(userId))
|
|
143
|
+
applied.change = this.#drop(userId);
|
|
144
|
+
}
|
|
145
|
+
else {
|
|
146
|
+
const user = this.#users.get(userId);
|
|
147
|
+
const data = wire.data;
|
|
148
|
+
if (user && data !== null && typeof data === "object") {
|
|
149
|
+
const kinds = this.#change(user, name, data, event.data, applied);
|
|
150
|
+
if (kinds.length > 0) {
|
|
151
|
+
user.touch(kinds);
|
|
152
|
+
const id = name === "plan.updated" ? data.priority : data.id;
|
|
153
|
+
applied.change = {
|
|
154
|
+
userId,
|
|
155
|
+
kinds,
|
|
156
|
+
cause: {
|
|
157
|
+
name,
|
|
158
|
+
nonce: wire.nonce ?? null,
|
|
159
|
+
id: typeof id === "string" ? id : undefined,
|
|
160
|
+
},
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
if (applied.change)
|
|
166
|
+
this.#notify(applied.change);
|
|
167
|
+
return applied;
|
|
168
|
+
}
|
|
169
|
+
#sync(wire, event, applied) {
|
|
170
|
+
const userId = wire.user_id;
|
|
171
|
+
let slots = this.#pending.get(userId);
|
|
172
|
+
if (wire.chunk.index === 0) {
|
|
173
|
+
slots = new Slots();
|
|
174
|
+
this.#pending.set(userId, slots);
|
|
175
|
+
slots.profile = event.user;
|
|
176
|
+
for (const list of event.lists ?? [])
|
|
177
|
+
slots.lists.set(list.id, list);
|
|
178
|
+
for (const plan of event.plans ?? [])
|
|
179
|
+
slots.plans.set(plan.priority, plan);
|
|
180
|
+
}
|
|
181
|
+
if (!slots)
|
|
182
|
+
return;
|
|
183
|
+
for (const item of event.items ?? [])
|
|
184
|
+
slots.items.set(item.id, item);
|
|
185
|
+
(event.history ?? []).forEach((item, i) => {
|
|
186
|
+
slots.insertDone(item, wire.history[i].completed_at);
|
|
187
|
+
});
|
|
188
|
+
if (wire.history_cursor !== undefined)
|
|
189
|
+
slots.historyCursor = wire.history_cursor;
|
|
190
|
+
if (wire.chunk.index < wire.chunk.count - 1)
|
|
191
|
+
return;
|
|
192
|
+
this.#pending.delete(userId);
|
|
193
|
+
let user = this.#users.get(userId);
|
|
194
|
+
if (!user) {
|
|
195
|
+
user = new UserData(userId);
|
|
196
|
+
this.#users.set(userId, user);
|
|
197
|
+
this.#list = undefined;
|
|
198
|
+
}
|
|
199
|
+
user.slots = slots;
|
|
200
|
+
user.touch(allKinds);
|
|
201
|
+
applied.synced = userId;
|
|
202
|
+
applied.change = { userId, kinds: allKinds, cause: undefined };
|
|
203
|
+
}
|
|
204
|
+
#change(user, name, wire, data, applied) {
|
|
205
|
+
const slots = user.slots;
|
|
206
|
+
const id = wire.id;
|
|
207
|
+
switch (name) {
|
|
208
|
+
case "user.updated":
|
|
209
|
+
applied.old = slots.profile;
|
|
210
|
+
slots.profile = data;
|
|
211
|
+
return ["profile"];
|
|
212
|
+
case "list.created":
|
|
213
|
+
case "list.updated":
|
|
214
|
+
applied.old = slots.lists.get(id);
|
|
215
|
+
slots.lists.set(id, data);
|
|
216
|
+
return ["lists"];
|
|
217
|
+
case "list.deleted":
|
|
218
|
+
applied.old = slots.lists.get(id);
|
|
219
|
+
return slots.lists.delete(id) ? ["lists"] : [];
|
|
220
|
+
case "plan.updated": {
|
|
221
|
+
const plan = data;
|
|
222
|
+
applied.old = slots.plans.get(plan.priority);
|
|
223
|
+
slots.plans.set(plan.priority, plan);
|
|
224
|
+
return ["plans"];
|
|
225
|
+
}
|
|
226
|
+
case "item.created":
|
|
227
|
+
case "item.updated": {
|
|
228
|
+
const item = data;
|
|
229
|
+
const open = slots.items.get(id);
|
|
230
|
+
if (item.status === "open") {
|
|
231
|
+
const done = slots.removeDone(id);
|
|
232
|
+
applied.old = open ?? done;
|
|
233
|
+
slots.items.set(id, item);
|
|
234
|
+
return done ? ["items", "history"] : ["items"];
|
|
235
|
+
}
|
|
236
|
+
const kinds = [];
|
|
237
|
+
if (open) {
|
|
238
|
+
slots.items.delete(id);
|
|
239
|
+
kinds.push("items");
|
|
240
|
+
}
|
|
241
|
+
if (this.#history && typeof wire.completed_at === "string") {
|
|
242
|
+
applied.old = open ?? slots.removeDone(id);
|
|
243
|
+
slots.insertDone(item, wire.completed_at);
|
|
244
|
+
kinds.push("history");
|
|
245
|
+
}
|
|
246
|
+
else {
|
|
247
|
+
applied.old = open;
|
|
248
|
+
}
|
|
249
|
+
return kinds;
|
|
250
|
+
}
|
|
251
|
+
case "item.deleted": {
|
|
252
|
+
const open = slots.items.get(id);
|
|
253
|
+
if (open) {
|
|
254
|
+
applied.old = open;
|
|
255
|
+
slots.items.delete(id);
|
|
256
|
+
return ["items"];
|
|
257
|
+
}
|
|
258
|
+
applied.old = slots.removeDone(id);
|
|
259
|
+
return applied.old ? ["history"] : [];
|
|
260
|
+
}
|
|
261
|
+
case "subitem.updated":
|
|
262
|
+
case "subitem.deleted":
|
|
263
|
+
applied.old = user.item(wire.item_id)?.subitems.find((sub) => sub.id === id);
|
|
264
|
+
return [];
|
|
265
|
+
case "reminder.deleted":
|
|
266
|
+
applied.old = user.item(wire.item_id)?.reminders.find((rem) => rem.id === id);
|
|
267
|
+
return [];
|
|
268
|
+
default:
|
|
269
|
+
return [];
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
#drop(userId) {
|
|
273
|
+
this.#users.delete(userId);
|
|
274
|
+
this.#list = undefined;
|
|
275
|
+
return { userId, kinds: allKinds, cause: undefined };
|
|
276
|
+
}
|
|
277
|
+
#notify(change) {
|
|
278
|
+
for (const listener of [...this.#listeners]) {
|
|
279
|
+
try {
|
|
280
|
+
listener(change);
|
|
281
|
+
}
|
|
282
|
+
catch (error) {
|
|
283
|
+
console.error("plsremind: a cache listener threw", error);
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
}
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { type Cache } from "./cache.js";
|
|
2
|
+
import { type EventMap, type Principal } from "./events.js";
|
|
3
|
+
import { type SocketLike } from "./gateway.js";
|
|
4
|
+
import { RestClient, type RestOptions } from "./rest.js";
|
|
5
|
+
import type { Intent } from "./types.js";
|
|
6
|
+
export interface ClientOptions extends RestOptions {
|
|
7
|
+
/** What the gateway session should receive. Without it the client can only use REST. */
|
|
8
|
+
intents?: readonly Intent[];
|
|
9
|
+
}
|
|
10
|
+
export type ClientStatus = "idle" | "connecting" | "connected" | "reconnecting" | "closed";
|
|
11
|
+
export interface ClientInternals {
|
|
12
|
+
createSocket?: (url: string) => SocketLike;
|
|
13
|
+
random?: () => number;
|
|
14
|
+
}
|
|
15
|
+
/** A gateway session with a cache of what it covers, typed events and the REST API. */
|
|
16
|
+
export declare class Client {
|
|
17
|
+
#private;
|
|
18
|
+
/** Every call of the REST API. Answers do not change the cache; the events that follow do. */
|
|
19
|
+
readonly rest: RestClient;
|
|
20
|
+
/** The state the session covers, kept current by the gateway. */
|
|
21
|
+
readonly cache: Cache;
|
|
22
|
+
constructor(options?: ClientOptions, internals?: ClientInternals);
|
|
23
|
+
/** Who the client is logged in as. Set once the gateway said READY. */
|
|
24
|
+
get principal(): Principal | undefined;
|
|
25
|
+
/** The intents of the session, or the ones asked for while there is none yet. */
|
|
26
|
+
get intents(): readonly Intent[];
|
|
27
|
+
get status(): ClientStatus;
|
|
28
|
+
/**
|
|
29
|
+
* Resolves once the state of every user of the session is in the cache. Rejects with a
|
|
30
|
+
* GatewayError if the first attempt fails; later drops are reconnected without the caller.
|
|
31
|
+
*/
|
|
32
|
+
connect(): Promise<void>;
|
|
33
|
+
/** Ends the session and every retry. The cache stays readable; connect() starts over. */
|
|
34
|
+
close(): void;
|
|
35
|
+
/** Calls the handler for every event of that name. Returns a function that unsubscribes. */
|
|
36
|
+
on<K extends keyof EventMap>(name: K, handler: (event: EventMap[K]) => unknown): () => void;
|
|
37
|
+
/** Like on(), for the next event of that name only. */
|
|
38
|
+
once<K extends keyof EventMap>(name: K, handler: (event: EventMap[K]) => unknown): () => void;
|
|
39
|
+
}
|