slopkit 0.2.0 → 0.4.0-rc.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.
Files changed (52) hide show
  1. package/DEPS.md +5 -3
  2. package/README.md +103 -1
  3. package/RULES.md +26 -6
  4. package/dist/api.d.ts +93 -0
  5. package/dist/api.js +111 -0
  6. package/dist/client.d.ts +21 -4
  7. package/dist/client.js +21 -2
  8. package/dist/conformance/agent-access.test.d.ts +1 -0
  9. package/dist/conformance/agent-access.test.js +74 -0
  10. package/dist/conformance/client.test.js +7 -7
  11. package/dist/conformance/fixtures.d.ts +1 -0
  12. package/dist/conformance/fixtures.js +5 -1
  13. package/dist/conformance/outbox-bound.test.d.ts +1 -0
  14. package/dist/conformance/outbox-bound.test.js +268 -0
  15. package/dist/conformance/paging-state.test.js +1 -0
  16. package/dist/conformance/push-bytes.test.d.ts +1 -0
  17. package/dist/conformance/push-bytes.test.js +174 -0
  18. package/dist/conformance/push-refusal.test.d.ts +1 -0
  19. package/dist/conformance/push-refusal.test.js +644 -0
  20. package/dist/conformance/states.test.js +19 -8
  21. package/dist/contract.d.ts +19 -6
  22. package/dist/contract.js +76 -9
  23. package/dist/server/auth.d.ts +4 -3
  24. package/dist/server/auth.js +14 -6
  25. package/dist/server/cli.d.ts +117 -0
  26. package/dist/server/cli.js +1534 -0
  27. package/dist/server/config.d.ts +4 -1
  28. package/dist/server/config.js +2 -2
  29. package/dist/server/keys.d.ts +17 -0
  30. package/dist/server/keys.js +127 -0
  31. package/dist/server/pull.js +158 -67
  32. package/dist/server/store.d.ts +101 -0
  33. package/dist/server/store.js +347 -0
  34. package/dist/server/sync.d.ts +158 -0
  35. package/dist/server/sync.js +293 -0
  36. package/dist/server/web.d.ts +62 -9
  37. package/dist/server/web.js +260 -35
  38. package/dist/states.d.ts +52 -4
  39. package/dist/states.js +20 -0
  40. package/dist/sync.d.ts +86 -2
  41. package/dist/sync.js +277 -59
  42. package/dist/test/agents.d.ts +19 -0
  43. package/dist/test/agents.js +62 -0
  44. package/dist/test/page.d.ts +91 -0
  45. package/dist/test/page.js +763 -0
  46. package/dist/test/states.d.ts +44 -7
  47. package/dist/test/states.js +152 -0
  48. package/dist/web/replica.d.ts +7 -0
  49. package/dist/web/replica.js +260 -47
  50. package/dist/web/runtime.d.ts +102 -0
  51. package/dist/web/runtime.js +335 -0
  52. package/package.json +39 -1
