@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/write.ts CHANGED
@@ -1,4 +1,4 @@
1
- // A write, as the database's transaction holds it (docs/plan.md, The architecture: Write and Broadcast): what an app's
1
+ // A write, as the database's transaction holds it (docs/plan.md, "The four flows": Write and Broadcast): what an app's
2
2
  // own rules say (its trust.ts), what the stories grant, what the server fills and copies, the rows, what the
3
3
  // definitions hold, the rules over values, and what follows (each app's reactions), whole or none of it. Then who is
4
4
  // told: each document holding a row it changed, in its own paths (the store's), and each part of one a page holds
@@ -6,6 +6,7 @@
6
6
  // sees only some of (owns), or one read as each member has it, as they had it and have it now. The server names the
7
7
  // member and passes the write on; it holds none of this.
8
8
 
9
+ import { AsyncLocalStorage } from "node:async_hooks";
9
10
  import { grantOf } from "./definitions.ts";
10
11
  import { docParts, parts, type Change, type Op } from "./ops.ts";
11
12
  import { settled, settingsNow, type Settings } from "./settings.ts";
@@ -20,7 +21,7 @@ import {
20
21
  type Rules as StoreRules,
21
22
  type Store,
22
23
  } from "./store.ts";
23
- import { inTurn, type Part } from "./together.ts";
24
+ import { named, type Part } from "./together.ts";
24
25
  import { admits, guestRole, levelled } from "./visitors.ts";
25
26
 
26
27
  /** A way to read any document as it is now: whole, or as a member sees it (owns). */
