@blueshed/joined 0.3.3 → 0.3.4
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/reference.md +13 -5
- package/examples/cafe/migrations/003-guard-supplies.ts +6 -0
- package/examples/index.html +2 -2
- package/examples/trip/stories.jsonl +1 -0
- package/package.json +1 -1
- package/src/attachment.ts +2 -2
- package/src/compile.ts +45 -9
- package/src/drawer.ts +18 -2
- package/src/engine.ts +11 -2
- package/src/file-value.ts +4 -3
- package/src/files.ts +2 -7
- package/src/ics.ts +1 -1
- package/src/link.ts +11 -6
- package/src/map.ts +2 -1
- package/src/mcp.ts +5 -2
- package/src/members/demo.ts +6 -3
- package/src/members/group.ts +2 -1
- package/src/migrate.ts +125 -24
- package/src/page.ts +42 -37
- package/src/postgres-server.ts +69 -14
- package/src/proxy.ts +12 -0
- package/src/reading.ts +21 -3
- package/src/server.ts +32 -25
- package/src/store.ts +27 -18
- package/src/upkeep.ts +9 -8
- package/src/write.ts +71 -21
package/src/migrate.ts
CHANGED
|
@@ -39,10 +39,10 @@ export type Table = {
|
|
|
39
39
|
export type State = Record<string, Table>;
|
|
40
40
|
export type Change =
|
|
41
41
|
| { change: "createTable"; key: string; table: Table }
|
|
42
|
-
| { change: "dropTable"; key: string }
|
|
42
|
+
| { change: "dropTable"; key: string; lose?: true }
|
|
43
43
|
| { change: "renameTable"; key: string; to: string }
|
|
44
|
-
| { change: "addColumn"; key: string; column: string; def: Column }
|
|
45
|
-
| { change: "dropColumn"; key: string; column: string }
|
|
44
|
+
| { change: "addColumn"; key: string; column: string; def: Column; fill?: string | number }
|
|
45
|
+
| { change: "dropColumn"; key: string; column: string; lose?: true }
|
|
46
46
|
| { change: "renameColumn"; key: string; column: string; to: string }
|
|
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
|
|
@@ -89,19 +89,35 @@ const tableOf = (def: TableIn): Table => {
|
|
|
89
89
|
|
|
90
90
|
/** Make a table: `createTable("people", { columns: { name: "text" } })`. */
|
|
91
91
|
export const createTable = (key: string, def: TableIn): Change => ({ change: "createTable", key, table: tableOf(def) });
|
|
92
|
-
/** Drop a table, and every row of it.
|
|
93
|
-
|
|
92
|
+
/** Drop a table, and every row of it. Where another is made beside it, its rows, if it has any, are dropped only if it's
|
|
93
|
+
* said they're to go (`lose`): it may be a rename. */
|
|
94
|
+
export const dropTable = (key: string, { lose }: { lose?: true } = {}): Change => ({
|
|
95
|
+
change: "dropTable",
|
|
96
|
+
key,
|
|
97
|
+
...(lose ? { lose } : {}),
|
|
98
|
+
});
|
|
94
99
|
/** Rename a table, keeping its rows. */
|
|
95
100
|
export const renameTable = (key: string, to: string): Change => ({ change: "renameTable", key, to });
|
|
96
|
-
/** Add a column: every row takes its empty value. */
|
|
97
|
-
export const addColumn = (
|
|
101
|
+
/** Add a column: every row takes what it's filled with (`fill`), or its empty value. */
|
|
102
|
+
export const addColumn = (
|
|
103
|
+
key: string,
|
|
104
|
+
name: string,
|
|
105
|
+
def: ColumnIn | (Column & { fill?: string | number }),
|
|
106
|
+
): Change => ({
|
|
98
107
|
change: "addColumn",
|
|
99
108
|
key,
|
|
100
109
|
column: name,
|
|
101
110
|
def: column(def),
|
|
111
|
+
...(typeof def === "object" && "fill" in def ? { fill: def.fill } : {}),
|
|
112
|
+
});
|
|
113
|
+
/** Drop a column, and its values. Where another is added beside it, its values, if it has any, are dropped only if it's
|
|
114
|
+
* said they're to go (`lose`): it may be a rename. */
|
|
115
|
+
export const dropColumn = (key: string, name: string, { lose }: { lose?: true } = {}): Change => ({
|
|
116
|
+
change: "dropColumn",
|
|
117
|
+
key,
|
|
118
|
+
column: name,
|
|
119
|
+
...(lose ? { lose } : {}),
|
|
102
120
|
});
|
|
103
|
-
/** Drop a column, and its values. */
|
|
104
|
-
export const dropColumn = (key: string, name: string): Change => ({ change: "dropColumn", key, column: name });
|
|
105
121
|
/** A table guarded as it's given: what its values are (made again, its rows kept, where that changed), what it links
|
|
106
122
|
* to, what an add needs. */
|
|
107
123
|
export const guardTable = (key: string, def: TableIn): Change => ({
|
|
@@ -134,8 +150,12 @@ export function applyChange(state: State, c: Change): State {
|
|
|
134
150
|
// what links to it links to it by its new name
|
|
135
151
|
for (const t of Object.values(next))
|
|
136
152
|
for (const d of Object.values(t.columns)) if (d.to?.table === c.key) d.to.table = c.to;
|
|
137
|
-
} else if (c.change === "guardTable")
|
|
138
|
-
|
|
153
|
+
} else if (c.change === "guardTable") {
|
|
154
|
+
// a column it doesn't name is another branch's, added before it: kept, with all it is
|
|
155
|
+
const { columns } = there(c.key);
|
|
156
|
+
next[c.key] = structuredClone(c.table);
|
|
157
|
+
for (const [name, d] of Object.entries(columns)) next[c.key]!.columns[name] ??= d;
|
|
158
|
+
} else {
|
|
139
159
|
const t = there(c.key);
|
|
140
160
|
if ((c.change === "addColumn") === c.column in t.columns)
|
|
141
161
|
throw new Error(
|
|
@@ -177,6 +197,8 @@ const same = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b)
|
|
|
177
197
|
const bare = ({ type, nullable }: Column) => ({ type, ...(nullable ? { nullable } : {}) });
|
|
178
198
|
/** A column made optional, its type as it was: no row is refused by it, so it isn't a person's to write. */
|
|
179
199
|
const loosened = (was: Column, now: Column) => was.type === now.type && !was.nullable && !!now.nullable;
|
|
200
|
+
/** A column no row can be without, whose empty value isn't one of its own: a date, a link. */
|
|
201
|
+
const unfilled = (d: Column) => !d.nullable && (d.is?.type === "form" || !!d.to);
|
|
180
202
|
/** What guards a table: whether it's strict, what each of the columns given is and links to, what an add needs. */
|
|
181
203
|
const guards = (t: Table, columns: string[]) => ({
|
|
182
204
|
strict: !!t.strict,
|
|
@@ -198,7 +220,11 @@ export function diff(state: State, want: State): { changes: Change[]; byHand: st
|
|
|
198
220
|
}
|
|
199
221
|
const gone = Object.keys(was.columns).filter((c) => !(c in t.columns));
|
|
200
222
|
const added = Object.keys(t.columns).filter((c) => !(c in was.columns));
|
|
201
|
-
for (const c of added)
|
|
223
|
+
for (const c of added) {
|
|
224
|
+
changes.push({ change: "addColumn", key, column: c, def: t.columns[c]! });
|
|
225
|
+
if (unfilled(t.columns[c]!))
|
|
226
|
+
byHand.push(`${key}.${c} is needed, and a row there has none: give them one ({ …, fill: "…" })`);
|
|
227
|
+
}
|
|
202
228
|
for (const c of gone) changes.push({ change: "dropColumn", key, column: c });
|
|
203
229
|
// what guards a table changed (what its values are, what it links to, what an add needs): made again, once its
|
|
204
230
|
// columns are added and dropped
|
|
@@ -490,6 +516,49 @@ const checks = (t: Table) => [
|
|
|
490
516
|
.sort(([a], [b]) => (String(a) < String(b) ? -1 : 1)),
|
|
491
517
|
];
|
|
492
518
|
|
|
519
|
+
/** What a migration would drop as it adds another like it, which may be the same renamed: refused while it has values,
|
|
520
|
+
* until it's said which. */
|
|
521
|
+
async function lost(db: Engine, changes: Change[]) {
|
|
522
|
+
for (const c of changes) {
|
|
523
|
+
if ((c.change !== "dropColumn" && c.change !== "dropTable") || c.lose) continue;
|
|
524
|
+
const column = c.change === "dropColumn" ? c.column : undefined;
|
|
525
|
+
const made = changes.flatMap((x) =>
|
|
526
|
+
column === undefined
|
|
527
|
+
? x.change === "createTable"
|
|
528
|
+
? [x.key]
|
|
529
|
+
: []
|
|
530
|
+
: x.change === "addColumn" && x.key === c.key
|
|
531
|
+
? [x.column]
|
|
532
|
+
: [],
|
|
533
|
+
);
|
|
534
|
+
// (one this migration adds itself isn't there yet)
|
|
535
|
+
const there = await db.columns(c.key);
|
|
536
|
+
if (!made.length || !(column === undefined ? there.length : there.includes(column))) continue;
|
|
537
|
+
const any = column === undefined ? "" : ` WHERE ${q(column)} IS NOT NULL AND CAST(${q(column)} AS TEXT) <> ''`;
|
|
538
|
+
if (!(await db.query(`SELECT 1 FROM ${q(c.key)}${any} LIMIT 1`).get())) continue;
|
|
539
|
+
const [of, what, args, rename] =
|
|
540
|
+
column === undefined
|
|
541
|
+
? [c.key, "rows", `"${c.key}"`, "renameTable"]
|
|
542
|
+
: [`${c.key}.${column}`, "values", `"${c.key}", "${column}"`, "renameColumn"];
|
|
543
|
+
const named = made.map((m) => (column === undefined ? m : `${c.key}.${m}`)).join(", ");
|
|
544
|
+
throw new Error(
|
|
545
|
+
`${of} has ${what} and ${named} ${made.length === 1 ? "is" : "are"} new: if it's the same renamed, ${rename}(${args}, "${made[0]}"); if its ${what} are to go, ${c.change}(${args}, { lose: true })`,
|
|
546
|
+
);
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
/** A migration's changes, as they were when it ran: the same however their keys were ordered. */
|
|
551
|
+
const hashOf = (changes: Change[]) =>
|
|
552
|
+
new Bun.CryptoHasher("sha256")
|
|
553
|
+
.update(
|
|
554
|
+
JSON.stringify(changes, (_, v) =>
|
|
555
|
+
v && typeof v === "object" && !Array.isArray(v)
|
|
556
|
+
? Object.fromEntries(Object.entries(v).sort(([a], [b]) => (a < b ? -1 : 1)))
|
|
557
|
+
: v,
|
|
558
|
+
),
|
|
559
|
+
)
|
|
560
|
+
.digest("hex");
|
|
561
|
+
|
|
493
562
|
/** One change made on the database, the tables before it and after: its table's triggers made again from what it
|
|
494
563
|
* is. */
|
|
495
564
|
async function make(db: Engine, c: Change, before: State, after: State) {
|
|
@@ -498,27 +567,28 @@ async function make(db: Engine, c: Change, before: State, after: State) {
|
|
|
498
567
|
if (!(await has(db, c.key))) await db.run(tableSql(db, c.key, c.table));
|
|
499
568
|
for (const u of c.table.unique ?? []) await makeUnique(db, c.key, u);
|
|
500
569
|
} else if (c.change === "guardTable") {
|
|
570
|
+
const t = after[c.key]!;
|
|
501
571
|
// its triggers alone, unless what a CHECK says changed: then
|
|
502
|
-
if (same(checks(before[c.key]!), checks(
|
|
572
|
+
if (same(checks(before[c.key]!), checks(t))) return guardWith(db, c.key, after[c.key]);
|
|
503
573
|
// Postgres changes a table's CHECKs and foreign keys in place: each dropped, and made again from what it is
|
|
504
574
|
if (db.dialect === "postgres") {
|
|
505
575
|
for (const { name } of (await db
|
|
506
576
|
.query("SELECT conname AS name FROM pg_constraint WHERE conrelid = to_regclass(?) AND contype IN ('c', 'f')")
|
|
507
577
|
.all(q(c.key))) as { name: string }[])
|
|
508
578
|
await db.run(`ALTER TABLE ${q(c.key)} DROP CONSTRAINT ${q(name)}`);
|
|
509
|
-
for (const [col, d] of Object.entries(
|
|
579
|
+
for (const [col, d] of Object.entries(t.columns)) {
|
|
510
580
|
if (d.is) await db.run(`ALTER TABLE ${q(c.key)} ADD${checkSql(db, col, d)}`);
|
|
511
581
|
// a column made optional (one made needed is a person's, and its empty rows theirs to fill)
|
|
512
582
|
if (d.nullable) await db.run(`ALTER TABLE ${q(c.key)} ALTER COLUMN ${q(col)} DROP NOT NULL`);
|
|
513
583
|
}
|
|
514
|
-
await linked(db, c.key,
|
|
584
|
+
await linked(db, c.key, t);
|
|
515
585
|
return guardWith(db, c.key, after[c.key]);
|
|
516
586
|
}
|
|
517
587
|
// made anew beside it, its rows copied, and put in its place; what else names it (another's trigger) isn't
|
|
518
588
|
// rewritten as it's renamed, so it names this one
|
|
519
589
|
const there = await db.columns(c.key),
|
|
520
|
-
was = Object.keys(
|
|
521
|
-
await db.run(tableSql(db, `${c.key}__new`,
|
|
590
|
+
was = Object.keys(t.columns).filter((col) => there.includes(col));
|
|
591
|
+
await db.run(tableSql(db, `${c.key}__new`, t));
|
|
522
592
|
await db.run(
|
|
523
593
|
`INSERT INTO ${q(`${c.key}__new`)} (${["id", ...was].map(q).join(", ")}) SELECT ${["id", ...was].map(q).join(", ")} FROM ${q(c.key)}`,
|
|
524
594
|
);
|
|
@@ -526,7 +596,7 @@ async function make(db: Engine, c: Change, before: State, after: State) {
|
|
|
526
596
|
await db.run("PRAGMA legacy_alter_table = ON");
|
|
527
597
|
await db.run(`ALTER TABLE ${q(`${c.key}__new`)} RENAME TO ${q(c.key)}`);
|
|
528
598
|
await db.run("PRAGMA legacy_alter_table = OFF");
|
|
529
|
-
for (const u of
|
|
599
|
+
for (const u of t.unique ?? []) await makeUnique(db, c.key, u);
|
|
530
600
|
} else if (c.change === "dropTable") {
|
|
531
601
|
await db.run(`DROP TABLE IF EXISTS ${q(c.key)}`);
|
|
532
602
|
await db.run(`DELETE FROM ${SEQUENCES} WHERE collection = ?`, [c.key]);
|
|
@@ -540,8 +610,20 @@ async function make(db: Engine, c: Change, before: State, after: State) {
|
|
|
540
610
|
(await db.run(`DROP INDEX ${q(u.name)}`), await makeUnique(db, c.to, u.columns));
|
|
541
611
|
await db.run(`UPDATE ${SEQUENCES} SET collection = ? WHERE collection = ?`, [c.to, c.key]);
|
|
542
612
|
} else if (c.change === "addColumn") {
|
|
543
|
-
// every row takes the column's empty value; one with none (json, a time) is left to be empty
|
|
544
|
-
const
|
|
613
|
+
// every row takes what it's given, or the column's empty value; one with none (json, a time) is left to be empty
|
|
614
|
+
const empty =
|
|
615
|
+
c.fill === undefined
|
|
616
|
+
? SQL[c.def.type].empty
|
|
617
|
+
: typeof c.fill === "number"
|
|
618
|
+
? String(c.fill)
|
|
619
|
+
: `'${c.fill.replaceAll("'", "''")}'`;
|
|
620
|
+
if (c.fill === undefined && unfilled(c.def)) {
|
|
621
|
+
const { n } = (await db.query(`SELECT COUNT(*) AS n FROM ${q(c.key)}`).get()) as { n: number };
|
|
622
|
+
if (n)
|
|
623
|
+
throw new Error(
|
|
624
|
+
`${c.key}.${c.column} is needed, and ${n} row${n === 1 ? " there has" : "s there have"} none: give them one (addColumn("${c.key}", "${c.column}", { …, fill: "…" }))`,
|
|
625
|
+
);
|
|
626
|
+
}
|
|
545
627
|
const fill = c.def.nullable || empty === "NULL" ? "" : ` NOT NULL DEFAULT ${empty}`;
|
|
546
628
|
await db.run(
|
|
547
629
|
`ALTER TABLE ${q(c.key)} ADD COLUMN ${columnSql(db, c.column, { ...c.def, nullable: true }, after[c.key]!.strict)}${fill}`,
|
|
@@ -571,17 +653,30 @@ export async function migrate(db: Engine, app: string, list: Migration[]): Promi
|
|
|
571
653
|
await db.run(
|
|
572
654
|
`CREATE TABLE IF NOT EXISTS ${RAN} (app TEXT NOT NULL, id TEXT NOT NULL, ran_at TEXT NOT NULL, PRIMARY KEY (app, id))`,
|
|
573
655
|
);
|
|
656
|
+
// what each said as it ran (none kept, of one from before this was)
|
|
657
|
+
if (!(await db.columns(RAN)).includes("hash")) await db.run(`ALTER TABLE ${RAN} ADD COLUMN hash TEXT`);
|
|
574
658
|
await db.run(`CREATE TABLE IF NOT EXISTS ${SEQUENCES} (collection TEXT PRIMARY KEY, last INTEGER NOT NULL)`);
|
|
575
659
|
});
|
|
576
|
-
const done = new
|
|
577
|
-
(
|
|
660
|
+
const done = new Map(
|
|
661
|
+
(
|
|
662
|
+
(await db.query(`SELECT id, hash FROM ${RAN} WHERE app = ?`).all(app)) as { id: string; hash: string | null }[]
|
|
663
|
+
).map((r) => [r.id, r.hash]),
|
|
578
664
|
);
|
|
579
665
|
const ran: string[] = [];
|
|
580
666
|
let state: State = {};
|
|
581
667
|
for (const m of list) {
|
|
582
668
|
const before = state;
|
|
583
669
|
state = m.changes.reduce(applyChange, state);
|
|
584
|
-
|
|
670
|
+
const hash = hashOf(m.changes);
|
|
671
|
+
if (done.has(m.id)) {
|
|
672
|
+
const was = done.get(m.id);
|
|
673
|
+
if (!was) await db.run(`UPDATE ${RAN} SET hash = ? WHERE app = ? AND id = ?`, [hash, app, m.id]);
|
|
674
|
+
else if (was !== hash)
|
|
675
|
+
console.warn(
|
|
676
|
+
`${app}'s migration ${m.id} has changed since it ran here, and isn't run again: what it says now isn't what the store has`,
|
|
677
|
+
);
|
|
678
|
+
continue;
|
|
679
|
+
}
|
|
585
680
|
// SQLite makes a table again by dropping it, and a drop deletes its rows first, taking with them the rows that
|
|
586
681
|
// link to it (or refused by them): its foreign keys are off while it runs (they can't be turned off inside its
|
|
587
682
|
// transaction), and checked whole before it commits
|
|
@@ -594,6 +689,7 @@ export async function migrate(db: Engine, app: string, list: Migration[]): Promi
|
|
|
594
689
|
if (await db.query(`SELECT 1 FROM ${RAN} WHERE app = ? AND id = ?`).get(app, m.id)) return;
|
|
595
690
|
// a table made again beside itself is put in its place by commit, its links whole again by then
|
|
596
691
|
await db.defer();
|
|
692
|
+
await lost(db, m.changes);
|
|
597
693
|
let s = before;
|
|
598
694
|
for (const c of m.changes) {
|
|
599
695
|
const after = applyChange(s, c);
|
|
@@ -617,7 +713,12 @@ export async function migrate(db: Engine, app: string, list: Migration[]): Promi
|
|
|
617
713
|
const loose = (await db.query("PRAGMA foreign_key_check").get()) as { table: string; parent: string } | null;
|
|
618
714
|
if (loose) throw new Error(`${loose.table} links to no row of ${loose.parent}`);
|
|
619
715
|
}
|
|
620
|
-
await db.run(`INSERT INTO ${RAN} (app, id, ran_at) VALUES (?, ?, ?)`, [
|
|
716
|
+
await db.run(`INSERT INTO ${RAN} (app, id, ran_at, hash) VALUES (?, ?, ?, ?)`, [
|
|
717
|
+
app,
|
|
718
|
+
m.id,
|
|
719
|
+
new Date().toISOString(),
|
|
720
|
+
hash,
|
|
721
|
+
]);
|
|
621
722
|
made = true;
|
|
622
723
|
});
|
|
623
724
|
} catch (e) {
|
package/src/page.ts
CHANGED
|
@@ -431,38 +431,44 @@ function apply(held: Map<string, Held>, o: Op): Element | undefined {
|
|
|
431
431
|
const ids = (el?.getAttribute(field!) ?? "").split(" ").filter(Boolean).map(Number);
|
|
432
432
|
if (el) set(el, "ids", field!, o.op === "add" ? [...ids, o.value] : ids.filter((id) => id !== Number(link)));
|
|
433
433
|
} else if (o.op === "add") placed(h, element(h, o.value));
|
|
434
|
-
else if (o.op === "remove"
|
|
435
|
-
else if (el)
|
|
434
|
+
else if (o.op === "remove" && !field) (el?.remove(), h.items.delete(key!));
|
|
435
|
+
else if (el) {
|
|
436
|
+
set(el, h.fields[field!], field!, o.op === "remove" ? undefined : o.value);
|
|
437
|
+
if (field === h.order) placed(h, el);
|
|
438
|
+
}
|
|
436
439
|
return h.items.get(o.op === "add" && field === undefined ? String(o.value.id) : key!);
|
|
437
440
|
}
|
|
438
441
|
|
|
439
|
-
/** An item put where it goes:
|
|
440
|
-
*
|
|
442
|
+
/** An item put where it goes: after the last that ranks before it, found from the end, where most are added. The
|
|
443
|
+
* others are in their order already. */
|
|
441
444
|
function placed(h: Held, el: Element) {
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
if (after
|
|
452
|
-
h.el.insertBefore(el, after ?? null);
|
|
445
|
+
const [rank, key] = rankOf(h, el);
|
|
446
|
+
let before = h.el.lastElementChild;
|
|
447
|
+
for (; before; before = before.previousElementSibling) {
|
|
448
|
+
if (before === el) continue;
|
|
449
|
+
const [r, k] = rankOf(h, before);
|
|
450
|
+
if (r < rank || (r === rank && k < key)) break;
|
|
451
|
+
}
|
|
452
|
+
// moved only if it isn't there already
|
|
453
|
+
const after = before ? before.nextElementSibling : h.el.firstElementChild;
|
|
454
|
+
if (after !== el) h.el.insertBefore(el, after);
|
|
453
455
|
}
|
|
454
456
|
|
|
455
|
-
/** Where an item ranks
|
|
456
|
-
const rankOf = (h: Held, el: Element) =>
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
457
|
+
/** Where an item ranks: by its collection's order (without one, or a place in it, by its key), then by its key. */
|
|
458
|
+
const rankOf = (h: Held, el: Element) => {
|
|
459
|
+
const key = Number(el.getAttribute("key"));
|
|
460
|
+
return [Number((h.order && el.getAttribute(h.order)) ?? key), key] as const;
|
|
461
|
+
};
|
|
462
|
+
|
|
463
|
+
/** A collection's items all put in their order: its own, each one's rank read once, or as they're given. The longest
|
|
464
|
+
* run of them in order already stays where it is, and only the rest are moved, each before the next that stays. */
|
|
465
|
+
function inOrder(h: Held, items: Element[]) {
|
|
466
|
+
const want = h.order
|
|
467
|
+
? items
|
|
468
|
+
.map((el) => ({ el, at: rankOf(h, el) }))
|
|
469
|
+
.sort((a, b) => a.at[0] - b.at[0] || a.at[1] - b.at[1])
|
|
470
|
+
.map(({ el }) => el)
|
|
471
|
+
: items;
|
|
466
472
|
const now = new Map([...h.el.children].map((el, i) => [el, i]));
|
|
467
473
|
// the longest run: for each length, the item one so long ends with (the earliest on the page), and for each item the
|
|
468
474
|
// one before it in its run
|
|
@@ -496,18 +502,17 @@ function inOrder(h: Held) {
|
|
|
496
502
|
/** A collection, whole, as the document has it: each item kept by key and changed only where it
|
|
497
503
|
* differs, those gone taken away, and those new added. */
|
|
498
504
|
function whole(h: Held, items: Record<string, unknown>[]) {
|
|
499
|
-
const gone = new Set(h.items.keys())
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
const
|
|
505
|
-
|
|
506
|
-
}
|
|
507
|
-
gone.delete(String(item.id));
|
|
508
|
-
}
|
|
505
|
+
const gone = new Set(h.items.keys()),
|
|
506
|
+
given = items.map((item) => {
|
|
507
|
+
const el = h.items.get(String(item.id));
|
|
508
|
+
gone.delete(String(item.id));
|
|
509
|
+
if (!el) return element(h, item);
|
|
510
|
+
for (const [field, type] of Object.entries(h.fields)) set(el, type, field, valueAt(item, field));
|
|
511
|
+
return el;
|
|
512
|
+
});
|
|
509
513
|
for (const key of gone) (h.items.get(key)!.remove(), h.items.delete(key));
|
|
510
|
-
|
|
514
|
+
// (a document's own element holds no items)
|
|
515
|
+
if (!h.own) inOrder(h, given);
|
|
511
516
|
}
|
|
512
517
|
|
|
513
518
|
function element({ tag, fields, items, may }: Held, item: Record<string, unknown>) {
|
package/src/postgres-server.ts
CHANGED
|
@@ -3,6 +3,9 @@
|
|
|
3
3
|
|
|
4
4
|
import { postgresOf, type Engine } from "./engine.ts";
|
|
5
5
|
|
|
6
|
+
/** What Bun.sql calls no answer at all: its connection closed, reset, or timed out. */
|
|
7
|
+
const GONE = /^(ERR_POSTGRES_(CONNECTION|IDLE|LIFETIME)|ECONN|EPIPE)/;
|
|
8
|
+
|
|
6
9
|
/** A Postgres server, by its URL (JOINED_POSTGRES: postgres://user:password@host:port/database), through Bun.sql: one
|
|
7
10
|
* connection held for the store, and LISTEN on a connection of its own. `fresh`: a database of its own, made as it
|
|
8
11
|
* opens and dropped as it closes (a test's). */
|
|
@@ -20,33 +23,85 @@ export async function server(url: string, { fresh = false } = {}): Promise<Engin
|
|
|
20
23
|
}
|
|
21
24
|
at.pathname = `/${made}`;
|
|
22
25
|
}
|
|
26
|
+
// (a connection lost isn't given back to a pool that may hand it out again: each is a pool of its own, of one)
|
|
23
27
|
const sql = new SQL(at.href, { max: 2 });
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
28
|
+
const hold = async () => {
|
|
29
|
+
const pool = new SQL(at.href, { max: 1 });
|
|
30
|
+
try {
|
|
31
|
+
return { pool, held: await pool.reserve() };
|
|
32
|
+
} catch (e) {
|
|
33
|
+
await pool.close();
|
|
34
|
+
throw e;
|
|
35
|
+
}
|
|
36
|
+
};
|
|
37
|
+
let { pool, held } = await hold();
|
|
38
|
+
// the connection lost (the server restarted, a network gone): another is made in its place as the next thing is asked,
|
|
39
|
+
// with what's the connection's own. What was asked is asked again only where that's safe: a transaction begun, or a
|
|
40
|
+
// read outside one. A transaction it was lost in is refused whole, however much of it is still asked. (Bun listens
|
|
41
|
+
// again by itself.)
|
|
42
|
+
const own: string[] = [];
|
|
43
|
+
let lost = false,
|
|
44
|
+
within = false,
|
|
45
|
+
making: Promise<void> | undefined;
|
|
46
|
+
const on = async <T>(text: string, ask: () => Promise<T>): Promise<T | undefined> => {
|
|
47
|
+
const ends = /^(COMMIT|ROLLBACK)$/.test(text);
|
|
48
|
+
if (lost && within) {
|
|
49
|
+
if (ends) within = false;
|
|
50
|
+
if (/^ROLLBACK/.test(text)) return undefined;
|
|
51
|
+
throw new Error("the database's connection was lost in the middle of a write: none of it was made");
|
|
52
|
+
}
|
|
53
|
+
for (let again = false; ; again = true) {
|
|
54
|
+
// (one made, however much is asked meanwhile)
|
|
55
|
+
if (lost)
|
|
56
|
+
await (making ??= (async () => {
|
|
57
|
+
const [gone, was] = [pool, held];
|
|
58
|
+
({ pool, held } = await hold());
|
|
59
|
+
for (const s of own) await held.unsafe(s);
|
|
60
|
+
lost = false;
|
|
61
|
+
// (not waited for: nothing answers it)
|
|
62
|
+
was.release();
|
|
63
|
+
void gone.close({ timeout: 0 }).catch(() => {});
|
|
64
|
+
})().finally(() => (making = undefined)));
|
|
65
|
+
const asked = held;
|
|
66
|
+
try {
|
|
67
|
+
const answer = await ask();
|
|
68
|
+
if (text === "BEGIN") within = true;
|
|
69
|
+
if (ends) within = false;
|
|
70
|
+
return answer;
|
|
71
|
+
} catch (e) {
|
|
72
|
+
// refused by a server that's going (57P…), or by no server at all
|
|
73
|
+
const { errno, code } = e as { errno?: unknown; code?: string };
|
|
74
|
+
const gone = /^(57P|08)/.test(String(errno)) || GONE.test(String(code));
|
|
75
|
+
// (said by one another has taken the place of already, it's said of that one alone)
|
|
76
|
+
if (gone && asked === held) lost = true;
|
|
77
|
+
if (!gone || again || within || !/^(BEGIN$|SELECT\b)/.test(text)) {
|
|
78
|
+
if (ends) within = false;
|
|
79
|
+
throw e;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
};
|
|
31
84
|
const types = (columns: unknown) =>
|
|
32
85
|
new Map(((columns as { name: string; type: number }[] | undefined) ?? []).map((f) => [f.name, f.type]));
|
|
33
86
|
return postgresOf(
|
|
34
87
|
{
|
|
35
88
|
async query(text, values) {
|
|
36
|
-
const r = (await held.unsafe(text, values as never[])) as unknown as
|
|
37
|
-
count: number | null;
|
|
38
|
-
|
|
39
|
-
};
|
|
89
|
+
const r = (await on(text, async () => held.unsafe(text, values as never[]))) as unknown as
|
|
90
|
+
(Record<string, unknown>[] & { count: number | null; columns?: unknown }) | undefined;
|
|
91
|
+
if (!r) return { rows: [], changes: 0, types: new Map() };
|
|
40
92
|
return { rows: [...r], changes: r.count ?? 0, types: types(r.columns) };
|
|
41
93
|
},
|
|
42
|
-
many: (text) => held.unsafe(text).simple(),
|
|
94
|
+
many: (text) => on(text, async () => held.unsafe(text).simple()),
|
|
43
95
|
},
|
|
44
96
|
{
|
|
45
97
|
listen: async (channel, heard) => void (await sql.listen(channel, heard)),
|
|
98
|
+
each: (text) => (own.push(text), on(text, async () => held.unsafe(text))),
|
|
46
99
|
notify: (channel, payload) => held.unsafe("SELECT pg_notify($1, $2)", [channel, payload]),
|
|
47
100
|
async close() {
|
|
48
|
-
|
|
49
|
-
|
|
101
|
+
await making?.catch(() => {});
|
|
102
|
+
if (!lost) held.release();
|
|
103
|
+
await pool.close({ timeout: 1 });
|
|
104
|
+
await sql.close({ timeout: 1 });
|
|
50
105
|
if (!made) return;
|
|
51
106
|
const admin = new SQL(url, { max: 1 });
|
|
52
107
|
try {
|
package/src/proxy.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
// What a proxy in front (Railway's) says of a request it passed on: joined itself is asked over http, on this machine.
|
|
2
|
+
// Anyone may say it; nothing is let in by it: an https said falsely only keeps the speaker's own cookie to https.
|
|
3
|
+
|
|
4
|
+
/** The scheme a request came by: the first a proxy says, being the one nearest the person, else its own URL's. */
|
|
5
|
+
export const schemeOf = (req: Request) =>
|
|
6
|
+
req.headers.get("x-forwarded-proto")?.split(",")[0]!.trim() || new URL(req.url).protocol.slice(0, -1);
|
|
7
|
+
|
|
8
|
+
/** Whether a request was passed on by a proxy, so its address is the proxy's and not who asked. */
|
|
9
|
+
export const passedOn = (req: Request) =>
|
|
10
|
+
["x-forwarded-for", "x-real-ip", "x-forwarded-host", "x-forwarded-proto", "forwarded", "via"].some((h) =>
|
|
11
|
+
req.headers.has(h),
|
|
12
|
+
);
|
package/src/reading.ts
CHANGED
|
@@ -40,6 +40,11 @@ export abstract class Reading extends HTMLElement {
|
|
|
40
40
|
#watch = new MutationObserver(() => this.again());
|
|
41
41
|
#away = new AbortController();
|
|
42
42
|
#due = false;
|
|
43
|
+
/** While it draws, the page's sheet, found once: asked for each item, it cost a look through the page each. */
|
|
44
|
+
#sheet?: PageSheet | null;
|
|
45
|
+
#stale = false;
|
|
46
|
+
#drawn = false;
|
|
47
|
+
#shown = new ResizeObserver(() => this.#stale && this.again());
|
|
43
48
|
|
|
44
49
|
get for() {
|
|
45
50
|
return this.getAttribute("for") ?? "";
|
|
@@ -91,18 +96,31 @@ export abstract class Reading extends HTMLElement {
|
|
|
91
96
|
this.root.append(this.line);
|
|
92
97
|
}
|
|
93
98
|
this.#watch.observe(document.body, { childList: true, subtree: true, attributes: true });
|
|
99
|
+
this.#shown.observe(this);
|
|
94
100
|
this.again();
|
|
95
101
|
});
|
|
96
102
|
}
|
|
97
103
|
disconnectedCallback() {
|
|
98
104
|
this.#watch.disconnect();
|
|
105
|
+
this.#shown.disconnect();
|
|
99
106
|
this.#away.abort();
|
|
100
107
|
}
|
|
101
|
-
/** Drawn again, once a moment however much changed; hidden, when it's shown again. */
|
|
108
|
+
/** Drawn again, once a moment however much changed; hidden, when it's shown again (its first drawing apart). */
|
|
102
109
|
again() {
|
|
103
110
|
if (this.#due || !this.spec) return;
|
|
104
111
|
this.#due = true;
|
|
105
|
-
queueMicrotask(() =>
|
|
112
|
+
queueMicrotask(() => {
|
|
113
|
+
this.#due = false;
|
|
114
|
+
this.#stale = this.#drawn && !this.checkVisibility();
|
|
115
|
+
if (this.#stale) return;
|
|
116
|
+
this.#drawn = true;
|
|
117
|
+
this.#sheet = this.sheet;
|
|
118
|
+
try {
|
|
119
|
+
this.draw();
|
|
120
|
+
} finally {
|
|
121
|
+
this.#sheet = undefined;
|
|
122
|
+
}
|
|
123
|
+
});
|
|
106
124
|
}
|
|
107
125
|
/** Its collection's items on the page, as the search finds them. */
|
|
108
126
|
items(): Item[] {
|
|
@@ -127,7 +145,7 @@ export abstract class Reading extends HTMLElement {
|
|
|
127
145
|
}
|
|
128
146
|
/** The page's sheet of its collection. */
|
|
129
147
|
get sheet() {
|
|
130
|
-
return document.querySelector<PageSheet>(`j-sheet[for="${this.for}"]`);
|
|
148
|
+
return this.#sheet !== undefined ? this.#sheet : document.querySelector<PageSheet>(`j-sheet[for="${this.for}"]`);
|
|
131
149
|
}
|
|
132
150
|
open(it: Item) {
|
|
133
151
|
this.sheet?.show(it);
|