@blueshed/joined 0.0.0-stage → 0.1.20

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 (213) hide show
  1. package/.claude/skills/joined/SKILL.md +17 -0
  2. package/.claude/skills/joined/reference.md +768 -0
  3. package/LICENSE +19 -0
  4. package/README.md +115 -2
  5. package/docs/design.md +148 -0
  6. package/docs/introduction.md +193 -0
  7. package/docs/learning.md +76 -0
  8. package/docs/stories.md +82 -0
  9. package/examples/app.css +27 -0
  10. package/examples/cafe/books.html +38 -0
  11. package/examples/cafe/books.json +13 -0
  12. package/examples/cafe/books.ts +64 -0
  13. package/examples/cafe/cafe.css +512 -0
  14. package/examples/cafe/front.html +115 -0
  15. package/examples/cafe/front.ts +7 -0
  16. package/examples/cafe/generated/books.elements.ts +52 -0
  17. package/examples/cafe/generated/books.queries.ts +11 -0
  18. package/examples/cafe/generated/books.rules.ts +42 -0
  19. package/examples/cafe/generated/kitchen.elements.ts +87 -0
  20. package/examples/cafe/generated/kitchen.queries.ts +47 -0
  21. package/examples/cafe/generated/kitchen.rules.ts +98 -0
  22. package/examples/cafe/generated/menu.elements.ts +61 -0
  23. package/examples/cafe/generated/menu.queries.ts +28 -0
  24. package/examples/cafe/generated/menu.rules.ts +65 -0
  25. package/examples/cafe/generated/order.elements.ts +87 -0
  26. package/examples/cafe/generated/order.queries.ts +47 -0
  27. package/examples/cafe/generated/order.rules.ts +95 -0
  28. package/examples/cafe/generated/staff.elements.ts +55 -0
  29. package/examples/cafe/generated/staff.queries.ts +27 -0
  30. package/examples/cafe/generated/staff.rules.ts +59 -0
  31. package/examples/cafe/generated/supplies.elements.ts +62 -0
  32. package/examples/cafe/generated/supplies.queries.ts +43 -0
  33. package/examples/cafe/generated/supplies.rules.ts +84 -0
  34. package/examples/cafe/generated/till.elements.ts +93 -0
  35. package/examples/cafe/generated/till.queries.ts +57 -0
  36. package/examples/cafe/generated/till.rules.ts +113 -0
  37. package/examples/cafe/index.html +70 -0
  38. package/examples/cafe/kitchen.css +107 -0
  39. package/examples/cafe/kitchen.html +39 -0
  40. package/examples/cafe/kitchen.ts +125 -0
  41. package/examples/cafe/menu.html +55 -0
  42. package/examples/cafe/menu.json +41 -0
  43. package/examples/cafe/menu.ts +84 -0
  44. package/examples/cafe/migrations/001-cafe.ts +11 -0
  45. package/examples/cafe/order.html +37 -0
  46. package/examples/cafe/order.ts +45 -0
  47. package/examples/cafe/rail-drag.ts +30 -0
  48. package/examples/cafe/routes.ts +32 -0
  49. package/examples/cafe/staff.json +20 -0
  50. package/examples/cafe/stories.jsonl +43 -0
  51. package/examples/cafe/supplies.html +77 -0
  52. package/examples/cafe/supplies.json +33 -0
  53. package/examples/cafe/supplies.ts +170 -0
  54. package/examples/cafe/till.json +95 -0
  55. package/examples/cafe/till.ts +122 -0
  56. package/examples/cafe/trust.ts +20 -0
  57. package/examples/cafe/views.ts +171 -0
  58. package/examples/docs.ts +28 -0
  59. package/examples/film.jpg +0 -0
  60. package/examples/hello/generated/elements.ts +45 -0
  61. package/examples/hello/generated/queries.ts +24 -0
  62. package/examples/hello/generated/rules.ts +45 -0
  63. package/examples/hello/hello.css +27 -0
  64. package/examples/hello/hello.json +1 -0
  65. package/examples/hello/index.html +32 -0
  66. package/examples/hello/migrations/001-hello.ts +6 -0
  67. package/examples/hello/page.ts +49 -0
  68. package/examples/hello/routes.ts +6 -0
  69. package/examples/hello/stories.jsonl +3 -0
  70. package/examples/index.html +146 -0
  71. package/examples/page.ts +11 -0
  72. package/examples/people/adding.ts +20 -0
  73. package/examples/people/generated/elements.ts +68 -0
  74. package/examples/people/generated/queries.ts +28 -0
  75. package/examples/people/generated/rules.ts +85 -0
  76. package/examples/people/links.ts +124 -0
  77. package/examples/people/migrations/001-people.ts +6 -0
  78. package/examples/people/migrations/002-add-people-member-and-guard-people.ts +7 -0
  79. package/examples/people/migrations/003-add-people-rank-and-guard-people.ts +7 -0
  80. package/examples/people/order.ts +61 -0
  81. package/examples/people/people.css +65 -0
  82. package/examples/people/people.json +26 -0
  83. package/examples/people/routes.ts +12 -0
  84. package/examples/people/stories.jsonl +20 -0
  85. package/examples/people/trust.ts +14 -0
  86. package/examples/people/view.ts +115 -0
  87. package/examples/routes.ts +11 -0
  88. package/examples/trip/answer-rows.ts +70 -0
  89. package/examples/trip/answers.ts +11 -0
  90. package/examples/trip/bar.ts +89 -0
  91. package/examples/trip/calendar-map.css +709 -0
  92. package/examples/trip/calendar-map.ts +249 -0
  93. package/examples/trip/drags.ts +143 -0
  94. package/examples/trip/drawer.ts +250 -0
  95. package/examples/trip/event-form.ts +199 -0
  96. package/examples/trip/generated/elements.ts +144 -0
  97. package/examples/trip/generated/queries.ts +46 -0
  98. package/examples/trip/generated/rules.ts +239 -0
  99. package/examples/trip/holding.ts +61 -0
  100. package/examples/trip/ics.ts +117 -0
  101. package/examples/trip/index.html +82 -0
  102. package/examples/trip/line-stops.ts +92 -0
  103. package/examples/trip/line-words.ts +79 -0
  104. package/examples/trip/line.ts +121 -0
  105. package/examples/trip/map.ts +234 -0
  106. package/examples/trip/mercator.ts +28 -0
  107. package/examples/trip/migrations/001-trip.ts +7 -0
  108. package/examples/trip/migrations/002-add-events-zone-and-guard-events.ts +7 -0
  109. package/examples/trip/migrations/003-guard-events-and-create-events_asked-and-more.ts +9 -0
  110. package/examples/trip/migrations/004-create-stays.ts +6 -0
  111. package/examples/trip/migrations/005-guard-events-and-create-events_arrives-and-more.ts +8 -0
  112. package/examples/trip/month.ts +87 -0
  113. package/examples/trip/other-weeks.ts +67 -0
  114. package/examples/trip/page.ts +121 -0
  115. package/examples/trip/peek.ts +71 -0
  116. package/examples/trip/people-chips.ts +74 -0
  117. package/examples/trip/place-search.ts +51 -0
  118. package/examples/trip/places.ts +34 -0
  119. package/examples/trip/routes.ts +27 -0
  120. package/examples/trip/shell.ts +39 -0
  121. package/examples/trip/stays.css +51 -0
  122. package/examples/trip/stays.ts +68 -0
  123. package/examples/trip/stories.jsonl +72 -0
  124. package/examples/trip/time.ts +46 -0
  125. package/examples/trip/told.ts +48 -0
  126. package/examples/trip/trip.json +69 -0
  127. package/examples/trip/trust.ts +51 -0
  128. package/examples/trip/week.ts +237 -0
  129. package/examples/trip/words.ts +4 -0
  130. package/examples/trip/writes.ts +91 -0
  131. package/examples/trip/zones.ts +16 -0
  132. package/examples/trips/card.ts +149 -0
  133. package/examples/trips/generated/elements.ts +60 -0
  134. package/examples/trips/generated/queries.ts +28 -0
  135. package/examples/trips/generated/rules.ts +62 -0
  136. package/examples/trips/index.html +47 -0
  137. package/examples/trips/map.ts +52 -0
  138. package/examples/trips/migrations/001-trips.ts +8 -0
  139. package/examples/trips/new-trip.ts +46 -0
  140. package/examples/trips/page.ts +9 -0
  141. package/examples/trips/routes.ts +7 -0
  142. package/examples/trips/stories.jsonl +12 -0
  143. package/examples/trips/trips.css +183 -0
  144. package/examples/trips/trips.json +7 -0
  145. package/examples/weeks/derive.ts +23 -0
  146. package/examples/weeks/generated/elements.ts +52 -0
  147. package/examples/weeks/generated/rules.ts +33 -0
  148. package/examples/weeks/routes.ts +4 -0
  149. package/examples/weeks/weeks.json +1 -0
  150. package/examples/welcome.css +299 -0
  151. package/package.json +55 -4
  152. package/src/attachment.ts +70 -0
  153. package/src/cli.ts +52 -0
  154. package/src/client.ts +98 -0
  155. package/src/compile.ts +2034 -0
  156. package/src/css.d.ts +5 -0
  157. package/src/definitions.ts +268 -0
  158. package/src/demo.css +29 -0
  159. package/src/demo.ts +42 -0
  160. package/src/draft.ts +69 -0
  161. package/src/engine.ts +288 -0
  162. package/src/file-value.ts +13 -0
  163. package/src/files.ts +187 -0
  164. package/src/follow.ts +56 -0
  165. package/src/hues.ts +3 -0
  166. package/src/icon-names.ts +77 -0
  167. package/src/icon.png +0 -0
  168. package/src/icons.ts +32 -0
  169. package/src/keep.ts +33 -0
  170. package/src/link.ts +31 -0
  171. package/src/mcp.ts +252 -0
  172. package/src/members/demo.ts +53 -0
  173. package/src/members/generated/elements.ts +68 -0
  174. package/src/members/generated/queries.ts +29 -0
  175. package/src/members/generated/rules.ts +65 -0
  176. package/src/members/group.ts +294 -0
  177. package/src/members/keys.ts +221 -0
  178. package/src/members/members.json +9 -0
  179. package/src/members/migrations/001-members.ts +6 -0
  180. package/src/members/migrations/002-guard-members.ts +11 -0
  181. package/src/members/migrations/003-add-members-act-and-guard-members.ts +7 -0
  182. package/src/members/panel.css +208 -0
  183. package/src/members/panel.ts +398 -0
  184. package/src/members/routes.ts +4 -0
  185. package/src/members/stories.jsonl +27 -0
  186. package/src/members/trust.ts +116 -0
  187. package/src/migrate.ts +597 -0
  188. package/src/migrations/001-joined.ts +13 -0
  189. package/src/migrations/002-group-keys.ts +16 -0
  190. package/src/migrations/003-change-inverse.ts +10 -0
  191. package/src/migrations/004-change-followed.ts +6 -0
  192. package/src/ops.ts +61 -0
  193. package/src/page.css +79 -0
  194. package/src/page.ts +413 -0
  195. package/src/parts.css +471 -0
  196. package/src/parts.ts +152 -0
  197. package/src/server.ts +862 -0
  198. package/src/settings.ts +94 -0
  199. package/src/starter.ts +89 -0
  200. package/src/store.ts +815 -0
  201. package/src/stories.ts +387 -0
  202. package/src/toast.ts +52 -0
  203. package/src/together.ts +167 -0
  204. package/src/tokens.css +85 -0
  205. package/src/tokens.json +457 -0
  206. package/src/upkeep.ts +86 -0
  207. package/src/visitors.ts +43 -0
  208. package/src/write.ts +567 -0
  209. package/starter/CLAUDE.md +37 -0
  210. package/starter/gitignore +3 -0
  211. package/starter/tests/hello-page.test.ts +14 -0
  212. package/starter/tests/hello.test.ts +8 -0
  213. package/starter/tsconfig.json +17 -0
