@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
@@ -17,7 +17,8 @@ import { collections } from "./generated/rules.ts";
17
17
  import { JMember, type JMembers } from "./generated/elements.ts";
18
18
  import { consequences, type Member } from "./trust.ts";
19
19
  import STYLE from "./panel.css" with { type: "text" };
20
- import { adopt, said, showsOpen } from "../parts.ts";
20
+ import { adopt, said } from "../parts.ts";
21
+ import { Surface } from "../surface.ts";
21
22
  import type { Answer } from "../page.ts";
22
23
 
23
24
  customElements.define(collections.members.tag, JMember);
@@ -80,25 +81,36 @@ class MembersPanel extends HTMLElement {
80
81
  if (!this.querySelector(collections.members.place)) this.append(document.createElement(collections.members.place));
81
82
  adopt(this.#root, SHEET);
82
83
  this.#root.innerHTML = `
83
- <div class="bar" part="bar"><button class="who act" part="who" popovertarget="group" type="button"><span>The group</span></button><span class="status" role="status"></span><span class="waiting" part="waiting" role="status"></span><span class="note"></span></div>
84
+ <div class="bar" part="bar"><button class="who act" part="who" type="button" aria-expanded="false"><span>The group</span></button><span class="status" role="status"></span><span class="waiting" part="waiting" role="status"></span><span class="note"></span></div>
84
85
  <div class="notice" part="notice" hidden><p></p><button class="icon-only" type="button" name="close" aria-label="Close" title="Close" data-icon="close"></button></div>
85
- <div id="group" class="sheet" part="sheet" popover>
86
- <header><h2>The group</h2><button type="button" class="icon-only" popovertarget="group" popovertargetaction="hide" aria-label="Close" title="Close" data-icon="close"></button></header>
87
- <div class="j-tabs" role="tablist" aria-label="The group"><button type="button" role="tab" name="people"></button><button type="button" role="tab" name="agents"></button></div>
88
- <div class="people" role="tabpanel"><ul class="tree"></ul>
89
- <form class="invite"><input name="name" placeholder="Invite someone by name" aria-label="Invite someone by name" required autocomplete="off"><button type="button" name="readonly" class="act icon-only" aria-pressed="false" aria-label="Invite them read-only" title="Invite them read-only" data-icon="read-only"></button><button class="act ink icon-only" aria-label="Invite" title="Invite" data-icon="person-add"></button></form></div>
90
- <div class="agents" role="tabpanel"><ul></ul>
91
- <form class="agent"><input name="label" placeholder="A label, as claude" aria-label="An agent's label" required autocomplete="off"><button class="act" data-icon="add">Make</button></form></div>
86
+ <div class="group">
87
+ <wa-tab-group aria-label="The group"><wa-tab slot="nav" panel="people"></wa-tab><wa-tab slot="nav" panel="agents"></wa-tab>
88
+ <wa-tab-panel name="people" class="people"><ul class="tree"></ul>
89
+ <form class="invite"><wa-input class="j-bare" name="name" placeholder="Invite someone by name" label="Invite someone by name" required autocomplete="off"></wa-input><button type="button" name="readonly" class="act icon-only" aria-pressed="false" aria-label="Invite them read-only" title="Invite them read-only" data-icon="read-only"></button><button class="act ink icon-only" aria-label="Invite" title="Invite" data-icon="person-add"></button></form></wa-tab-panel>
90
+ <wa-tab-panel name="agents" class="agents"><ul></ul>
91
+ <form class="agent"><wa-input class="j-bare" name="label" placeholder="A label, as claude" label="An agent's label" required autocomplete="off"></wa-input><button class="act" data-icon="add">Make</button></form></wa-tab-panel></wa-tab-group>
92
92
  <div class="leave"><form class="out" method="post" action="/out"><button class="act quiet" data-icon="out">Sign out of this browser</button></form><a class="act quiet" href="/export" download="joined.json" data-icon="download">Download all you can see</a></div>
93
93
  <div class="menu j-choices" part="menu" popover role="menu"></div>
94
- <dialog class="ask" part="ask"><h2></h2><p></p><label>Why, in words they'll read<textarea></textarea></label>
95
- <footer><button type="button" name="no" class="act">Never mind</button><button type="button" name="yes" class="act danger"></button></footer></dialog>
96
- </div>`;
94
+ </div>
95
+ <wa-dialog class="ask j-ask" part="ask" light-dismiss><h2 slot="label"></h2><p></p><wa-textarea label="Why, in words they'll read" resize="auto"></wa-textarea>
96
+ <footer slot="footer"><button type="button" name="no" class="act">Never mind</button><button type="button" name="yes" class="act danger"></button></footer></wa-dialog>`;
97
97
  iconify(this.#root);
98
- showsOpen(this.#root);
99
98
  const $ = <T extends Element>(s: string) => this.#root.querySelector<T>(s)!;
100
- for (const tab of ["people", "agents"] as const)
101
- $(`[role=tab][name=${tab}]`).addEventListener("click", () => ((this.#tab = tab), this.#draw()));
99
+ const who = $<HTMLButtonElement>(".who"),
100
+ sheet: Surface = new Surface("sheet", $(".group"), null, () => shown(false), { label: "The group" }),
101
+ // the button that opens it says so while it's open
102
+ shown = (open: boolean) => ((sheet.open = open), who.setAttribute("aria-expanded", String(open)));
103
+ sheet.title.textContent = "The group";
104
+ for (const el of sheet.els) el.id = el === sheet.wide ? "group" : "group-phone";
105
+ this.#root.append(...sheet.els);
106
+ // pressed while it's open, it closes: as it was when the press began (a tap away closes a popover first)
107
+ let was = false;
108
+ who.addEventListener("pointerdown", () => (was = sheet.open));
109
+ who.addEventListener("click", (e) => shown(e.detail ? !was : !sheet.open));
110
+ $("wa-tab-group").addEventListener("wa-tab-show", (e) => {
111
+ this.#tab = (e as CustomEvent<{ name: "people" | "agents" }>).detail.name;
112
+ this.#draw();
113
+ });
102
114
  // inviting someone read-only: they see everything and change nothing until you give it back
103
115
  const readonly = $<HTMLButtonElement>("form.invite [name=readonly]");
104
116
  const pressed = () => readonly.getAttribute("aria-pressed") === "true";
@@ -106,7 +118,7 @@ class MembersPanel extends HTMLElement {
106
118
  $("form.invite").addEventListener("submit", (e) => {
107
119
  e.preventDefault();
108
120
  const name = ($("form.invite") as HTMLFormElement).elements.namedItem("name") as HTMLInputElement;
109
- if (this.#told && name.value.trim())
121
+ if (this.#told && name.value?.trim())
110
122
  this.#said(
111
123
  this.querySelector<JMembers>(collections.members.place)!.add({
112
124
  name: name.value.trim(),
@@ -120,18 +132,19 @@ class MembersPanel extends HTMLElement {
120
132
  $("form.agent").addEventListener("submit", (e) => {
121
133
  e.preventDefault();
122
134
  const label = ($("form.agent") as HTMLFormElement).elements.namedItem("label") as HTMLInputElement;
123
- this.#said(ask("members", { agent: label.value.trim().toLowerCase() }));
135
+ this.#said(ask("members", { agent: (label.value ?? "").trim().toLowerCase() }));
124
136
  label.value = "";
125
137
  });
126
138
  $("[name=close]").addEventListener("click", () => this.#said(ask("members", { closeNotice: true })));
127
- $("[name=no]").addEventListener("click", () => $<HTMLDialogElement>("dialog.ask").close());
128
- // a dialog's close event comes a moment after it closes: if it's been asked again since, it's that act's
129
- $("dialog.ask").addEventListener(
130
- "close",
131
- (e) => !(e.target as HTMLDialogElement).open && ((this.#act = null), this.#draw()),
139
+ const asking = $<HTMLElement & { open: boolean }>("wa-dialog.ask");
140
+ $("[name=no]").addEventListener("click", () => (asking.open = false));
141
+ // closed (Never mind, its ×, Escape, a tap away): the act asked for is let go; asked again since, it's that act's
142
+ asking.addEventListener(
143
+ "wa-after-hide",
144
+ (e) => e.target === asking && !asking.open && ((this.#act = null), this.#draw()),
132
145
  );
133
146
  $("[name=yes]").addEventListener("click", () => this.#confirm());
134
- $("textarea").addEventListener("input", () => this.#draw());
147
+ $("wa-textarea").addEventListener("input", () => this.#draw());
135
148
 
136
149
  document.addEventListener("told", (e) => {
137
150
  const m = (e as CustomEvent).detail;
@@ -207,15 +220,16 @@ class MembersPanel extends HTMLElement {
207
220
  // people and agents, a tab each; an agent, or someone signed out, sees only the people
208
221
  const ours = !!told && !told.agent;
209
222
  if (!ours) this.#tab = "people";
210
- $<HTMLElement>(".j-tabs")!.hidden = !ours;
223
+ const tabs = $<HTMLElement & { active: string }>("wa-tab-group")!;
224
+ tabs.classList.toggle("alone", !ours);
211
225
  for (const [tab, words] of [
212
226
  ["people", `People · ${members.length}`],
213
227
  ["agents", `Agents · ${told?.agents.length ?? 0}`],
214
228
  ] as const) {
215
- $(`[role=tab][name=${tab}]`)!.textContent = words;
216
- $(`[role=tab][name=${tab}]`)!.ariaSelected = String(tab === this.#tab);
217
- $<HTMLElement>(`[role=tabpanel].${tab}`)!.hidden = tab !== this.#tab;
229
+ const t = $(`wa-tab[panel=${tab}]`)!;
230
+ if (t.textContent !== words) t.textContent = words;
218
231
  }
232
+ if (tabs.active !== this.#tab) tabs.setAttribute("active", this.#tab);
219
233
  $<HTMLElement>("form.invite")!.hidden = !ours;
220
234
  $<HTMLElement>(".leave")!.hidden = !told; // signed in: a way out, and what they can see to take
221
235
  keep(
@@ -238,14 +252,14 @@ class MembersPanel extends HTMLElement {
238
252
  })),
239
253
  );
240
254
  // an act asked for, in a dialog: what follows, why, and yes; gone meanwhile, it closes
241
- const asked = $<HTMLDialogElement>("dialog.ask")!,
255
+ const asked = $<HTMLElement & { open: boolean }>("wa-dialog.ask")!,
242
256
  them = members.find((m) => m.id === this.#act?.member);
243
257
  if (!this.#act || !them) {
244
- if (asked.open) asked.close();
258
+ if (asked.open) asked.open = false;
245
259
  return;
246
260
  }
247
261
  const yes = asked.querySelector<HTMLButtonElement>("[name=yes]")!,
248
- why = asked.querySelector("textarea")!;
262
+ why = asked.querySelector<HTMLTextAreaElement>("wa-textarea")!;
249
263
  const does =
250
264
  this.#act.kind === "removed"
251
265
  ? `Remove ${them.name}`
@@ -254,11 +268,11 @@ class MembersPanel extends HTMLElement {
254
268
  : `Give ${them.name} back what they could do`;
255
269
  asked.querySelector("h2")!.textContent = `${does}?`;
256
270
  asked.querySelector("p")!.textContent = consequences(this.#act.kind, them, members);
257
- asked.querySelector("label")!.hidden = this.#act.kind === "restored";
271
+ why.hidden = this.#act.kind === "restored";
258
272
  yes.replaceChildren(icon(MARKS[this.#act.kind]), does);
259
273
  yes.className = this.#act.kind === "restored" ? "act ink" : "act danger";
260
- yes.disabled = this.#act.kind !== "restored" && !why.value.trim();
261
- if (!asked.open) asked.showModal();
274
+ yes.disabled = this.#act.kind !== "restored" && !why.value?.trim();
275
+ if (!asked.open) asked.open = true;
262
276
  }
263
277
 
264
278
  /** Each member's row, depth first from the BDFL: their name, what they are, and what you may do. What
@@ -384,14 +398,14 @@ class MembersPanel extends HTMLElement {
384
398
 
385
399
  #ask(act: Act) {
386
400
  this.#act = act;
387
- this.#root.querySelector("textarea")!.value = "";
401
+ this.#root.querySelector<HTMLTextAreaElement>("wa-textarea")!.value = "";
388
402
  this.#draw();
389
403
  }
390
404
 
391
405
  #confirm() {
392
406
  const act = this.#act,
393
407
  el = act && this.#element(act.member),
394
- why = this.#root.querySelector("textarea")!.value.trim();
408
+ why = (this.#root.querySelector<HTMLTextAreaElement>("wa-textarea")!.value ?? "").trim();
395
409
  if (!act || !el) return;
396
410
  this.#said(
397
411
  act.kind === "removed"
package/src/migrate.ts CHANGED
@@ -47,7 +47,7 @@ export type Change =
47
47
  | { change: "guardTable"; key: string; table: Table };
48
48
  /** What a step does to the rows, once its changes are made, in its transaction: moves or fills them, by
49
49
  * SQL; a row it adds takes `nextId(table)`, so no write later meets it. */
50
- export type Up = (db: Engine, tools: { nextId: (table: string) => number }) => void;
50
+ export type Up = (db: Engine, tools: { nextId: (table: string) => Promise<number> }) => unknown;
51
51
  /** One step of a history: its name (the file's), recorded once it has run, its changes, and its `up`. */
52
52
  export type Migration = { id: string; changes: Change[]; up?: Up };
53
53
 
@@ -279,26 +279,32 @@ const SQL: Record<ColumnType, Record<Dialect, string> & { empty: string }> = {
279
279
  /** Where joined records what has run, and keeps each table's last id. */
280
280
  const RAN = "joined_migrations",
281
281
  SEQUENCES = "joined_sequences";
282
- const has = (db: Engine, table: string) => db.columns(table).length > 0;
282
+ const has = async (db: Engine, table: string) => (await db.columns(table)).length > 0;
283
283
  const uniqueName = (table: string, columns: string[]) => `idx_${table}_unique_${columns.join("_")}`;
284
284
  /** A table's unique indexes, by name and columns. */
285
- const uniquesOf = (db: Engine, table: string): { name: string; columns: string[] }[] =>
286
- db.dialect === "sqlite"
287
- ? (db.query(`PRAGMA index_list(${q(table)})`).all() as { name: string; origin: string }[])
288
- .filter((i) => i.origin === "c")
289
- .map((i) => ({
290
- name: i.name,
291
- columns: (db.query(`PRAGMA index_info(${q(i.name)})`).all() as { name: string }[]).map((c) => c.name),
292
- }))
293
- : (
294
- db
295
- .query(
296
- `SELECT i.relname AS name, json_agg(a.attname ORDER BY k.n)::text AS columns FROM pg_index x JOIN pg_class i ON i.oid = x.indexrelid
285
+ async function uniquesOf(db: Engine, table: string): Promise<{ name: string; columns: string[] }[]> {
286
+ if (db.dialect === "sqlite") {
287
+ const made = (
288
+ (await db.query(`PRAGMA index_list(${q(table)})`).all()) as { name: string; origin: string }[]
289
+ ).filter((i) => i.origin === "c");
290
+ const out = [];
291
+ for (const i of made)
292
+ out.push({
293
+ name: i.name,
294
+ columns: ((await db.query(`PRAGMA index_info(${q(i.name)})`).all()) as { name: string }[]).map((c) => c.name),
295
+ });
296
+ return out;
297
+ }
298
+ return (
299
+ (await db
300
+ .query(
301
+ `SELECT i.relname AS name, json_agg(a.attname ORDER BY k.n)::text AS columns FROM pg_index x JOIN pg_class i ON i.oid = x.indexrelid
297
302
  CROSS JOIN LATERAL unnest(x.indkey) WITH ORDINALITY k(attnum, n) JOIN pg_attribute a ON a.attrelid = x.indrelid AND a.attnum = k.attnum
298
303
  WHERE x.indrelid = to_regclass(?) AND x.indisunique AND NOT x.indisprimary GROUP BY i.relname`,
299
- )
300
- .all(q(table)) as { name: string; columns: string }[]
301
- ).map((i) => ({ name: i.name, columns: JSON.parse(i.columns) }));
304
+ )
305
+ .all(q(table))) as { name: string; columns: string }[]
306
+ ).map((i) => ({ name: i.name, columns: JSON.parse(i.columns) }));
307
+ }
302
308
  const makeUnique = (db: Engine, table: string, columns: string[]) =>
303
309
  db.run(
304
310
  `CREATE UNIQUE INDEX IF NOT EXISTS ${q(uniqueName(table, columns))} ON ${q(table)} (${columns.map(q).join(", ")})`,
@@ -351,23 +357,23 @@ const tableSql = (db: Engine, key: string, t: Table) =>
351
357
  "PRIMARY KEY (id)",
352
358
  ].join(", ")})${t.strict && db.dialect === "sqlite" ? " STRICT" : ""}`;
353
359
  /** The triggers named so, whatever table each is on, dropped. */
354
- export const dropTriggers = (db: Engine, like: string) => {
355
- const found = db
360
+ export const dropTriggers = async (db: Engine, like: string) => {
361
+ const found = (await db
356
362
  .query(
357
363
  db.dialect === "sqlite"
358
364
  ? "SELECT name, tbl_name AS tbl FROM sqlite_master WHERE type = 'trigger' AND name LIKE ?"
359
365
  : "SELECT tgname AS name, c.relname AS tbl FROM pg_trigger t JOIN pg_class c ON c.oid = t.tgrelid WHERE NOT t.tgisinternal AND tgname LIKE ?",
360
366
  )
361
- .all(like) as { name: string; tbl: string }[];
367
+ .all(like)) as { name: string; tbl: string }[];
362
368
  for (const { name, tbl } of found)
363
- db.run(`DROP TRIGGER ${q(name)}${db.dialect === "postgres" ? ` ON ${q(tbl)}` : ""}`);
369
+ await db.run(`DROP TRIGGER ${q(name)}${db.dialect === "postgres" ? ` ON ${q(tbl)}` : ""}`);
364
370
  };
365
371
  /** A table's guards that a CHECK can't say, as its triggers: an add without what it needs (an add: the row its
366
372
  * sequence has just given out); a link to a row that
367
373
  * isn't there; a unique set written again. Each refused in its words, the first that says so. */
368
- function guardWith(db: Engine, key: string, t: Table | undefined) {
369
- for (const when of ["insert", "update"]) dropTriggers(db, `joined_${key}_${when}`);
370
- guardHeld(db, key, t);
374
+ async function guardWith(db: Engine, key: string, t: Table | undefined) {
375
+ for (const when of ["insert", "update"]) await dropTriggers(db, `joined_${key}_${when}`);
376
+ await guardHeld(db, key, t);
371
377
  if (!t) return;
372
378
  const links = Object.entries(t.columns).flatMap(([c, d]): [string, string][] =>
373
379
  d.to
@@ -386,9 +392,9 @@ function guardWith(db: Engine, key: string, t: Table | undefined) {
386
392
  `EXISTS (SELECT 1 FROM ${q(key)} WHERE ${t.unique[0].map((c) => `${q(c)} = NEW.${q(c)}`).join(" AND ")})`,
387
393
  t.once,
388
394
  ]);
389
- const trigger = (when: string, cases: [string, string][]) =>
395
+ const trigger = async (when: string, cases: [string, string][]) =>
390
396
  cases.length &&
391
- db.run(
397
+ (await db.run(
392
398
  triggerSql(db.dialect, {
393
399
  name: `joined_${key}_${when}`,
394
400
  at: "BEFORE",
@@ -396,36 +402,36 @@ function guardWith(db: Engine, key: string, t: Table | undefined) {
396
402
  table: key,
397
403
  body: cases.map(([cond, said]) => refuseSql(db.dialect, cond, words(said))).join(" "),
398
404
  }),
399
- );
400
- trigger("insert", insert);
401
- trigger("update", links);
405
+ ));
406
+ await trigger("insert", insert);
407
+ await trigger("update", links);
402
408
  }
403
409
 
404
410
  /** A Postgres table's links made its foreign keys, each once the table it links to is there (another app's may come
405
411
  * later: the store makes them, once every app's have run). */
406
- export function linked(db: Engine, key: string, t: Table | undefined) {
412
+ export async function linked(db: Engine, key: string, t: Table | undefined) {
407
413
  if (db.dialect === "sqlite") return;
408
414
  for (const [c, d] of Object.entries(t?.columns ?? {})) {
409
415
  const name = `${key}_${c}_fkey`;
410
416
  if (
411
417
  d.to &&
412
- has(db, d.to.table) &&
413
- !db.query("SELECT 1 FROM pg_constraint WHERE conrelid = to_regclass(?) AND conname = ?").get(q(key), name)
418
+ (await has(db, d.to.table)) &&
419
+ !(await db.query("SELECT 1 FROM pg_constraint WHERE conrelid = to_regclass(?) AND conname = ?").get(q(key), name))
414
420
  )
415
- db.run(`ALTER TABLE ${q(key)} ADD CONSTRAINT ${q(name)} FOREIGN KEY (${q(c)})${references(db, d, true)}`);
421
+ await db.run(`ALTER TABLE ${q(key)} ADD CONSTRAINT ${q(name)} FOREIGN KEY (${q(c)})${references(db, d, true)}`);
416
422
  }
417
423
  }
418
424
 
419
425
  /** A table's links guarded where they point: a row linked to, removed, is refused before its foreign key would, in
420
426
  * words saying how many link to it. A trigger on the table linked to, made once that's there (another app's may
421
427
  * come later: the store makes them all again, once every app's have run). */
422
- export function guardHeld(db: Engine, key: string, t: Table | undefined) {
423
- dropTriggers(db, `joined_${key}_held_%`);
428
+ export async function guardHeld(db: Engine, key: string, t: Table | undefined) {
429
+ await dropTriggers(db, `joined_${key}_held_%`);
424
430
  for (const [c, d] of Object.entries(t?.columns ?? {}))
425
- if (d.to?.held && has(db, d.to.table)) {
431
+ if (d.to?.held && (await has(db, d.to.table))) {
426
432
  const n = `(SELECT COUNT(*) FROM ${q(key)} WHERE ${q(c)} = OLD.id)`;
427
433
  const [one, many] = d.to.held.map((w) => `'${w.replaceAll("'", "''")}'`);
428
- db.run(
434
+ await db.run(
429
435
  triggerSql(db.dialect, {
430
436
  name: `joined_${key}_held_${c}`,
431
437
  at: "BEFORE",
@@ -456,83 +462,87 @@ const checks = (t: Table) => [
456
462
 
457
463
  /** One change made on the database, the tables before it and after: its table's triggers made again from what it
458
464
  * is. */
459
- function make(db: Engine, c: Change, before: State, after: State) {
460
- guardWith(db, c.key, undefined);
465
+ async function make(db: Engine, c: Change, before: State, after: State) {
466
+ await guardWith(db, c.key, undefined);
461
467
  if (c.change === "createTable") {
462
- if (!has(db, c.key)) db.run(tableSql(db, c.key, c.table));
463
- for (const u of c.table.unique ?? []) makeUnique(db, c.key, u);
468
+ if (!(await has(db, c.key))) await db.run(tableSql(db, c.key, c.table));
469
+ for (const u of c.table.unique ?? []) await makeUnique(db, c.key, u);
464
470
  } else if (c.change === "guardTable") {
465
471
  // its triggers alone, unless what a CHECK says changed: then
466
472
  if (same(checks(before[c.key]!), checks(c.table))) return guardWith(db, c.key, after[c.key]);
467
473
  // Postgres changes a table's CHECKs and foreign keys in place: each dropped, and made again from what it is
468
474
  if (db.dialect === "postgres") {
469
- for (const { name } of db
475
+ for (const { name } of (await db
470
476
  .query("SELECT conname AS name FROM pg_constraint WHERE conrelid = to_regclass(?) AND contype IN ('c', 'f')")
471
- .all(q(c.key)) as { name: string }[])
472
- db.run(`ALTER TABLE ${q(c.key)} DROP CONSTRAINT ${q(name)}`);
477
+ .all(q(c.key))) as { name: string }[])
478
+ await db.run(`ALTER TABLE ${q(c.key)} DROP CONSTRAINT ${q(name)}`);
473
479
  for (const [col, d] of Object.entries(c.table.columns)) {
474
- if (d.is) db.run(`ALTER TABLE ${q(c.key)} ADD${checkSql(db, col, d)}`);
480
+ if (d.is) await db.run(`ALTER TABLE ${q(c.key)} ADD${checkSql(db, col, d)}`);
475
481
  // a column made optional (one made needed is a person's, and its empty rows theirs to fill)
476
- if (d.nullable) db.run(`ALTER TABLE ${q(c.key)} ALTER COLUMN ${q(col)} DROP NOT NULL`);
482
+ if (d.nullable) await db.run(`ALTER TABLE ${q(c.key)} ALTER COLUMN ${q(col)} DROP NOT NULL`);
477
483
  }
478
- linked(db, c.key, c.table);
484
+ await linked(db, c.key, c.table);
479
485
  return guardWith(db, c.key, after[c.key]);
480
486
  }
481
487
  // made anew beside it, its rows copied, and put in its place; what else names it (another's trigger) isn't
482
488
  // rewritten as it's renamed, so it names this one
483
- const there = db.columns(c.key),
489
+ const there = await db.columns(c.key),
484
490
  was = Object.keys(c.table.columns).filter((col) => there.includes(col));
485
- db.run(tableSql(db, `${c.key}__new`, c.table));
486
- db.run(
491
+ await db.run(tableSql(db, `${c.key}__new`, c.table));
492
+ await db.run(
487
493
  `INSERT INTO ${q(`${c.key}__new`)} (${["id", ...was].map(q).join(", ")}) SELECT ${["id", ...was].map(q).join(", ")} FROM ${q(c.key)}`,
488
494
  );
489
- db.run(`DROP TABLE ${q(c.key)}`);
490
- db.run("PRAGMA legacy_alter_table = ON");
491
- db.run(`ALTER TABLE ${q(`${c.key}__new`)} RENAME TO ${q(c.key)}`);
492
- db.run("PRAGMA legacy_alter_table = OFF");
493
- for (const u of c.table.unique ?? []) makeUnique(db, c.key, u);
495
+ await db.run(`DROP TABLE ${q(c.key)}`);
496
+ await db.run("PRAGMA legacy_alter_table = ON");
497
+ await db.run(`ALTER TABLE ${q(`${c.key}__new`)} RENAME TO ${q(c.key)}`);
498
+ await db.run("PRAGMA legacy_alter_table = OFF");
499
+ for (const u of c.table.unique ?? []) await makeUnique(db, c.key, u);
494
500
  } else if (c.change === "dropTable") {
495
- db.run(`DROP TABLE IF EXISTS ${q(c.key)}`);
496
- db.run(`DELETE FROM ${SEQUENCES} WHERE collection = ?`, [c.key]);
501
+ await db.run(`DROP TABLE IF EXISTS ${q(c.key)}`);
502
+ await db.run(`DELETE FROM ${SEQUENCES} WHERE collection = ?`, [c.key]);
497
503
  } else if (c.change === "renameTable") {
498
- db.run(`ALTER TABLE ${q(c.key)} RENAME TO ${q(c.to)}`);
499
- guardWith(db, c.to, after[c.to]);
500
- for (const u of uniquesOf(db, c.to)) (db.run(`DROP INDEX ${q(u.name)}`), makeUnique(db, c.to, u.columns));
501
- db.run(`UPDATE ${SEQUENCES} SET collection = ? WHERE collection = ?`, [c.to, c.key]);
504
+ await db.run(`ALTER TABLE ${q(c.key)} RENAME TO ${q(c.to)}`);
505
+ await guardWith(db, c.to, after[c.to]);
506
+ for (const u of await uniquesOf(db, c.to))
507
+ (await db.run(`DROP INDEX ${q(u.name)}`), await makeUnique(db, c.to, u.columns));
508
+ await db.run(`UPDATE ${SEQUENCES} SET collection = ? WHERE collection = ?`, [c.to, c.key]);
502
509
  } else if (c.change === "addColumn") {
503
510
  // every row takes the column's empty value; one with none (json, a time) is left to be empty
504
511
  const { empty } = SQL[c.def.type];
505
512
  const fill = c.def.nullable || empty === "NULL" ? "" : ` NOT NULL DEFAULT ${empty}`;
506
- db.run(
513
+ await db.run(
507
514
  `ALTER TABLE ${q(c.key)} ADD COLUMN ${columnSql(db, c.column, { ...c.def, nullable: true }, after[c.key]!.strict)}${fill}`,
508
515
  );
509
516
  } else if (c.change === "dropColumn") {
510
- for (const u of uniquesOf(db, c.key)) if (u.columns.includes(c.column)) db.run(`DROP INDEX ${q(u.name)}`);
511
- db.run(`ALTER TABLE ${q(c.key)} DROP COLUMN ${q(c.column)}`);
517
+ for (const u of await uniquesOf(db, c.key))
518
+ if (u.columns.includes(c.column)) await db.run(`DROP INDEX ${q(u.name)}`);
519
+ await db.run(`ALTER TABLE ${q(c.key)} DROP COLUMN ${q(c.column)}`);
512
520
  } else {
513
- db.run(`ALTER TABLE ${q(c.key)} RENAME COLUMN ${q(c.column)} TO ${q(c.to)}`);
514
- for (const u of uniquesOf(db, c.key)) db.run(`DROP INDEX ${q(u.name)}`);
515
- for (const u of after[c.key]!.unique ?? []) makeUnique(db, c.key, u);
521
+ await db.run(`ALTER TABLE ${q(c.key)} RENAME COLUMN ${q(c.column)} TO ${q(c.to)}`);
522
+ for (const u of await uniquesOf(db, c.key)) await db.run(`DROP INDEX ${q(u.name)}`);
523
+ for (const u of after[c.key]!.unique ?? []) await makeUnique(db, c.key, u);
516
524
  }
517
- guardWith(db, c.key, after[c.key]);
525
+ await guardWith(db, c.key, after[c.key]);
518
526
  }
519
527
 
520
528
  /** An app's migrations not yet run here, run in order, each with its `up` and its record in one transaction; the
521
529
  * ids it ran. A database from before 0.8 has delta's names for joined's two tables: they're renamed,
522
530
  * and what they hold is kept. */
523
- export function migrate(db: Engine, app: string, list: Migration[]): string[] {
524
- db.transaction(() => {
531
+ export async function migrate(db: Engine, app: string, list: Migration[]): Promise<string[]> {
532
+ await db.transaction(async () => {
525
533
  for (const [was, now] of [
526
534
  ["delta_migrations", RAN],
527
535
  ["_delta_sequences", SEQUENCES],
528
536
  ] as const)
529
- if (has(db, was) && !has(db, now)) db.run(`ALTER TABLE ${q(was)} RENAME TO ${now}`);
530
- db.run(
537
+ if ((await has(db, was)) && !(await has(db, now))) await db.run(`ALTER TABLE ${q(was)} RENAME TO ${now}`);
538
+ await db.run(
531
539
  `CREATE TABLE IF NOT EXISTS ${RAN} (app TEXT NOT NULL, id TEXT NOT NULL, ran_at TEXT NOT NULL, PRIMARY KEY (app, id))`,
532
540
  );
533
- db.run(`CREATE TABLE IF NOT EXISTS ${SEQUENCES} (collection TEXT PRIMARY KEY, last INTEGER NOT NULL)`);
534
- }).immediate();
535
- const done = new Set((db.query(`SELECT id FROM ${RAN} WHERE app = ?`).all(app) as { id: string }[]).map((r) => r.id));
541
+ await db.run(`CREATE TABLE IF NOT EXISTS ${SEQUENCES} (collection TEXT PRIMARY KEY, last INTEGER NOT NULL)`);
542
+ });
543
+ const done = new Set(
544
+ ((await db.query(`SELECT id FROM ${RAN} WHERE app = ?`).all(app)) as { id: string }[]).map((r) => r.id),
545
+ );
536
546
  const ran: string[] = [];
537
547
  let state: State = {};
538
548
  for (const m of list) {
@@ -543,50 +553,56 @@ export function migrate(db: Engine, app: string, list: Migration[]): string[] {
543
553
  // link to it (or refused by them): its foreign keys are off while it runs (they can't be turned off inside its
544
554
  // transaction), and checked whole before it commits
545
555
  const rebuilds = db.dialect === "sqlite" && m.changes.some((c) => c.change === "guardTable");
546
- if (rebuilds) db.run("PRAGMA foreign_keys = OFF");
556
+ if (rebuilds) await db.run("PRAGMA foreign_keys = OFF");
547
557
  try {
548
- db.transaction(() => {
558
+ await db.transaction(async () => {
549
559
  // a table made again beside itself is put in its place by commit, its links whole again by then
550
- db.defer();
551
- m.changes.reduce((s, c) => {
560
+ await db.defer();
561
+ let s = before;
562
+ for (const c of m.changes) {
552
563
  const after = applyChange(s, c);
553
- make(db, c, s, after);
554
- return after;
555
- }, before);
556
- // the transaction is synchronous: an up that awaits would land outside it
557
- if ((m.up?.(db, { nextId: (table) => nextId(db, table) }) as unknown) instanceof Promise)
558
- throw new Error("its up is async: an up is synchronous, as the transaction is");
564
+ await make(db, c, s, after);
565
+ s = after;
566
+ }
567
+ // an up's statements, each waited for (one written before joined was async runs them without waiting)
568
+ const asked: Promise<unknown>[] = [];
569
+ const said = <T>(p: Promise<T>) => (asked.push(p), p);
570
+ const its: Engine = {
571
+ ...db,
572
+ run: (sql, args) => said(db.run(sql, args)),
573
+ query: (sql) => ({
574
+ get: (...args) => said(db.query(sql).get(...args)),
575
+ all: (...args) => said(db.query(sql).all(...args)),
576
+ }),
577
+ };
578
+ await m.up?.(its, { nextId: (table) => said(nextId(db, table)) });
579
+ await Promise.all(asked);
559
580
  if (rebuilds) {
560
- const loose = db.query("PRAGMA foreign_key_check").get() as { table: string; parent: string } | null;
581
+ const loose = (await db.query("PRAGMA foreign_key_check").get()) as { table: string; parent: string } | null;
561
582
  if (loose) throw new Error(`${loose.table} links to no row of ${loose.parent}`);
562
583
  }
563
- db.run(`INSERT INTO ${RAN} (app, id, ran_at) VALUES (?, ?, ?)`, [app, m.id, new Date().toISOString()]);
564
- }).immediate();
584
+ await db.run(`INSERT INTO ${RAN} (app, id, ran_at) VALUES (?, ?, ?)`, [app, m.id, new Date().toISOString()]);
585
+ });
565
586
  } catch (e) {
566
587
  throw new Error(`${app}'s migration ${m.id} failed, and was rolled back: ${(e as Error).message}`);
567
588
  } finally {
568
- if (rebuilds) db.run("PRAGMA foreign_keys = ON");
589
+ if (rebuilds) await db.run("PRAGMA foreign_keys = ON");
569
590
  }
570
591
  ran.push(m.id);
571
592
  }
572
593
  return ran;
573
594
  }
574
595
 
575
- /** The id a table hands out next, without handing it out: its sequence, or the largest id it holds, then one on. */
576
- export function peekId(db: Engine, table: string) {
577
- const seq = db.query(`SELECT last FROM ${SEQUENCES} WHERE collection = ?`).get(table) as { last: number } | null;
578
- const most = (db.query(`SELECT MAX(id) AS m FROM ${q(table)}`).get() as { m: number | null }).m ?? 0;
579
- return Math.max(seq?.last ?? 0, most) + 1;
580
- }
581
-
582
- /** The next id for a table, handed out: never one handed out before, even when that row is gone. */
583
- export function nextId(db: Engine, table: string) {
584
- const next = peekId(db, table);
585
- db.run(
586
- `INSERT INTO ${SEQUENCES} (collection, last) VALUES (?, ?) ON CONFLICT (collection) DO UPDATE SET last = excluded.last`,
587
- [table, next],
588
- );
589
- return next;
596
+ /** The next id for a table, handed out in one statement (two servers on one database never take the same): never
597
+ * one handed out before, even when that row is gone. */
598
+ export async function nextId(db: Engine, table: string) {
599
+ const most = `(SELECT COALESCE(MAX(id), 0) + 1 FROM ${q(table)})`;
600
+ const r = (await db
601
+ .query(
602
+ `INSERT INTO ${SEQUENCES} (collection, last) VALUES (?, ${most}) ON CONFLICT (collection) DO UPDATE SET last = ${db.dialect === "sqlite" ? "MAX" : "GREATEST"}(${SEQUENCES}.last + 1, ${most}) RETURNING last`,
603
+ )
604
+ .get(table)) as { last: number };
605
+ return r.last;
590
606
  }
591
607
 
592
608
  /** A table's last id kept at least `id`: a document brought in with ids of its own. */