@blueshed/joined 0.3.3 → 0.3.5
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 +23 -8
- package/.claude/skills/joined-door/SKILL.md +17 -2
- package/docs/introduction.md +6 -2
- 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 +102 -36
- 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 +57 -28
- package/src/skill.ts +100 -33
- package/src/store.ts +27 -18
- package/src/upkeep.ts +9 -8
- package/src/upload.ts +136 -0
- package/src/write.ts +71 -21
package/src/mcp.ts
CHANGED
|
@@ -7,14 +7,18 @@
|
|
|
7
7
|
// rules, never the stories: read_<doc>, the document as its member sees it, and write_<doc>, one write, its ops typed
|
|
8
8
|
// as the grants allow; a kind's (trip:1) take the instance's key. A window isn't a tool's: a document is read as its
|
|
9
9
|
// member sees it, whole or one collection's items (some, by id). How any document is read and written here is the
|
|
10
|
-
// door's own skill (src/skill.ts), served by MCP's skills extension
|
|
11
|
-
//
|
|
10
|
+
// door's own skill (src/skill.ts), served by MCP's skills extension beside each app's own (its words, its routes.ts's
|
|
11
|
+
// `instructions`, and what its documents hold, from their rules), and said as it opens. A document that names files
|
|
12
|
+
// has upload_<doc> too: a link the server makes for the agent's member to send a file by (src/upload.ts), since the
|
|
13
|
+
// agent never sees its own key. It speaks both eras of MCP: the modern (2026-07-28), each request saying its
|
|
12
14
|
// version and the client's capabilities in its _meta, its headers checked against its body, server/discover in place
|
|
13
15
|
// of a handshake, and the skills extension declared; and the legacy, opened by initialize. To a client that loads
|
|
14
|
-
// skills itself the instructions say where the
|
|
16
|
+
// skills itself the instructions say where the skills are, and the apps' words; to any other, what the skills say.
|
|
15
17
|
|
|
16
18
|
import { FORMS, SAID } from "./compile.ts";
|
|
17
|
-
import { skill, SKILLS } from "./skill.ts";
|
|
19
|
+
import { pointer, skill, skillOf, SKILLS } from "./skill.ts";
|
|
20
|
+
import type { Made } from "./upload.ts";
|
|
21
|
+
import { schemeOf } from "./proxy.ts";
|
|
18
22
|
import type { Who } from "./members/group.ts";
|
|
19
23
|
import { upTo } from "./files.ts";
|
|
20
24
|
import { isOp, MESSAGE, NTH, OPS, parts, type Op, type Type } from "./ops.ts";
|
|
@@ -34,7 +38,16 @@ type Door = {
|
|
|
34
38
|
read(doc: string, member: number): Promise<Doc>;
|
|
35
39
|
/** A write by an agent's member; or, at a door that's anyone's, nobody's (null), as a stranger's page writes. */
|
|
36
40
|
write(doc: string, ops: Op[], why: string | undefined, who: Who | null): Promise<Written>;
|
|
37
|
-
|
|
41
|
+
/** Each app: its name, its words for an agent, and its documents. */
|
|
42
|
+
apps: { app: string; words: string; docs: string[] }[];
|
|
43
|
+
/** A link for a member's agent (nobody's, at a door that's anyone's) to send a file for a document by (src/upload.ts). */
|
|
44
|
+
upload?(
|
|
45
|
+
origin: string,
|
|
46
|
+
doc: string,
|
|
47
|
+
who: Who | null,
|
|
48
|
+
name: string,
|
|
49
|
+
then: { ops?: Op[]; why?: string },
|
|
50
|
+
): Promise<Made>;
|
|
38
51
|
version: string;
|
|
39
52
|
};
|
|
40
53
|
type Schema = Record<string, unknown>;
|
|
@@ -205,9 +218,17 @@ const ANYONE: Who = { member: 0, token: "" };
|
|
|
205
218
|
export function door(d: Door) {
|
|
206
219
|
const rpc = (id: unknown, result: unknown) => ({ jsonrpc: "2.0", id, result });
|
|
207
220
|
const fail = (id: unknown, code: number, message: string) => ({ jsonrpc: "2.0", id, error: { code, message } });
|
|
221
|
+
// each app's skill, beside the door's: its words and what its documents hold
|
|
222
|
+
const apps = d.apps.flatMap((a) => {
|
|
223
|
+
const rules = d.rules.filter((r) => a.docs.includes(r.doc));
|
|
224
|
+
return rules.length ? [skillOf(a.app, a.words, rules)] : [];
|
|
225
|
+
});
|
|
226
|
+
const skills = [skill, ...apps],
|
|
227
|
+
words = d.apps.map((a) => a.words).filter(Boolean);
|
|
228
|
+
const skillAt = (uri: unknown) => skills.find((s) => s.uri === uri);
|
|
208
229
|
|
|
209
230
|
/** The tools for a member's agent: each document's read and, where pages write it, its write; a kind's take its key. */
|
|
210
|
-
async function toolsFor(who: Who) {
|
|
231
|
+
async function toolsFor(who: Who, origin: string) {
|
|
211
232
|
const tools: {
|
|
212
233
|
name: string;
|
|
213
234
|
description: string;
|
|
@@ -218,9 +239,17 @@ export function door(d: Door) {
|
|
|
218
239
|
for (const r of d.rules) {
|
|
219
240
|
// the document a call names: a kind's instance by its key (trip:1), or the one
|
|
220
241
|
const name = (args: { key?: unknown }) => (r.kind ? `${r.doc}:${args.key}` : r.doc);
|
|
242
|
+
// (a whole number alone, so it names an instance and nothing more: no code, no window)
|
|
243
|
+
const unkeyed = (args: { key?: unknown }) =>
|
|
244
|
+
r.kind && !/^[1-9]\d*$/.test(String(args.key)) ? `key: which ${r.doc}, a whole number` : null;
|
|
221
245
|
if (!r.kind && (await d.holds(r.doc, who.member))) continue;
|
|
222
246
|
const key = r.kind
|
|
223
|
-
? {
|
|
247
|
+
? {
|
|
248
|
+
key: {
|
|
249
|
+
type: "integer",
|
|
250
|
+
description: `which ${r.doc}: the id of one of the ${r.kind.root} in ${r.kind.doc}`,
|
|
251
|
+
},
|
|
252
|
+
}
|
|
224
253
|
: {};
|
|
225
254
|
const colls = Object.entries(r.collections)
|
|
226
255
|
.filter(([, c]) => !c.own)
|
|
@@ -242,7 +271,7 @@ export function door(d: Door) {
|
|
|
242
271
|
// a read changes nothing: a client needn't ask before it
|
|
243
272
|
annotations: { readOnlyHint: true },
|
|
244
273
|
run: async (args) => {
|
|
245
|
-
const no = await d.holds(name(args), who.member);
|
|
274
|
+
const no = unkeyed(args) ?? (await d.holds(name(args), who.member));
|
|
246
275
|
if (no) return refused(no);
|
|
247
276
|
const read = readOf(await d.read(name(args), who.member), args);
|
|
248
277
|
return typeof read === "string" ? refused(read) : answered(read);
|
|
@@ -252,6 +281,22 @@ export function door(d: Door) {
|
|
|
252
281
|
// an op's path as it's said: an add by a first step, what it gives
|
|
253
282
|
const said = (o: (typeof ops)[number]) => `${o.path}${o.gives ? ` giving ${o.gives}` : ""}`;
|
|
254
283
|
if (r.type !== "shared" || !ops.length) continue;
|
|
284
|
+
const opsOfWrite = {
|
|
285
|
+
type: "array",
|
|
286
|
+
minItems: 1,
|
|
287
|
+
items: {
|
|
288
|
+
anyOf: ops.map((o) => ({
|
|
289
|
+
type: "object",
|
|
290
|
+
properties: {
|
|
291
|
+
op: { type: "string", enum: [o.op] },
|
|
292
|
+
path: { type: "string", pattern: o.pattern, description: said(o) },
|
|
293
|
+
...(o.value ? { value: o.value } : {}),
|
|
294
|
+
},
|
|
295
|
+
required: ["op", "path", ...(o.value ? ["value"] : [])],
|
|
296
|
+
})),
|
|
297
|
+
},
|
|
298
|
+
};
|
|
299
|
+
const why = { type: "string", description: "why, in a few words, where it helps those who read it" };
|
|
255
300
|
tools.push({
|
|
256
301
|
name: `write_${r.doc}`,
|
|
257
302
|
description: `One write to ${r.doc}, whole or not at all, told to every page at once: its ops, each one of ${ops.map((o) => `${o.op} ${said(o)}`).join(", ")}. {id} is an item's id, as read_${r.doc} shows it. Done answers with its version and the ids of what it added; refused, with why.`,
|
|
@@ -259,22 +304,8 @@ export function door(d: Door) {
|
|
|
259
304
|
type: "object",
|
|
260
305
|
properties: {
|
|
261
306
|
...key,
|
|
262
|
-
ops:
|
|
263
|
-
|
|
264
|
-
minItems: 1,
|
|
265
|
-
items: {
|
|
266
|
-
anyOf: ops.map((o) => ({
|
|
267
|
-
type: "object",
|
|
268
|
-
properties: {
|
|
269
|
-
op: { type: "string", enum: [o.op] },
|
|
270
|
-
path: { type: "string", pattern: o.pattern, description: said(o) },
|
|
271
|
-
...(o.value ? { value: o.value } : {}),
|
|
272
|
-
},
|
|
273
|
-
required: ["op", "path", ...(o.value ? ["value"] : [])],
|
|
274
|
-
})),
|
|
275
|
-
},
|
|
276
|
-
},
|
|
277
|
-
why: { type: "string", description: "why, in a few words, where it helps those who read it" },
|
|
307
|
+
ops: opsOfWrite,
|
|
308
|
+
why,
|
|
278
309
|
},
|
|
279
310
|
required: [...Object.keys(key), "ops"],
|
|
280
311
|
},
|
|
@@ -284,7 +315,7 @@ export function door(d: Door) {
|
|
|
284
315
|
if (!Array.isArray(args.ops) || !args.ops.length)
|
|
285
316
|
return refused("ops: one write's ops, a list of at least one");
|
|
286
317
|
if (!args.ops.every(isOp)) return refused(OPS);
|
|
287
|
-
const no = await d.holds(name(args), who.member);
|
|
318
|
+
const no = unkeyed(args) ?? (await d.holds(name(args), who.member));
|
|
288
319
|
if (no) return refused(no);
|
|
289
320
|
const w = await d.write(
|
|
290
321
|
name(args),
|
|
@@ -295,13 +326,45 @@ export function door(d: Door) {
|
|
|
295
326
|
return "why" in w ? refused(w.why) : answered(w);
|
|
296
327
|
},
|
|
297
328
|
});
|
|
329
|
+
// a file it names comes by a link the server makes: the agent never sees its own key, the server does
|
|
330
|
+
if (!d.upload || !Object.values(r.collections).some((c) => Object.values(c.fields).includes("file"))) continue;
|
|
331
|
+
const upload = d.upload;
|
|
332
|
+
tools.push({
|
|
333
|
+
name: `upload_${r.doc}`,
|
|
334
|
+
description: `A link to send one file to ${r.doc} by, made for you (you never see your key; the server does): good once, for 15 minutes, a photo, an SVG, a PDF or a Markdown file under 20 MB. POST the file's bytes to its url, answered its value (file:<sha256>.<ext>) to put in a write; or, where you can't reach the site, give the url to your person to open and choose the file. With ops, the write it's for, "$file" in a value standing for the file, that write is made as yours once the file is in, and the url answers it.`,
|
|
335
|
+
inputSchema: {
|
|
336
|
+
type: "object",
|
|
337
|
+
properties: {
|
|
338
|
+
...key,
|
|
339
|
+
name: {
|
|
340
|
+
type: "string",
|
|
341
|
+
description: "the file's name, as receipt.pdf (a Markdown file is known by its .md)",
|
|
342
|
+
},
|
|
343
|
+
ops: { ...opsOfWrite, description: 'the write it\'s for, made once the file is in: "$file" stands for it' },
|
|
344
|
+
why,
|
|
345
|
+
},
|
|
346
|
+
required: Object.keys(key),
|
|
347
|
+
},
|
|
348
|
+
annotations: { readOnlyHint: false, destructiveHint: false },
|
|
349
|
+
run: async (args) => {
|
|
350
|
+
if (args.ops !== undefined && (!Array.isArray(args.ops) || !args.ops.length || !args.ops.every(isOp)))
|
|
351
|
+
return refused(OPS);
|
|
352
|
+
const no = unkeyed(args) ?? (await d.holds(name(args), who.member));
|
|
353
|
+
if (no) return refused(no);
|
|
354
|
+
const made = await upload(origin, name(args), d.anyone ? null : who, String(args.name ?? ""), {
|
|
355
|
+
...(args.ops ? { ops: texted(r, args.ops) } : {}),
|
|
356
|
+
...(typeof args.why === "string" && args.why.trim() ? { why: args.why.trim() } : {}),
|
|
357
|
+
});
|
|
358
|
+
return "why" in made ? refused(made.why) : answered(made);
|
|
359
|
+
},
|
|
360
|
+
});
|
|
298
361
|
}
|
|
299
362
|
return tools;
|
|
300
363
|
}
|
|
301
364
|
|
|
302
365
|
/** One message, in its era: answered, or a notification (no id), which isn't. A modern answer says it's complete,
|
|
303
366
|
* and where it may be kept a while, for how long (none: the grants can change) and for whom. */
|
|
304
|
-
async function one(m: Message, who: Who, modern: boolean) {
|
|
367
|
+
async function one(m: Message, who: Who, modern: boolean, origin: string) {
|
|
305
368
|
if (m.id === undefined) return null;
|
|
306
369
|
const done = (result: object, kept?: "public" | "private") =>
|
|
307
370
|
rpc(
|
|
@@ -310,7 +373,7 @@ export function door(d: Door) {
|
|
|
310
373
|
);
|
|
311
374
|
// to a client that loads skills itself (it says so in the request's capabilities), where the skill is
|
|
312
375
|
const loads = !!m.params?._meta?.[`${MCP}clientCapabilities`]?.extensions?.[SKILLS];
|
|
313
|
-
const instructions =
|
|
376
|
+
const instructions = (loads ? [pointer(apps), ...words] : skills.map((s) => s.body)).join("\n\n");
|
|
314
377
|
if (modern && m.method === "server/discover")
|
|
315
378
|
return done(
|
|
316
379
|
{
|
|
@@ -329,20 +392,21 @@ export function door(d: Door) {
|
|
|
329
392
|
instructions,
|
|
330
393
|
});
|
|
331
394
|
if (!modern && m.method === "ping") return rpc(m.id, {});
|
|
332
|
-
|
|
395
|
+
const asked = skillAt(m.params?.uri);
|
|
396
|
+
if (m.method === "resources/list") return done({ resources: skills.map((s) => s.resource) }, "public");
|
|
333
397
|
if (m.method === "resources/read")
|
|
334
|
-
return
|
|
335
|
-
? done({ contents: [{ uri:
|
|
398
|
+
return asked
|
|
399
|
+
? done({ contents: [{ uri: asked.uri, mimeType: "text/markdown", text: asked.text }] }, "public")
|
|
336
400
|
: fail(m.id, -32602, `there's no resource at ${m.params?.uri}`);
|
|
337
|
-
if (modern && m.method === "skills/list") return done({ skills:
|
|
401
|
+
if (modern && m.method === "skills/list") return done({ skills: skills.map((s) => s.entry) }, "public");
|
|
338
402
|
if (modern && m.method === "skills/get")
|
|
339
|
-
return
|
|
340
|
-
? done({ skill:
|
|
403
|
+
return asked
|
|
404
|
+
? done({ skill: asked.entry }, "public")
|
|
341
405
|
: fail(m.id, -32602, `No skill is served at ${m.params?.uri}`);
|
|
342
406
|
if (m.method === "tools/list")
|
|
343
|
-
return done({ tools: (await toolsFor(who)).map(({ run: _, ...t }) => t) }, "private");
|
|
407
|
+
return done({ tools: (await toolsFor(who, origin)).map(({ run: _, ...t }) => t) }, "private");
|
|
344
408
|
if (m.method === "tools/call") {
|
|
345
|
-
const tool = (await toolsFor(who)).find((t) => t.name === m.params?.name);
|
|
409
|
+
const tool = (await toolsFor(who, origin)).find((t) => t.name === m.params?.name);
|
|
346
410
|
return tool
|
|
347
411
|
? done(await tool.run(m.params.arguments ?? {}))
|
|
348
412
|
: fail(m.id, -32602, `no tool called ${m.params?.name}`);
|
|
@@ -398,7 +462,9 @@ export function door(d: Door) {
|
|
|
398
462
|
);
|
|
399
463
|
}
|
|
400
464
|
// never thrown: Bun's line for a request that throws names its URL, and the URL holds the agent's token
|
|
401
|
-
|
|
465
|
+
// where the door was asked, as a link it makes is said: the site's, behind its proxy too
|
|
466
|
+
const origin = `${schemeOf(req)}://${new URL(req.url).host}`;
|
|
467
|
+
const answer = await one(m, who!, version !== undefined, origin).catch((e) => {
|
|
402
468
|
console.error("the MCP door failed:", e);
|
|
403
469
|
return fail(m.id ?? null, -32603, "That wasn't done: the server had a problem with it.");
|
|
404
470
|
});
|
package/src/members/demo.ts
CHANGED
|
@@ -1,19 +1,22 @@
|
|
|
1
1
|
// A demo on this machine, never live (start refuses one in production): anyone here may be any member, without their
|
|
2
2
|
// link, from the root page's line, so a demo of Nora's or Nick's pages always has a way back to the BDFL. It's asked
|
|
3
3
|
// of this machine alone: from its loopback, by its own name (a name that only resolves to it, a page elsewhere, is
|
|
4
|
-
// refused), and never by a page on another site (a picture's address there would sign this
|
|
4
|
+
// refused), never passed on by a proxy, and never by a page on another site (a picture's address there would sign this
|
|
5
|
+
// browser in).
|
|
5
6
|
|
|
7
|
+
import { passedOn } from "../proxy.ts";
|
|
6
8
|
import type { Member } from "./trust.ts";
|
|
7
9
|
|
|
8
10
|
const LOOPBACK = ["127.0.0.1", "::1", "::ffff:127.0.0.1"];
|
|
9
11
|
const HOSTS = ["localhost", "127.0.0.1", "[::1]"];
|
|
10
12
|
|
|
11
13
|
/** Whether a request is this machine's own: from its loopback (its address, `ip`), by its own name, from no other
|
|
12
|
-
* site. */
|
|
14
|
+
* site, and not passed on by a proxy here (a tunnel, for anyone). */
|
|
13
15
|
export const fromHere = (req: Request, ip?: string) =>
|
|
14
16
|
LOOPBACK.includes(ip ?? "") &&
|
|
15
17
|
HOSTS.includes(new URL(req.url).hostname) &&
|
|
16
|
-
req.headers.get("sec-fetch-site") !== "cross-site"
|
|
18
|
+
req.headers.get("sec-fetch-site") !== "cross-site" &&
|
|
19
|
+
!passedOn(req);
|
|
17
20
|
|
|
18
21
|
/** The demo's routes: who there is to be, the BDFL first, and who this browser is (`me`, none signed out); and
|
|
19
22
|
* being one, this browser signed in as them by the server (`signIn`), their link never shown. Refused to anyone not
|
package/src/members/group.ts
CHANGED
|
@@ -14,6 +14,7 @@ import { timingSafeEqual } from "node:crypto";
|
|
|
14
14
|
import type { Engine } from "../engine.ts";
|
|
15
15
|
import { demoRoutes } from "./demo.ts";
|
|
16
16
|
import { parts, type Op } from "../ops.ts";
|
|
17
|
+
import { schemeOf } from "../proxy.ts";
|
|
17
18
|
import { openKeys, type Agent } from "./keys.ts";
|
|
18
19
|
import { doc as OWN } from "./generated/rules.ts";
|
|
19
20
|
import { bdflOf, mayAsk, mayWrite, trust, withMovesUp, type Asked, type Member } from "./trust.ts";
|
|
@@ -126,7 +127,7 @@ export async function groupOf({
|
|
|
126
127
|
path: "/",
|
|
127
128
|
httpOnly: true,
|
|
128
129
|
sameSite: "lax",
|
|
129
|
-
secure:
|
|
130
|
+
secure: schemeOf(req) === "https",
|
|
130
131
|
maxAge,
|
|
131
132
|
}).serialize();
|
|
132
133
|
/** Home, this browser signed in by a token, for a year. */
|
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) {
|