package/src/write.ts ADDED
@@ -0,0 +1,567 @@
1
+ // A write, as the database's transaction holds it (docs/plan.md, The architecture: Write and Broadcast): what an app's
2
+ // own rules say (its trust.ts), what the stories grant, what the server fills and copies, the rows, what the
3
+ // definitions hold, the rules over values, and what follows (each app's reactions), whole or none of it. Then who is
4
+ // told: each document holding a row it changed, in its own paths (the store's), and each part of one a page holds
5
+ // alone, worked out here in the same transaction: a window, by its query's own test of a row; a document a person
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
+ // member and passes the write on; it holds none of this.
8
+
9
+ import { grantOf } from "./definitions.ts";
10
+ import { docParts, parts, type Change, type Op } from "./ops.ts";
11
+ import { settled, settingsNow, type Settings } from "./settings.ts";
12
+ import {
13
+ rootCode,
14
+ rootItem,
15
+ docOps,
16
+ Refused,
17
+ rowOps,
18
+ type Doc,
19
+ type Row,
20
+ type Rules as StoreRules,
21
+ type Store,
22
+ } from "./store.ts";
23
+ import { inTurn, type Part } from "./together.ts";
24
+ import { admits, guestRole, levelled } from "./visitors.ts";
25
+
26
+ /** A way to read any document as it is now: whole, or as a member sees it (owns). */
27
+ export type Read = (doc: string, member?: number) => Doc;
28
+ /** An app's compiled rules: its grants, who someone is (rolesOf), what they see (sees: null, all of it), what its
29
+ * definitions hold of it (holds), and its window's test of an item (inWindow). */
30
+ export type Rules = StoreRules & {
31
+ anonymous?: boolean;
32
+ derived?: readonly string[];
33
+ holds?(d: Doc, touched: Record<string, number[]>): string | null;
34
+ grants: Record<string, string[]>;
35
+ /** Who someone is to it: none, of a derived document. */
36
+ rolesOf?(m: number, read: Read, doc: string, at?: any): string[];
37
+ /** Each field whose value moves only as the stories move it (definitions' moves), by collection. */
38
+ moves?: Record<string, string>;
39
+ /** The field holding an item's own code, by collection: a page holding the document by it is the item's guest. */
40
+ guests?: Record<string, string>;
41
+ /** Of a kind, its root item's own fields that govern it (definitions' frozen and waits). */
42
+ settings?: Settings;
43
+ /** The field of a kind's root holding its guest's level (definitions' visitors, src/visitors.ts). */
44
+ visitors?: Record<string, string>;
45
+ sees: boolean | null;
46
+ inWindow?(coll: string, item: any, p: Record<string, string | null>): boolean;
47
+ /** The tables its query reads, of a document read as each member has it or holding only some of their rows: a
48
+ * change to one moves its version. */
49
+ reads?: readonly string[];
50
+ /** Who may hold it at all (definitions' where), each a role: null, anyone. */
51
+ mayHold?: readonly string[] | null;
52
+ type?: "static" | "read-only" | "shared";
53
+ };
54
+ /** An app's own rules for a write (its trust.ts), which no story can say: why it's refused, or null. Asked
55
+ * first, so a refusal is in the app's own words; it reads the write's ops as sent, before they're checked. */
56
+ export type Trust = (
57
+ write: { doc: string; ops: Op[]; why?: string },
58
+ who: { member: number; roles: string[] },
59
+ read: Read,
60
+ ) => string | null;
61
+ /** An app's reactions (its routes.ts's): the writes that follow from a change to its document, landed in the
62
+ * change's transaction; what they write is followed in turn, until nothing more is. */
63
+ export type Reactions = (change: Change, read: Read) => { doc: string; ops: Op[] }[];
64
+ /** What pages hold apart from a document whole, as their topics name them: each window held, and each document as a
65
+ * person (a member, or nobody, 0) sees it, where that's only some of it (owns), or it's read as each has it. */
66
+ export type Held = { windows: string[]; views: { topic: string; doc: string; member: number }[] };
67
+ /** What a write tells, past its changes: to each topic a page holds, what changed of it. */
68
+ export type Told = { topic: string; change: Change & { doc: string } }[];
69
+
70
+ /** How many rounds of reactions a write may set off before it's refused as never settling. */
71
+ const ROUNDS = 10;
72
+
73
+ export function writes({
74
+ store,
75
+ rules,
76
+ group,
77
+ trusts,
78
+ reacts,
79
+ }: {
80
+ store: Store;
81
+ rules: Record<string, Rules>;
82
+ /** The group's document: never a reaction's to write. */
83
+ group: string;
84
+ trusts: Record<string, Trust>;
85
+ reacts: Record<string, Reactions>;
86
+ }) {
87
+ /** A document's rules: an instance of a kind's (shelf:1) are the kind's. */
88
+ const rulesOf = (doc: string) => rules[docParts(doc).name]!;
89
+ /** Whether the group has no say in a write: an anonymous document is anyone's, and a guest's write (a stranger
90
+ * holding an item by its own code) is as the grants say. */
91
+ const groupless = (doc: string, who: { member: number } | null | undefined) =>
92
+ !!(rulesOf(doc).anonymous || (!who && rulesOf(doc).guests));
93
+ const read: Read = store.read;
94
+
95
+ /** The kind whose root's own document a page holds by an item's code (`boards?code=…`, a board's secret link, to
96
+ * draw the board): its guests name the root's code, given alone. None, held otherwise. */
97
+ const rootKind = (doc: string) => {
98
+ const { base, params } = docParts(doc),
99
+ given = Object.keys(params);
100
+ return given.length === 1
101
+ ? Object.values(rules).find((k) => k.kind?.doc === base && rootCode(k) === given[0])
102
+ : undefined;
103
+ };
104
+ /** Of the root's document held by an item's code, that item, as the root's document has it (`whole`): none, the
105
+ * code is no item's. */
106
+ const codeItem = (doc: string, k: Rules, whole: Doc) => {
107
+ const code = rootCode(k)!;
108
+ return (whole[k.kind!.root] as Record<string, unknown>[]).find((i) => i[code] === docParts(doc).params[code]);
109
+ };
110
+ /** The root's document a page holding a document by a root item's code is let in by (src/visitors.ts, admits): a
111
+ * kind's instance's (`board:1?code=…`), or the root's own (`boards?code=…`, that item alone). Its guest is sent it
112
+ * whole, and told each change as a window's page is (mayHold has asked the code is the root's own). None, held
113
+ * otherwise. */
114
+ const byCode = (doc: string) => {
115
+ const r = rulesOf(doc),
116
+ code = rootCode(r);
117
+ return code && docParts(doc).params[code] !== undefined ? r.kind!.doc : rootKind(doc)?.kind!.doc;
118
+ };
119
+ /** 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);
121
+ /** 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
+ * 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
+ * an item's code, that item alone, past any owns (none: the code is no one's). */
124
+ const view = (doc: string, member: number): Doc => {
125
+ const r = rulesOf(doc),
126
+ k = rootKind(doc);
127
+ if (k) {
128
+ const whole = read(docParts(doc).base),
129
+ item = codeItem(doc, k, whole);
130
+ return { version: whole.version, [k.kind!.root]: item ? [item] : [] };
131
+ }
132
+ return (r.member || r.sees) && !byCode(doc) ? store.read(doc, member) : read(doc);
133
+ };
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. */
137
+ const anyoneIs = (doc: string, member: number | null) =>
138
+ member !== null || !byCode(doc) || (!levelled(rulesOf(doc)) && !rootKind(doc));
139
+
140
+ /** 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
+ * writer's roles may not; null if neither. `roles` null: the server's own write, or nobody's on an open group,
142
+ * asked only whether a story does it; `anyone`, whether what's granted anyone is the writer's. Asked in the write's
143
+ * transaction: the values are the tables' to refuse. */
144
+ function ungranted(doc: string, ops: Op[], roles: ((o: Op) => string[]) | null, anyone = true) {
145
+ const { grants, collections, moves } = rulesOf(doc);
146
+ for (const o of ops) {
147
+ const { coll, key, field, link, more } = parts(o.path);
148
+ // a field the server fills is replaced by the server alone (a page's write of it is refused before)
149
+ const filled = o.op === "replace" && field !== undefined && field in (collections[coll]?.fills ?? {});
150
+ const id = /^[1-9]\d*$/.test(key ?? "");
151
+ // a field of the document's own (/greeting)
152
+ const own = Object.values(collections).find((c) => c.own);
153
+ const formed =
154
+ !more?.length &&
155
+ (key === ""
156
+ ? !!own && o.op !== "add" && coll in own.fields
157
+ : o.op === "add"
158
+ ? field === undefined
159
+ ? key === "-"
160
+ : id && link === "-"
161
+ : id &&
162
+ link !== "-" &&
163
+ (o.op === "remove" ||
164
+ (field !== undefined &&
165
+ // a field, or one of an object's (terms/days)
166
+ (link === undefined || `${field}.${link}` in (collections[coll]?.fields ?? {})))));
167
+ // a field that moves only as the stories move it: the step, from where its item is to where it's going
168
+ const moved = formed && o.op === "replace" && field !== undefined && moves?.[coll] === field;
169
+ // an add giving a field that moves: its first step, from nothing
170
+ const first =
171
+ formed && o.op === "add" && field === undefined && moves?.[coll] ? (o.value as any)?.[moves[coll]] : undefined;
172
+ const to = formed
173
+ ? (grants[
174
+ moved
175
+ ? `${grantOf(o)}:${itemAt(doc, o)?.[field!]}>${o.value}`
176
+ : first !== undefined
177
+ ? `${grantOf(o)}.${moves![coll]}:>${first}`
178
+ : grantOf(o)
179
+ ] ?? (filled && !moved ? [] : undefined))
180
+ : undefined;
181
+ if (!to) return moved || first !== undefined ? "that isn't a move you can make" : `no ${o.op} at ${o.path}`;
182
+ if (roles && !grantsTo(to, () => roles(o), anyone)) return `you may not ${o.op} at ${o.path}`;
183
+ }
184
+ return null;
185
+ }
186
+ /** Whether a grant's roles take in someone's: anyone's, where it's a member's and what's anyone's is theirs. */
187
+ const grantsTo = (to: string[], roles: () => string[], anyone: boolean) =>
188
+ (anyone && to.includes("member")) || to.some((r) => roles().includes(r));
189
+ /** What a person may do in a document, as they see it, by the grants and the roles a write is held to (ungranted):
190
+ * for each collection, by key, its element's `may`. "" is the collection's own element: "add"; or a document's own
191
+ * fields', "replace:greeting". An item's: "remove"; "replace:price", "replace:terms.days", "remove:due";
192
+ * "add:people[]" and "remove:people[]", an id of a list; a move from where it is, "replace:status>being%20made", the
193
+ * step's value as a URL's, so a space doesn't part it. An add's item is its writer's to give: their roles to it are
194
+ * those to an item naming them in every field. `member` null: nobody, who may do what any story does in a document
195
+ * that's anonymous. Only what says something is there. */
196
+ function mayOf(doc: string, member: number | null) {
197
+ const r = rulesOf(doc),
198
+ may: Record<string, Record<string, string>> = {};
199
+ // each document read once, however many items' roles read it
200
+ const once = new Map<string, Doc>(),
201
+ readOnce: Read = (d) => once.get(d) ?? once.set(d, read(d)).get(d)!;
202
+ // of a kind, what its root item's settings say now: frozen, or held for approval, an add only by its first step
203
+ const now = settingsNow(r, () => rootItem(r, doc, readOnce));
204
+ // (a document no page writes has no grants; one kept as it is, frozen, is written by none)
205
+ if (!Object.keys(r.grants ?? {}).length || now.frozen) return may;
206
+ const anyone = member === null && !!r.anonymous,
207
+ seen = view(doc, member ?? 0);
208
+ /** What someone may do to one element: each grant it takes (`token`), if their roles to its item do; once (an add
209
+ * by either of two first steps is one add). */
210
+ const tokens = (coll: string, item: any, token: (grant: string) => string | undefined) => {
211
+ const roles = anyone ? [] : rolesTo(doc, member, coll, item, readOnce);
212
+ const words = Object.entries(r.grants).flatMap(([g, to]) => {
213
+ const t = token(g);
214
+ return t !== undefined && (anyone || grantsTo(to, () => roles, anyoneIs(doc, member))) ? [t] : [];
215
+ });
216
+ return [...new Set(words)].join(" ");
217
+ };
218
+ const { first } = now;
219
+ for (const [coll, c] of Object.entries(r.collections)) {
220
+ const at: Record<string, string> = {};
221
+ if (c.own)
222
+ at[""] = tokens(coll, undefined, (g) => {
223
+ const [op, field] = g.split(" ") as [string, string];
224
+ return field in c.fields ? `${op}:${field}` : undefined;
225
+ });
226
+ else {
227
+ const theirs = Object.fromEntries(Object.keys(c.fields).map((f) => [f, member]));
228
+ // add, by any first step too (an add giving a field that moves)
229
+ at[""] = tokens(coll, theirs, (g) =>
230
+ (
231
+ coll in first
232
+ ? g === `add ${coll}.${r.moves![coll]}:>${first[coll]}`
233
+ : g === `add ${coll}` || g.startsWith(`add ${coll}.${r.moves?.[coll]}:>`)
234
+ )
235
+ ? "add"
236
+ : undefined,
237
+ );
238
+ for (const item of (seen[coll] ?? []) as Record<string, unknown>[])
239
+ at[String(item.id)] = tokens(coll, item, (g) => itemToken(g, coll, item, r.moves?.[coll]));
240
+ }
241
+ const said = Object.entries(at).filter(([, t]) => t);
242
+ if (said.length) may[coll] = Object.fromEntries(said);
243
+ }
244
+ return may;
245
+ }
246
+ /** The item an op is to, as the document has it now (an add's, the value it gives): what roles are asked of. */
247
+ function itemAt(doc: string, o: Op): any {
248
+ const { coll, key } = parts(o.path);
249
+ if (key === "-") return o.value;
250
+ // the document as a whole: a window of it holds only some (a guest's, their own order)
251
+ const items = read(docParts(doc).base)[coll];
252
+ return Array.isArray(items) ? items.find((i) => i.id === Number(key)) : undefined;
253
+ }
254
+ /** Who someone is to an item of a collection: their roles, and its guest's (at its level: src/visitors.ts). */
255
+ function rolesTo(doc: string, member: number | null, coll: string, item: any, from: Read = read) {
256
+ const r = rulesOf(doc);
257
+ const roles = member === null ? [] : r.rolesOf!(member, from, doc, item);
258
+ const of = guestOf(doc, coll, item, from);
259
+ return of ? [...roles, guestRole(r, of)] : roles;
260
+ }
261
+ /** The item a page is a guest of, holding a document by the code that makes it one: an item's own (`order?code=…`),
262
+ * or in a kind, its root item's (`board:1?code=…`, a board's secret link), given and that item's. None, no guest. */
263
+ function guestOf(doc: string, coll: string, item: any, from: Read = read): any {
264
+ const r = rulesOf(doc),
265
+ { key, params } = docParts(doc);
266
+ const root = rootCode(r);
267
+ const code = root || r.guests?.[coll],
268
+ of = root ? rootItem(r, doc, from) : item;
269
+ return code && of && params[code] !== undefined && (of as any)[code] === params[code] ? of : undefined;
270
+ }
271
+ /** Whether an op makes a code the server fills new (a board's secret link rotated): a replace of a field filled
272
+ * "random", which a story grants. The server makes the new code, whatever the op gives (renewed). */
273
+ const renews = (doc: string, o: Op) => {
274
+ const { coll, field, link } = parts(o.path),
275
+ r = rulesOf(doc);
276
+ return (
277
+ o.op === "replace" &&
278
+ link === undefined &&
279
+ r.collections[coll]?.fills?.[field!] === "random" &&
280
+ !!r.grants[grantOf(o)]
281
+ );
282
+ };
283
+ /** A page's write with each code it makes new made by the server, as an add's is: what's checked, kept and told. */
284
+ const renewed = (doc: string, ops: Op[]) => ops.map((o) => (renews(doc, o) ? { ...o, value: random() } : o));
285
+ /** Why a page's write is refused for writing a field the server fills, or one copied, or null. */
286
+ function serversIn(doc: string, ops: Op[]) {
287
+ for (const o of ops) {
288
+ const { coll, key, field } = parts(o.path);
289
+ const { fills = {}, copies } = rulesOf(doc).collections[coll] ?? {};
290
+ const given = field ?? (o.op === "add" && key === "-" ? Object.keys(o.value ?? {}) : []).find((f) => f in fills);
291
+ // (a field that moves only as the stories move it is filled as it's added, and then moved; a code, made new)
292
+ if (
293
+ given !== undefined &&
294
+ given in fills &&
295
+ !(o.op === "replace" && rulesOf(doc).moves?.[coll] === given) &&
296
+ !renews(doc, o)
297
+ )
298
+ return `${given} is the server's to fill`;
299
+ const copied = (field === undefined ? Object.keys(o.value ?? {}) : [field]).find((f) =>
300
+ copies?.fields.includes(f),
301
+ );
302
+ if (copied) return `${copied} is copied from its ${copies!.from}`;
303
+ }
304
+ return null;
305
+ }
306
+ /** The items each collection's ops touched, by id: an add's the id it was given. */
307
+ function touchedBy(ops: Op[]) {
308
+ const touched: Record<string, number[]> = {};
309
+ for (const o of ops) {
310
+ const { coll, key } = parts(o.path);
311
+ (touched[coll] ??= []).push(key === "-" ? o.value.id : Number(key));
312
+ }
313
+ return touched;
314
+ }
315
+ /** A code no one can guess: twelve characters of a URL's own, from 72 random bits. */
316
+ const random = () =>
317
+ btoa(String.fromCharCode(...crypto.getRandomValues(new Uint8Array(9))))
318
+ .replace(/\+/g, "-")
319
+ .replace(/\//g, "_");
320
+ /** A write's adds with the fields the server fills, where they don't give them: "now" is the instant, "random" a code
321
+ * no one can guess, "me" its writer (`by`); and those
322
+ * copied from what a link points at, as it is now (none, where it points at nothing: the table refuses that). */
323
+ function fill(doc: string, ops: Op[], by: number | null) {
324
+ return ops.map((o) => {
325
+ const { coll, key, field } = parts(o.path);
326
+ const { fills, copies } = rulesOf(doc).collections[coll] ?? {};
327
+ if (copies && o.op === "add" && key === "-" && field === undefined) {
328
+ const from = (read(copies.at)[copies.to] as Record<string, unknown>[]).find(
329
+ (i) => i.id === o.value?.[copies.from],
330
+ );
331
+ o = { ...o, value: { ...Object.fromEntries(copies.fields.map((f) => [f, from?.[f]])), ...o.value } };
332
+ }
333
+ if (!fills || o.op !== "add" || key !== "-" || field !== undefined) return o;
334
+ const now = new Date().toISOString().replace(/\.\d+Z$/, "Z");
335
+ return {
336
+ ...o,
337
+ value: {
338
+ ...Object.fromEntries(
339
+ Object.entries(fills).map(([f, v]) => [
340
+ f,
341
+ v === "now" ? now : v === "random" ? random() : v === "me" ? by : v,
342
+ ]),
343
+ ),
344
+ ...o.value,
345
+ },
346
+ };
347
+ });
348
+ }
349
+
350
+ /** A write's removals, each with what goes with it: every item of the document whose link that goes with what it
351
+ * points at (its definitions' gone: "with") points at the removed one, removed first, and what goes with that, so
352
+ * the tables find nothing linking to it. An item removed once isn't again, however the write names it. */
353
+ function withGone(doc: string, ops: Op[]) {
354
+ const { collections } = rulesOf(doc);
355
+ if (!Object.values(collections).some((c) => c.goes)) return ops;
356
+ const items = read(docParts(doc).base),
357
+ out: Op[] = [];
358
+ const removed = new Set<string>();
359
+ const gone = (coll: string, id: number) => {
360
+ for (const [c, def] of Object.entries(collections))
361
+ for (const f of def.goes ?? [])
362
+ if (def.links[f] === coll)
363
+ for (const i of (items[c] ?? []) as { id: number; [f: string]: unknown }[]) {
364
+ const path = `/${c}/${i.id}`;
365
+ if (i[f] !== id || removed.has(path)) continue;
366
+ removed.add(path);
367
+ gone(c, i.id);
368
+ out.push({ op: "remove", path });
369
+ }
370
+ };
371
+ for (const o of ops) {
372
+ const { coll, key, field } = parts(o.path);
373
+ if (o.op === "remove" && field === undefined && /^[1-9]\d*$/.test(key)) {
374
+ // removed already, as what goes with an earlier removal: once
375
+ if (removed.has(o.path)) continue;
376
+ removed.add(o.path);
377
+ gone(coll, Number(key));
378
+ }
379
+ out.push(o);
380
+ }
381
+ return out;
382
+ }
383
+
384
+ /** Whether a page may hold a document at all: anyone, but where its where says who (`mayHold`, each a role); and
385
+ * on a group that's invite-only, a stranger only what's anonymous, or an item's own as its guest (`order?code=…`). */
386
+ function mayHold(doc: string, member: number | null, open: boolean): string | null {
387
+ const r = rulesOf(doc),
388
+ { params } = docParts(doc);
389
+ // a kind's root's code given, its own, at a level the stories let a guest act on, or No access (the root's own
390
+ // document held by it too: the item whose code it is); an item's, its window holds that item alone
391
+ const k = rootKind(doc);
392
+ if (
393
+ k
394
+ ? !admits(k, codeItem(doc, k, read(k.kind!.doc)))
395
+ : byCode(doc) && !admits(r, guestOf(doc, r.kind!.root, undefined))
396
+ )
397
+ return "No access";
398
+ const guest = byCode(doc) || Object.values(r.guests ?? {}).some((code) => params[code] !== undefined);
399
+ if (member === null && !open && !r.anonymous && !guest) return "sign in with your link first";
400
+ if (r.mayHold && !guest && !(member !== null && r.rolesOf!(member, read, doc).some((x) => r.mayHold!.includes(x))))
401
+ return "No access";
402
+ return null;
403
+ }
404
+ /** A page's write asked, in its transaction, in order, refused at the first that says no: the app's own rules (its
405
+ * trust.ts, in its own words, asked of nobody, 0, where the group is open); a field the server fills or copies;
406
+ * what the stories do, and what the writer's roles may (the grants); of a kind, its root item's settings
407
+ * (src/settings.ts), so only someone the grants allow hears their words; and the group's rules, which say what lands
408
+ * with it (`within`). A derived document, or one read as each member has it, is written where it's read from. */
409
+ function ask(
410
+ doc: string,
411
+ ops: Op[],
412
+ why: string | undefined,
413
+ who: { member: number } | null,
414
+ group: (doc: string, ops: Op[]) => { ops: Op[]; within?: (applied: Op[]) => void } | { refused: string },
415
+ ) {
416
+ const r = rulesOf(doc);
417
+ if (r.derived) throw new Refused(`${doc} is derived from ${r.derived.join(" and ")}: write that`);
418
+ if (r.member) throw new Refused(`${doc} is read off ${r.reads!.join(", ")}: write those`);
419
+ const roles = who ? r.rolesOf!(who.member, read, doc) : [];
420
+ // an anonymous document's writes are anyone's; any other's, each op's by who the writer is to its item
421
+ const ruled =
422
+ trusts[r.doc]?.({ doc: docParts(doc).base, ops, why }, { member: who?.member ?? 0, roles }, read) ??
423
+ serversIn(doc, ops) ??
424
+ // 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
425
+ // the item's own code: definitions' guests)
426
+ ungranted(
427
+ doc,
428
+ ops,
429
+ !who && r.anonymous ? null : (o) => rolesTo(doc, who?.member ?? null, parts(o.path).coll, itemAt(doc, o)),
430
+ anyoneIs(doc, who?.member ?? null),
431
+ ) ??
432
+ // of a kind, what its root item's settings say of a write the grants allow (a frozen board, one held for approval)
433
+ settled(
434
+ r,
435
+ settingsNow(r, () => rootItem(r, doc, read)),
436
+ ops,
437
+ );
438
+ if (ruled) throw new Refused(ruled);
439
+ // a code it makes new, the server's (whatever the page gave), before it's kept
440
+ ops = renewed(doc, ops);
441
+ if (groupless(doc, who)) return { ops };
442
+ const write = group(docParts(doc).base, ops);
443
+ if ("refused" in write) throw new Refused(write.refused);
444
+ return write;
445
+ }
446
+
447
+ /** A write and what follows from it (each app's reactions, round after round until none writes), in one
448
+ * transaction: whole, or none of it. A write is of one document, or several (src/together.ts), each part landed in
449
+ * turn, named by the adds before it. Its changes, the first the document written first's; each part's own (`parts`);
450
+ * what's told to each part of a document the pages hold (`held`); and the ops as its parts made them. `asked`: a
451
+ * page's write, each part asked its rules first, in the transaction; `undoes`, the version the write puts back, if
452
+ * it's an undo. */
453
+ function land(
454
+ writes: Part[],
455
+ by: number | null,
456
+ via: string | null,
457
+ {
458
+ undoes,
459
+ asked,
460
+ held,
461
+ }: {
462
+ undoes?: number;
463
+ asked?: (doc: string, ops: Op[], why?: string) => { ops: Op[]; within?: (applied: Op[]) => void };
464
+ held: Held;
465
+ },
466
+ ) {
467
+ return store.db.transaction(() => {
468
+ // what each person holding a part of a document saw of it, before
469
+ const before = new Map(held.views.map((v) => [v.topic, view(v.doc, v.member)]));
470
+ const changes: Change[] = [],
471
+ rows: Record<string, Row[]> = {},
472
+ applied: Op[] = [],
473
+ own: Change[] = [];
474
+ const one = (d: string, o: Op[], b: number | null, v: string | null, w?: (applied: Op[]) => void, u?: number) => {
475
+ const made = store.write(d, fill(d, withGone(d, o), b), b, v, w, { undoes: u });
476
+ // what the definitions hold of it (unique, noOverlap), once the write is done: refused whole if not
477
+ const held = rulesOf(d).holds?.(read(d), touchedBy(made.applied));
478
+ if (held) throw new Refused(held);
479
+ for (const [name, r] of Object.entries(made.rows)) (rows[name] ??= []).push(...r);
480
+ // a document read as each member has it moves its version with what it reads
481
+ // (the document written first: its change is the write's)
482
+ changes.push(...made.changes);
483
+ const tables = new Set(made.tables);
484
+ for (const r of Object.values(rules))
485
+ if (r.reads?.some((t) => tables.has(t)) && !made.changes.some((c) => c.doc === r.doc))
486
+ changes.push({ doc: r.doc, version: store.moved(r.doc), ops: [], by: b, via: v });
487
+ return made;
488
+ };
489
+ let next: Change[] = [];
490
+ inTurn(
491
+ writes,
492
+ (name) => rules[name]?.kind?.root,
493
+ (w) => {
494
+ // a page's write is asked first, here: refused, none of it lands
495
+ const { ops, within } = asked?.(w.doc, w.ops, w.why) ?? { ops: w.ops };
496
+ const made = one(docParts(w.doc).base, ops, by, via, within, undoes);
497
+ applied.push(...made.applied);
498
+ own.push(made.changes[0]!);
499
+ next.push(...made.changes);
500
+ return made.applied;
501
+ },
502
+ );
503
+ for (let round = 0; next.length; round++) {
504
+ if (round === ROUNDS) throw new Error(`what follows from a write to ${writes[0]!.doc} never settles`);
505
+ next = next.flatMap((c) =>
506
+ (reacts[docParts(c.doc).name]?.(c, read) ?? [])
507
+ .filter((w) => w.ops.length)
508
+ .flatMap((w) => {
509
+ if (docParts(w.doc).name === group || !store.exists(w.doc))
510
+ throw new Error(`a reaction can't write ${w.doc}`);
511
+ const why = ungranted(w.doc, w.ops, null);
512
+ if (why) throw new Error(`a reaction wrote what no story does: ${why}`);
513
+ return one(w.doc, w.ops, null, null).changes;
514
+ }),
515
+ );
516
+ }
517
+ const last = (name: string) => changes.findLast((c) => c.doc === name)?.version;
518
+ const told: Told = [];
519
+ // each window held: what changed in it, by its own test of each row, as it was and is
520
+ for (const topic of held.windows) {
521
+ const { base, params } = docParts(topic);
522
+ const r = rulesOf(base),
523
+ k = rootKind(topic),
524
+ code = k && rootCode(k)!;
525
+ const p = Object.fromEntries(Object.keys(params).map((k) => [k, params[k] ?? null]));
526
+ const ops = (rows[base] ?? []).flatMap(({ coll, before, after }) => {
527
+ // (held by its root's code, a kind's instance is whole: no window to test; the root's own, the item whose
528
+ // code it is alone)
529
+ const shown = (i: NonNullable<Row["before"]>) =>
530
+ code ? coll === k!.kind!.root && i[code] === params[code] : !r.inWindow || r.inWindow(coll, i, p);
531
+ const has = (i: Row["before"]) => (i && shown(i) ? i : null);
532
+ return rowOps(coll, has(before), has(after), !!r.collections[coll]?.own);
533
+ });
534
+ if (ops.length) told.push({ topic, change: { doc: topic, version: last(base)!, ops, by, via } });
535
+ }
536
+ // each part of a document a person sees: what changed of it, as they had it and have it now
537
+ for (const { topic, doc: d, member } of held.views) {
538
+ const version = last(docParts(d).base);
539
+ if (version === undefined) continue;
540
+ const ops = docOps(before.get(topic)!, view(d, member));
541
+ if (ops.length) told.push({ topic, change: { doc: d, version, ops, by, via } });
542
+ }
543
+ return { changes, told, applied, parts: own };
544
+ })();
545
+ }
546
+
547
+ return { land, view, ask, ungranted, mayOf, read, rulesOf, mayHold, groupless, byCode, exists };
548
+ }
549
+
550
+ /** A grant as an item's `may` token (mayOf), or undefined where it isn't one to an item: `remove orders` is "remove",
551
+ * `replace supplies.terms.days` "replace:terms.days"; a move (`replace orders.status:placed>being made`), only from
552
+ * where the item is, "replace:status>being%20made". */
553
+ function itemToken(grant: string, coll: string, item: Record<string, unknown>, moved?: string) {
554
+ const sp = grant.indexOf(" "),
555
+ op = grant.slice(0, sp),
556
+ of = grant.slice(sp + 1);
557
+ if (of === coll) return op === "remove" ? op : undefined;
558
+ // (an add's first step is the collection's add, no item's)
559
+ if (!of.startsWith(`${coll}.`) || (op === "add" && moved && of.startsWith(`${coll}.${moved}:`))) return undefined;
560
+ const field = of.slice(coll.length + 1),
561
+ step = moved && field.startsWith(`${moved}:`) ? field.slice(moved.length + 1) : undefined;
562
+ if (step === undefined) return `${op}:${field}`;
563
+ const gt = step.indexOf(">"),
564
+ from = step.slice(0, gt),
565
+ to = step.slice(gt + 1);
566
+ return from === `${item[moved!]}` ? `${op}:${moved}>${encodeURIComponent(to)}` : undefined;
567
+ }
@@ -0,0 +1,37 @@
1
+ # An app on joined
2
+
3
+ Context for an AI working here. To build anything, load the `joined` skill (`.claude/skills/joined/`) and read
4
+ only the section of its `reference.md` your task needs. joined's own files (`src/`, `examples/`, `docs/`) are in
5
+ `node_modules/joined/`: its examples are what to copy, smallest first, as the skill's contents table points.
6
+
7
+ ## Where things are
8
+
9
+ - `apps/hello/` is where an app starts: a greeting anyone may change, at `/`. It's there to be replaced: an app of
10
+ your own that takes `/` deletes it and `tests/hello*` first (two apps can't answer one path).
11
+ - `apps/<app>/`, each app: its `stories.jsonl` (what happens to its document, one story a line), its seed
12
+ (`<doc>.json`), `routes.ts`, its page (`index.html`, `page.ts`, its stylesheet), and what the compiler writes:
13
+ `generated/` and `migrations/`. `apps/app.css` is the apps' shared look.
14
+ - `apps/members.json`, once an app has members: the group's seed, its people by id and name (§11 of the skill).
15
+ - `tests/`: each app's stories told (`joined/stories`), its page's in a browser (`hello-page.test.ts`), and
16
+ anything else of the app's own.
17
+ - What the pages change is kept in `.data/` (`JOINED_DATA`); `.env` holds `ROOT_TOKEN` once an app has members.
18
+
19
+ ## Rules
20
+
21
+ - **Stories first.** A new behaviour starts as a story; build only what a story needs.
22
+ - **The compiler is deterministic; never stand in for it.** Change the stories, then `bun run compile`; never edit
23
+ `generated/`. Commit the migration it writes; never change one that has run anywhere.
24
+ - **The light DOM is the document; the shadow DOM is the display.** Only joined's applier writes a document's
25
+ elements; a view or a display changes one only through its element's ops. A display moves only what changed.
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).
28
+ - **An element is defined last in its module,** and a document's elements are named by the compiler's
29
+ collections, never by a tag typed out.
30
+ - **Never put `.env`, `.data/` or anyone's link in a commit,** nor in chat.
31
+ - **Look at a change in the page** (`bun run dev`) before calling it done. `dev` runs a demo on this machine: an
32
+ app's home page carries `<joined-demo>` (`import "joined/demo"`), a line to be anyone in the group, the BDFL first,
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`.
36
+ - **joined is upgraded by `bun run upgrade [version]`:** it moves the version, refreshes the skill and
37
+ compiles again.
@@ -0,0 +1,3 @@
1
+ node_modules/
2
+ .data/
3
+ .env
@@ -0,0 +1,14 @@
1
+ // hello's page, in a browser: each story the page offers, told as the page sends it, as its member
2
+ // (joined/stories' inBrowser); what the page didn't offer, or didn't send, said a line each.
3
+
4
+ import { expect, test } from "bun:test";
5
+ import { inBrowser } from "joined/stories";
6
+
7
+ test("hello's page offers each of its stories, and sends it as a page does", async () => {
8
+ const view = new Bun.WebView({ width: 900, height: 1000 });
9
+ try {
10
+ expect(await inBrowser("hello", () => "/hello", view)).toEqual([]);
11
+ } finally {
12
+ view.close();
13
+ }
14
+ }, 120_000);
@@ -0,0 +1,8 @@
1
+ // hello's stories, told: each does what it says, and what it says can't be done is refused (joined/stories).
2
+
3
+ import { expect, test } from "bun:test";
4
+ import { tell } from "joined/stories";
5
+
6
+ test("hello's stories go as they say", async () => {
7
+ expect(await tell("hello")).toEqual([]);
8
+ });
@@ -0,0 +1,17 @@
1
+ {
2
+ "compilerOptions": {
3
+ "lib": ["ESNext", "DOM", "DOM.Iterable"],
4
+ "target": "ESNext",
5
+ "module": "Preserve",
6
+ "moduleDetection": "force",
7
+ "types": ["bun"],
8
+ "moduleResolution": "bundler",
9
+ "allowImportingTsExtensions": true,
10
+ "verbatimModuleSyntax": true,
11
+ "noEmit": true,
12
+ "strict": true,
13
+ "skipLibCheck": true,
14
+ "noUncheckedIndexedAccess": true
15
+ },
16
+ "include": ["**/*", "node_modules/joined/src/css.d.ts"]
17
+ }