@@ -0,0 +1,347 @@
1
+ /**
2
+ * The replicated store's core: a home's SQLite file (Node's built-in SQLite, WAL), owned by the one server under the
3
+ * home's lock, that a replica pulls from. An app's store extends `SyncStore` (or holds one) and adds its own tables and
4
+ * queries; the mechanics every replicated store needs are here.
5
+ *
6
+ * - **Nothing opens a store it can't read.** A store from a newer release, or older than the schema this release
7
+ * starts from, is refused before anything is written to it.
8
+ * - **Migrations are append only** and each runs in its own transaction, foreign keys checked at its end; a store with
9
+ * data is first copied whole (`<path>.schema-<n>.bak`, the oldest kept), so a rollback can put it back.
10
+ * - **Every write is stamped:** the rows a transaction writes to a replicated table carry the revision `stamp()` made
11
+ * in it (a trigger refuses any other), and nothing replicated is deleted (tombstones). Each revision is logged, so a
12
+ * page holding one this history never had (a restore's lost future) is told apart from one that is behind.
13
+ * - **A restore is told apart:** the newest revision served is kept beside the store (`<path>.head`), written before
14
+ * the reply carrying it leaves; a store that opens behind it went back, and takes a new dataset.
15
+ * - **Retention never deletes a key:** receipts retire, old revisions are forgotten (a page holding one starts over),
16
+ * finished jobs beyond the newest are pruned.
17
+ */
18
+ import { randomBytes } from "node:crypto";
19
+ import { closeSync, existsSync, fsyncSync, openSync, readFileSync, renameSync, writeSync, } from "node:fs";
20
+ import { dirname } from "node:path";
21
+ import { DatabaseSync } from "node:sqlite";
22
+ import { check, number, object, string } from "../schema.js";
23
+ import { Jobs } from "./jobs.js";
24
+ import { Ledger } from "./ledger.js";
25
+ /**
26
+ * The core tables every replicated store has, before the app's own: `meta`, the command ledger's `commands`
27
+ * (`slopkit/server/ledger`), `jobs` (`slopkit/server/jobs`) and the `revisions` log. Never edited once shipped.
28
+ */
29
+ export const CORE_TABLES = `create table meta(key text primary key, value text not null);
30
+ create table commands(
31
+ principal text not null check (length(principal) > 0),
32
+ client text not null, id integer not null check (id > 0),
33
+ name text not null, args text not null,
34
+ state text not null check (state in ('accepted', 'done', 'retired')),
35
+ outcome text check ((state = 'done') = (outcome is not null)),
36
+ revision integer check ((state = 'accepted') = (revision is null)),
37
+ created_at text not null,
38
+ primary key (principal, client, id)) strict;
39
+ create index commands_revision on commands(principal, client, revision);
40
+ create trigger commands_never_deleted before delete on commands
41
+ begin select raise(abort, 'a command key is kept forever: retire it'); end;
42
+ create table jobs(
43
+ id integer primary key,
44
+ kind text not null check (length(kind) > 0),
45
+ key text not null,
46
+ state text not null check (state in ('due', 'running', 'done', 'failed')),
47
+ due_at text not null, deadline_at text not null,
48
+ attempts integer not null default 0 check (attempts >= 0),
49
+ note text,
50
+ result text check ((state = 'done') = (result is not null)),
51
+ who text check ((state = 'failed') = (who is not null) and (who is null or who in ('you', 'us', 'gone'))),
52
+ reason text check ((state = 'failed') = (reason is not null)),
53
+ asked_by text not null default '[]',
54
+ created_at text not null, updated_at text not null);
55
+ create unique index jobs_open on jobs(kind, key) where state in ('due', 'running');
56
+ create table revisions(revision integer primary key, at text not null) strict;
57
+ insert into meta(key, value) values ('revision', '1'), ('history_floor', '1'),
58
+ ('dataset', lower(hex(randomblob(12))));`;
59
+ /** A replicated table's triggers: every write carries the revision stamped in its own transaction; no delete. */
60
+ function stamped(table) {
61
+ const revision = "(select cast(value as integer) from meta where key = 'revision')";
62
+ const stamping = "(select cast(value as integer) from meta where key = 'stamping')";
63
+ return [
64
+ ...["insert", "update"].map((event) => `create trigger ${table}_stamped_${event} before ${event} on ${table}
65
+ when new.revision is not ${revision} or ${revision} is not ${stamping}
66
+ begin select raise(abort, 'a replicated row must carry a revision stamped in its own transaction'); end;`),
67
+ `create trigger ${table}_never_deleted before delete on ${table}
68
+ begin select raise(abort, 'a replicated row is never deleted: tombstone it'); end;`,
69
+ ].join("\n");
70
+ }
71
+ /** The store schema a release writes: what `version --json` reports and a rollback compares. */
72
+ export function schemaVersion(schema) {
73
+ return schema.baseVersion + schema.migrations.length;
74
+ }
75
+ const DAY = 86_400_000;
76
+ /** What `<path>.head` holds: the newest revision of a dataset that left the server. */
77
+ const HEAD = object({ dataset: string(), revision: number() });
78
+ /** Retention reads no receipt or result: these stand in for an app's own codecs. */
79
+ const OPAQUE = {
80
+ encode: (value) => JSON.stringify(value),
81
+ decode: (text) => text,
82
+ };
83
+ /** A safe name for a table: it is spliced into the trigger SQL. */
84
+ const TABLE = /^[a-z_][a-z0-9_]*$/;
85
+ export class SyncStore {
86
+ db;
87
+ path;
88
+ now;
89
+ /**
90
+ * Set when the store opened older than what it had already served (restored from a backup), or a caller proved it
91
+ * went back: the dataset and revision it had served, and its revision then. It took a new dataset, so every replica
92
+ * starts over and no intent made against the lost history runs here.
93
+ */
94
+ restored;
95
+ head;
96
+ servedHead;
97
+ depth = 0;
98
+ constructor(path, options) {
99
+ const { schema } = options;
100
+ for (const table of schema.replicated) {
101
+ if (!TABLE.test(table)) {
102
+ throw new Error(`not a table name: ${table}`);
103
+ }
104
+ }
105
+ this.path = path;
106
+ this.now = options.now ?? Date.now;
107
+ this.db = new DatabaseSync(path);
108
+ const version = this.userVersion();
109
+ const latest = schemaVersion(schema);
110
+ // A file at version 0 is new only while it holds nothing: one with tables is from before any release could say.
111
+ const empty = this.db.prepare("select count(*) as n from sqlite_master").get()?.n === 0;
112
+ const refused = version > latest
113
+ ? `The store is from a newer version (schema ${version}); update ${options.name}`
114
+ : (version > 0 || !empty) && version < schema.baseVersion
115
+ ? `The store is at schema ${version}, from before ${schema.baseVersion}, the schema this release starts from: it can't be opened`
116
+ : undefined;
117
+ if (refused !== undefined) {
118
+ this.db.close();
119
+ throw new Error(refused);
120
+ }
121
+ // FULL: a commit is on the disk before it is acknowledged.
122
+ this.db.exec("pragma journal_mode = wal; pragma synchronous = full; pragma foreign_keys = on;");
123
+ this.migrate(schema, version);
124
+ this.head = `${path}.head`;
125
+ this.restored = this.checkHead();
126
+ }
127
+ userVersion() {
128
+ return Number(this.db.prepare("pragma user_version").get()?.user_version ?? 0);
129
+ }
130
+ migrate(schema, version) {
131
+ if (version === 0) {
132
+ this.transaction(() => {
133
+ this.db.exec(CORE_TABLES);
134
+ this.db.exec(schema.base);
135
+ for (const table of schema.replicated) {
136
+ this.db.exec(stamped(table));
137
+ }
138
+ this.db.exec(`pragma user_version = ${schema.baseVersion}`);
139
+ });
140
+ }
141
+ const from = Math.max(version, schema.baseVersion);
142
+ const latest = schemaVersion(schema);
143
+ const backup = `${this.path}.schema-${from}.bak`;
144
+ if (version > 0 && version < latest && !existsSync(backup)) {
145
+ this.db.prepare("vacuum into ?").run(backup);
146
+ }
147
+ for (let next = from; next < latest; next++) {
148
+ // A rebuild drops tables other tables reference; foreign keys are checked once it is done.
149
+ this.db.exec("pragma foreign_keys = off");
150
+ try {
151
+ this.transaction(() => {
152
+ this.db.exec(schema.migrations[next - schema.baseVersion] ?? "");
153
+ this.db.exec(`pragma user_version = ${next + 1}`);
154
+ const broken = this.db.prepare("pragma foreign_key_check").all();
155
+ if (broken.length > 0) {
156
+ throw new Error(`Migration ${next + 1} leaves ${broken.length} broken references`);
157
+ }
158
+ });
159
+ }
160
+ finally {
161
+ this.db.exec("pragma foreign_keys = on");
162
+ }
163
+ }
164
+ if (schema.indexes !== undefined) {
165
+ this.db.exec(schema.indexes);
166
+ }
167
+ }
168
+ /** The head beside the store: a store that opens behind what it served went back, and takes a new dataset. */
169
+ checkHead() {
170
+ let head;
171
+ try {
172
+ head = JSON.parse(readFileSync(this.head, "utf-8"));
173
+ }
174
+ catch {
175
+ return undefined;
176
+ }
177
+ const read = check(HEAD, head);
178
+ if (!read.ok) {
179
+ return undefined;
180
+ }
181
+ const { dataset, revision: served } = read.value;
182
+ if (dataset !== this.dataset() || this.revision() >= served) {
183
+ return undefined;
184
+ }
185
+ const replaced = { dataset, served, revision: this.revision() };
186
+ this.setMeta("dataset", randomBytes(12).toString("hex"));
187
+ return replaced;
188
+ }
189
+ /** A caller proved this store went back: it holds `seen` of this very dataset, more than the store has. */
190
+ wentBack(seen) {
191
+ if (seen <= this.revision()) {
192
+ return false;
193
+ }
194
+ this.restored = { dataset: this.dataset(), served: seen, revision: this.revision() };
195
+ this.setMeta("dataset", randomBytes(12).toString("hex"));
196
+ return true;
197
+ }
198
+ /** Record that `revision` of this dataset left the server (a pull or push reply), before the reply does. */
199
+ served(revision) {
200
+ const dataset = this.dataset();
201
+ const last = this.servedHead;
202
+ if (last !== undefined && last.dataset === dataset && last.revision >= revision) {
203
+ return;
204
+ }
205
+ const temporary = `${this.head}.tmp`;
206
+ const fd = openSync(temporary, "w", 0o600);
207
+ try {
208
+ const bytes = Buffer.from(JSON.stringify({ dataset, revision }), "utf-8");
209
+ for (let at = 0; at < bytes.length;) {
210
+ at += writeSync(fd, bytes, at, bytes.length - at);
211
+ }
212
+ fsyncSync(fd);
213
+ }
214
+ finally {
215
+ closeSync(fd);
216
+ }
217
+ renameSync(temporary, this.head);
218
+ // The rename itself on the disk too.
219
+ const dir = openSync(dirname(this.head), "r");
220
+ try {
221
+ fsyncSync(dir);
222
+ }
223
+ finally {
224
+ closeSync(dir);
225
+ }
226
+ this.servedHead = { dataset, revision };
227
+ }
228
+ close() {
229
+ if (this.db.isOpen) {
230
+ this.db.close();
231
+ }
232
+ }
233
+ /** All of `body` or none of it. Nested calls join the outer transaction: a failure anywhere undoes all of it. */
234
+ transaction(body) {
235
+ if (this.depth > 0) {
236
+ return body();
237
+ }
238
+ this.db.exec("begin immediate");
239
+ this.depth++;
240
+ try {
241
+ const result = body();
242
+ this.db.exec("delete from meta where key = 'stamping'");
243
+ this.db.exec("commit");
244
+ return result;
245
+ }
246
+ catch (error) {
247
+ this.db.exec("rollback");
248
+ throw error;
249
+ }
250
+ finally {
251
+ this.depth--;
252
+ }
253
+ }
254
+ meta(key) {
255
+ const value = this.db.prepare("select value from meta where key = ?").get(key)?.value;
256
+ return typeof value === "string" ? value : undefined;
257
+ }
258
+ setMeta(key, value) {
259
+ this.db
260
+ .prepare("insert into meta(key, value) values (?, ?) on conflict(key) do update set value = excluded.value")
261
+ .run(key, value);
262
+ }
263
+ /** This store's identity: a replica of another store starts over. */
264
+ dataset() {
265
+ let dataset = this.meta("dataset");
266
+ if (dataset === undefined) {
267
+ dataset = randomBytes(12).toString("hex");
268
+ this.setMeta("dataset", dataset);
269
+ }
270
+ return dataset;
271
+ }
272
+ revision() {
273
+ return Number(this.meta("revision") ?? 0);
274
+ }
275
+ /** The store's clock as stored: now, or `at` (milliseconds). */
276
+ iso(at) {
277
+ return new Date(at ?? this.now()).toISOString();
278
+ }
279
+ /**
280
+ * Whether `revision` is one of this history: none (0), the head, at or before the floor (the revisions before they
281
+ * were logged), or one this store stamped and still remembers. A page holding another came from a history this store
282
+ * doesn't have (a restore's lost future), or is older than the log keeps: it starts over, and its taps don't run.
283
+ */
284
+ known(revision) {
285
+ if (revision === 0 || revision === this.revision()) {
286
+ return true;
287
+ }
288
+ if (revision <= Number(this.meta("history_floor") ?? 0)) {
289
+ return true;
290
+ }
291
+ return (this.db.prepare("select 1 from revisions where revision = ?").get(revision) !== undefined);
292
+ }
293
+ /**
294
+ * The next revision, for rows written in the current transaction: past the last, and at least the clock in
295
+ * microseconds (plus a random part below a millisecond), so two histories forked from one copy never stamp the same
296
+ * number while the clock moves forward. Each is logged (`known`).
297
+ */
298
+ stamp() {
299
+ if (!this.db.isTransaction) {
300
+ throw new Error("A revision is stamped inside the transaction that writes its rows");
301
+ }
302
+ const next = Math.max(this.revision() + 1, this.now() * 1000 + Math.floor(Math.random() * 1000));
303
+ if (!Number.isSafeInteger(next)) {
304
+ throw new TypeError(`Revision ${next} is past a safe integer`);
305
+ }
306
+ this.db.prepare("insert into revisions(revision, at) values (?, ?)").run(next, this.iso());
307
+ this.setMeta("revision", String(next));
308
+ this.setMeta("stamping", String(next));
309
+ return next;
310
+ }
311
+ /** The command ledger (`slopkit/server/ledger`) on this store: its transaction and its stamp. */
312
+ createLedger(codec) {
313
+ return new Ledger({
314
+ db: this.db,
315
+ transaction: (body) => this.transaction(body),
316
+ stamp: () => this.stamp(),
317
+ encode: codec.encode,
318
+ decode: codec.decode,
319
+ ...(codec.recover === undefined ? {} : { recover: codec.recover }),
320
+ });
321
+ }
322
+ /** Jobs (`slopkit/server/jobs`) on this store. */
323
+ createJobs(codec) {
324
+ return new Jobs({
325
+ db: this.db,
326
+ transaction: (body) => this.transaction(body),
327
+ encode: codec.encode,
328
+ decode: codec.decode,
329
+ now: this.now,
330
+ });
331
+ }
332
+ /**
333
+ * Retention, which never deletes a key: receipts accepted more than `receiptsMs` ago retire (their outcome dropped, never acting
334
+ * again), logged revisions older than `revisionsMs` are forgotten except the head (a page holding one starts over),
335
+ * and finished jobs beyond the newest `jobsKept` of each kind are pruned.
336
+ */
337
+ retain(options = {}) {
338
+ const now = this.now();
339
+ this.transaction(() => {
340
+ this.createLedger(OPAQUE).retire(this.iso(now - (options.receiptsMs ?? 90 * DAY)));
341
+ this.db
342
+ .prepare("delete from revisions where at < ? and revision <> ?")
343
+ .run(this.iso(now - (options.revisionsMs ?? 400 * DAY)), this.revision());
344
+ });
345
+ this.createJobs(OPAQUE).prune(options.jobsKept ?? 200);
346
+ }
347
+ }
@@ -0,0 +1,158 @@
1
+ /**
2
+ * The server's half of sync, over a replicated store (`slopkit/server/store`) and the app's sync contract
3
+ * (`slopkit/api`): pull and push handlers, their routes with telemetry, the poke socket, and `serveSync`, which serves
4
+ * them all on the kit's web server. An app supplies its tables, its commands and what its server says of itself.
5
+ *
6
+ * - **A push acts only on the history it was tapped against:** one naming another dataset, or a revision this store
7
+ * doesn't know, runs none of its commands.
8
+ * - **Authorization before the ledger, every time,** replays included; then each command runs once through the ledger,
9
+ * in order, and its receipt carries the revision where its effects are.
10
+ * - **Served before replied:** the store records each reply's revision (`served`) before the reply leaves.
11
+ * - **The socket only hints:** a poke carries the store's revision when it moves and as a heartbeat; the page pulls
12
+ * whatever it hears.
13
+ * - **Telemetry is written, never trusted:** the page's events go to the log under the caller's identity.
14
+ */
15
+ import type { KitOutcome, PullReply, PullRequest, PushReply, PushRequest, SyncApi } from "../api.ts";
16
+ import type { CommandKey, Ledger } from "./ledger.ts";
17
+ import type { Logger } from "./log.ts";
18
+ import type { PullLimits, PullOptions } from "./pull.ts";
19
+ import type { SyncStore } from "./store.ts";
20
+ import { serveWeb } from "./web.ts";
21
+ import type { Caller, RawRoute, Route, Socket, WebOptions } from "./web.ts";
22
+ export type { KitOutcome } from "../api.ts";
23
+ /** The kit's own refusal messages, said the same in every app. */
24
+ export declare const KIT_ANSWERS: {
25
+ replaced: string;
26
+ history: string;
27
+ forbidden: (name: string) => string;
28
+ reused: (id: number) => string;
29
+ };
30
+ /**
31
+ * Nothing when the api's outcome union admits the kit's own answers, else `never`: where the handlers meet the api,
32
+ * an outcome schema that would refuse them doesn't compile.
33
+ */
34
+ type Admits<O> = KitOutcome extends O ? unknown : never;
35
+ /** How a command acts: only in the store, inside its claim's transaction, or elsewhere after it. */
36
+ export type Act<K> = {
37
+ local: () => K;
38
+ } | {
39
+ local: () => K | undefined;
40
+ remote: () => Promise<K>;
41
+ };
42
+ /** One command a push ran: its key, the command, what the ledger kept, and whether it acted just now. */
43
+ export type Ran<C, K> = {
44
+ key: CommandKey;
45
+ command: C;
46
+ kept: K;
47
+ fresh: boolean;
48
+ };
49
+ /** Who asks, as the handlers read it: a `Caller`, or anything carrying its identities and whether a person. */
50
+ export type Who = {
51
+ identities: readonly string[];
52
+ person: boolean;
53
+ };
54
+ /** What `serveSync` and the routes need of the handlers. */
55
+ export type Sync<R, S, C, O, V extends Who = Caller> = {
56
+ pull: (request: PullRequest, caller: V) => Promise<PullReply<R, S, O>>;
57
+ push: (request: PushRequest<C>, caller: V) => Promise<PushReply<O>>;
58
+ revision: () => number;
59
+ subscribe: (listener: () => void) => () => void;
60
+ };
61
+ /** A row read from SQLite, as `createPull` hands it to `read`. */
62
+ type HistoryOptions<R> = PullOptions<R, Record<string, readonly unknown[]>, never, never, never>["paged"];
63
+ /**
64
+ * Whose commands these are: every person is the one owner (single user by design), so a person is one principal
65
+ * whichever login they came through; each service or key is its own.
66
+ */
67
+ export declare function principalOf(caller: Who): string;
68
+ export declare function syncHandlers<R extends Record<string, {
69
+ id: string | number;
70
+ }>, S, C extends {
71
+ name: string;
72
+ }, O, K extends {
73
+ kind: string;
74
+ }, H extends keyof R & string, V extends Who = Caller>(options: {
75
+ api: SyncApi<R, S, C, O>;
76
+ store: SyncStore;
77
+ ledger: Ledger<K>;
78
+ log: Logger;
79
+ /** What the server says of itself, with every pull. */
80
+ server: (caller: V) => S;
81
+ /** The history: the table paged newest first (`slopkit/server/pull`), and its row key in the api. */
82
+ history: HistoryOptions<R[H]> & {
83
+ row: H;
84
+ };
85
+ /** The other row keys' rows changed after `since`, or every live row for 0. */
86
+ unpaged: (since: number) => {
87
+ [Key in Exclude<keyof R, H>]: R[Key][];
88
+ };
89
+ /** Every live row of every table (what a complete copy holds), for a verifying pull's checksum. */
90
+ everything: () => {
91
+ [Key in keyof R]: readonly R[Key][];
92
+ };
93
+ /** The history rows (by key) a receipt names: they come in the reply that carries it. */
94
+ names: (kept: K) => readonly (string | number)[];
95
+ limits: PullLimits;
96
+ act: (command: C, caller: V, key: CommandKey) => Act<K>;
97
+ /** A kept receipt as callers see it (a link as its row now); `(kept) => kept` when they are the same. */
98
+ outcome: (kept: K) => O;
99
+ /** Commands only a person's login may run. */
100
+ personOnly?: (command: C) => boolean;
101
+ principal?: (caller: V) => string;
102
+ /** After a push's commands ran, before its reply: what each did. */
103
+ pushed?: (ran: Ran<C, K>[], caller: V) => void;
104
+ }): Sync<R, S, C, O | KitOutcome, V> & {
105
+ changed: () => void;
106
+ };
107
+ /**
108
+ * The sync contract's routes: pull, push and telemetry. Each telemetry event is one `page` log line at `info`, its
109
+ * attributes the event's own with the kit's (`client`, `at`, `person`) set last, so a page can't claim another sender.
110
+ */
111
+ export declare function syncRoutes<R, S, C, O>(api: SyncApi<R, S, C, O>, handlers: Pick<Sync<R, S, C, NoInfer<O> | KitOutcome>, "pull" | "push"> & {
112
+ page: Logger;
113
+ } & Admits<NoInfer<O>>): Route[];
114
+ /**
115
+ * The poke socket: one poke with the revision on open, one for the changes within `gatherMs` (carrying the revision
116
+ * when it is sent), and a beat every `beatMs`, so a lost poke is made up for and a quiet socket is a dead one.
117
+ */
118
+ export declare function pokes<R, S, C, O>(api: SyncApi<R, S, C, O>, options: {
119
+ revision: () => number;
120
+ subscribe: (listener: () => void) => () => void;
121
+ beatMs?: number;
122
+ gatherMs?: number;
123
+ }): Socket;
124
+ /** The install manifest's fields an app sets. */
125
+ export type Manifest = {
126
+ id: string;
127
+ name: string;
128
+ short_name: string;
129
+ description?: string;
130
+ start_url: string;
131
+ scope: string;
132
+ display: "standalone" | "fullscreen" | "minimal-ui" | "browser";
133
+ background_color: string;
134
+ theme_color: string;
135
+ icons: {
136
+ src: string;
137
+ sizes: string;
138
+ type: string;
139
+ purpose?: string;
140
+ }[];
141
+ };
142
+ /**
143
+ * An app's web server: `serveWeb` with the sync routes, the poke socket, the session cookie `<name>_session` and the
144
+ * install manifest made from the name (black, `/icon.svg`), each field overridable. Extra routes are served beside them.
145
+ */
146
+ /** What `serveSync` takes: `serveWeb`'s options, less what it makes from these. */
147
+ export type SyncServerOptions<R, S, C, O> = Omit<WebOptions, "routes" | "socket" | "cookie" | "manifest"> & {
148
+ name: string;
149
+ api: SyncApi<R, S, C, O>;
150
+ sync: Sync<R, S, C, O | KitOutcome>;
151
+ /** Where the page's telemetry is written. */
152
+ page: Logger;
153
+ routes?: (Route | RawRoute)[];
154
+ manifest?: Partial<Manifest>;
155
+ };
156
+ export declare function serveSync<R, S, C, O>(options: SyncServerOptions<R, S, C, NoInfer<O>> & {
157
+ api: SyncApi<R, S, C, O>;
158
+ } & Admits<NoInfer<O>>): Promise<Awaited<ReturnType<typeof serveWeb>>>;