@blueshed/joined 0.2.2 → 0.3.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 (209) hide show
  1. package/.claude/skills/joined/SKILL.md +9 -1
  2. package/.claude/skills/joined/reference.md +267 -53
  3. package/.claude/skills/joined-door/SKILL.md +57 -0
  4. package/README.md +19 -50
  5. package/docs/design.md +76 -10
  6. package/docs/introduction.md +18 -18
  7. package/docs/light-and-shadow.svg +1 -1
  8. package/examples/README.md +20 -0
  9. package/examples/account/account.json +1 -0
  10. package/examples/account/derive.ts +41 -0
  11. package/examples/account/generated/elements.ts +52 -0
  12. package/examples/account/generated/rows.ts +22 -0
  13. package/examples/account/generated/rules.ts +32 -0
  14. package/examples/account/routes.ts +5 -0
  15. package/examples/app.css +2 -1
  16. package/examples/cafe/books.html +2 -2
  17. package/examples/cafe/cafe.css +9 -16
  18. package/examples/cafe/generated/books.rows.ts +22 -0
  19. package/examples/cafe/generated/books.rules.ts +3 -2
  20. package/examples/cafe/generated/kitchen.rows.ts +27 -0
  21. package/examples/cafe/generated/kitchen.rules.ts +11 -1
  22. package/examples/cafe/generated/menu.rows.ts +22 -0
  23. package/examples/cafe/generated/menu.rules.ts +3 -2
  24. package/examples/cafe/generated/order.rows.ts +27 -0
  25. package/examples/cafe/generated/order.rules.ts +11 -1
  26. package/examples/cafe/generated/staff.rows.ts +22 -0
  27. package/examples/cafe/generated/staff.rules.ts +6 -1
  28. package/examples/cafe/generated/supplies.queries.ts +4 -2
  29. package/examples/cafe/generated/supplies.rows.ts +22 -0
  30. package/examples/cafe/generated/supplies.rules.ts +12 -1
  31. package/examples/cafe/generated/till.queries.ts +2 -0
  32. package/examples/cafe/generated/till.rows.ts +27 -0
  33. package/examples/cafe/generated/till.rules.ts +11 -1
  34. package/examples/cafe/index.html +14 -15
  35. package/examples/cafe/kitchen.ts +1 -1
  36. package/examples/cafe/look.ts +30 -0
  37. package/examples/cafe/menu.html +10 -26
  38. package/examples/cafe/menu.ts +8 -80
  39. package/examples/cafe/order.html +6 -6
  40. package/examples/cafe/order.ts +5 -1
  41. package/examples/cafe/routes.ts +0 -1
  42. package/examples/cafe/stories.jsonl +3 -1
  43. package/examples/cafe/supplies.html +34 -34
  44. package/examples/cafe/supplies.ts +14 -11
  45. package/examples/cafe/till.ts +5 -1
  46. package/examples/chart/arches.ts +148 -0
  47. package/examples/chart/chart.css +6 -0
  48. package/examples/chart/chart.json +87 -0
  49. package/examples/chart/generated/elements.ts +105 -0
  50. package/examples/chart/generated/queries.ts +36 -0
  51. package/examples/chart/generated/rows.ts +27 -0
  52. package/examples/chart/generated/rules.ts +111 -0
  53. package/examples/chart/grid.ts +118 -0
  54. package/examples/chart/index.html +78 -0
  55. package/examples/chart/migrations/001-chart.ts +6 -0
  56. package/examples/chart/migrations/002-create-conditions.ts +6 -0
  57. package/examples/chart/page.ts +20 -0
  58. package/examples/chart/routes.ts +7 -0
  59. package/examples/chart/stories.jsonl +14 -0
  60. package/examples/chart/teeth.ts +57 -0
  61. package/examples/desk/generated/rows.ts +22 -0
  62. package/examples/desk/generated/rules.ts +34 -1
  63. package/examples/desk/index.html +9 -2
  64. package/examples/desk/routes.ts +0 -2
  65. package/examples/desk/stories.jsonl +3 -2
  66. package/examples/desk/thumbs.ts +2 -2
  67. package/examples/hello/generated/elements.ts +2 -2
  68. package/examples/hello/generated/rules.ts +3 -2
  69. package/examples/hello/hello.css +2 -4
  70. package/examples/hello/index.html +10 -3
  71. package/examples/hello/page.ts +4 -4
  72. package/examples/index.html +4 -5
  73. package/examples/notes/generated/elements.ts +112 -0
  74. package/examples/notes/generated/queries.ts +36 -0
  75. package/examples/notes/generated/rows.ts +27 -0
  76. package/examples/notes/generated/rules.ts +133 -0
  77. package/examples/notes/index.html +32 -0
  78. package/examples/notes/look.ts +41 -0
  79. package/examples/notes/migrations/001-notes.ts +7 -0
  80. package/examples/notes/notes.json +78 -0
  81. package/examples/notes/page.ts +21 -0
  82. package/examples/notes/routes.ts +6 -0
  83. package/examples/notes/stories.jsonl +21 -0
  84. package/examples/people/generated/rows.ts +22 -0
  85. package/examples/people/generated/rules.ts +11 -1
  86. package/examples/people/links.ts +2 -1
  87. package/examples/people/routes.ts +1 -3
  88. package/examples/people/stories.jsonl +1 -0
  89. package/examples/people/view.ts +5 -2
  90. package/examples/trip/generated/elements.ts +4 -2
  91. package/examples/trip/generated/queries.ts +12 -1
  92. package/examples/trip/generated/rows.ts +27 -0
  93. package/examples/trip/generated/rules.ts +56 -2
  94. package/examples/trip/index.html +58 -12
  95. package/examples/trip/line.css +186 -0
  96. package/examples/trip/line.ts +51 -40
  97. package/examples/trip/page.ts +65 -71
  98. package/examples/trip/routes.ts +9 -5
  99. package/examples/trip/stays.css +12 -12
  100. package/examples/trip/stays.ts +15 -10
  101. package/examples/trip/stories.jsonl +2 -0
  102. package/examples/trip/told.ts +3 -26
  103. package/examples/trip/trip.css +16 -0
  104. package/examples/trips/generated/rows.ts +22 -0
  105. package/examples/trips/generated/rules.ts +9 -1
  106. package/examples/trips/index.html +10 -10
  107. package/examples/trips/map.ts +3 -14
  108. package/examples/trips/new-trip.ts +14 -16
  109. package/examples/weeks/generated/elements.ts +1 -1
  110. package/examples/weeks/generated/queries.ts +11 -0
  111. package/examples/weeks/generated/rows.ts +22 -0
  112. package/examples/weeks/generated/rules.ts +11 -5
  113. package/examples/weeks/routes.ts +3 -2
  114. package/examples/weeks/stories.jsonl +1 -0
  115. package/examples/welcome.css +7 -5
  116. package/package.json +8 -2
  117. package/src/awesome.ts +103 -0
  118. package/src/board.css +75 -0
  119. package/src/board.ts +173 -0
  120. package/src/cli.ts +15 -2
  121. package/src/compile.ts +569 -35
  122. package/src/definitions.ts +53 -15
  123. package/src/draft.ts +38 -23
  124. package/src/drawer.ts +222 -0
  125. package/src/engine.ts +240 -166
  126. package/src/fields.ts +268 -0
  127. package/src/files.ts +6 -4
  128. package/src/ground.ts +110 -0
  129. package/src/icon-names.ts +15 -2
  130. package/src/kit.ts +51 -0
  131. package/src/link.ts +3 -3
  132. package/src/map.css +133 -0
  133. package/src/map.ts +200 -0
  134. package/src/mcp.ts +106 -22
  135. package/src/members/demo.ts +13 -12
  136. package/src/members/generated/rows.ts +22 -0
  137. package/src/members/generated/rules.ts +3 -2
  138. package/src/members/group.ts +65 -39
  139. package/src/members/keys.ts +93 -77
  140. package/src/members/panel.css +23 -17
  141. package/src/members/panel.ts +49 -35
  142. package/src/migrate.ts +120 -104
  143. package/src/month.css +125 -0
  144. package/src/month.ts +179 -0
  145. package/src/page.css +8 -0
  146. package/src/page.ts +7 -4
  147. package/src/parts.css +462 -170
  148. package/src/parts.ts +209 -26
  149. package/src/plane.css +56 -0
  150. package/src/plane.ts +151 -0
  151. package/src/postgres-server.ts +60 -0
  152. package/src/reading.css +77 -0
  153. package/src/reading.ts +238 -0
  154. package/src/rows.css +308 -0
  155. package/src/rows.ts +780 -0
  156. package/src/search.css +80 -0
  157. package/src/search.ts +130 -0
  158. package/src/server.ts +205 -114
  159. package/src/settings.ts +9 -4
  160. package/src/sheet.ts +114 -0
  161. package/src/skill.ts +40 -0
  162. package/src/slots.css +94 -0
  163. package/src/slots.ts +213 -0
  164. package/src/specs.ts +38 -0
  165. package/src/starter.ts +5 -2
  166. package/src/store.ts +184 -143
  167. package/src/stories.ts +43 -11
  168. package/src/surface.ts +159 -0
  169. package/src/timeline.css +111 -0
  170. package/src/timeline.ts +226 -0
  171. package/src/toast.ts +21 -48
  172. package/src/together.ts +0 -7
  173. package/src/tokens.css +78 -1
  174. package/src/tokens.json +249 -0
  175. package/src/tool.ts +211 -0
  176. package/src/upkeep.ts +18 -20
  177. package/src/views.css +44 -0
  178. package/src/views.ts +94 -0
  179. package/src/week.css +151 -0
  180. package/src/week.ts +250 -0
  181. package/src/write.ts +202 -69
  182. package/starter/CLAUDE.md +3 -3
  183. package/starter/bunfig +4 -0
  184. package/starter/prettierignore +4 -0
  185. package/starter/tests/hello.test.ts +2 -0
  186. package/docs/learning.md +0 -76
  187. package/examples/cafe/trust.ts +0 -20
  188. package/examples/desk/trust.ts +0 -24
  189. package/examples/people/trust.ts +0 -14
  190. package/examples/trip/answer-rows.ts +0 -70
  191. package/examples/trip/bar.ts +0 -89
  192. package/examples/trip/calendar-map.css +0 -711
  193. package/examples/trip/calendar-map.ts +0 -249
  194. package/examples/trip/drags.ts +0 -143
  195. package/examples/trip/drawer.ts +0 -250
  196. package/examples/trip/event-form.ts +0 -200
  197. package/examples/trip/holding.ts +0 -61
  198. package/examples/trip/map.ts +0 -234
  199. package/examples/trip/month.ts +0 -87
  200. package/examples/trip/other-weeks.ts +0 -67
  201. package/examples/trip/peek.ts +0 -71
  202. package/examples/trip/people-chips.ts +0 -74
  203. package/examples/trip/shell.ts +0 -39
  204. package/examples/trip/trust.ts +0 -51
  205. package/examples/trip/week.ts +0 -237
  206. package/examples/trip/writes.ts +0 -91
  207. package/examples/trip/zones.ts +0 -16
  208. package/examples/weeks/derive.ts +0 -23
  209. package/src/scrim.ts +0 -81
