@blueshed/joined 0.2.2 → 0.3.1
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.
- package/.claude/skills/joined/SKILL.md +9 -1
- package/.claude/skills/joined/reference.md +316 -63
- package/.claude/skills/joined-door/SKILL.md +57 -0
- package/README.md +19 -50
- package/docs/design.md +158 -37
- package/docs/introduction.md +27 -27
- package/docs/light-and-shadow.svg +2 -1
- package/docs/links-and-trust.svg +1 -0
- package/docs/stories-to-code.svg +2 -1
- package/docs/wire-op.svg +1 -0
- package/examples/README.md +20 -0
- package/examples/account/account.json +1 -0
- package/examples/account/derive.ts +41 -0
- package/examples/account/generated/elements.ts +52 -0
- package/examples/account/generated/rows.ts +22 -0
- package/examples/account/generated/rules.ts +32 -0
- package/examples/account/routes.ts +5 -0
- package/examples/app.css +11 -1
- package/examples/cafe/books.html +2 -2
- package/examples/cafe/cafe.css +96 -85
- package/examples/cafe/generated/books.rows.ts +22 -0
- package/examples/cafe/generated/books.rules.ts +3 -2
- package/examples/cafe/generated/kitchen.rows.ts +27 -0
- package/examples/cafe/generated/kitchen.rules.ts +11 -1
- package/examples/cafe/generated/menu.rows.ts +22 -0
- package/examples/cafe/generated/menu.rules.ts +3 -2
- package/examples/cafe/generated/order.rows.ts +27 -0
- package/examples/cafe/generated/order.rules.ts +11 -1
- package/examples/cafe/generated/staff.elements.ts +7 -2
- package/examples/cafe/generated/staff.rows.ts +22 -0
- package/examples/cafe/generated/staff.rules.ts +9 -1
- package/examples/cafe/generated/supplies.queries.ts +4 -2
- package/examples/cafe/generated/supplies.rows.ts +22 -0
- package/examples/cafe/generated/supplies.rules.ts +17 -1
- package/examples/cafe/generated/till.queries.ts +2 -0
- package/examples/cafe/generated/till.rows.ts +27 -0
- package/examples/cafe/generated/till.rules.ts +11 -1
- package/examples/cafe/index.html +14 -15
- package/examples/cafe/kitchen.css +11 -19
- package/examples/cafe/kitchen.ts +7 -3
- package/examples/cafe/look.ts +30 -0
- package/examples/cafe/menu.html +10 -26
- package/examples/cafe/menu.ts +8 -80
- package/examples/cafe/migrations/002-guard-supplies.ts +15 -0
- package/examples/cafe/order.html +8 -7
- package/examples/cafe/order.ts +6 -2
- package/examples/cafe/routes.ts +0 -1
- package/examples/cafe/staff.json +5 -0
- package/examples/cafe/stories.jsonl +6 -2
- package/examples/cafe/supplies.html +35 -34
- package/examples/cafe/supplies.ts +59 -39
- package/examples/cafe/till.ts +19 -11
- package/examples/cafe/views.ts +7 -5
- package/examples/chart/arches.ts +150 -0
- package/examples/chart/chart.css +11 -0
- package/examples/chart/chart.json +87 -0
- package/examples/chart/generated/elements.ts +105 -0
- package/examples/chart/generated/queries.ts +36 -0
- package/examples/chart/generated/rows.ts +27 -0
- package/examples/chart/generated/rules.ts +111 -0
- package/examples/chart/grid.ts +118 -0
- package/examples/chart/index.html +78 -0
- package/examples/chart/migrations/001-chart.ts +6 -0
- package/examples/chart/migrations/002-create-conditions.ts +6 -0
- package/examples/chart/page.ts +20 -0
- package/examples/chart/routes.ts +7 -0
- package/examples/chart/stories.jsonl +14 -0
- package/examples/chart/teeth.ts +57 -0
- package/examples/desk/desk.css +6 -10
- package/examples/desk/generated/elements.ts +1 -1
- package/examples/desk/generated/rows.ts +22 -0
- package/examples/desk/generated/rules.ts +34 -1
- package/examples/desk/index.html +10 -3
- package/examples/desk/lanes.css +21 -19
- package/examples/desk/routes.ts +0 -2
- package/examples/desk/stories.jsonl +4 -3
- package/examples/desk/tally.css +1 -1
- package/examples/desk/thumbs.ts +2 -2
- package/examples/docs.ts +7 -4
- package/examples/hello/generated/elements.ts +2 -2
- package/examples/hello/generated/rules.ts +3 -2
- package/examples/hello/hello.css +2 -4
- package/examples/hello/index.html +10 -3
- package/examples/hello/page.ts +4 -4
- package/examples/index.html +20 -12
- package/examples/notes/generated/elements.ts +112 -0
- package/examples/notes/generated/queries.ts +42 -0
- package/examples/notes/generated/rows.ts +27 -0
- package/examples/notes/generated/rules.ts +133 -0
- package/examples/notes/index.html +32 -0
- package/examples/notes/look.ts +41 -0
- package/examples/notes/migrations/001-notes.ts +7 -0
- package/examples/notes/notes.json +78 -0
- package/examples/notes/page.ts +21 -0
- package/examples/notes/routes.ts +6 -0
- package/examples/notes/stories.jsonl +24 -0
- package/examples/page.ts +9 -2
- package/examples/people/generated/rows.ts +22 -0
- package/examples/people/generated/rules.ts +11 -1
- package/examples/people/links.ts +8 -9
- package/examples/people/people.css +1 -1
- package/examples/people/routes.ts +1 -3
- package/examples/people/stories.jsonl +1 -0
- package/examples/people/view.ts +5 -2
- package/examples/trip/generated/elements.ts +5 -3
- package/examples/trip/generated/queries.ts +12 -1
- package/examples/trip/generated/rows.ts +27 -0
- package/examples/trip/generated/rules.ts +56 -2
- package/examples/trip/index.html +58 -12
- package/examples/trip/line.css +186 -0
- package/examples/trip/line.ts +51 -40
- package/examples/trip/page.ts +65 -71
- package/examples/trip/routes.ts +9 -5
- package/examples/trip/stays.css +13 -13
- package/examples/trip/stays.ts +15 -10
- package/examples/trip/stories.jsonl +2 -0
- package/examples/trip/told.ts +3 -26
- package/examples/trip/trip.css +16 -0
- package/examples/trips/generated/elements.ts +1 -1
- package/examples/trips/generated/rows.ts +22 -0
- package/examples/trips/generated/rules.ts +9 -1
- package/examples/trips/index.html +10 -10
- package/examples/trips/map.ts +3 -14
- package/examples/trips/new-trip.ts +14 -16
- package/examples/trips/trips.css +24 -23
- package/examples/weeks/generated/elements.ts +1 -1
- package/examples/weeks/generated/queries.ts +11 -0
- package/examples/weeks/generated/rows.ts +22 -0
- package/examples/weeks/generated/rules.ts +11 -5
- package/examples/weeks/routes.ts +3 -2
- package/examples/weeks/stories.jsonl +1 -0
- package/examples/welcome.css +43 -33
- package/package.json +8 -2
- package/src/attachment.ts +17 -2
- package/src/awesome.ts +103 -0
- package/src/board.css +76 -0
- package/src/board.ts +173 -0
- package/src/cli.ts +28 -3
- package/src/compile.ts +821 -109
- package/src/definitions.ts +113 -27
- package/src/demo.css +2 -5
- package/src/draft.ts +48 -27
- package/src/drawer.ts +248 -0
- package/src/engine.ts +253 -170
- package/src/fields.ts +341 -0
- package/src/file-value.ts +12 -2
- package/src/files.ts +113 -33
- package/src/ground.ts +110 -0
- package/src/icon-names.ts +19 -2
- package/src/keep.ts +16 -3
- package/src/kit.ts +51 -0
- package/src/link.ts +3 -3
- package/src/map.css +140 -0
- package/src/map.ts +200 -0
- package/src/mcp.ts +129 -24
- package/src/members/demo.ts +13 -12
- package/src/members/generated/rows.ts +22 -0
- package/src/members/generated/rules.ts +3 -2
- package/src/members/group.ts +105 -55
- package/src/members/keys.ts +95 -79
- package/src/members/panel.css +40 -35
- package/src/members/panel.ts +58 -37
- package/src/migrate.ts +178 -125
- package/src/migrations/005-change-kept.ts +7 -0
- package/src/month.css +129 -0
- package/src/month.ts +179 -0
- package/src/ops.ts +40 -1
- package/src/page.css +11 -2
- package/src/page.ts +68 -17
- package/src/parts.css +614 -230
- package/src/parts.ts +259 -36
- package/src/plane.css +61 -0
- package/src/plane.ts +153 -0
- package/src/postgres-server.ts +60 -0
- package/src/reading.css +73 -0
- package/src/reading.ts +238 -0
- package/src/rows.css +289 -0
- package/src/rows.ts +864 -0
- package/src/search.css +80 -0
- package/src/search.ts +130 -0
- package/src/server.ts +355 -137
- package/src/settings.ts +9 -4
- package/src/sheet.ts +116 -0
- package/src/skill.ts +40 -0
- package/src/slots.css +90 -0
- package/src/slots.ts +213 -0
- package/src/specs.ts +38 -0
- package/src/starter.ts +19 -2
- package/src/store.ts +224 -161
- package/src/stories.ts +43 -11
- package/src/surface.ts +164 -0
- package/src/time.ts +2 -0
- package/src/timeline.css +111 -0
- package/src/timeline.ts +235 -0
- package/src/toast.ts +21 -48
- package/src/together.ts +15 -24
- package/src/tokens.css +89 -3
- package/src/tokens.json +287 -7
- package/src/tool.ts +210 -0
- package/src/upkeep.ts +47 -22
- package/src/views.css +43 -0
- package/src/views.ts +111 -0
- package/src/week.css +150 -0
- package/src/week.ts +254 -0
- package/src/write.ts +326 -78
- package/starter/CHANGELOG.md +8 -0
- package/starter/CLAUDE.md +9 -3
- package/starter/bunfig +5 -0
- package/starter/githooks/pre-commit +13 -0
- package/starter/prettierignore +5 -0
- package/starter/tests/hello.test.ts +2 -0
- package/starter/tests/records.test.ts +40 -0
- package/starter/todo.jsonl +0 -0
- package/docs/learning.md +0 -76
- package/examples/cafe/trust.ts +0 -20
- package/examples/desk/trust.ts +0 -24
- package/examples/people/trust.ts +0 -14
- package/examples/trip/answer-rows.ts +0 -70
- package/examples/trip/bar.ts +0 -89
- package/examples/trip/calendar-map.css +0 -711
- package/examples/trip/calendar-map.ts +0 -249
- package/examples/trip/drags.ts +0 -143
- package/examples/trip/drawer.ts +0 -250
- package/examples/trip/event-form.ts +0 -200
- package/examples/trip/holding.ts +0 -61
- package/examples/trip/map.ts +0 -234
- package/examples/trip/month.ts +0 -87
- package/examples/trip/other-weeks.ts +0 -67
- package/examples/trip/peek.ts +0 -71
- package/examples/trip/people-chips.ts +0 -74
- package/examples/trip/shell.ts +0 -39
- package/examples/trip/trust.ts +0 -51
- package/examples/trip/week.ts +0 -237
- package/examples/trip/writes.ts +0 -91
- package/examples/trip/zones.ts +0 -16
- package/examples/weeks/derive.ts +0 -23
- package/src/scrim.ts +0 -81
package/src/store.ts
CHANGED
|
@@ -22,7 +22,7 @@ import {
|
|
|
22
22
|
stateOf,
|
|
23
23
|
type State,
|
|
24
24
|
} from "./migrate.ts";
|
|
25
|
-
import { docParts, parts, valueAt, type Change, type Op, type Type } from "./ops.ts";
|
|
25
|
+
import { docParts, linksNamed, parts, valueAt, type Change, type Op, type Type } from "./ops.ts";
|
|
26
26
|
|
|
27
27
|
/** An app's compiled rules, as the store reads them: its document, each collection's tag, fields and links (the
|
|
28
28
|
* collection each is to), and its kind: a document for each item of another's collection (doc:root), its rows
|
|
@@ -39,12 +39,13 @@ export type Rules = {
|
|
|
39
39
|
/** Its links that go with what they point at: that item removed, this one is removed first. */
|
|
40
40
|
goes?: string[];
|
|
41
41
|
fills?: Record<string, unknown>;
|
|
42
|
+
clock?: readonly ("item" | "root" | "document")[];
|
|
42
43
|
timed?: string;
|
|
43
44
|
own?: boolean;
|
|
44
45
|
copies?: { from: string; fields: string[]; to: string; at: string };
|
|
45
46
|
}
|
|
46
47
|
>;
|
|
47
|
-
kind: { root: string; doc: string; column: string } | null;
|
|
48
|
+
kind: { root: string; doc: string; column: string; files?: "apart" } | null;
|
|
48
49
|
/** The field holding an item's own code (definitions' guests); of a kind, its root's: a board's secret link. */
|
|
49
50
|
guests?: Record<string, string>;
|
|
50
51
|
/** The document as one statement over its tables (generated/queries.ts): $doc, $key of a kind's instance, and
|
|
@@ -195,6 +196,8 @@ const BEHIND = 500;
|
|
|
195
196
|
|
|
196
197
|
/** The store in its database: migrated, joined's own and then each app's, in the order given. */
|
|
197
198
|
export async function openStore(db: Engine, given: { name: string; dir: string; rules: Rules }[]) {
|
|
199
|
+
/** This store's own name, on what it notifies: what it hears of its own is skipped. */
|
|
200
|
+
const self = crypto.randomUUID();
|
|
198
201
|
// each app's SQL as its engine says it
|
|
199
202
|
const apps = given.map((a) => ({
|
|
200
203
|
...a,
|
|
@@ -202,33 +205,42 @@ export async function openStore(db: Engine, given: { name: string; dir: string;
|
|
|
202
205
|
}));
|
|
203
206
|
// what a write changes, noted by the database as each row was before its first change (none: added), whoever
|
|
204
207
|
// changes it, in the connection's own table; a Postgres store's triggers last, and are made again below
|
|
205
|
-
db.run(
|
|
208
|
+
await db.run(
|
|
206
209
|
`CREATE TEMP TABLE IF NOT EXISTS joined_touched (n ${db.dialect === "sqlite" ? "INTEGER PRIMARY KEY" : "SERIAL PRIMARY KEY"}, tbl TEXT NOT NULL, id INTEGER NOT NULL, was INTEGER, before TEXT, UNIQUE (tbl, id))`,
|
|
207
210
|
);
|
|
208
211
|
if (db.dialect === "postgres")
|
|
209
|
-
for (const like of [
|
|
210
|
-
|
|
212
|
+
for (const like of [
|
|
213
|
+
"joined_touch_%",
|
|
214
|
+
"joined_takes_%",
|
|
215
|
+
"joined_gives_%",
|
|
216
|
+
"joined_totals_%",
|
|
217
|
+
"joined_with_%",
|
|
218
|
+
"joined_frozen_%",
|
|
219
|
+
"joined_within_%",
|
|
220
|
+
"joined_apart_%",
|
|
221
|
+
])
|
|
222
|
+
await dropTriggers(db, like);
|
|
211
223
|
// each app's migrations, as its own: told its tables, so another's being there doesn't make it old here
|
|
212
224
|
const histories: Awaited<ReturnType<typeof fromFolder>>[] = [];
|
|
213
225
|
for (const [app, dir] of [["joined", OWN], ...apps.map((a) => [a.name, `${a.dir}/migrations`])] as const) {
|
|
214
226
|
const list = existsSync(dir) ? await fromFolder(dir) : [];
|
|
215
|
-
migrate(db, app, list);
|
|
227
|
+
await migrate(db, app, list);
|
|
216
228
|
histories.push(list);
|
|
217
229
|
}
|
|
218
230
|
// each link a foreign key (Postgres's made now) and guarded where it points, now every app's tables are there (one
|
|
219
231
|
// app's may link to another's after it)
|
|
220
232
|
const tables: State = Object.assign({}, ...histories.map(stateOf));
|
|
221
|
-
db.transaction(() => {
|
|
222
|
-
for (const [key, t] of Object.entries(tables)) (linked(db, key, t), guardHeld(db, key, t));
|
|
223
|
-
})
|
|
233
|
+
await db.transaction(async () => {
|
|
234
|
+
for (const [key, t] of Object.entries(tables)) (await linked(db, key, t), await guardHeld(db, key, t));
|
|
235
|
+
});
|
|
224
236
|
// a collection the migrations made no table for, or a field no column (or pairs), or a kind's rows no column to be
|
|
225
237
|
// kept with their instance by: its stories changed, and weren't compiled (or a migration that had run was changed)
|
|
226
238
|
for (const { name, rules } of apps.filter((a) => !a.rules.member))
|
|
227
239
|
for (const [coll, c] of Object.entries(rules.collections)) {
|
|
228
|
-
const cols = db.columns(coll);
|
|
240
|
+
const cols = await db.columns(coll);
|
|
229
241
|
if (!cols.length) throw new Error(`${name}'s ${coll} has no table: bun run compile writes its migrations`);
|
|
230
242
|
for (const f of [...Object.keys(c.fields), ...(rules.kind ? [rules.kind.column] : [])])
|
|
231
|
-
if (c.fields[f] === "ids" ? !db.columns(`${coll}_${f}`).length : !cols.includes(f))
|
|
243
|
+
if (c.fields[f] === "ids" ? !(await db.columns(`${coll}_${f}`)).length : !cols.includes(f))
|
|
232
244
|
throw new Error(`${name}'s ${coll}.${f} has nowhere to be kept: bun run compile writes its migrations`);
|
|
233
245
|
}
|
|
234
246
|
const docs = new Map(apps.map((a) => [a.rules.doc, a.rules]));
|
|
@@ -250,55 +262,61 @@ export async function openStore(db: Engine, given: { name: string; dir: string;
|
|
|
250
262
|
const rules = apps.find((a) => a.rules.collections[coll])!.rules;
|
|
251
263
|
const keep = (row: string) =>
|
|
252
264
|
`INSERT INTO ${noted} (tbl, id, was, before) SELECT '${coll}', t.id, ${of}, CAST(${item} AS TEXT) FROM ${q(coll)} t WHERE t.id = ${row} ON CONFLICT DO NOTHING;`;
|
|
253
|
-
const on = (name: string, event: string, table: string, body: string) =>
|
|
254
|
-
db.run(
|
|
255
|
-
|
|
265
|
+
const on = async (name: string, event: string, table: string, body: string) =>
|
|
266
|
+
await db.run(
|
|
267
|
+
triggerSql(db.dialect, { name: `joined_touch_${name}`, at: "BEFORE", event, table, body, temp: true }),
|
|
268
|
+
);
|
|
269
|
+
await on(
|
|
256
270
|
`${coll}_insert`,
|
|
257
271
|
"INSERT",
|
|
258
272
|
coll,
|
|
259
273
|
`INSERT INTO ${noted} (tbl, id) VALUES ('${coll}', NEW.id) ON CONFLICT DO NOTHING;`,
|
|
260
274
|
);
|
|
261
|
-
on(`${coll}_update`, "UPDATE", coll, keep("OLD.id"));
|
|
262
|
-
on(`${coll}_delete`, "DELETE", coll, keep("OLD.id"));
|
|
275
|
+
await on(`${coll}_update`, "UPDATE", coll, keep("OLD.id"));
|
|
276
|
+
await on(`${coll}_delete`, "DELETE", coll, keep("OLD.id"));
|
|
263
277
|
for (const [f, t] of Object.entries(rules.collections[coll]!.fields))
|
|
264
278
|
if (t === "ids") {
|
|
265
|
-
on(`${coll}_${f}_insert`, "INSERT", `${coll}_${f}`, keep(`NEW.${q(coll)}`))
|
|
266
|
-
|
|
279
|
+
(await on(`${coll}_${f}_insert`, "INSERT", `${coll}_${f}`, keep(`NEW.${q(coll)}`)),
|
|
280
|
+
await on(`${coll}_${f}_delete`, "DELETE", `${coll}_${f}`, keep(`OLD.${q(coll)}`)));
|
|
267
281
|
}
|
|
268
282
|
}
|
|
269
283
|
// the rules over values, run in each write's transaction: made once the seeds are in (a seed is the state as it
|
|
270
284
|
// is: a supply delivered before isn't delivered again as it's taken)
|
|
271
285
|
const ruled = apps.flatMap(({ rules }) => rules.triggers ?? []);
|
|
272
|
-
const rule = (on: boolean) => {
|
|
273
|
-
for (const sql of ruled) db.run(on ? sql : dropTriggerSql(db.dialect, sql));
|
|
286
|
+
const rule = async (on: boolean) => {
|
|
287
|
+
for (const sql of ruled) await db.run(on ? sql : dropTriggerSql(db.dialect, sql));
|
|
274
288
|
};
|
|
275
|
-
rule(true);
|
|
289
|
+
await rule(true);
|
|
290
|
+
/** The triggers that wait for a write's end (Postgres's constraint triggers), by name. */
|
|
291
|
+
const waiting = ruled.flatMap((sql) => /CREATE CONSTRAINT TRIGGER ("(?:[^"]|"")+")/.exec(sql)?.[1] ?? []).join(", ");
|
|
276
292
|
/** The rows a write changed, in the order it first changed them: each as it was and is. */
|
|
277
|
-
const touched = (): Row[] =>
|
|
278
|
-
(
|
|
279
|
-
|
|
280
|
-
tbl
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
293
|
+
const touched = async (): Promise<Row[]> =>
|
|
294
|
+
Promise.all(
|
|
295
|
+
(
|
|
296
|
+
(await db.query(`SELECT tbl, id, was, before FROM ${noted} ORDER BY n`).all()) as {
|
|
297
|
+
tbl: string;
|
|
298
|
+
id: number;
|
|
299
|
+
was: number | null;
|
|
300
|
+
before: string | null;
|
|
301
|
+
}[]
|
|
302
|
+
).map(async ({ tbl, id, was, before }) => {
|
|
303
|
+
const { of, item } = holding.get(tbl)!;
|
|
304
|
+
const now = (await db
|
|
305
|
+
.query(`SELECT ${of} AS is_, CAST(${item} AS TEXT) AS item FROM ${q(tbl)} t WHERE t.id = ?`)
|
|
306
|
+
.get(id)) as {
|
|
307
|
+
is_: number | null;
|
|
308
|
+
item: string;
|
|
309
|
+
} | null;
|
|
310
|
+
return {
|
|
311
|
+
coll: tbl,
|
|
312
|
+
id,
|
|
313
|
+
before: before === null ? null : JSON.parse(before),
|
|
314
|
+
after: now && JSON.parse(now.item),
|
|
315
|
+
was,
|
|
316
|
+
is: now?.is_ ?? null,
|
|
317
|
+
};
|
|
318
|
+
}),
|
|
319
|
+
);
|
|
302
320
|
/** Each document a write's rows are in, by name (an instance's, shelf:1), and its ops in its own paths, with their
|
|
303
321
|
* inverse. The rows the write's own ops made, in the document written (`made`, by collection and id), are its ops
|
|
304
322
|
* as made. (An item never moves from one instance to another: no op writes the column it's kept with them by.) */
|
|
@@ -322,7 +340,7 @@ export async function openStore(db: Engine, given: { name: string; dir: string;
|
|
|
322
340
|
// a document's own fields are its one row's, there from the start (a store from before has it, empty)
|
|
323
341
|
for (const { rules } of apps)
|
|
324
342
|
for (const [coll, c] of Object.entries(rules.collections))
|
|
325
|
-
if (c.own) db.run(`INSERT INTO ${q(coll)} (id) VALUES (1) ON CONFLICT DO NOTHING`);
|
|
343
|
+
if (c.own) await db.run(`INSERT INTO ${q(coll)} (id) VALUES (1) ON CONFLICT DO NOTHING`);
|
|
326
344
|
/** A document's rules, and, of a kind's instance (shelf:1), the column its rows are kept by and its root item.
|
|
327
345
|
* A name is one way of writing it alone: shelf:01 and shelf:1.0 are no document. */
|
|
328
346
|
const of = (doc: string) => {
|
|
@@ -349,6 +367,10 @@ export async function openStore(db: Engine, given: { name: string; dir: string;
|
|
|
349
367
|
* text): what it was given is asked first, in the words its CHECK has. */
|
|
350
368
|
const cell = (coll: string, f: string, t: Type, v: unknown) => {
|
|
351
369
|
const out = v === undefined ? null : t === "boolean" && typeof v === "boolean" ? +v : v;
|
|
370
|
+
// a list or an object for a column of one value: no table can be asked of it, so it's refused here, in the words
|
|
371
|
+
// the column's CHECK has
|
|
372
|
+
if (out !== null && typeof out === "object")
|
|
373
|
+
throw new Refused(tables[coll]?.columns[f]?.is?.said ?? `${f} is one value, not a list or an object`);
|
|
352
374
|
const is = db.dialect === "postgres" && out !== null ? tables[coll]?.columns[f]?.is : undefined;
|
|
353
375
|
if (
|
|
354
376
|
is &&
|
|
@@ -365,11 +387,11 @@ export async function openStore(db: Engine, given: { name: string; dir: string;
|
|
|
365
387
|
};
|
|
366
388
|
|
|
367
389
|
/** A list's ids, each a pair: one named twice is refused by its table, in its words. */
|
|
368
|
-
function setPairs(coll: string, field: string, id: number, ids: number[]) {
|
|
369
|
-
db.run(`DELETE FROM ${q(`${coll}_${field}`)} WHERE ${q(coll)} = ?`, [id]);
|
|
390
|
+
async function setPairs(coll: string, field: string, id: number, ids: number[]) {
|
|
391
|
+
await db.run(`DELETE FROM ${q(`${coll}_${field}`)} WHERE ${q(coll)} = ?`, [id]);
|
|
370
392
|
for (const to of ids)
|
|
371
|
-
db.run(`INSERT INTO ${q(`${coll}_${field}`)} (id, ${q(coll)}, ${q(field)}) VALUES (?, ?, ?)`, [
|
|
372
|
-
nextId(`${coll}_${field}`),
|
|
393
|
+
await db.run(`INSERT INTO ${q(`${coll}_${field}`)} (id, ${q(coll)}, ${q(field)}) VALUES (?, ?, ?)`, [
|
|
394
|
+
await nextId(`${coll}_${field}`),
|
|
373
395
|
id,
|
|
374
396
|
to,
|
|
375
397
|
]);
|
|
@@ -377,17 +399,17 @@ export async function openStore(db: Engine, given: { name: string; dir: string;
|
|
|
377
399
|
|
|
378
400
|
/** One id added to an item's list (its table refusing one there already, or one that's no item), or taken from
|
|
379
401
|
* it: refused if it isn't there. */
|
|
380
|
-
function pair(coll: string, field: string, id: number, to: number, add: boolean) {
|
|
402
|
+
async function pair(coll: string, field: string, id: number, to: number, add: boolean) {
|
|
381
403
|
const table = q(`${coll}_${field}`);
|
|
382
|
-
if (!add && !db.query(`SELECT 1 FROM ${table} WHERE ${q(coll)} = ? AND ${q(field)} = ?`).get(id, to))
|
|
404
|
+
if (!add && !(await db.query(`SELECT 1 FROM ${table} WHERE ${q(coll)} = ? AND ${q(field)} = ?`).get(id, to)))
|
|
383
405
|
throw new Refused(`${field} doesn't link to ${to}`);
|
|
384
406
|
if (add)
|
|
385
|
-
db.run(`INSERT INTO ${table} (id, ${q(coll)}, ${q(field)}) VALUES (?, ?, ?)`, [
|
|
386
|
-
nextId(`${coll}_${field}`),
|
|
407
|
+
await db.run(`INSERT INTO ${table} (id, ${q(coll)}, ${q(field)}) VALUES (?, ?, ?)`, [
|
|
408
|
+
await nextId(`${coll}_${field}`),
|
|
387
409
|
id,
|
|
388
410
|
to,
|
|
389
411
|
]);
|
|
390
|
-
else db.run(`DELETE FROM ${table} WHERE ${q(coll)} = ? AND ${q(field)} = ?`, [id, to]);
|
|
412
|
+
else await db.run(`DELETE FROM ${table} WHERE ${q(coll)} = ? AND ${q(field)} = ?`, [id, to]);
|
|
391
413
|
}
|
|
392
414
|
|
|
393
415
|
/** The collection of a document's own fields (hello's), if it has them: named for it, of one item. */
|
|
@@ -404,14 +426,14 @@ export async function openStore(db: Engine, given: { name: string; dir: string;
|
|
|
404
426
|
};
|
|
405
427
|
|
|
406
428
|
/** An item as the document has it: its fields, null ones left out, and its lists (none: left out). */
|
|
407
|
-
function itemAt(coll: string, c: Rules["collections"][string], id: number): Item {
|
|
408
|
-
const row = db.query(`SELECT * FROM ${q(coll)} WHERE id = ?`).get(id) as Item;
|
|
429
|
+
async function itemAt(coll: string, c: Rules["collections"][string], id: number): Promise<Item> {
|
|
430
|
+
const row = (await db.query(`SELECT * FROM ${q(coll)} WHERE id = ?`).get(id)) as Item;
|
|
409
431
|
const item: Item = { id };
|
|
410
432
|
for (const [f, t] of Object.entries(c.fields)) {
|
|
411
433
|
if (t === "ids") {
|
|
412
|
-
const ids = db
|
|
434
|
+
const ids = (await db
|
|
413
435
|
.query(`SELECT ${q(f)} AS to_ FROM ${q(`${coll}_${f}`)} WHERE ${q(coll)} = ? ORDER BY id`)
|
|
414
|
-
.all(id) as { to_: number }[];
|
|
436
|
+
.all(id)) as { to_: number }[];
|
|
415
437
|
if (ids.length) item[f] = ids.map((r) => r.to_);
|
|
416
438
|
} else if (row[f] !== null) item[f] = t === "boolean" ? row[f] === 1 : row[f];
|
|
417
439
|
}
|
|
@@ -421,7 +443,7 @@ export async function openStore(db: Engine, given: { name: string; dir: string;
|
|
|
421
443
|
/** An op made on the rows, and the ops that put back what it did (its inverse): an add given the next id,
|
|
422
444
|
* which the pages are told, or, putting back an item removed, the id it had (an undo's, its value's id); an id
|
|
423
445
|
* added to a list or taken from it, the one pair. */
|
|
424
|
-
function apply(doc: string, o: Op, undoing: boolean): { applied: Op; inverse: Op[] } {
|
|
446
|
+
async function apply(doc: string, o: Op, undoing: boolean): Promise<{ applied: Op; inverse: Op[] }> {
|
|
425
447
|
const { coll, key, field, link } = parts(o.path);
|
|
426
448
|
const c = collectionOf(doc, coll);
|
|
427
449
|
// one of an object's fields (/orders/1/terms/days, its column terms.days), or an object whole (/orders/1/terms)
|
|
@@ -437,15 +459,15 @@ export async function openStore(db: Engine, given: { name: string; dir: string;
|
|
|
437
459
|
if (back !== undefined && !undoing) throw new Refused("id is the server's to give");
|
|
438
460
|
const other = Object.keys(value).find((f) => !(f in c.fields));
|
|
439
461
|
if (other) throw new Refused(`${an(c.tag)} has no ${other}`);
|
|
440
|
-
const id = (back as number | undefined) ?? nextId(coll);
|
|
462
|
+
const id = (back as number | undefined) ?? (await nextId(coll));
|
|
441
463
|
const cols = Object.keys(value).filter((f) => c.fields[f] !== "ids");
|
|
442
464
|
const all = by ? [...cols, by.column] : cols;
|
|
443
|
-
db.run(
|
|
465
|
+
await db.run(
|
|
444
466
|
`INSERT INTO ${q(coll)} (${["id", ...all].map(q).join(", ")}) VALUES (${["?", ...all.map(() => "?")].join(", ")})`,
|
|
445
467
|
[id, ...cols.map((f) => cell(coll, f, c.fields[f]!, value[f])), ...(by ? [by.n] : [])] as any[],
|
|
446
468
|
);
|
|
447
469
|
for (const f of Object.keys(value).filter((f) => c.fields[f] === "ids"))
|
|
448
|
-
setPairs(coll, f, id, value[f] as number[]);
|
|
470
|
+
await setPairs(coll, f, id, value[f] as number[]);
|
|
449
471
|
return {
|
|
450
472
|
applied: { op: "add", path: `/${coll}/-`, value: { ...nest(value), id } },
|
|
451
473
|
inverse: [{ op: "remove", path: `/${coll}/${id}` }],
|
|
@@ -453,16 +475,16 @@ export async function openStore(db: Engine, given: { name: string; dir: string;
|
|
|
453
475
|
}
|
|
454
476
|
const id = Number(key);
|
|
455
477
|
const { sql, args } = mine(doc, coll);
|
|
456
|
-
if (!db.query(`SELECT 1 FROM ${q(coll)} WHERE id = ?${sql}`).get(id, ...args))
|
|
478
|
+
if (!(await db.query(`SELECT 1 FROM ${q(coll)} WHERE id = ?${sql}`).get(id, ...args)))
|
|
457
479
|
throw new Refused(`no ${c.tag} at ${o.path}`);
|
|
458
|
-
const was = itemAt(coll, c, id);
|
|
480
|
+
const was = await itemAt(coll, c, id);
|
|
459
481
|
let inverse: Op[];
|
|
460
482
|
if (sub || whole.length) {
|
|
461
483
|
// an object's fields, each its column: one, or all of them (one not given, emptied)
|
|
462
484
|
const cols = sub ? [sub] : whole,
|
|
463
485
|
given = sub ? { [sub]: o.value } : flat({ [field!]: o.value ?? {} });
|
|
464
486
|
for (const col of cols)
|
|
465
|
-
db.run(`UPDATE ${q(coll)} SET ${q(col)} = ? WHERE id = ?`, [
|
|
487
|
+
await db.run(`UPDATE ${q(coll)} SET ${q(col)} = ? WHERE id = ?`, [
|
|
466
488
|
o.op === "remove" ? null : cell(coll, col, c.fields[col]!, given[col]),
|
|
467
489
|
id,
|
|
468
490
|
] as any[]);
|
|
@@ -473,20 +495,20 @@ export async function openStore(db: Engine, given: { name: string; dir: string;
|
|
|
473
495
|
inverse = [had === undefined ? { op: "remove", path } : { op: "replace", path, value: had }];
|
|
474
496
|
} else if (link !== undefined) {
|
|
475
497
|
const to = o.op === "add" ? (o.value as number) : Number(link);
|
|
476
|
-
pair(coll, field!, id, to, o.op === "add");
|
|
498
|
+
await pair(coll, field!, id, to, o.op === "add");
|
|
477
499
|
inverse = [
|
|
478
500
|
o.op === "add"
|
|
479
501
|
? { op: "remove", path: `/${coll}/${id}/${field}/${to}` }
|
|
480
502
|
: { op: "add", path: `/${coll}/${id}/${field}/-`, value: to },
|
|
481
503
|
];
|
|
482
504
|
} else if (o.op === "remove" && field === undefined) {
|
|
483
|
-
for (const [f, t] of Object.entries(c.fields)) if (t === "ids") setPairs(coll, f, id, []);
|
|
484
|
-
db.run(`DELETE FROM ${q(coll)} WHERE id = ?`, [id]);
|
|
505
|
+
for (const [f, t] of Object.entries(c.fields)) if (t === "ids") await setPairs(coll, f, id, []);
|
|
506
|
+
await db.run(`DELETE FROM ${q(coll)} WHERE id = ?`, [id]);
|
|
485
507
|
inverse = [{ op: "add", path: `/${coll}/-`, value: was }];
|
|
486
508
|
} else {
|
|
487
|
-
if (c.fields[field!] === "ids") setPairs(coll, field!, id, o.op === "remove" ? [] : (o.value as number[]));
|
|
509
|
+
if (c.fields[field!] === "ids") await setPairs(coll, field!, id, o.op === "remove" ? [] : (o.value as number[]));
|
|
488
510
|
else
|
|
489
|
-
db.run(`UPDATE ${q(coll)} SET ${q(field!)} = ? WHERE id = ?`, [
|
|
511
|
+
await db.run(`UPDATE ${q(coll)} SET ${q(field!)} = ? WHERE id = ?`, [
|
|
490
512
|
o.op === "remove" ? null : cell(coll, field!, c.fields[field!]!, o.value),
|
|
491
513
|
id,
|
|
492
514
|
] as any[]);
|
|
@@ -496,47 +518,63 @@ export async function openStore(db: Engine, given: { name: string; dir: string;
|
|
|
496
518
|
return { applied: o, inverse };
|
|
497
519
|
}
|
|
498
520
|
|
|
499
|
-
const versionOf = (doc: string) =>
|
|
500
|
-
(db.query("SELECT version FROM documents WHERE name = ?").get(doc) as { version: number } | null)?.version;
|
|
521
|
+
const versionOf = async (doc: string) =>
|
|
522
|
+
((await db.query("SELECT version FROM documents WHERE name = ?").get(doc)) as { version: number } | null)?.version;
|
|
501
523
|
/** A document's version moved on, its new one: an instance of a kind is begun by its first write, at version 0. */
|
|
502
|
-
function moved(doc: string) {
|
|
503
|
-
const
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
524
|
+
async function moved(doc: string) {
|
|
525
|
+
const r = (await db
|
|
526
|
+
.query("UPDATE documents SET version = version + 1 WHERE name = ? RETURNING version")
|
|
527
|
+
.get(doc)) as {
|
|
528
|
+
version: number;
|
|
529
|
+
} | null;
|
|
530
|
+
if (r) return r.version;
|
|
531
|
+
await db.run("INSERT INTO documents (id, name, version) VALUES (?, ?, 1)", [await nextId("documents"), doc]);
|
|
532
|
+
return 1;
|
|
508
533
|
}
|
|
509
534
|
|
|
535
|
+
let closed = false;
|
|
510
536
|
return {
|
|
511
537
|
db,
|
|
512
538
|
/** Whether a document holds an item: what a link may point at. */
|
|
513
|
-
has: (doc: string, coll: string, id: number) =>
|
|
539
|
+
has: async (doc: string, coll: string, id: number) =>
|
|
514
540
|
!!of(doc).rules?.collections[coll] &&
|
|
515
|
-
!!
|
|
541
|
+
!!(await db
|
|
542
|
+
.query(`SELECT 1 FROM ${q(coll)} WHERE id = ?${mine(doc, coll).sql}`)
|
|
543
|
+
.get(id, ...mine(doc, coll).args)),
|
|
544
|
+
/** Every row of a collection's table, each as the document has its item, whatever its where holds (an instance's:
|
|
545
|
+
* its own rows): what its definitions hold among them all (unique, noOverlap). */
|
|
546
|
+
async rowsOf(doc: string, coll: string): Promise<Item[]> {
|
|
547
|
+
const { sql, args } = mine(doc, coll);
|
|
548
|
+
const item = of(doc).rules!.items![coll]!;
|
|
549
|
+
const rows = await db
|
|
550
|
+
.query(`SELECT CAST(${item} AS TEXT) AS item FROM ${q(coll)} t WHERE 1 = 1${sql}`)
|
|
551
|
+
.all(...args);
|
|
552
|
+
return (rows as { item: string }[]).map((r) => JSON.parse(r.item));
|
|
553
|
+
},
|
|
516
554
|
/** Whether a document can be held: one of the documents, or an instance of a kind whose root item is there. */
|
|
517
|
-
exists(doc: string) {
|
|
555
|
+
async exists(doc: string): Promise<boolean> {
|
|
518
556
|
const { base, params } = docParts(doc);
|
|
519
557
|
const { rules, by } = of(base);
|
|
520
558
|
if (!rules || base.includes(":") !== !!rules.kind) return false;
|
|
521
559
|
// a window is written one way alone: its parameters, in its order, each once, a date one a date
|
|
522
560
|
if (doc.includes("?") && doc !== windowed(base, rules, params)) return false;
|
|
523
|
-
return !by || this.has(rules.kind!.doc, rules.kind!.root, by.n);
|
|
561
|
+
return !by || (await this.has(rules.kind!.doc, rules.kind!.root, by.n));
|
|
524
562
|
},
|
|
525
563
|
|
|
526
564
|
/** A document, whole, as a page is sent it, read by its query: each item with its fields, null ones left out,
|
|
527
565
|
* and its lists. */
|
|
528
|
-
read(doc: string, member?: number): Doc {
|
|
566
|
+
async read(doc: string, member?: number): Promise<Doc> {
|
|
529
567
|
const { base, params } = docParts(doc);
|
|
530
568
|
const { rules, by } = of(base);
|
|
531
569
|
// each of its window's parameters, given or not (null: the whole of it); a document read by member, its
|
|
532
570
|
// member's (nobody: 0)
|
|
533
571
|
const window = Object.fromEntries(windowOf(rules!).map((p) => [p, params[p] ?? null]));
|
|
534
|
-
const row = db.query(rules!.query).get({
|
|
572
|
+
const row = (await db.query(rules!.query).get({
|
|
535
573
|
doc: base,
|
|
536
574
|
...(by ? { key: by.n } : {}),
|
|
537
575
|
...window,
|
|
538
576
|
...(rules!.member ? { member: member ?? 0 } : rules!.sees ? { member: member ?? null } : {}),
|
|
539
|
-
}) as {
|
|
577
|
+
})) as {
|
|
540
578
|
doc: string;
|
|
541
579
|
};
|
|
542
580
|
return JSON.parse(row.doc);
|
|
@@ -546,42 +584,38 @@ export async function openStore(db: Engine, given: { name: string; dir: string;
|
|
|
546
584
|
* (`within`: the group's keys), and what the rules over values do as they follow. Then each document holding a row
|
|
547
585
|
* it changed is told it in its own paths, at its next version, in a row of its change: the document written always
|
|
548
586
|
* (first, its ops as they leave it), and every other a rule reached (`followed`). `undoes`, the version an undo
|
|
549
|
-
* puts back
|
|
550
|
-
*
|
|
551
|
-
|
|
587
|
+
* puts back; `kept`, the id a page gave a write it kept while away (src/outbox.ts), on the document written's row.
|
|
588
|
+
* Its changes, with the ops as they were made (what an add was given), and the rows it changed; or a refusal, with
|
|
589
|
+
* why. */
|
|
590
|
+
async write(
|
|
552
591
|
name: string,
|
|
553
592
|
ops: Op[],
|
|
554
593
|
by: number | null,
|
|
555
594
|
via: string | null,
|
|
556
|
-
within?: (applied: Op[]) =>
|
|
557
|
-
{ undoes }: { undoes?: number } = {},
|
|
558
|
-
): { changes: Change[]; applied: Op[]; rows: Record<string, Row[]>; tables: string[] } {
|
|
595
|
+
within?: (applied: Op[]) => unknown,
|
|
596
|
+
{ undoes, kept }: { undoes?: number; kept?: string } = {},
|
|
597
|
+
): Promise<{ changes: Change[]; applied: Op[]; rows: Record<string, Row[]>; tables: string[] }> {
|
|
559
598
|
// a window's write is its document's
|
|
560
599
|
const doc = docParts(name).base;
|
|
561
|
-
return db.transaction(() => {
|
|
562
|
-
db.run(`DELETE FROM ${noted}`);
|
|
563
|
-
// a
|
|
564
|
-
const done: ReturnType<typeof apply
|
|
600
|
+
return db.transaction(async () => {
|
|
601
|
+
await db.run(`DELETE FROM ${noted}`);
|
|
602
|
+
// a link naming an add before it in this write ("$1", the first add's) is the id that add was given
|
|
603
|
+
const done: Awaited<ReturnType<typeof apply>>[] = [];
|
|
565
604
|
const minted: number[] = [];
|
|
566
|
-
const
|
|
567
|
-
typeof v === "string" && /^\$[1-9]\d*$/.test(v)
|
|
568
|
-
? (minted[Number(v.slice(1)) - 1] ?? v)
|
|
569
|
-
: Array.isArray(v)
|
|
570
|
-
? v.map(named)
|
|
571
|
-
: v && typeof v === "object"
|
|
572
|
-
? Object.fromEntries(Object.entries(v).map(([k, x]) => [k, named(x)]))
|
|
573
|
-
: v;
|
|
605
|
+
const collections = of(doc).rules?.collections;
|
|
574
606
|
for (const o of ops) {
|
|
575
|
-
const d = apply(
|
|
607
|
+
const d = await apply(
|
|
576
608
|
doc,
|
|
577
|
-
inward(doc,
|
|
609
|
+
linksNamed(inward(doc, o), collections, (n, v) => minted[n - 1] ?? v),
|
|
578
610
|
undoes !== undefined,
|
|
579
611
|
);
|
|
580
612
|
if (d.applied.op === "add" && parts(d.applied.path).key === "-") minted.push(d.applied.value.id);
|
|
581
613
|
done.push(d);
|
|
582
614
|
}
|
|
583
615
|
const applied = done.map((d) => outward(doc, d.applied));
|
|
584
|
-
within?.(applied);
|
|
616
|
+
await within?.(applied);
|
|
617
|
+
// what waits for the write's end (Postgres's lists, within and apart), held now: refused in its words
|
|
618
|
+
if (waiting.length) await db.run(`SET CONSTRAINTS ${waiting} IMMEDIATE; SET CONSTRAINTS ${waiting} DEFERRED`);
|
|
585
619
|
// the document written is told its ops as made (what an add was given), and what a rule changed of it besides
|
|
586
620
|
const made = new Set(
|
|
587
621
|
done.map(({ applied: o }) => {
|
|
@@ -589,7 +623,7 @@ export async function openStore(db: Engine, given: { name: string; dir: string;
|
|
|
589
623
|
return `${coll}/${key === "-" ? o.value.id : key}`;
|
|
590
624
|
}),
|
|
591
625
|
);
|
|
592
|
-
const all = touched(),
|
|
626
|
+
const all = await touched(),
|
|
593
627
|
names = told(all, doc, made);
|
|
594
628
|
const own = names.get(doc) ?? { ops: [], inverse: [], rows: [] };
|
|
595
629
|
// an item it added as the write left it: what the server filled, and what a rule worked out (an order's total)
|
|
@@ -606,26 +640,30 @@ export async function openStore(db: Engine, given: { name: string; dir: string;
|
|
|
606
640
|
],
|
|
607
641
|
inverse: [...own.inverse, ...done.flatMap((d) => d.inverse.map((o) => outward(doc, o))).reverse()],
|
|
608
642
|
});
|
|
609
|
-
const changes
|
|
643
|
+
const changes: Change[] = [];
|
|
644
|
+
for (const name of [doc, ...[...names.keys()].filter((n) => n !== doc)]) {
|
|
610
645
|
const { ops, inverse } = names.get(name)!,
|
|
611
|
-
version = moved(name);
|
|
612
|
-
db.run(
|
|
613
|
-
"INSERT INTO changes (id, doc, version, ops, inverse, undoes, followed, member, via, at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
|
|
646
|
+
version = await moved(name);
|
|
647
|
+
await db.run(
|
|
648
|
+
"INSERT INTO changes (id, doc, version, ops, inverse, undoes, followed, kept, member, via, at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
|
|
614
649
|
[
|
|
615
|
-
nextId("changes"),
|
|
650
|
+
await nextId("changes"),
|
|
616
651
|
name,
|
|
617
652
|
version,
|
|
618
653
|
JSON.stringify(ops),
|
|
619
654
|
JSON.stringify(inverse),
|
|
620
655
|
name === doc ? (undoes ?? null) : null,
|
|
621
656
|
name === doc ? null : 1,
|
|
657
|
+
name === doc ? (kept ?? null) : null,
|
|
622
658
|
by,
|
|
623
659
|
via,
|
|
624
660
|
new Date().toISOString(),
|
|
625
661
|
],
|
|
626
662
|
);
|
|
627
|
-
|
|
628
|
-
|
|
663
|
+
changes.push({ doc: name, version, ops, by, via });
|
|
664
|
+
// every server on the database told it as it commits (Postgres's NOTIFY; SQLite's one server tells its own)
|
|
665
|
+
await db.notify("joined", JSON.stringify({ doc: name, version, from: self }));
|
|
666
|
+
}
|
|
629
667
|
return {
|
|
630
668
|
changes,
|
|
631
669
|
applied,
|
|
@@ -633,19 +671,26 @@ export async function openStore(db: Engine, given: { name: string; dir: string;
|
|
|
633
671
|
// every table it changed, whatever holds it (a document holding only some of a table's rows is told as a whole)
|
|
634
672
|
tables: [...new Set(all.map((r) => r.coll))],
|
|
635
673
|
};
|
|
636
|
-
})
|
|
674
|
+
});
|
|
637
675
|
},
|
|
638
676
|
|
|
639
677
|
/** A document's version moved on, with no change of its own to keep (one read as each member has it, whose
|
|
640
678
|
* rows a write changed): its new version. */
|
|
641
679
|
moved,
|
|
642
680
|
|
|
681
|
+
/** The version a write kept while away made (src/outbox.ts), by the id its page gave it; undefined, if it hasn't
|
|
682
|
+
* been made (or its change has been let go). */
|
|
683
|
+
async keptAs(kept: string): Promise<number | undefined> {
|
|
684
|
+
const row = await db.query("SELECT version FROM changes WHERE kept = ?").get(kept);
|
|
685
|
+
return (row as { version: number } | null)?.version;
|
|
686
|
+
},
|
|
687
|
+
|
|
643
688
|
/** A change as its row keeps it: its ops, their inverse, what it undoes, and whether a rule made it;
|
|
644
689
|
* or undefined, if it isn't kept (let go, or from before inverses were). */
|
|
645
|
-
change(doc: string, version: number): Kept | undefined {
|
|
646
|
-
const r = db
|
|
690
|
+
async change(doc: string, version: number): Promise<Kept | undefined> {
|
|
691
|
+
const r = (await db
|
|
647
692
|
.query("SELECT ops, inverse, undoes, followed, member, via FROM changes WHERE doc = ? AND version = ?")
|
|
648
|
-
.get(doc, version) as {
|
|
693
|
+
.get(doc, version)) as {
|
|
649
694
|
ops: string;
|
|
650
695
|
inverse: string | null;
|
|
651
696
|
undoes: number | null;
|
|
@@ -669,8 +714,8 @@ export async function openStore(db: Engine, given: { name: string; dir: string;
|
|
|
669
714
|
/** The ops that undo a change, guarded as delta's walk is: what it left at each path it changed (an item it
|
|
670
715
|
* added, whole; a field it set or cleared; an id it put in a list or took out) must be there still. A value
|
|
671
716
|
* someone has changed since refuses the undo, saying where: undone, it would lose their change. */
|
|
672
|
-
undoing(doc: string, version: number): Op[] {
|
|
673
|
-
const c = this.change(doc, version);
|
|
717
|
+
async undoing(doc: string, version: number): Promise<Op[]> {
|
|
718
|
+
const c = await this.change(doc, version);
|
|
674
719
|
if (!c) throw new Refused(`${doc}'s change ${version} isn't kept, so it can't be undone`);
|
|
675
720
|
if (c.followed) throw new Refused(`${doc}'s change ${version} followed another write: undo that`);
|
|
676
721
|
const left = new Map<string, unknown>();
|
|
@@ -694,18 +739,18 @@ export async function openStore(db: Engine, given: { name: string; dir: string;
|
|
|
694
739
|
}
|
|
695
740
|
}
|
|
696
741
|
// each row as it is now, read by its id (a document holding only some rows may hold it no longer)
|
|
697
|
-
const at = (coll: string, id: string) => {
|
|
698
|
-
if (of(doc).rules!.collections[coll]?.own) return ownOf(this.read(doc)) as Item;
|
|
699
|
-
const row = db
|
|
742
|
+
const at = async (coll: string, id: string) => {
|
|
743
|
+
if (of(doc).rules!.collections[coll]?.own) return ownOf(await this.read(doc)) as Item;
|
|
744
|
+
const row = (await db
|
|
700
745
|
.query(`SELECT ${holding.get(coll)!.item} AS item FROM ${q(coll)} t WHERE t.id = ?`)
|
|
701
|
-
.get(Number(id)) as {
|
|
746
|
+
.get(Number(id))) as {
|
|
702
747
|
item: string;
|
|
703
748
|
} | null;
|
|
704
749
|
return row ? (JSON.parse(row.item) as Item) : undefined;
|
|
705
750
|
};
|
|
706
751
|
for (const [path, was] of left) {
|
|
707
752
|
const [, coll, id, field, to] = path.split("/") as [string, string, string, string?, string?];
|
|
708
|
-
const here = at(coll, id);
|
|
753
|
+
const here = await at(coll, id);
|
|
709
754
|
const still =
|
|
710
755
|
field === undefined
|
|
711
756
|
? same(here, was)
|
|
@@ -720,50 +765,53 @@ export async function openStore(db: Engine, given: { name: string; dir: string;
|
|
|
720
765
|
/** The changes after a version, in order, for a page catching up; null when they aren't all here (a
|
|
721
766
|
* document brought in from its JSON has no changes for the versions before it), or it's too far
|
|
722
767
|
* behind, or ahead (a page from before the store was): then it must be sent the document whole. */
|
|
723
|
-
since(doc: string, version: number): Change[] | null {
|
|
724
|
-
const now = versionOf(doc) ?? 0;
|
|
768
|
+
async since(doc: string, version: number): Promise<Change[] | null> {
|
|
769
|
+
const now = (await versionOf(doc)) ?? 0;
|
|
725
770
|
if (version > now || now - version > BEHIND) return null;
|
|
726
|
-
const rows = db
|
|
771
|
+
const rows = (await db
|
|
727
772
|
.query("SELECT version, ops, member, via FROM changes WHERE doc = ? AND version > ? ORDER BY version")
|
|
728
|
-
.all(doc, version) as { version: number; ops: string; member: number | null; via: string | null }[];
|
|
773
|
+
.all(doc, version)) as { version: number; ops: string; member: number | null; via: string | null }[];
|
|
729
774
|
if (rows.length !== now - version) return null;
|
|
730
775
|
return rows.map((r) => ({ doc, version: r.version, ops: JSON.parse(r.ops), by: r.member, via: r.via }));
|
|
731
776
|
},
|
|
732
777
|
|
|
733
778
|
/** The changes made before a time (ms) that no page catching up needs, each beyond its document's last
|
|
734
779
|
* BEHIND, let go; how many. */
|
|
735
|
-
trim: (before: number) =>
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
780
|
+
trim: async (before: number) =>
|
|
781
|
+
(
|
|
782
|
+
await db.run(
|
|
783
|
+
"DELETE FROM changes WHERE at < ? AND version <= (SELECT version FROM documents WHERE name = changes.doc) - ?",
|
|
784
|
+
[new Date(before).toISOString(), BEHIND],
|
|
785
|
+
)
|
|
739
786
|
).changes,
|
|
740
787
|
|
|
741
788
|
/** A document's version, or a kind's (order: every instance's, together): what a document derived from it is
|
|
742
789
|
* versioned by. */
|
|
743
|
-
versions: (name: string) =>
|
|
790
|
+
versions: async (name: string) =>
|
|
744
791
|
(
|
|
745
|
-
db
|
|
746
|
-
.query("SELECT COALESCE(SUM(version), 0) AS n FROM documents WHERE name = ? OR name LIKE ?
|
|
747
|
-
.get(name, name) as { n: number }
|
|
792
|
+
(await db
|
|
793
|
+
.query("SELECT COALESCE(SUM(version), 0) AS n FROM documents WHERE name = ? OR name LIKE ?")
|
|
794
|
+
.get(name, `${name}:%`)) as { n: number }
|
|
748
795
|
).n,
|
|
749
796
|
|
|
750
797
|
/** Whether a document is here yet: a new store is begun from a document's JSON (`take`). */
|
|
751
|
-
holds: (doc: string) => versionOf(doc) !== undefined,
|
|
798
|
+
holds: async (doc: string) => (await versionOf(doc)) !== undefined,
|
|
752
799
|
|
|
753
800
|
/** A document begun from its JSON (the seed, or a file from before the store): its items with their ids,
|
|
754
801
|
* each sequence past the largest, and its version; all in one transaction. `again`: a static document's, its
|
|
755
802
|
* seed a release's, in place of what was. */
|
|
756
|
-
take(doc: string, json: Doc, again = false) {
|
|
803
|
+
async take(doc: string, json: Doc, again = false) {
|
|
757
804
|
const rules = docs.get(doc)!;
|
|
758
|
-
db.transaction(() => {
|
|
805
|
+
await db.transaction(async () => {
|
|
759
806
|
// a seed's items may link to those further on: its links whole by commit
|
|
760
|
-
db.defer();
|
|
807
|
+
await db.defer();
|
|
761
808
|
if (again) {
|
|
762
809
|
for (const [coll, c] of Object.entries(rules.collections)) {
|
|
763
|
-
for (const [f, t] of Object.entries(c.fields))
|
|
764
|
-
|
|
810
|
+
for (const [f, t] of Object.entries(c.fields))
|
|
811
|
+
if (t === "ids") await db.run(`DELETE FROM ${q(`${coll}_${f}`)}`);
|
|
812
|
+
await db.run(`DELETE FROM ${q(coll)}`);
|
|
765
813
|
}
|
|
766
|
-
db.run("DELETE FROM documents WHERE name = ?", [doc]);
|
|
814
|
+
await db.run("DELETE FROM documents WHERE name = ?", [doc]);
|
|
767
815
|
}
|
|
768
816
|
for (const [coll, c] of Object.entries(rules.collections)) {
|
|
769
817
|
// an item the seed gives no id is numbered after the largest it gives, as an add would be
|
|
@@ -778,8 +826,8 @@ export async function openStore(db: Engine, given: { name: string; dir: string;
|
|
|
778
826
|
(f) => c.fields[f] !== "ids" && item[f] !== undefined,
|
|
779
827
|
);
|
|
780
828
|
// (the document's own row is there already: put in its place)
|
|
781
|
-
if (c.own) db.run(`DELETE FROM ${q(coll)} WHERE id = 1`);
|
|
782
|
-
db.run(
|
|
829
|
+
if (c.own) await db.run(`DELETE FROM ${q(coll)} WHERE id = 1`);
|
|
830
|
+
await db.run(
|
|
783
831
|
`INSERT INTO ${q(coll)} (${["id", ...cols].map(q).join(", ")}) VALUES (${["?", ...cols.map(() => "?")].join(", ")})`,
|
|
784
832
|
[item.id, ...cols.map((f) => cell(coll, f, c.fields[f] ?? "integer", item[f]))] as any[],
|
|
785
833
|
);
|
|
@@ -787,28 +835,43 @@ export async function openStore(db: Engine, given: { name: string; dir: string;
|
|
|
787
835
|
// the pairs once every item is in: a list may name an item of this collection further on
|
|
788
836
|
for (const item of c.own ? [] : items)
|
|
789
837
|
for (const [f, t] of Object.entries(c.fields))
|
|
790
|
-
if (t === "ids" && Array.isArray(item[f])) setPairs(coll, f, item.id, item[f] as number[]);
|
|
791
|
-
passed(db, coll, c.own ? 1 : last);
|
|
838
|
+
if (t === "ids" && Array.isArray(item[f])) await setPairs(coll, f, item.id, item[f] as number[]);
|
|
839
|
+
await passed(db, coll, c.own ? 1 : last);
|
|
792
840
|
}
|
|
793
|
-
db.run("INSERT INTO documents (id, name, version) VALUES (?, ?, ?)", [
|
|
794
|
-
|
|
841
|
+
await db.run("INSERT INTO documents (id, name, version) VALUES (?, ?, ?)", [
|
|
842
|
+
await nextId("documents"),
|
|
843
|
+
doc,
|
|
844
|
+
json.version,
|
|
845
|
+
]);
|
|
846
|
+
});
|
|
795
847
|
},
|
|
796
848
|
|
|
797
849
|
/** Documents begun from their JSON, together, in one transaction: one's may link to another's. */
|
|
798
|
-
takeAll(docs: { doc: string; json: Doc; again?: boolean }[]) {
|
|
799
|
-
rule(false);
|
|
850
|
+
async takeAll(docs: { doc: string; json: Doc; again?: boolean }[]) {
|
|
851
|
+
await rule(false);
|
|
800
852
|
try {
|
|
801
|
-
db.transaction(() => {
|
|
802
|
-
db.defer();
|
|
803
|
-
for (const { doc, json, again } of docs) this.take(doc, json, again);
|
|
804
|
-
})
|
|
853
|
+
await db.transaction(async () => {
|
|
854
|
+
await db.defer();
|
|
855
|
+
for (const { doc, json, again } of docs) await this.take(doc, json, again);
|
|
856
|
+
});
|
|
805
857
|
} finally {
|
|
806
|
-
rule(true);
|
|
858
|
+
await rule(true);
|
|
807
859
|
}
|
|
808
860
|
},
|
|
809
861
|
|
|
810
|
-
/** The file let go (a server stopped). */
|
|
811
|
-
close
|
|
862
|
+
/** The file let go (a server stopped), once: closing it again does nothing (PGlite's would throw). */
|
|
863
|
+
async close() {
|
|
864
|
+
if (closed) return;
|
|
865
|
+
closed = true;
|
|
866
|
+
await db.close();
|
|
867
|
+
},
|
|
868
|
+
/** Each change committed by another server on the database, heard as its document and version (Postgres's
|
|
869
|
+
* LISTEN): this one's own it tells as it writes. */
|
|
870
|
+
heard: (fn: (doc: string, version: number) => void) =>
|
|
871
|
+
db.listen("joined", (payload) => {
|
|
872
|
+
const { doc, version, from } = JSON.parse(payload) as { doc: string; version: number; from: string };
|
|
873
|
+
if (from !== self) fn(doc, version);
|
|
874
|
+
}),
|
|
812
875
|
};
|
|
813
876
|
}
|
|
814
877
|
|