@@ -31,6 +32,15 @@ export type Rules = StoreRules & {
31
32
  anonymous?: boolean;
32
33
  derived?: readonly string[];
33
34
  holds?(d: Doc, touched: Record<string, number[]>): string | null;
35
+ /** What its lists hold as a write leaves them (definitions' within and apart), asked on SQLite: Postgres's triggers
36
+ * hold them, at the write's end (the store's settle). */
37
+ listsHold?(d: Doc, touched: Record<string, number[]>): string | null;
38
+ /** The lists that are each member's own (definitions' mine), by collection. */
39
+ mine?: Record<string, string[]>;
40
+ /** The words a write giving or taking another's is refused in, where its mine says them, by collection and field. */
41
+ mineSaid?: Record<string, Record<string, string>>;
42
+ /** The collections of values that are each member's own (definitions' mine, { of, by }), by collection. */
43
+ own?: Record<string, { of: string; by: string }>;
34
44
  grants: Record<string, string[]>;
35
45
  /** Who someone is to it: none, of a derived document. */
36
46
  rolesOf?(m: number, read: Read, doc: string, at?: any): string[];
@@ -67,6 +77,14 @@ export type Held = { windows: string[]; views: { topic: string; doc: string; mem
67
77
  /** What a write tells, past its changes: to each topic a page holds, what changed of it. */
68
78
  export type Told = { topic: string; change: Change & { doc: string } }[];
69
79
 
80
+ /** A document a rule read that isn't held yet: settle reads it, and asks again. */
81
+ class Missing {
82
+ constructor(
83
+ readonly doc: string,
84
+ readonly member?: number,
85
+ ) {}
86
+ }
87
+
70
88
  /** How many rounds of reactions a write may set off before it's refused as never settling. */
71
89
  const ROUNDS = 10;
72
90
 
@@ -76,6 +94,7 @@ export function writes({
76
94
  group,
77
95
  trusts,
78
96
  reacts,
97
+ open = true,
79
98
  }: {
80
99
  store: Store;
81
100
  rules: Record<string, Rules>;
@@ -83,6 +102,8 @@ export function writes({
83
102
  group: string;
84
103
  trusts: Record<string, Trust>;
85
104
  reacts: Record<string, Reactions>;
105
+ /** Whether the group is open (no ROOT_TOKEN): everyone is nobody, and what's granted any member is theirs. */
106
+ open?: boolean;
86
107
  }) {
87
108
  /** A document's rules: an instance of a kind's (shelf:1) are the kind's. */
88
109
  const rulesOf = (doc: string) => rules[docParts(doc).name]!;
@@ -90,7 +111,36 @@ export function writes({
90
111
  * holding an item by its own code) is as the grants say. */
91
112
  const groupless = (doc: string, who: { member: number } | null | undefined) =>
92
113
  !!(rulesOf(doc).anonymous || (!who && rulesOf(doc).guests));
93
- const read: Read = store.read;
114
+ /** The documents a rule reads, as they are now: each read once by the store (it waits for the database), then
115
+ * held while what asks it runs again; the rules themselves, the compiled ones, an app's trust.ts, its reactions and
116
+ * derive.ts, read as they always have, at once (settle). */
117
+ const reading = new AsyncLocalStorage<{ at: Read; wrote: boolean }>();
118
+ const read: Read = (doc, member) => {
119
+ const r = reading.getStore();
120
+ if (!r) throw new Error(`${doc} read outside settle`);
121
+ return r.at(doc, member);
122
+ };
123
+ /** What asks the documents (`fn`, at once, as the rules are), run until every document it reads is here: one it
124
+ * hasn't is read by the store, and it's asked again (it has changed nothing yet). Each settle reads afresh. */
125
+ async function settle<T>(fn: () => T): Promise<T> {
126
+ const held = new Map<string, Doc>();
127
+ const at: Read = (doc, member) => {
128
+ const d = held.get(`${doc}@${member ?? ""}`);
129
+ if (!d) throw new Missing(doc, member);
130
+ return d;
131
+ };
132
+ for (;;) {
133
+ const frame = { at, wrote: false };
134
+ try {
135
+ return await reading.run(frame, fn);
136
+ } catch (e) {
137
+ if (!(e instanceof Missing)) throw e;
138
+ // asked again, a route would write twice: it reads what it needs first
139
+ if (frame.wrote) throw new Error(`${e.doc} was read after a write: read every document before writing`);
140
+ held.set(`${e.doc}@${e.member ?? ""}`, await store.read(e.doc, e.member));
141
+ }
142
+ }
143
+ }
94
144
 
95
145
  /** The kind whose root's own document a page holds by an item's code (`boards?code=…`, a board's secret link, to
96
146
  * draw the board): its guests name the root's code, given alone. None, held otherwise. */
@@ -117,7 +167,7 @@ export function writes({
117
167
  return code && docParts(doc).params[code] !== undefined ? r.kind!.doc : rootKind(doc)?.kind!.doc;
118
168
  };
119
169
  /** Whether a document can be held: one of the store's, or a kind's root by an item's code. */
120
- const exists = (doc: string) => store.exists(rootKind(doc) ? docParts(doc).base : doc);
170
+ const exists = (doc: string): Promise<boolean> => store.exists(rootKind(doc) ? docParts(doc).base : doc);
121
171
  /** A document whole, as a person sees it (nobody: 0): all of it, but for one read as each member has it, or one
122
172
  * each sees only some of (owns): its query, by its member; held by its root's code, all of it; the root's own held by
123
173
  * an item's code, that item alone, past any owns (none: the code is no one's). */
@@ -129,13 +179,14 @@ export function writes({
129
179
  item = codeItem(doc, k, whole);
130
180
  return { version: whole.version, [k.kind!.root]: item ? [item] : [] };
131
181
  }
132
- return (r.member || r.sees) && !byCode(doc) ? store.read(doc, member) : read(doc);
182
+ return (r.member || r.sees) && !byCode(doc) ? read(doc, member) : read(doc);
133
183
  };
134
- /** Whether what's granted anyone (member) is someone's: a member's, or anyone's but a visitor who is nobody, holding
135
- * an instance by its root's code at a level (src/visitors.ts), who may do what its level may alone, or the root's
136
- * own by an item's code, where a guest may do nothing. */
184
+ /** Whether what's granted anyone (member) is someone's: a member's; on an invite-only group, never a stranger's (a
185
+ * guest may do what's granted its guest alone); open, anyone's but a visitor who is nobody, holding an instance by its
186
+ * root's code at a level (src/visitors.ts), who may do what its level may alone, or the root's own by an item's
187
+ * code, where a guest may do nothing. */
137
188
  const anyoneIs = (doc: string, member: number | null) =>
138
- member !== null || !byCode(doc) || (!levelled(rulesOf(doc)) && !rootKind(doc));
189
+ member !== null || (open && (!byCode(doc) || (!levelled(rulesOf(doc)) && !rootKind(doc))));
139
190
 
140
191
  /** Why a write does what no story does (an op of a form no path has, or one no story grants), or what the
141
192
  * writer's roles may not; null if neither. `roles` null: the server's own write, or nobody's on an open group,
@@ -252,13 +303,17 @@ export function writes({
252
303
  // granted any member, or anyone) and none moves it a step from where it is: said once, as "*"
253
304
  const moved = r.moves?.[coll],
254
305
  toItems = Object.entries(r.grants).filter(([g]) => itemToken(g, coll, {}, undefined) !== undefined);
306
+ // (nor where each item is one member's own, definitions' mine: another's is nobody else's to change)
307
+ const own = r.own?.[coll];
255
308
  const same =
309
+ !own &&
256
310
  (anyone || (everyone && toItems.every(([, to]) => to.includes("member")))) &&
257
311
  !toItems.some(([g]) => moved && g.startsWith(`replace ${coll}.${moved}:`));
258
312
  if (same) at["*"] = tokens(coll, {}, (g) => itemToken(g, coll, {}, moved));
259
313
  else
260
314
  for (const item of ((seen ??= view(doc, member ?? 0))[coll] ?? []) as Record<string, unknown>[])
261
- at[String(item.id)] = tokens(coll, item, (g) => itemToken(g, coll, item, moved));
315
+ at[String(item.id)] =
316
+ own && item[own.by] !== member ? "" : tokens(coll, item, (g) => itemToken(g, coll, item, moved));
262
317
  }
263
318
  const said = Object.entries(at).filter(([, t]) => t);
264
319
  if (said.length) may[coll] = Object.fromEntries(said);
@@ -325,6 +380,39 @@ export function writes({
325
380
  }
326
381
  return null;
327
382
  }
383
+ /** Why a write gives or takes another's id in a list that's each member's own (definitions' mine), or null: an id
384
+ * added or taken, a list replaced or removed whole (the ids that changes), or an item added with one. */
385
+ function othersIn(doc: string, ops: Op[], member: number) {
386
+ for (const o of ops) {
387
+ const { coll, key, field, link } = parts(o.path);
388
+ for (const f of rulesOf(doc).mine?.[coll] ?? []) {
389
+ if (field === undefined ? o.op !== "add" : field !== f) continue;
390
+ // a list's ids, or a link's one
391
+ const ids = (v: unknown): number[] => [v ?? []].flat() as number[];
392
+ const had = ids(key !== "-" && link === undefined ? itemAt(doc, o)?.[f] : undefined);
393
+ const has = ids(o.op !== "remove" ? (field === undefined ? o.value?.[f] : o.value) : undefined);
394
+ const changed =
395
+ link !== undefined
396
+ ? [o.op === "add" ? o.value : Number(link)]
397
+ : [...had, ...has].filter((m) => had.includes(m) !== has.includes(m));
398
+ if (changed.some((m) => m !== member))
399
+ return rulesOf(doc).mineSaid?.[coll]?.[f] ?? `${f} is each member's own to give`;
400
+ }
401
+ }
402
+ return null;
403
+ }
404
+ /** Why a write changes or removes another's value in a collection that's each member's own (definitions' mine,
405
+ * { of, by }), or null: an add is its writer's, whose it is being the server's to fill. */
406
+ function othersOwn(doc: string, ops: Op[], member: number) {
407
+ for (const o of ops) {
408
+ const { coll, key } = parts(o.path);
409
+ const own = rulesOf(doc).own?.[coll];
410
+ if (!own || key === "-") continue;
411
+ const whose = itemAt(doc, o)?.[own.by];
412
+ if (whose !== undefined && whose !== member) return `${coll} are each member's own to change`;
413
+ }
414
+ return null;
415
+ }
328
416
  /** The items each collection's ops touched, by id: an add's the id it was given. */
329
417
  function touchedBy(ops: Op[]) {
330
418
  const touched: Record<string, number[]> = {};
@@ -428,44 +516,55 @@ export function writes({
428
516
  * what the stories do, and what the writer's roles may (the grants); of a kind, its root item's settings
429
517
  * (src/settings.ts), so only someone the grants allow hears their words; and the group's rules, which say what lands
430
518
  * with it (`within`). A derived document, or one read as each member has it, is written where it's read from. */
431
- function ask(
519
+ async function ask(
432
520
  doc: string,
433
521
  ops: Op[],
434
522
  why: string | undefined,
435
523
  who: { member: number } | null,
436
- group: (doc: string, ops: Op[]) => { ops: Op[]; within?: (applied: Op[]) => void } | { refused: string },
524
+ group: (
525
+ doc: string,
526
+ ops: Op[],
527
+ ) =>
528
+ | { ops: Op[]; within?: (applied: Op[]) => unknown }
529
+ | { refused: string }
530
+ | Promise<{ ops: Op[]; within?: (applied: Op[]) => unknown } | { refused: string }>,
437
531
  undoing = false,
438
532
  ) {
439
533
  const r = rulesOf(doc);
440
534
  if (r.derived) throw new Refused(`${doc} is derived from ${r.derived.join(" and ")}: write that`);
441
535
  if (r.member) throw new Refused(`${doc} is read off ${r.reads!.join(", ")}: write those`);
442
- const roles = who ? r.rolesOf!(who.member, read, doc) : [];
443
536
  // an anonymous document's writes are anyone's; any other's, each op's by who the writer is to its item
444
- const ruled =
445
- trusts[r.doc]?.({ doc: docParts(doc).base, ops, why }, { member: who?.member ?? 0, roles }, read) ??
446
- // (an undo puts back what the server filled, as it was)
447
- (undoing ? null : serversIn(doc, ops)) ??
448
- // who the writer is to the item each op is to: a member's roles, and a guest's (a page holding the document by
449
- // the item's own code: definitions' guests)
450
- ungranted(
451
- doc,
452
- ops,
453
- !who && r.anonymous ? null : (o) => rolesTo(doc, who?.member ?? null, parts(o.path).coll, itemAt(doc, o)),
454
- anyoneIs(doc, who?.member ?? null),
455
- undoing,
456
- ) ??
457
- // of a kind, what its root item's settings say of a write the grants allow (a frozen board, one held for approval)
458
- settled(
459
- r,
460
- // (an undo puts an item back at the step it had come to: frozen alone refuses it)
461
- ((now) => (undoing ? { ...now, first: {} } : now))(settingsNow(r, () => rootItem(r, doc, read))),
462
- ops,
537
+ const ruled = await settle(() => {
538
+ const roles = who ? r.rolesOf!(who.member, read, doc) : [];
539
+ return (
540
+ trusts[r.doc]?.({ doc: docParts(doc).base, ops, why }, { member: who?.member ?? 0, roles }, read) ??
541
+ othersIn(doc, ops, who?.member ?? 0) ??
542
+ othersOwn(doc, ops, who?.member ?? 0) ??
543
+ // (an undo puts back what the server filled, as it was)
544
+ (undoing ? null : serversIn(doc, ops)) ??
545
+ // who the writer is to the item each op is to: a member's roles, and a guest's (a page holding the document by
546
+ // the item's own code: definitions' guests)
547
+ ungranted(
548
+ doc,
549
+ ops,
550
+ !who && r.anonymous ? null : (o) => rolesTo(doc, who?.member ?? null, parts(o.path).coll, itemAt(doc, o)),
551
+ anyoneIs(doc, who?.member ?? null),
552
+ undoing,
553
+ ) ??
554
+ // of a kind, what its root item's settings say of a write the grants allow (a frozen board, one held for approval)
555
+ settled(
556
+ r,
557
+ // (an undo puts an item back at the step it had come to: frozen alone refuses it)
558
+ ((now) => (undoing ? { ...now, first: {} } : now))(settingsNow(r, () => rootItem(r, doc, read))),
559
+ ops,
560
+ )
463
561
  );
562
+ });
464
563
  if (ruled) throw new Refused(ruled);
465
564
  // a code it makes new, the server's (whatever the page gave), before it's kept
466
565
  ops = renewed(doc, ops);
467
566
  if (groupless(doc, who)) return { ops };
468
- const write = group(docParts(doc).base, ops);
567
+ const write = await group(docParts(doc).base, ops);
469
568
  if ("refused" in write) throw new Refused(write.refused);
470
569
  return write;
471
570
  }
@@ -476,7 +575,7 @@ export function writes({
476
575
  * what's told to each part of a document the pages hold (`held`); and the ops as its parts made them. `asked`: a
477
576
  * page's write, each part asked its rules first, in the transaction; `undoes`, the version the write puts back, if
478
577
  * it's an undo. */
479
- function land(
578
+ async function land(
480
579
  writes: Part[],
481
580
  by: number | null,
482
581
  via: string | null,
@@ -486,23 +585,35 @@ export function writes({
486
585
  held,
487
586
  }: {
488
587
  undoes?: number;
489
- asked?: (doc: string, ops: Op[], why?: string) => { ops: Op[]; within?: (applied: Op[]) => void };
588
+ asked?: (doc: string, ops: Op[], why?: string) => Promise<{ ops: Op[]; within?: (applied: Op[]) => unknown }>;
490
589
  held: Held;
491
590
  },
492
591
  ) {
493
- return store.db.transaction(() => {
592
+ return store.db.transaction(async () => {
494
593
  // what each person holding a part of a document saw of it, before
495
- const before = new Map(held.views.map((v) => [v.topic, view(v.doc, v.member)]));
594
+ const before = await settle(() => new Map(held.views.map((v) => [v.topic, view(v.doc, v.member)])));
496
595
  const changes: Change[] = [],
497
596
  rows: Record<string, Row[]> = {},
498
597
  applied: Op[] = [],
499
598
  own: Change[] = [];
500
- const one = (d: string, o: Op[], b: number | null, v: string | null, w?: (applied: Op[]) => void, u?: number) => {
599
+ const one = async (
600
+ d: string,
601
+ o: Op[],
602
+ b: number | null,
603
+ v: string | null,
604
+ w?: (applied: Op[]) => unknown,
605
+ u?: number,
606
+ ) => {
501
607
  // (an undo puts back what was, filled as it was then: a field cleared since stays clear)
502
- const gone = withGone(d, o);
503
- const made = store.write(d, u === undefined ? fill(d, gone, b) : gone, b, v, w, { undoes: u });
608
+ const gone = await settle(() => withGone(d, o));
609
+ const filled = u === undefined ? await settle(() => fill(d, gone, b)) : gone;
610
+ const made = await store.write(d, filled, b, v, w, { undoes: u });
504
611
  // what the definitions hold of it (unique, noOverlap), once the write is done: refused whole if not
505
- const held = rulesOf(d).holds?.(read(d), touchedBy(made.applied));
612
+ const r = rulesOf(d),
613
+ touched = touchedBy(made.applied);
614
+ const held = await settle(
615
+ () => r.holds?.(read(d), touched) ?? (store.db.dialect === "sqlite" ? r.listsHold?.(read(d), touched) : null),
616
+ );
506
617
  if (held) throw new Refused(held);
507
618
  for (const [name, r] of Object.entries(made.rows)) (rows[name] ??= []).push(...r);
508
619
  // a document read as each member has it moves its version with what it reads
@@ -511,36 +622,38 @@ export function writes({
511
622
  const tables = new Set(made.tables);
512
623
  for (const r of Object.values(rules))
513
624
  if (r.reads?.some((t) => tables.has(t)) && !made.changes.some((c) => c.doc === r.doc))
514
- changes.push({ doc: r.doc, version: store.moved(r.doc), ops: [], by: b, via: v });
625
+ changes.push({ doc: r.doc, version: await store.moved(r.doc), ops: [], by: b, via: v });
515
626
  return made;
516
627
  };
517
628
  let next: Change[] = [];
518
- inTurn(
519
- writes,
520
- (name) => rules[name]?.kind?.root,
521
- (w) => {
522
- // a page's write is asked first, here: refused, none of it lands
523
- const { ops, within } = asked?.(w.doc, w.ops, w.why) ?? { ops: w.ops };
524
- const made = one(docParts(w.doc).base, ops, by, via, within, undoes);
525
- applied.push(...made.applied);
526
- own.push(made.changes[0]!);
527
- next.push(...made.changes);
528
- return made.applied;
529
- },
530
- );
629
+ // each part named as the write names it (src/together.ts), and landed in turn
630
+ const adds: { coll: string; id: number }[] = [];
631
+ for (const part of writes) {
632
+ const w = named(part, adds, (name) => rules[name]?.kind?.root);
633
+ // a page's write is asked first, here: refused, none of it lands
634
+ const { ops, within } = (await asked?.(w.doc, w.ops, w.why)) ?? { ops: w.ops };
635
+ const made = await one(docParts(w.doc).base, ops, by, via, within, undoes);
636
+ applied.push(...made.applied);
637
+ own.push(made.changes[0]!);
638
+ next.push(...made.changes);
639
+ for (const o of made.applied)
640
+ if (o.op === "add" && parts(o.path).key === "-" && parts(o.path).field === undefined)
641
+ adds.push({ coll: parts(o.path).coll, id: o.value.id });
642
+ }
531
643
  for (let round = 0; next.length; round++) {
532
644
  if (round === ROUNDS) throw new Error(`what follows from a write to ${writes[0]!.doc} never settles`);
533
- next = next.flatMap((c) =>
534
- (reacts[docParts(c.doc).name]?.(c, read) ?? [])
535
- .filter((w) => w.ops.length)
536
- .flatMap((w) => {
537
- if (docParts(w.doc).name === group || !store.exists(w.doc))
538
- throw new Error(`a reaction can't write ${w.doc}`);
539
- const why = ungranted(w.doc, w.ops, null);
540
- if (why) throw new Error(`a reaction wrote what no story does: ${why}`);
541
- return one(w.doc, w.ops, null, null).changes;
542
- }),
543
- );
645
+ const now: Change[] = [];
646
+ for (const c of next) {
647
+ const follows = await settle(() => reacts[docParts(c.doc).name]?.(c, read) ?? []);
648
+ for (const w of follows.filter((w) => w.ops.length)) {
649
+ if (docParts(w.doc).name === group || !(await store.exists(w.doc)))
650
+ throw new Error(`a reaction can't write ${w.doc}`);
651
+ const why = await settle(() => ungranted(w.doc, w.ops, null));
652
+ if (why) throw new Error(`a reaction wrote what no story does: ${why}`);
653
+ now.push(...(await one(w.doc, w.ops, null, null)).changes);
654
+ }
655
+ }
656
+ next = now;
544
657
  }
545
658
  const last = (name: string) => changes.findLast((c) => c.doc === name)?.version;
546
659
  const told: Told = [];
@@ -565,14 +678,34 @@ export function writes({
565
678
  for (const { topic, doc: d, member } of held.views) {
566
679
  const version = last(docParts(d).base);
567
680
  if (version === undefined) continue;
568
- const ops = docOps(before.get(topic)!, view(d, member));
681
+ const ops = docOps(before.get(topic)!, await settle(() => view(d, member)));
569
682
  if (ops.length) told.push({ topic, change: { doc: d, version, ops, by, via } });
570
683
  }
571
684
  return { changes, told, applied, parts: own };
572
- })();
685
+ });
573
686
  }
574
687
 
575
- return { land, view, ask, ungranted, mayOf, read, rulesOf, mayHold, groupless, byCode, exists };
688
+ return {
689
+ land,
690
+ ask,
691
+ /** A document as a person sees it (view), read as it is now. */
692
+ view: (doc: string, member: number) => settle(() => view(doc, member)),
693
+ ungranted: (...args: Parameters<typeof ungranted>) => settle(() => ungranted(...args)),
694
+ mayOf: (doc: string, member: number | null) => settle(() => mayOf(doc, member)),
695
+ mayHold: (doc: string, member: number | null, open: boolean) => settle(() => mayHold(doc, member, open)),
696
+ /** A document read as it is now, whole, or as a member has it. */
697
+ read: (doc: string, member?: number) => store.read(doc, member),
698
+ /** What asks the documents (the rules, an app's derive.ts), given them as they are now. */
699
+ settle: <T>(fn: (read: Read) => T) => settle(() => fn(read)),
700
+ /** The documents read at once, as the rules read them: only inside settle. */
701
+ now: read,
702
+ /** A write made inside settle (a route's): a document read after it can't be asked again. */
703
+ wrote: () => void (reading.getStore() && (reading.getStore()!.wrote = true)),
704
+ rulesOf,
705
+ groupless,
706
+ byCode,
707
+ exists,
708
+ };
576
709
  }
577
710
 
578
711
  /** A grant as an item's `may` token (mayOf), or undefined where it isn't one to an item: `remove orders` is "remove",
package/starter/CLAUDE.md CHANGED
@@ -24,14 +24,14 @@ only the section of its `reference.md` your task needs. joined's own files (`src
24
24
  - **The light DOM is the document; the shadow DOM is the display.** Only joined's applier writes a document's
25
25
  elements; a view or a display changes one only through its element's ops. A display moves only what changed.
26
26
  - **One concept a file, named for it, under 250 lines;** a display is a file that composes its parts (joined's
27
- `examples/trip/calendar-map.ts`, beside `week.ts`, `map.ts` and the rest).
27
+ `examples/trip/line.ts`, a reading of the kit's).
28
28
  - **An element is defined last in its module,** and a document's elements are named by the compiler's
29
29
  collections, never by a tag typed out.
30
30
  - **Never put `.env`, `.data/` or anyone's link in a commit,** nor in chat.
31
31
  - **Look at a change in the page** (`bun run dev`) before calling it done. `dev` runs a demo on this machine: an
32
32
  app's home page carries `<joined-demo>` (`import "joined/demo"`), a line to be anyone in the group, the BDFL first,
33
33
  so looking as Nora always has a way back. The live site is never a demo.
34
- - **The gate**, before a commit: `bun check` (the types: a link to one member may be none, once they've left) and
35
- `bun test`.
34
+ - **The gate**, before a commit: `bun check` (the types: a link to one member may be none, once they've left),
35
+ `bun fmt --check` (`bun fmt` formats; never what the compiler writes) and `bun test`.
36
36
  - **joined is upgraded by `bun run upgrade [version]`:** it moves the version, refreshes the skill and
37
37
  compiles again.
package/starter/bunfig ADDED
@@ -0,0 +1,4 @@
1
+ [fmt]
2
+ # bun fmt: every file but what the compiler writes (.prettierignore), as joined has it
3
+ printWidth = 120
4
+ embeddedLanguageFormatting = "off"
@@ -0,0 +1,4 @@
1
+ apps/*/generated/
2
+ apps/*/migrations/
3
+ # joined's skill, refreshed by bun run upgrade: left as it comes
4
+ .claude/skills/
@@ -1,4 +1,6 @@
1
1
  // hello's stories, told: each does what it says, and what it says can't be done is refused (joined/stories).
2
+ // tell() is by app folder, not by document: an app whose stories write several documents (apps/race/, a race and
3
+ // its entries) is told whole by tell("race"), every document it writes; tell("entries") is refused, saying whose.
2
4
 
3
5
  import { expect, test } from "bun:test";
4
6
  import { tell } from "joined/stories";
package/docs/learning.md DELETED
@@ -1,76 +0,0 @@
1
- # Learning joined
2
-
3
- Why joined is hard to pick up, and what would make it easier. It isn't the size: the compiler, the
4
- server, the page's side and the store are about 4,700 lines of code, and every line is tested. It's that a
5
- newcomer meets several unfamiliar things at once, with nothing familiar to hold on to.
6
-
7
- ## Why it's hard
8
-
9
- ### Its own words, chosen for how they read
10
-
11
- - **The code's names are joined's, not the trade's:** `say()`, `seen()`, `once()`,
12
- `whole()`, `keep()`, `held`, `behind`, `again`; the group's doors `at`, `admit`, `within`, `after`,
13
- `edge`. Someone searching for _broadcast_, _subscribe_, _permission_, _validate_ or _schema_ finds
14
- nothing: those words aren't used.
15
- - **Some words mean two things.** A _link_ is a field (`people="1 3"`) and a sign-in link. _Told_ is a
16
- story's refusal words, the page's event, and the server's publish. A _key_ is an item's id
17
- attribute and a member's secret.
18
- - **The comments are compressed:** "A link is who you are." "The light DOM is the document; the
19
- shadow DOM is the display." Each is right, and lovely once you know the system; before that, each
20
- is a riddle.
21
-
22
- ### About forty ideas before anything past hello
23
-
24
- The plan's table of words has over thirty: story, cast, premise, seen, unseen, document, kind,
25
- instance, collection, item, field, link, role, owns, grant, may, trust, the group, BDFL, agent's
26
- link, view, display, reading, applier and more. Then the who-paths have a syntax of their own:
27
- `posts[role=keeper]@members`, `members/members[!inviter]`, `@owners`. Each is simple; you need most
28
- of them at once.
29
-
30
- ### What's allowed is inferred, so it can't be read
31
-
32
- A field is needed if every story that adds one gives it. An op is granted to its teller's
33
- narrowest role, as the seeds have them. So to know why a write is refused, you run the compiler in
34
- your head. `generated/rules.ts` is readable, but it's what came out, not what you wrote, and nothing
35
- says which story granted what. (`bun run compile` now says when a story lets a needed field go.)
36
-
37
- ### Stories are written for the machine
38
-
39
- A story is one JSON line of about 250 characters, with JSON Patch inside. Its ids are the seed's
40
- (`/events/2`), so the seed is held in your head as you write. There's no shorthand, and no `then` to
41
- say what the document holds after (todo 36).
42
-
43
- ### The model is new, and nothing is around it
44
-
45
- The DOM is the state, a field is a string attribute, and a display is a custom element watching
46
- its children with a `MutationObserver`. Someone who thinks in components and reactive stores has to
47
- put that down first. There's no community, no answers to search, and the models that help people code
48
- don't know joined. The trip's display alone is about 800 lines of DOM by hand.
49
-
50
- ### The docs are for those who know
51
-
52
- The best guide, the skill's `reference.md`, is written for an AI, as `CLAUDE.md` is. The README and
53
- the introduction are good, with pictures, but in the same compressed voice. Until 30 October,
54
- `docs/plan.md` described another joined.
55
-
56
- ### A narrow way in
57
-
58
- Bun only, and Bun 1.4's own (HTML imports, `Bun.WebView`); TypeScript 7; hot reload off; not
59
- published, so a project takes a tarball; the page tests ran only on a Mac until 30 October; and the
60
- gate holds every line and function to its tests before a first contribution lands.
61
-
62
- ## What would help, cheapest first
63
-
64
- 1. **Plain names in the code, the voice in the docs.** `catchUp` for `behind` (`publish` is
65
- `told()` no more); or keep joined's and give a table from each to the trade's word.
66
- 2. **A tutorial:** one small app, from its first story to a display, showing what the compiler
67
- writes at each step.
68
- 3. **`joined why <doc> <op>`:** which check refuses it, or which story grants it, and to whom.
69
- 4. **Stories a person writes:** a shorter form, `then`, and a way to make them that shows what each
70
- part may be (see below).
71
-
72
- ## Stories from blocks
73
-
74
- Item 4 goes further than a shorter syntax: stories made of blocks, each shaped by what it is, so only
75
- what fits goes together, in the file's own words: one block a key, and the ops add, replace and remove
76
- (`docs/blocks.md`).
@@ -1,20 +0,0 @@
1
- // The cafe's own rules, which no definition can say: an order's lines are set in the write that places it, and
2
- // never after (a line added to an order there already is refused); and a supply delivered keeps its price and terms,
3
- // as both sides' books have them.
4
- import type { Trust } from "joined/server";
5
-
6
- export const trust: Trust = ({ doc, ops }, _who, read) => {
7
- if (
8
- ops.some((o) => o.op === "add" && o.path === "/lines/-") &&
9
- !ops.some((o) => o.op === "add" && o.path === "/orders/-")
10
- )
11
- return "an order's lines are set when it's placed";
12
- if (doc === "supplies") {
13
- const delivered = new Set(
14
- (read("supplies").supplies as { id: number; delivered: boolean }[]).filter((s) => s.delivered).map((s) => s.id),
15
- );
16
- const kept = (path: string) => delivered.has(Number(path.match(/^\/supplies\/(\d+)\/(price|terms)/)?.[1]));
17
- if (ops.some((o) => kept(o.path))) return "a delivered supply keeps its price and terms";
18
- }
19
- return null;
20
- };
@@ -1,24 +0,0 @@
1
- // The desk's own rule, which no story can say: a thumb is your own, and a task has one of yours at most (up or down,
2
- // the other taken back in the same write). idea-cards' and cardlet's votes are this rule.
3
-
4
- import type { Trust } from "joined/server";
5
-
6
- const THUMB = /^\/tasks\/(\d+)\/(ups|downs)\/(-|\d+)$/;
7
- type Task = { id: number; ups?: number[]; downs?: number[] };
8
-
9
- export const trust: Trust = ({ doc, ops }, { member }, read) => {
10
- const thumbs = ops.flatMap((o) => {
11
- const m = THUMB.exec(o.path);
12
- const who = m && (o.op === "add" ? o.value : Number(m[3]));
13
- return m ? [{ add: o.op === "add", task: Number(m[1]), list: m[2] as "ups" | "downs", who }] : [];
14
- });
15
- if (thumbs.some((t) => t.who !== member)) return "You thumb only for yourself.";
16
- const tasks = read(doc).tasks as Task[];
17
- for (const t of thumbs.filter((t) => t.add)) {
18
- const other = t.list === "ups" ? "downs" : "ups";
19
- const taken = thumbs.some((o) => !o.add && o.task === t.task && o.list === other);
20
- if (!taken && tasks.find((x) => x.id === t.task)?.[other]?.includes(member))
21
- return "One thumb a task: take the other back first.";
22
- }
23
- return null;
24
- };
@@ -1,14 +0,0 @@
1
- // The people's own rule, which no definition can say: which person you are (their member) is yours to say, as
2
- // yourself, and to take back; nobody says it for someone else.
3
- import type { Trust } from "joined/server";
4
-
5
- export const trust: Trust = ({ doc, ops }, { member }, read) => {
6
- const people = (read(doc).people ?? []) as { id: number; member?: number }[];
7
- for (const o of ops) {
8
- const [, coll, id, field] = o.path.split("/");
9
- if (coll !== "people" || field !== "member") continue;
10
- const now = people.find((p) => p.id === Number(id))?.member;
11
- if (o.op === "remove" ? now !== member : o.value !== member) return "you say which person you are, as yourself";
12
- }
13
- return null;
14
- };