package/src/server.ts CHANGED
@@ -98,12 +98,16 @@ const anotherSite = (req: Request) => {
98
98
  return !!origin && (!URL.canParse(origin) || new URL(origin).host !== new URL(req.url).host);
99
99
  };
100
100
 
101
+ /** What fails in the background (a change told, the clock, another server's change heard), said, and the server goes on. */
102
+ const failed = (what: string) => (e: unknown) => console.error(`${what} failed:`, e);
103
+
101
104
  /** joined's icon (an elephant in wood joinery, its trunk a j), 180 square. */
102
105
  const ICON = `${import.meta.dir}/icon.png`;
103
106
 
104
107
  /** A write by the server itself, a route's or a job's: shaped as the stories say, but asked of no roles and no
105
- * trust.ts, since it's the app's own; landed with what follows from it, and told. Its change, or Refused. */
106
- export type Write = (doc: string, ops: Op[]) => Change;
108
+ * trust.ts, since it's the app's own; landed with what follows from it, and told. Its change, or Refused, once it
109
+ * has (await it). A route reads what it needs before it writes. */
110
+ export type Write = (doc: string, ops: Op[]) => Promise<Change>;
107
111
  /** A derived document (its app's derive.ts, exported from its routes.ts): what it is now, for a member (nobody, 0),
108
112
  * read off the documents it's derived from. Read-only: its pages write the documents it's read from. */
109
113
  export type Derive = (read: Read, member: number) => Record<string, { id: number }[]>;
@@ -228,7 +232,18 @@ export async function start({
228
232
  : [],
229
233
  );
230
234
  for (const { rules: r } of held) rules[r.doc] = r;
231
- const trusts = Object.fromEntries(apps.flatMap((a) => (a.trust ? docsOf(a).map((d) => [d.doc, a.trust!]) : [])));
235
+ // each app's own rules, and how many writes each has refused: its stories, told, hold it to one (src/stories.ts)
236
+ const ruled = new Map(apps.flatMap((a) => (a.trust ? [[a.app, 0] as [string, number]] : [])));
237
+ const noting =
238
+ (app: string, trust: Trust): Trust =>
239
+ (...asked) => {
240
+ const why = trust(...asked);
241
+ if (why) ruled.set(app, ruled.get(app)! + 1);
242
+ return why;
243
+ };
244
+ const trusts = Object.fromEntries(
245
+ apps.flatMap((a) => (a.trust ? docsOf(a).map((d) => [d.doc, noting(a.app, a.trust!)]) : [])),
246
+ );
232
247
  const reacts = Object.fromEntries(
233
248
  apps.flatMap((a) => (a.reactions ? docsOf(a).map((d) => [d.doc, a.reactions!]) : [])),
234
249
  );
@@ -258,12 +273,12 @@ export async function start({
258
273
  // a static document is its seed: a release's, past the store's version, is taken in place of what was
259
274
  if (r.type === "static") {
260
275
  const seed = await Bun.file(await seedOf(at, r.doc)).json();
261
- if (!store.holds(r.doc) || seed.version > store.read(r.doc).version)
262
- taken.push({ doc: r.doc, json: seed, again: store.holds(r.doc) });
276
+ const had = await store.holds(r.doc);
277
+ if (!had || seed.version > (await store.read(r.doc)).version) taken.push({ doc: r.doc, json: seed, again: had });
263
278
  continue;
264
279
  }
265
280
  // a document read by member is a query over others' rows: there's nothing of its own to begin
266
- if (r.derived || r.member || store.holds(r.doc)) continue;
281
+ if (r.derived || r.member || (await store.holds(r.doc))) continue;
267
282
  const before = data[r.doc] ?? `${DATA}/${r.doc}.json`;
268
283
  const kept = await Bun.file(before).exists();
269
284
  const seed = await seedOf(at, r.doc);
@@ -272,26 +287,28 @@ export async function start({
272
287
  const json = (await from.exists()) ? await from.json() : { version: 1 };
273
288
  taken.push({ doc: r.doc, json, ...(kept ? { kept: before } : {}) });
274
289
  }
275
- store.takeAll(taken);
290
+ await store.takeAll(taken);
276
291
  for (const { kept } of taken) if (kept && lasts) renameSync(kept, `${kept}.imported`);
277
- // (a SQLite file's: a Postgres store's vacuum and backups aren't joined's, nor letting its files go); a file nothing
278
- // names is let go once it's older than the history, and than a week's backups, which may name it still
292
+ // (old changes and files on any store; vacuum and backups a SQLite file's alone, Postgres keeping its own); a file
293
+ // nothing names is let go once it's older than the history, and than a week's backups, which may name it still
279
294
  const tables = held.filter((h) => !h.rules.derived && !h.rules.member).map((h) => h.rules),
280
295
  filesKept = typeof files === "string" ? filesAt(files) : files;
281
- const kept =
282
- lasts && engine === "sqlite"
283
- ? upkeep(store.db, backups, console.log, {
284
- trim: () => store.trim(Date.now() - history * DAY),
285
- letGo: () => letGo(filesKept, named(store.db, tables), Date.now() - Math.max(history, KEEP) * DAY),
286
- })
287
- : null;
288
- const { land, view, ungranted, ask, read, rulesOf, mayHold, mayOf, groupless, byCode, exists } = writes({
289
- store,
290
- rules,
291
- group: GROUP,
292
- trusts,
293
- reacts,
294
- });
296
+ const kept = lasts
297
+ ? upkeep(store.db, backups, console.log, {
298
+ sqlite: engine === "sqlite",
299
+ trim: () => store.trim(Date.now() - history * DAY),
300
+ letGo: async () => letGo(filesKept, await named(store.db, tables), Date.now() - Math.max(history, KEEP) * DAY),
301
+ })
302
+ : null;
303
+ const { land, view, ungranted, ask, read, settle, now, wrote, rulesOf, mayHold, mayOf, groupless, byCode, exists } =
304
+ writes({
305
+ store,
306
+ rules,
307
+ group: GROUP,
308
+ trusts,
309
+ reacts,
310
+ open: !(members && rootToken),
311
+ });
295
312
 
296
313
  // What each page holds beside whole documents, by its topic: a window of one (trip?week=2026-11-02), or a document as
297
314
  // a person sees it (`<doc>@<member>`, nobody 0), where that's only some of it (owns) or it's read as each has it;
@@ -320,9 +337,11 @@ export async function start({
320
337
  };
321
338
  /** What landed, published once it has committed: each change to its document's topic (a document seen whole), and
322
339
  * what's told to each window and view; and each document derived from one of them, derived again for each page
323
- * holding it. The one place anything is published: here, once the store's write commits; on Postgres, as each
324
- * commit is notified. */
325
- const tell = ({ changes, told }: { changes: Change[]; told: Told }) => {
340
+ * holding it. The one place anything is published: here, once the store's write commits. */
341
+ let telling = Promise.resolve();
342
+ const tell = (landed: { changes: Change[]; told: Told }) =>
343
+ (telling = telling.then(() => toldAll(landed)).catch(failed("telling a change")));
344
+ async function toldAll({ changes, told }: { changes: Change[]; told: Told }) {
326
345
  const written = new Set(changes.map((change) => docParts(change.doc).name));
327
346
  // a page holding a document by a root item's code (an instance, or the root's own), where the root's document
328
347
  // changed (its level, its code), asked again whether it may hold it, and refused as at the door if not, before
@@ -330,7 +349,8 @@ export async function start({
330
349
  for (const ws of pages)
331
350
  for (const doc of ws.data.docs) {
332
351
  const root = !derives.has(doc) && byCode(doc);
333
- const no = root && written.has(root) && mayHold(doc, ws.data.who?.member ?? null, !(members && rootToken));
352
+ const no =
353
+ root && written.has(root) && (await mayHold(doc, ws.data.who?.member ?? null, !(members && rootToken)));
334
354
  if (no)
335
355
  (ws.data.docs.delete(doc),
336
356
  ws.unsubscribe(topicOf(ws, doc)),
@@ -350,12 +370,12 @@ export async function start({
350
370
  }
351
371
  for (const doc of derives.keys())
352
372
  if (rulesOf(doc).derived!.some((d) => written.has(d)))
353
- for (const ws of pages) if (ws.data.docs.has(doc)) derivedTo(ws, doc);
373
+ for (const ws of pages) if (ws.data.docs.has(doc)) await derivedTo(ws, doc);
354
374
  // what each page's person may do, where the write changed it (an item come or moved, a role gained): worked out
355
375
  // once for each person and document, however many pages they have open
356
376
  const asked = new Map<string, ReturnType<typeof mayIn>>();
357
- for (const ws of pages) for (const doc of ws.data.docs) if (!derives.has(doc)) mayTo(ws, doc, asked);
358
- };
377
+ for (const ws of pages) for (const doc of ws.data.docs) if (!derives.has(doc)) await mayTo(ws, doc, asked);
378
+ }
359
379
  /** What each page was last sent of each derived document (by its name) and told it may do in each it holds
360
380
  * (`may <doc>`): each sent again only when it's changed. */
361
381
  const last = new WeakMap<ServerWebSocket<Data>, Map<string, string>>();
@@ -371,32 +391,40 @@ export async function start({
371
391
  );
372
392
  /** A derived document, as a page's member has it now, sent to the page if it isn't what it was sent last; its
373
393
  * version, the sum of the versions of the documents it's derived from. */
374
- function derivedTo(ws: ServerWebSocket<Data>, doc: string) {
375
- const value = derives.get(doc)!(read, ws.data.who?.member ?? 0);
394
+ async function derivedTo(ws: ServerWebSocket<Data>, doc: string) {
395
+ const value = await settle((read) => derives.get(doc)!(read, ws.data.who?.member ?? 0));
376
396
  if (!fresh(ws, doc, JSON.stringify(value))) return;
377
- const version = rulesOf(doc).derived!.reduce((n, d) => n + store.versions(d), 0);
397
+ const version = await versionsOf(doc);
378
398
  say(ws, { doc, version, ops: [{ op: "replace", path: "", value }] });
379
399
  }
380
400
  /** What a person may do in a document they hold (src/write.ts, mayOf): nothing, where the group would refuse them any
381
401
  * write (removed, read-only, not signed in), but in a document that's anonymous, which is anyone's, or as a
382
402
  * stranger its guest. */
383
- const mayIn = (doc: string, who: Data["who"]) =>
384
- groupless(doc, who) || !("refused" in group.write(docParts(doc).base, [], who))
403
+ const mayIn = async (doc: string, who: Data["who"]): ReturnType<typeof mayOf> =>
404
+ groupless(doc, who) || !("refused" in (await group.write(docParts(doc).base, [], who)))
385
405
  ? mayOf(doc, who?.member ?? null)
386
406
  : {};
407
+ /** A derived document's version: the sum of the versions of the documents it's derived from. */
408
+ const versionsOf = async (doc: string) => {
409
+ let n = 0;
410
+ for (const d of rulesOf(doc).derived!) n += await store.versions(d);
411
+ return n;
412
+ };
387
413
  /** What a page's person may do in a document, told to the page (`{ doc, may }`) if it isn't what it was told last. */
388
- function mayTo(ws: ServerWebSocket<Data>, doc: string, asked?: Map<string, ReturnType<typeof mayIn>>) {
414
+ async function mayTo(ws: ServerWebSocket<Data>, doc: string, asked?: Map<string, ReturnType<typeof mayIn>>) {
389
415
  const key = `${doc} ${ws.data.who?.member ?? ""} ${ws.data.who?.agent?.id ?? ""}`;
390
- const may = asked?.get(key) ?? mayIn(doc, ws.data.who);
391
- asked?.set(key, may);
416
+ const asking = asked?.get(key) ?? mayIn(doc, ws.data.who);
417
+ asked?.set(key, asking);
418
+ const may = await asking;
392
419
  if (fresh(ws, `may ${doc}`, JSON.stringify(may))) say(ws, { doc, may });
393
420
  }
394
- const write: Write = (doc, ops) => {
395
- if (docParts(doc).name === GROUP || !store.exists(doc)) throw new Refused(`the server can't write ${doc}`);
396
- const why = ungranted(doc, ops, null);
421
+ const write: Write = async (doc, ops) => {
422
+ wrote();
423
+ if (docParts(doc).name === GROUP || !(await store.exists(doc))) throw new Refused(`the server can't write ${doc}`);
424
+ const why = await ungranted(doc, ops, null);
397
425
  if (why) throw new Refused(why);
398
- const landed = land([{ doc, ops }], null, null, { held: pagesHold() });
399
- tell(landed);
426
+ const landed = await land([{ doc, ops }], null, null, { held: pagesHold() });
427
+ await tell(landed);
400
428
  retime();
401
429
  return landed.changes[0]!;
402
430
  };
@@ -404,16 +432,16 @@ export async function start({
404
432
  * since), written as the server's own write, by whoever undoes it, and told as any change is; what the rules
405
433
  * over values did as it was made, they undo as it's undone. An undo undone is a redo. Never the group's: its links
406
434
  * and its keys aren't put back. */
407
- const undo = (name: string, version: number, by: number | null = null) => {
435
+ const undo = async (name: string, version: number, by: number | null = null) => {
408
436
  // a window's change is its document's
409
437
  const doc = docParts(name).base;
410
438
  if (docParts(doc).name === GROUP) throw new Refused("the group's changes aren't undone");
411
- const ops = store.undoing(doc, version);
439
+ const ops = await store.undoing(doc, version);
412
440
  // held to the stories as any write is
413
- const why = ungranted(doc, ops, null, true, true);
441
+ const why = await ungranted(doc, ops, null, true, true);
414
442
  if (why) throw new Refused(why);
415
- const landed = land([{ doc, ops }], by, null, { undoes: version, held: pagesHold() });
416
- tell(landed);
443
+ const landed = await land([{ doc, ops }], by, null, { undoes: version, held: pagesHold() });
444
+ await tell(landed);
417
445
  retime();
418
446
  return landed.changes[0]!;
419
447
  };
@@ -431,12 +459,16 @@ export async function start({
431
459
  lasts,
432
460
  read,
433
461
  // what each member may hold (asked once the server's made, as each page is told who it is)
434
- holds: (member) => Object.keys(rules).filter((doc) => doc !== GROUP && !mayRead(doc, member)),
462
+ holds: async (member) => {
463
+ const docs: string[] = [];
464
+ for (const doc of Object.keys(rules)) if (doc !== GROUP && !(await mayRead(doc, member))) docs.push(doc);
465
+ return docs;
466
+ },
435
467
  // a demo's, from this machine alone: asked once the server listens, of each request
436
468
  demo: demo ? (req) => fromHere(req, server.requestIP(req)?.address) : undefined,
437
469
  // in by their link: the act their invitation names, done for them as them, once, then gone
438
470
  accepted: async (who) => {
439
- const act = (read(GROUP).members as Member[]).find((m) => m.id === who.member)?.act;
471
+ const act = ((await read(GROUP)).members as Member[]).find((m) => m.id === who.member)?.act;
440
472
  if (!act) return;
441
473
  const [name = "", word = ""] = act.split(" ");
442
474
  const w = acts[name]?.(who.member, word);
@@ -453,14 +485,14 @@ export async function start({
453
485
  // group's, then every app's, and no path answered by two; an app's edge is guarded by the group
454
486
  const icon = () => new Response(Bun.file(ICON));
455
487
  /** Whether a member may read a document: why not, or nothing (as the door and /export ask it). */
456
- const mayRead = (doc: string, member: number) =>
457
- derives.has(doc) || exists(doc) ? mayHold(doc, member, false) : `there's no document called ${doc}`;
488
+ const mayRead = async (doc: string, member: number) =>
489
+ derives.has(doc) || (await exists(doc)) ? mayHold(doc, member, false) : `there's no document called ${doc}`;
458
490
  /** A document as a member sees it, with its version (a derived one's, the sum of what it's derived from). */
459
- const asMember = (doc: string, member: number) =>
491
+ const asMember = async (doc: string, member: number): Promise<Doc> =>
460
492
  derives.has(doc)
461
493
  ? {
462
- version: rulesOf(doc).derived!.reduce((n, d) => n + store.versions(d), 0),
463
- ...derives.get(doc)!(read, member),
494
+ version: await versionsOf(doc),
495
+ ...(await settle((read) => derives.get(doc)!(read, member))),
464
496
  }
465
497
  : view(doc, member);
466
498
  /** The MCP door, for an agent's link (src/mcp.ts): the documents' rules, read and written as a page does. */
@@ -479,10 +511,12 @@ export async function start({
479
511
  if (anotherSite(req)) return "another site";
480
512
  const signed = await group.at(req),
481
513
  who = signed instanceof Response ? null : signed;
482
- if (!store.exists(doc)) return `there's no document called ${doc}`;
514
+ if (!(await store.exists(doc))) return `there's no document called ${doc}`;
483
515
  return (
484
- mayHold(doc, who?.member ?? null, !(members && rootToken)) ??
485
- (putsFile(rulesOf(doc).collections, mayIn(doc, who)) ? null : `you may not put a file in ${docParts(doc).base}`)
516
+ (await mayHold(doc, who?.member ?? null, !(members && rootToken))) ??
517
+ (putsFile(rulesOf(doc).collections, await mayIn(doc, who))
518
+ ? null
519
+ : `you may not put a file in ${docParts(doc).base}`)
486
520
  );
487
521
  };
488
522
  const routes: Routes = {
@@ -494,14 +528,16 @@ export async function start({
494
528
  ...group.routes,
495
529
  // everything a member can see, as JSON: each document as they see it, each kind's instances by their key; theirs
496
530
  // to keep, or to take elsewhere
497
- "/export": group.edge((_req, who) => {
531
+ "/export": group.edge(async (_req, who) => {
498
532
  const member = who?.member ?? 0,
499
533
  everything: Record<string, unknown> = {};
500
534
  for (const r of Object.values(rules)) {
501
535
  const docs = r.kind
502
- ? ((asMember(r.kind.doc, member)[r.kind.root] ?? []) as { id: number }[]).map((i) => `${r.doc}:${i.id}`)
536
+ ? (((await asMember(r.kind.doc, member))[r.kind.root] ?? []) as { id: number }[]).map(
537
+ (i) => `${r.doc}:${i.id}`,
538
+ )
503
539
  : [r.doc];
504
- for (const doc of docs) if (!mayRead(doc, member)) everything[doc] = asMember(doc, member);
540
+ for (const doc of docs) if (!(await mayRead(doc, member))) everything[doc] = await asMember(doc, member);
505
541
  }
506
542
  return Response.json(everything, { headers: { "content-disposition": 'attachment; filename="joined.json"' } });
507
543
  }),
@@ -512,8 +548,14 @@ export async function start({
512
548
  // a file a document names: sent by whoever may put one in it, kept by its hash, and served for good
513
549
  ...fileRoutes(filesKept, mayPut),
514
550
  };
551
+ // an app's routes read the documents at once, as its rules do: each handler is run in settle, again until every
552
+ // document it reads is here (src/write.ts)
553
+ const settled =
554
+ <A extends unknown[]>(fn: (...a: A) => Response | Promise<Response>) =>
555
+ async (...a: A): Promise<Response> =>
556
+ await settle(async () => await fn(...a));
515
557
  for (const { app, routes: of = {} } of apps)
516
- for (const [path, answer] of Object.entries(typeof of === "function" ? of(read, write) : of)) {
558
+ for (const [path, answer] of Object.entries(typeof of === "function" ? of(now, write) : of)) {
517
559
  if (path in routes) throw new Error(`${app || "the root"} and another app both answer ${path}`);
518
560
  // a page (Bun's bundle of its index.html) is kept at /_page<path>, and served at its own path rendered
519
561
  if (typeof answer === "object" && "index" in answer) {
@@ -523,21 +565,25 @@ export async function start({
523
565
  }
524
566
  routes[path] =
525
567
  typeof answer === "function"
526
- ? group.edge(answer)
568
+ ? group.edge(settled(answer))
527
569
  : answer instanceof Response
528
570
  ? answer
529
- : Object.fromEntries(Object.entries(answer).map(([method, fn]) => [method, group.edge(fn as Handler)]));
571
+ : Object.fromEntries(
572
+ Object.entries(answer).map(([method, fn]) => [method, group.edge(settled(fn as Handler))]),
573
+ );
530
574
  }
531
575
  // an app's open routes, anyone's and never guarded: each document read as nobody (owns and sees apply, the group's
532
576
  // door doesn't), so each shows only what it picks
533
- const nobody: Read = (doc) => read(doc, 0);
577
+ const nobody: Read = (doc) => now(doc, 0);
534
578
  for (const { app, open: of = {} } of apps)
535
579
  for (const [path, answer] of Object.entries(typeof of === "function" ? of(nobody) : of)) {
536
580
  if (path in routes) throw new Error(`${app || "the root"} and another app both answer ${path}`);
537
- routes[path] = answer;
581
+ routes[path] = typeof answer === "function" ? settled(answer) : answer;
538
582
  }
539
583
 
540
584
  const pages = new Set<ServerWebSocket<Data>>();
585
+ /** The messages a page sent that are being answered, waited for as the server stops. */
586
+ const answering = new Set<Promise<unknown>>();
541
587
 
542
588
  // A page served with its documents in it: each collection element it holds filled with its items, as the
543
589
  // person asking sees them, and each document's version on <body>, so the page subscribes since it and is sent only
@@ -562,7 +608,9 @@ export async function start({
562
608
  for (const [place, { doc }] of places)
563
609
  finding.on(place, { element: (el) => void docs.add(el.getAttribute("doc") ?? doc) });
564
610
  await finding.transform(new Response(html)).text();
565
- const page = { html, docs: [...docs].filter((d) => exists(d)) };
611
+ const held: string[] = [];
612
+ for (const d of docs) if (await exists(d)) held.push(d);
613
+ const page = { html, docs: held };
566
614
  if (production) shells.set(path, page);
567
615
  return page;
568
616
  }
@@ -582,11 +630,16 @@ export async function start({
582
630
  who = signed instanceof Response ? null : signed;
583
631
  // a stranger is served the page as it is, but for what's anonymous, which is anyone's; and anyone, only what
584
632
  // they may hold (a cook, none of the till's orders)
585
- const held = docs.filter(
586
- (d) => (who || !members || rulesOf(d).anonymous) && !mayHold(d, who?.member ?? null, !(members && rootToken)),
587
- );
588
- const seen = new Map(held.map((d) => [d, view(d, who?.member ?? 0)]));
589
- const may = new Map(held.map((d) => [d, mayIn(d, who)]));
633
+ const seen = new Map<string, Doc>(),
634
+ may = new Map<string, Awaited<ReturnType<typeof mayIn>>>();
635
+ for (const d of docs)
636
+ if (
637
+ (who || !members || rulesOf(d).anonymous) &&
638
+ !(await mayHold(d, who?.member ?? null, !(members && rootToken)))
639
+ ) {
640
+ seen.set(d, await view(d, who?.member ?? 0));
641
+ may.set(d, await mayIn(d, who));
642
+ }
590
643
  const filling = new HTMLRewriter().on("body", {
591
644
  element(el) {
592
645
  el.setAttribute("data-build", build);
@@ -624,17 +677,18 @@ export async function start({
624
677
  // or without, a collection of it put back on the page (another kept it held meanwhile): it's sent whole.
625
678
  if (m.subscribe !== undefined) {
626
679
  const doc = m.subscribe;
680
+ if (!derives.has(doc) && !(await exists(doc)))
681
+ return say(ws, { doc, refused: true, why: `there's no document called ${doc}` });
682
+ // a stranger's page, on a group that's invite-only, holds what's anonymous alone, or an item's own as its guest;
683
+ // a document only some may hold (its where's), those its roles name; a derived one too
684
+ const no = await mayHold(doc, ws.data.who?.member ?? null, !(members && rootToken));
685
+ if (no) return say(ws, { doc, refused: true, why: no });
627
686
  // a derived document is derived for the page, and sent whole, subscribed again or not
628
687
  if (derives.has(doc)) {
629
688
  ws.data.docs.add(doc);
630
689
  forget(ws, doc);
631
- return derivedTo(ws, doc);
690
+ return await derivedTo(ws, doc);
632
691
  }
633
- if (!exists(doc)) return say(ws, { doc, refused: true, why: `there's no document called ${doc}` });
634
- // a stranger's page, on a group that's invite-only, holds what's anonymous alone, or an item's own as its guest;
635
- // a document only some may hold (its where's), those its roles name
636
- const no = mayHold(doc, ws.data.who?.member ?? null, !(members && rootToken));
637
- if (no) return say(ws, { doc, refused: true, why: no });
638
692
  // a static document is read with its page, and changes only with a release: there's nothing to be told
639
693
  if (rulesOf(doc).type === "static")
640
694
  return say(ws, { doc, refused: true, why: `${doc} is static: it changes only with a release` });
@@ -644,11 +698,11 @@ export async function start({
644
698
  const topic = topicOf(ws, doc),
645
699
  part = isPart(doc, topic);
646
700
  ws.subscribe(topic);
647
- const missed = m.since === undefined || part ? null : store.since(doc, m.since);
701
+ const missed = m.since === undefined || part ? null : await store.since(doc, m.since);
648
702
  if (missed) for (const c of missed) say(ws, c);
649
703
  else {
650
704
  const member = ws.data.who?.member ?? 0;
651
- const { version, ...value } = view(doc, member);
705
+ const { version, ...value } = await view(doc, member);
652
706
  const t = part
653
707
  ? (topics.get(topic) ??
654
708
  topics
@@ -659,7 +713,7 @@ export async function start({
659
713
  }
660
714
  // and what its person may do there, told afresh
661
715
  forget(ws, doc);
662
- mayTo(ws, doc);
716
+ await mayTo(ws, doc);
663
717
  return again ? undefined : group.opened(ws, doc);
664
718
  }
665
719
  // a page unsubscribes from a document (its elements taken off it): it's told it no more
@@ -674,7 +728,7 @@ export async function start({
674
728
  const doc = m.doc!,
675
729
  base = docParts(doc).base,
676
730
  by = who?.member ?? null;
677
- const made = store.change(base, m.undo);
731
+ const made = await store.change(base, m.undo);
678
732
  // nobody's change (a stranger's, the server's own, a rule's, a reaction's) is undone only by the page that made it
679
733
  const no = !ws.data.docs.has(doc)
680
734
  ? `this page isn't subscribed to ${base}`
@@ -688,7 +742,7 @@ export async function start({
688
742
  let w: Written;
689
743
  try {
690
744
  if (no) throw new Refused(no);
691
- w = await written([{ doc, ops: store.undoing(base, m.undo) }], who, m.undo);
745
+ w = await written([{ doc, ops: await store.undoing(base, m.undo) }], who, m.undo);
692
746
  } catch (e) {
693
747
  if (!(e instanceof Refused)) throw e;
694
748
  log?.(`undo ${base} ${m.undo} by ${byOf(who)}: refused, ${e.message}`);
@@ -740,19 +794,19 @@ export async function start({
740
794
  // In the write's transaction, in order, refused at the first that says no: the app's own rules, the grants, and
741
795
  // the group's rules (src/write.ts), and, as its rows are written, the tables' constraints; each part's.
742
796
  const afters: ((applied: Op[]) => Promise<void>)[] = [];
743
- const asked = (name: string, ops: Op[], why?: string) => {
797
+ const asked = async (name: string, ops: Op[], why?: string) => {
744
798
  // each part's document one its writer may hold (a where's holds, a visitor's level): one the write makes
745
799
  // (board:$1) no page has held
746
- const no = mayHold(name, who?.member ?? null, !(members && rootToken));
800
+ const no = await mayHold(name, who?.member ?? null, !(members && rootToken));
747
801
  if (no) throw new Refused(no);
748
802
  let after: (applied: Op[]) => Promise<void> = async () => {};
749
- const asking = ask(
803
+ const asking = await ask(
750
804
  name,
751
805
  ops,
752
806
  why,
753
807
  who,
754
- (doc, ops) => {
755
- const write = group.write(doc, ops, who, why);
808
+ async (doc, ops) => {
809
+ const write = await group.write(doc, ops, who, why);
756
810
  if (!("refused" in write)) after = write.after;
757
811
  return write;
758
812
  },
@@ -762,9 +816,9 @@ export async function start({
762
816
  return asking;
763
817
  };
764
818
  // a write lands whole or not at all, with what follows from it, in the store's one transaction; then it's told
765
- let landed: ReturnType<typeof land>;
819
+ let landed: Awaited<ReturnType<typeof land>>;
766
820
  try {
767
- landed = land(writes, who?.member ?? null, who?.agent?.label ?? null, { undoes, asked, held: pagesHold() });
821
+ landed = await land(writes, who?.member ?? null, who?.agent?.label ?? null, { undoes, asked, held: pagesHold() });
768
822
  } catch (e) {
769
823
  // refused in words; anything else is the server's, logged, and the writer told it wasn't saved
770
824
  if (!(e instanceof Refused)) console.error(`a write to ${doc} failed:`, e);
@@ -772,7 +826,7 @@ export async function start({
772
826
  log?.(`${act} ${doc} by ${by}: refused, ${why}`);
773
827
  return { why };
774
828
  }
775
- tell(landed);
829
+ await tell(landed);
776
830
  retime();
777
831
  const change = landed.parts[0]!;
778
832
  // what follows each part (the group's pages told, a new member's link made), and then the writer's answer:
@@ -814,7 +868,7 @@ export async function start({
814
868
  open(ws) {
815
869
  say(ws, { build });
816
870
  pages.add(ws);
817
- group.admit(ws);
871
+ void group.admit(ws);
818
872
  },
819
873
  close(ws) {
820
874
  pages.delete(ws);
@@ -822,17 +876,23 @@ export async function start({
822
876
  },
823
877
  // a message that isn't one joined reads is refused; one the server fails on is logged and answered, and
824
878
  // the server goes on
825
- async message(ws, text) {
826
- const m = messageOf(String(text));
827
- if (typeof m === "string") return say(ws, { refused: null, why: m });
828
- try {
829
- await answer(ws, m);
830
- // a subscribe with an id is answered once it's done: a page woken asks so, to know its socket's still there
831
- if (m.subscribe !== undefined && m.id !== undefined) say(ws, { done: m.id });
832
- } catch (e) {
833
- console.error("a message failed:", e);
834
- say(ws, { refused: m.id ?? null, why: "The server had a problem with that." });
835
- }
879
+ // a page's messages are answered one at a time, in the order it sent them
880
+ message(ws, text) {
881
+ const queue = (ws.data.queue = (ws.data.queue ?? Promise.resolve()).then(async () => {
882
+ const m = messageOf(String(text));
883
+ if (typeof m === "string") return say(ws, { refused: null, why: m });
884
+ try {
885
+ await answer(ws, m);
886
+ // a subscribe with an id is answered once it's done: a page woken asks so, to know its socket's still there
887
+ if (m.subscribe !== undefined && m.id !== undefined) say(ws, { done: m.id });
888
+ } catch (e) {
889
+ console.error("a message failed:", e);
890
+ say(ws, { refused: m.id ?? null, why: "The server had a problem with that." });
891
+ }
892
+ }));
893
+ // what's being answered is finished before the server stops, and its store closes
894
+ answering.add(queue);
895
+ void queue.finally(() => answering.delete(queue));
836
896
  },
837
897
  },
838
898
  });
@@ -842,21 +902,22 @@ export async function start({
842
902
  const timed = held.flatMap(({ rules: r }) =>
843
903
  Object.entries(r.collections).flatMap(([coll, c]) => (c.timed ? [{ doc: r.doc, coll, field: c.timed }] : [])),
844
904
  );
845
- let clock: ReturnType<typeof setTimeout> | undefined;
846
- function tick() {
905
+ let clock: ReturnType<typeof setTimeout> | undefined,
906
+ ticking = Promise.resolve();
907
+ async function tick(): Promise<void> {
847
908
  clearTimeout(clock);
848
909
  let soonest = Infinity,
849
910
  cleared = false;
850
911
  for (const { doc, coll, field } of timed)
851
- for (const item of read(doc)[coll] as Record<string, any>[]) {
912
+ for (const item of (await read(doc))[coll] as Record<string, any>[]) {
852
913
  const at = Date.parse(item[field] ?? "");
853
914
  if (!(at <= Date.now())) {
854
915
  if (at < soonest) soonest = at;
855
916
  continue;
856
917
  }
857
918
  try {
858
- tell(
859
- land([{ doc, ops: [{ op: "remove", path: `/${coll}/${item.id}/${field}` }] }], null, null, {
919
+ await tell(
920
+ await land([{ doc, ops: [{ op: "remove", path: `/${coll}/${item.id}/${field}` }] }], null, null, {
860
921
  held: pagesHold(),
861
922
  }),
862
923
  );
@@ -867,24 +928,54 @@ export async function start({
867
928
  }
868
929
  }
869
930
  if (cleared) return tick();
870
- if (soonest < Infinity) (clock = setTimeout(tick, Math.min(soonest - Date.now(), LONGEST))).unref();
931
+ if (soonest < Infinity) (clock = setTimeout(retime, Math.min(soonest - Date.now(), LONGEST))).unref();
871
932
  }
872
- /** The clock set again, after a write that may have changed a time. */
933
+ /** The clock set again, after a write that may have changed a time: one look at a time. */
873
934
  function retime() {
874
- if (timed.length) tick();
935
+ if (timed.length) ticking = ticking.then(tick).catch(failed("the clock"));
875
936
  }
876
937
  retime();
877
938
 
939
+ // A change another server on the database made (Postgres: each server hears every commit), told here as this server
940
+ // tells its own: the change to each page holding its document whole, and each part a page holds (a window, what a
941
+ // person sees, a document read off others) sent whole again, as it is now; and where the members changed, every page
942
+ // whose link no longer opens (removed, replaced, taken back) closed.
943
+ async function heard(doc: string, version: number) {
944
+ const c = await store.change(doc, version);
945
+ const by = c?.by ?? null,
946
+ via = c?.via ?? null;
947
+ const told: Told = [];
948
+ for (const [topic, t] of topics) {
949
+ const r = rulesOf(t.doc);
950
+ if (docParts(t.doc).base !== doc && !r.member && !r.view) continue;
951
+ const { version: now, ...value } = await view(t.doc, t.member ?? 0);
952
+ told.push({ topic, change: { doc: t.doc, version: now, ops: [{ op: "replace", path: "", value }], by, via } });
953
+ }
954
+ await tell({ changes: c ? [{ doc, version, ops: c.ops, by, via }] : [], told });
955
+ if (docParts(doc).name === GROUP) await group.heard();
956
+ retime();
957
+ }
958
+ await store.heard((doc, version) => void heard(doc, version).catch(failed(`hearing ${doc}`)));
959
+
878
960
  // stopped, its clock stops too: a time it was waiting for comes to a store that may be closed
879
961
  const stop = server.stop.bind(server);
880
962
  return Object.assign(server, {
881
- stop: (closeActive?: boolean) => (clearTimeout(clock), stop(closeActive)),
963
+ stop: async (closeActive?: boolean) => {
964
+ clearTimeout(clock);
965
+ kept?.stop();
966
+ await stop(closeActive);
967
+ await Promise.all(answering);
968
+ await ticking;
969
+ await telling;
970
+ },
882
971
  apps: apps.map((a) => a.app).filter(Boolean),
883
972
  members,
884
973
  build,
885
974
  // what's answered, without the bundles the pages are rendered from
886
975
  paths: Object.keys(routes).filter((p) => !p.startsWith("/_page")),
887
976
  tokenOf: group.tokenOf,
977
+ /** Each app with rules of its own (a trust.ts), and how many writes they've refused. */
978
+ ruled,
888
979
  read,
889
980
  write,
890
981
  undo,
@@ -896,7 +987,7 @@ export async function start({
896
987
  /** What a server says as it starts: where it is, and the BDFL's link, or that it's open, or has no members. A ROOT_TOKEN
897
988
  * long enough to be a secret is never printed (on Railway, what's printed is in the logs); a short
898
989
  * one, fine on this machine alone, is, with a warning. */
899
- export function startUp(server: Awaited<ReturnType<typeof start>>, root = Bun.env.ROOT_TOKEN) {
990
+ export async function startUp(server: Awaited<ReturnType<typeof start>>, root = Bun.env.ROOT_TOKEN) {
900
991
  const said = [`joined on ${server.url}: ${server.apps.join(", ")}; ${server.paths.join(" ")}`];
901
992
  if (!server.members)
902
993
  return [
@@ -904,7 +995,7 @@ export function startUp(server: Awaited<ReturnType<typeof start>>, root = Bun.en
904
995
  "no members: no story is told as one, so anyone who reaches it may read and write, an agent too, at /mcp",
905
996
  ];
906
997
  if (!root) return [...said, "open: no ROOT_TOKEN, so anyone who reaches it may read and write"];
907
- const bdfl = `${bdflOf(server.read(GROUP).members as Member[])?.name ?? "The BDFL"}'s link (the BDFL's)`;
998
+ const bdfl = `${bdflOf((await server.read(GROUP)).members as Member[])?.name ?? "The BDFL"}'s link (the BDFL's)`;
908
999
  if (root.length >= 32) return [...said, `${bdfl} isn't printed: bun run link <name>, or .railway/root-link`];
909
1000
  return [
910
1001
  ...said,