@blueshed/joined 0.0.0-stage → 0.1.20
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude/skills/joined/SKILL.md +17 -0
- package/.claude/skills/joined/reference.md +768 -0
- package/LICENSE +19 -0
- package/README.md +115 -2
- package/docs/design.md +148 -0
- package/docs/introduction.md +193 -0
- package/docs/learning.md +76 -0
- package/docs/stories.md +82 -0
- package/examples/app.css +27 -0
- package/examples/cafe/books.html +38 -0
- package/examples/cafe/books.json +13 -0
- package/examples/cafe/books.ts +64 -0
- package/examples/cafe/cafe.css +512 -0
- package/examples/cafe/front.html +115 -0
- package/examples/cafe/front.ts +7 -0
- package/examples/cafe/generated/books.elements.ts +52 -0
- package/examples/cafe/generated/books.queries.ts +11 -0
- package/examples/cafe/generated/books.rules.ts +42 -0
- package/examples/cafe/generated/kitchen.elements.ts +87 -0
- package/examples/cafe/generated/kitchen.queries.ts +47 -0
- package/examples/cafe/generated/kitchen.rules.ts +98 -0
- package/examples/cafe/generated/menu.elements.ts +61 -0
- package/examples/cafe/generated/menu.queries.ts +28 -0
- package/examples/cafe/generated/menu.rules.ts +65 -0
- package/examples/cafe/generated/order.elements.ts +87 -0
- package/examples/cafe/generated/order.queries.ts +47 -0
- package/examples/cafe/generated/order.rules.ts +95 -0
- package/examples/cafe/generated/staff.elements.ts +55 -0
- package/examples/cafe/generated/staff.queries.ts +27 -0
- package/examples/cafe/generated/staff.rules.ts +59 -0
- package/examples/cafe/generated/supplies.elements.ts +62 -0
- package/examples/cafe/generated/supplies.queries.ts +43 -0
- package/examples/cafe/generated/supplies.rules.ts +84 -0
- package/examples/cafe/generated/till.elements.ts +93 -0
- package/examples/cafe/generated/till.queries.ts +57 -0
- package/examples/cafe/generated/till.rules.ts +113 -0
- package/examples/cafe/index.html +70 -0
- package/examples/cafe/kitchen.css +107 -0
- package/examples/cafe/kitchen.html +39 -0
- package/examples/cafe/kitchen.ts +125 -0
- package/examples/cafe/menu.html +55 -0
- package/examples/cafe/menu.json +41 -0
- package/examples/cafe/menu.ts +84 -0
- package/examples/cafe/migrations/001-cafe.ts +11 -0
- package/examples/cafe/order.html +37 -0
- package/examples/cafe/order.ts +45 -0
- package/examples/cafe/rail-drag.ts +30 -0
- package/examples/cafe/routes.ts +32 -0
- package/examples/cafe/staff.json +20 -0
- package/examples/cafe/stories.jsonl +43 -0
- package/examples/cafe/supplies.html +77 -0
- package/examples/cafe/supplies.json +33 -0
- package/examples/cafe/supplies.ts +170 -0
- package/examples/cafe/till.json +95 -0
- package/examples/cafe/till.ts +122 -0
- package/examples/cafe/trust.ts +20 -0
- package/examples/cafe/views.ts +171 -0
- package/examples/docs.ts +28 -0
- package/examples/film.jpg +0 -0
- package/examples/hello/generated/elements.ts +45 -0
- package/examples/hello/generated/queries.ts +24 -0
- package/examples/hello/generated/rules.ts +45 -0
- package/examples/hello/hello.css +27 -0
- package/examples/hello/hello.json +1 -0
- package/examples/hello/index.html +32 -0
- package/examples/hello/migrations/001-hello.ts +6 -0
- package/examples/hello/page.ts +49 -0
- package/examples/hello/routes.ts +6 -0
- package/examples/hello/stories.jsonl +3 -0
- package/examples/index.html +146 -0
- package/examples/page.ts +11 -0
- package/examples/people/adding.ts +20 -0
- package/examples/people/generated/elements.ts +68 -0
- package/examples/people/generated/queries.ts +28 -0
- package/examples/people/generated/rules.ts +85 -0
- package/examples/people/links.ts +124 -0
- package/examples/people/migrations/001-people.ts +6 -0
- package/examples/people/migrations/002-add-people-member-and-guard-people.ts +7 -0
- package/examples/people/migrations/003-add-people-rank-and-guard-people.ts +7 -0
- package/examples/people/order.ts +61 -0
- package/examples/people/people.css +65 -0
- package/examples/people/people.json +26 -0
- package/examples/people/routes.ts +12 -0
- package/examples/people/stories.jsonl +20 -0
- package/examples/people/trust.ts +14 -0
- package/examples/people/view.ts +115 -0
- package/examples/routes.ts +11 -0
- package/examples/trip/answer-rows.ts +70 -0
- package/examples/trip/answers.ts +11 -0
- package/examples/trip/bar.ts +89 -0
- package/examples/trip/calendar-map.css +709 -0
- package/examples/trip/calendar-map.ts +249 -0
- package/examples/trip/drags.ts +143 -0
- package/examples/trip/drawer.ts +250 -0
- package/examples/trip/event-form.ts +199 -0
- package/examples/trip/generated/elements.ts +144 -0
- package/examples/trip/generated/queries.ts +46 -0
- package/examples/trip/generated/rules.ts +239 -0
- package/examples/trip/holding.ts +61 -0
- package/examples/trip/ics.ts +117 -0
- package/examples/trip/index.html +82 -0
- package/examples/trip/line-stops.ts +92 -0
- package/examples/trip/line-words.ts +79 -0
- package/examples/trip/line.ts +121 -0
- package/examples/trip/map.ts +234 -0
- package/examples/trip/mercator.ts +28 -0
- package/examples/trip/migrations/001-trip.ts +7 -0
- package/examples/trip/migrations/002-add-events-zone-and-guard-events.ts +7 -0
- package/examples/trip/migrations/003-guard-events-and-create-events_asked-and-more.ts +9 -0
- package/examples/trip/migrations/004-create-stays.ts +6 -0
- package/examples/trip/migrations/005-guard-events-and-create-events_arrives-and-more.ts +8 -0
- package/examples/trip/month.ts +87 -0
- package/examples/trip/other-weeks.ts +67 -0
- package/examples/trip/page.ts +121 -0
- package/examples/trip/peek.ts +71 -0
- package/examples/trip/people-chips.ts +74 -0
- package/examples/trip/place-search.ts +51 -0
- package/examples/trip/places.ts +34 -0
- package/examples/trip/routes.ts +27 -0
- package/examples/trip/shell.ts +39 -0
- package/examples/trip/stays.css +51 -0
- package/examples/trip/stays.ts +68 -0
- package/examples/trip/stories.jsonl +72 -0
- package/examples/trip/time.ts +46 -0
- package/examples/trip/told.ts +48 -0
- package/examples/trip/trip.json +69 -0
- package/examples/trip/trust.ts +51 -0
- package/examples/trip/week.ts +237 -0
- package/examples/trip/words.ts +4 -0
- package/examples/trip/writes.ts +91 -0
- package/examples/trip/zones.ts +16 -0
- package/examples/trips/card.ts +149 -0
- package/examples/trips/generated/elements.ts +60 -0
- package/examples/trips/generated/queries.ts +28 -0
- package/examples/trips/generated/rules.ts +62 -0
- package/examples/trips/index.html +47 -0
- package/examples/trips/map.ts +52 -0
- package/examples/trips/migrations/001-trips.ts +8 -0
- package/examples/trips/new-trip.ts +46 -0
- package/examples/trips/page.ts +9 -0
- package/examples/trips/routes.ts +7 -0
- package/examples/trips/stories.jsonl +12 -0
- package/examples/trips/trips.css +183 -0
- package/examples/trips/trips.json +7 -0
- package/examples/weeks/derive.ts +23 -0
- package/examples/weeks/generated/elements.ts +52 -0
- package/examples/weeks/generated/rules.ts +33 -0
- package/examples/weeks/routes.ts +4 -0
- package/examples/weeks/weeks.json +1 -0
- package/examples/welcome.css +299 -0
- package/package.json +55 -4
- package/src/attachment.ts +70 -0
- package/src/cli.ts +52 -0
- package/src/client.ts +98 -0
- package/src/compile.ts +2034 -0
- package/src/css.d.ts +5 -0
- package/src/definitions.ts +268 -0
- package/src/demo.css +29 -0
- package/src/demo.ts +42 -0
- package/src/draft.ts +69 -0
- package/src/engine.ts +288 -0
- package/src/file-value.ts +13 -0
- package/src/files.ts +187 -0
- package/src/follow.ts +56 -0
- package/src/hues.ts +3 -0
- package/src/icon-names.ts +77 -0
- package/src/icon.png +0 -0
- package/src/icons.ts +32 -0
- package/src/keep.ts +33 -0
- package/src/link.ts +31 -0
- package/src/mcp.ts +252 -0
- package/src/members/demo.ts +53 -0
- package/src/members/generated/elements.ts +68 -0
- package/src/members/generated/queries.ts +29 -0
- package/src/members/generated/rules.ts +65 -0
- package/src/members/group.ts +294 -0
- package/src/members/keys.ts +221 -0
- package/src/members/members.json +9 -0
- package/src/members/migrations/001-members.ts +6 -0
- package/src/members/migrations/002-guard-members.ts +11 -0
- package/src/members/migrations/003-add-members-act-and-guard-members.ts +7 -0
- package/src/members/panel.css +208 -0
- package/src/members/panel.ts +398 -0
- package/src/members/routes.ts +4 -0
- package/src/members/stories.jsonl +27 -0
- package/src/members/trust.ts +116 -0
- package/src/migrate.ts +597 -0
- package/src/migrations/001-joined.ts +13 -0
- package/src/migrations/002-group-keys.ts +16 -0
- package/src/migrations/003-change-inverse.ts +10 -0
- package/src/migrations/004-change-followed.ts +6 -0
- package/src/ops.ts +61 -0
- package/src/page.css +79 -0
- package/src/page.ts +413 -0
- package/src/parts.css +471 -0
- package/src/parts.ts +152 -0
- package/src/server.ts +862 -0
- package/src/settings.ts +94 -0
- package/src/starter.ts +89 -0
- package/src/store.ts +815 -0
- package/src/stories.ts +387 -0
- package/src/toast.ts +52 -0
- package/src/together.ts +167 -0
- package/src/tokens.css +85 -0
- package/src/tokens.json +457 -0
- package/src/upkeep.ts +86 -0
- package/src/visitors.ts +43 -0
- package/src/write.ts +567 -0
- package/starter/CLAUDE.md +37 -0
- package/starter/gitignore +3 -0
- package/starter/tests/hello-page.test.ts +14 -0
- package/starter/tests/hello.test.ts +8 -0
- package/starter/tsconfig.json +17 -0
package/src/server.ts
ADDED
|
@@ -0,0 +1,862 @@
|
|
|
1
|
+
// The server imports each app's routes.ts, and nothing else of it. An app's routes.ts is its way
|
|
2
|
+
// in: its document (export * as document, its compiled rules) and its routes (Bun's routes: its
|
|
3
|
+
// page, an index.html it imports, which Bun's HTML import bundles with its scripts and stylesheets,
|
|
4
|
+
// a file, a Response, anyone's, as a page is, and its edges; a function of a way to read the
|
|
5
|
+
// documents, if an edge needs them). The folder's own routes.ts is the root's, and joined's own,
|
|
6
|
+
// the group's (src/members), is beside them all. A
|
|
7
|
+
// document is kept in the store (src/store.ts: SQLite, made by migrations) and changed only by ops
|
|
8
|
+
// its rules allow. A link is checked against the document it points into, and an item another
|
|
9
|
+
// document links to can't be removed. A write is made whole or not at all, in one transaction (src/write.ts: its
|
|
10
|
+
// rules, the rows, and who is told), and then published, with its version and its writer, to every page holding a
|
|
11
|
+
// document, or a part of one, it changed. A page is served with its documents in it, as its person sees them.
|
|
12
|
+
//
|
|
13
|
+
// Who may do what is the group's (src/members/group.ts): the server asks it who a request is,
|
|
14
|
+
// whether a write may go, what it brings and what follows it, what a page asks besides ops, and to
|
|
15
|
+
// guard an app's edges. It names no app.
|
|
16
|
+
|
|
17
|
+
import type { ServerWebSocket } from "bun";
|
|
18
|
+
import { mkdirSync, renameSync } from "node:fs";
|
|
19
|
+
import { basename, dirname } from "node:path";
|
|
20
|
+
import { APPS, DATA, DB, ENGINE, OWN } from "./compile.ts";
|
|
21
|
+
import { open, type Dialect } from "./engine.ts";
|
|
22
|
+
import { doc as GROUP } from "./members/generated/rules.ts";
|
|
23
|
+
import { groupOf, say, type Data, type Who } from "./members/group.ts";
|
|
24
|
+
import { fromHere } from "./members/demo.ts";
|
|
25
|
+
import { door, type Written } from "./mcp.ts";
|
|
26
|
+
import { bdflOf, type Asked, type Member } from "./members/trust.ts";
|
|
27
|
+
import { attribute, docParts, parts, valueAt, versionKey, type Change, type Op, type Type } from "./ops.ts";
|
|
28
|
+
import { openStore, Refused, type Doc } from "./store.ts";
|
|
29
|
+
import { madeBy, type Part } from "./together.ts";
|
|
30
|
+
import { writes, type Held, type Reactions, type Read, type Rules, type Told, type Trust } from "./write.ts";
|
|
31
|
+
/** A write refused, and why, in words a page shows as they are: a reaction or a route throws it. */
|
|
32
|
+
export { Refused };
|
|
33
|
+
export type { Reactions, Read, Trust };
|
|
34
|
+
import { upkeep, KEEP } from "./upkeep.ts";
|
|
35
|
+
import { filesAt, letGo, named, putsFile, routes as fileRoutes, type Files } from "./files.ts";
|
|
36
|
+
import { version } from "../package.json";
|
|
37
|
+
|
|
38
|
+
/** The most a page's message may be, in bytes. */
|
|
39
|
+
const MESSAGE = 1 << 20;
|
|
40
|
+
/** A timed field's clearing that failed is tried again a minute on; a timer waits at most what setTimeout can. */
|
|
41
|
+
const MINUTE = 60_000,
|
|
42
|
+
DAY = 1440 * MINUTE,
|
|
43
|
+
LONGEST = 2 ** 31 - 1;
|
|
44
|
+
/** A page's message: a document to subscribe to (and the version it had), a write to a document (or to several, each
|
|
45
|
+
* a part: src/together.ts), or an ask. */
|
|
46
|
+
type Message = {
|
|
47
|
+
id?: number;
|
|
48
|
+
subscribe?: string;
|
|
49
|
+
since?: number;
|
|
50
|
+
unsubscribe?: string;
|
|
51
|
+
doc?: string;
|
|
52
|
+
ops?: Op[];
|
|
53
|
+
why?: string;
|
|
54
|
+
writes?: Part[];
|
|
55
|
+
} & Asked;
|
|
56
|
+
|
|
57
|
+
/** A page's message, read; or why it isn't one joined reads. */
|
|
58
|
+
export function messageOf(text: string): Message | string {
|
|
59
|
+
let m: unknown;
|
|
60
|
+
try {
|
|
61
|
+
m = JSON.parse(text);
|
|
62
|
+
} catch {
|
|
63
|
+
return "that isn't JSON";
|
|
64
|
+
}
|
|
65
|
+
if (typeof m !== "object" || m === null || Array.isArray(m)) return "a message is a JSON object";
|
|
66
|
+
const { id, subscribe, since, unsubscribe, doc, ops, why, writes } = m as Record<string, unknown>;
|
|
67
|
+
const op = (o: any) =>
|
|
68
|
+
typeof o === "object" && o !== null && ["add", "replace", "remove"].includes(o.op) && typeof o.path === "string";
|
|
69
|
+
const part = (w: any) =>
|
|
70
|
+
typeof w === "object" &&
|
|
71
|
+
w !== null &&
|
|
72
|
+
typeof w.doc === "string" &&
|
|
73
|
+
(w.why === undefined || typeof w.why === "string") &&
|
|
74
|
+
Array.isArray(w.ops) &&
|
|
75
|
+
w.ops.every(op);
|
|
76
|
+
if (writes !== undefined && [doc, ops, why].some((x) => x !== undefined))
|
|
77
|
+
return "a write is a doc and its ops, or writes, each its own: not both";
|
|
78
|
+
if (writes !== undefined && !(Array.isArray(writes) && writes.length && writes.every(part)))
|
|
79
|
+
return "writes are each a doc and its ops, and why if it's said";
|
|
80
|
+
if (id !== undefined && typeof id !== "number") return "an id is a number";
|
|
81
|
+
if (subscribe === undefined && unsubscribe === undefined && id === undefined) return "a write or an ask has an id";
|
|
82
|
+
if ([subscribe, unsubscribe, doc, why].some((s) => s !== undefined && typeof s !== "string"))
|
|
83
|
+
return "subscribe, unsubscribe, doc and why are strings";
|
|
84
|
+
if (since !== undefined && !Number.isInteger(since)) return "since is a version";
|
|
85
|
+
if (ops !== undefined && !(Array.isArray(ops) && ops.every(op)))
|
|
86
|
+
return "ops are each an add, a replace or a remove, at a path";
|
|
87
|
+
return m as Message;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Whether a request comes from another site's page, which would send it with this one's cookie (a socket opened, a
|
|
91
|
+
* file sent); a sandboxed frame's says "null". None said: a program's, not a page's. */
|
|
92
|
+
const anotherSite = (req: Request) => {
|
|
93
|
+
const origin = req.headers.get("origin");
|
|
94
|
+
return !!origin && (!URL.canParse(origin) || new URL(origin).host !== new URL(req.url).host);
|
|
95
|
+
};
|
|
96
|
+
|
|
97
|
+
/** joined's icon (an elephant in wood joinery, its trunk a j), 180 square. */
|
|
98
|
+
const ICON = `${import.meta.dir}/icon.png`;
|
|
99
|
+
|
|
100
|
+
/** A write by the server itself, a route's or a job's: shaped as the stories say, but asked of no roles and no
|
|
101
|
+
* trust.ts, since it's the app's own; landed with what follows from it, and told. Its change, or Refused. */
|
|
102
|
+
export type Write = (doc: string, ops: Op[]) => Change;
|
|
103
|
+
/** A derived document (its app's derive.ts, exported from its routes.ts): what it is now, for a member (nobody, 0),
|
|
104
|
+
* read off the documents it's derived from. Read-only: its pages write the documents it's read from. */
|
|
105
|
+
export type Derive = (read: Read, member: number) => Record<string, { id: number }[]>;
|
|
106
|
+
type Handler = (req: any) => Response | Promise<Response>;
|
|
107
|
+
type Routes = Record<string, Bun.HTMLBundle | Response | Handler | Record<string, Handler>>;
|
|
108
|
+
/** Where a server listens, where its apps are, its database, a document's JSON to begin it from, a folder of
|
|
109
|
+
* seeds of its own, its ROOT_TOKEN, its keys file, and whether it's the live site. */
|
|
110
|
+
type Options = {
|
|
111
|
+
port?: number;
|
|
112
|
+
dir?: string;
|
|
113
|
+
db?: string;
|
|
114
|
+
engine?: Dialect;
|
|
115
|
+
data?: Record<string, string>;
|
|
116
|
+
seeds?: string;
|
|
117
|
+
rootToken?: string;
|
|
118
|
+
keys?: string;
|
|
119
|
+
backups?: string;
|
|
120
|
+
/** Where the files the documents name are kept (src/files.ts): JOINED_FILES, a folder or a bucket
|
|
121
|
+
* (`s3://<bucket>/<prefix>`), or files/ beside the store; or the files themselves. */
|
|
122
|
+
files?: string | Files;
|
|
123
|
+
history?: number;
|
|
124
|
+
production?: boolean;
|
|
125
|
+
/** A demo on this machine: anyone here may be any member, without their link, from the root page (JOINED_DEMO=1,
|
|
126
|
+
* as `bun run dev` sets it). Never live: refused in production. */
|
|
127
|
+
demo?: boolean;
|
|
128
|
+
/** Where each write's line goes: the console, but quiet under bun test. */
|
|
129
|
+
log?: (line: string) => void;
|
|
130
|
+
};
|
|
131
|
+
/** An app's open routes: anyone's, never guarded by the group (a link's preview of what's public). */
|
|
132
|
+
type Open = Record<string, Response | ((req: Request) => Response | Promise<Response>)>;
|
|
133
|
+
|
|
134
|
+
/** What an app's routes.ts exports: its document, its routes and its own rules for a write, each if any. */
|
|
135
|
+
type App = {
|
|
136
|
+
document?: Rules;
|
|
137
|
+
documents?: Rules[];
|
|
138
|
+
routes?: Routes | ((read: Read, write: Write) => Routes);
|
|
139
|
+
/** Routes anyone may ask, reading each document as nobody (member 0): owns and sees apply, so a part only some see
|
|
140
|
+
* isn't there, but the group's door doesn't, so a document any member sees whole is whole. An open route shows only
|
|
141
|
+
* what it picks, and what it picks is public. */
|
|
142
|
+
open?: Open | ((read: Read) => Open);
|
|
143
|
+
trust?: Trust;
|
|
144
|
+
reactions?: Reactions;
|
|
145
|
+
derive?: Derive;
|
|
146
|
+
/** The app's own words for an agent at the MCP door (src/mcp.ts): what it's for, and how to write it well. */
|
|
147
|
+
instructions?: string;
|
|
148
|
+
/** What an invitation may do once its member is in (`act` on a member, "person 3"): each by its name, the write it
|
|
149
|
+
* makes for them, given the member and the act's word; run as them, with their grants and the app's trust. */
|
|
150
|
+
acts?: Acts;
|
|
151
|
+
};
|
|
152
|
+
export type Acts = Record<string, (member: number, word: string) => { doc: string; ops: Op[] }>;
|
|
153
|
+
|
|
154
|
+
/** Each app, by its routes.ts: joined's own (the group's), the folder's own (the root's, named ""), and each folder's. */
|
|
155
|
+
async function appsIn(dir = APPS) {
|
|
156
|
+
const apps: ({ app: string; at: string } & App)[] = [];
|
|
157
|
+
const found = [{ app: basename(OWN), at: OWN }];
|
|
158
|
+
for (const pattern of ["routes.ts", "*/routes.ts"])
|
|
159
|
+
for await (const path of new Bun.Glob(pattern).scan(dir))
|
|
160
|
+
found.push(
|
|
161
|
+
path === "routes.ts" ? { app: "", at: dir } : { app: path.split("/")[0]!, at: `${dir}/${path.split("/")[0]}` },
|
|
162
|
+
);
|
|
163
|
+
for (const { app, at } of found) {
|
|
164
|
+
const { document, documents, routes, open, trust, reactions, derive, instructions, acts } = (await import(
|
|
165
|
+
`${at}/routes.ts`
|
|
166
|
+
)) as App;
|
|
167
|
+
if (document?.derived && !derive) throw new Error(`${app} is derived, but its routes.ts exports no derive`);
|
|
168
|
+
apps.push({ app, at, document, documents, routes, open, trust, reactions, derive, instructions, acts });
|
|
169
|
+
}
|
|
170
|
+
return apps.sort((x, y) => x.app.localeCompare(y.app));
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** The build: the release, and the model each app was compiled to (its generated/ files, as they're read at start).
|
|
174
|
+
* A page is served it, and told it on every socket it opens: told another (a deploy, a restart with the stories
|
|
175
|
+
* compiled anew), it reloads (src/page.ts), its elements being made for rules the server no longer holds. */
|
|
176
|
+
async function buildOf(apps: { app: string; at: string }[]) {
|
|
177
|
+
let model = "";
|
|
178
|
+
for (const { app, at } of apps)
|
|
179
|
+
for (const path of [...new Bun.Glob("generated/*").scanSync(at)].sort())
|
|
180
|
+
model += `${app}/${path}\n${await Bun.file(`${at}/${path}`).text()}\n`;
|
|
181
|
+
return `${version}+${Bun.hash(model).toString(36)}`;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// An app's committed <doc>.json is the seed, where its stories start; what the pages change is
|
|
185
|
+
// kept in the store, a file in the data folder (DB: JOINED_DB, or joined.sqlite in JOINED_DATA, or
|
|
186
|
+
// .data/), and so are the members' keys, and the files the documents name (files/ beside it, or a bucket: src/files.ts); it's
|
|
187
|
+
// kept up, and backed up daily, in backups/ beside it (src/upkeep.ts; JOINED_BACKUPS); a change is kept for its
|
|
188
|
+
// history 90 days (JOINED_HISTORY), and any of a document's last 500, which a page catching up is sent. A document new to the store is begun from its JSON: one kept
|
|
189
|
+
// from before the store (data gives another file), or the seed: a site's own, where it names a folder of them
|
|
190
|
+
// (JOINED_SEEDS: a second site from the same apps), else its app's. It listens on PORT, or 3380.
|
|
191
|
+
// With ROOT_TOKEN, the group is invite-only; without it, open, which the live site (production:
|
|
192
|
+
// NODE_ENV=production) never is. A project whose stories are all anonymous has no members: the group's
|
|
193
|
+
// document isn't held, and the server is open, live too. Live, Bun's development mode is off: an error shows no source.
|
|
194
|
+
export async function start({
|
|
195
|
+
port = Number(Bun.env.PORT) || 3380,
|
|
196
|
+
dir = APPS,
|
|
197
|
+
db = DB,
|
|
198
|
+
engine = ENGINE,
|
|
199
|
+
data = {},
|
|
200
|
+
seeds = Bun.env.JOINED_SEEDS,
|
|
201
|
+
rootToken = Bun.env.ROOT_TOKEN,
|
|
202
|
+
keys,
|
|
203
|
+
backups = Bun.env.JOINED_BACKUPS || `${dirname(db)}/backups`,
|
|
204
|
+
// beside the store, as its backups are: a store's own, which its upkeep lets go of (in memory: the data folder)
|
|
205
|
+
files = Bun.env.JOINED_FILES || `${db === ":memory:" ? DATA : dirname(db)}/files`,
|
|
206
|
+
history = Number(Bun.env.JOINED_HISTORY) || 90,
|
|
207
|
+
production = Bun.env.NODE_ENV === "production",
|
|
208
|
+
demo = Bun.env.JOINED_DEMO === "1",
|
|
209
|
+
log = Bun.env.NODE_ENV === "test" ? undefined : console.log,
|
|
210
|
+
}: Options) {
|
|
211
|
+
const apps = await appsIn(dir);
|
|
212
|
+
const build = await buildOf(apps);
|
|
213
|
+
// no members: the apps have stories, and none is told as a member
|
|
214
|
+
// an app's documents: one (document), or several over its entities (documents)
|
|
215
|
+
const docsOf = (a: App) => a.documents ?? (a.document ? [a.document] : []);
|
|
216
|
+
const storied = apps.filter((a) => a.at !== OWN && docsOf(a).length);
|
|
217
|
+
const members = !storied.length || storied.some((a) => docsOf(a).some((d) => !d.anonymous));
|
|
218
|
+
if (production && members && !rootToken) throw new Error("ROOT_TOKEN isn't set, and the live site is never open");
|
|
219
|
+
if (production && demo) throw new Error("JOINED_DEMO is set, and the live site is never a demo");
|
|
220
|
+
const rules: Record<string, Rules> = {};
|
|
221
|
+
const held = apps.flatMap(({ app, at, document, documents }) =>
|
|
222
|
+
members || at !== OWN
|
|
223
|
+
? (documents ?? (document ? [document] : [])).map((r) => ({ name: app, dir: at, rules: r }))
|
|
224
|
+
: [],
|
|
225
|
+
);
|
|
226
|
+
for (const { rules: r } of held) rules[r.doc] = r;
|
|
227
|
+
const trusts = Object.fromEntries(apps.flatMap((a) => (a.trust ? docsOf(a).map((d) => [d.doc, a.trust!]) : [])));
|
|
228
|
+
const reacts = Object.fromEntries(
|
|
229
|
+
apps.flatMap((a) => (a.reactions ? docsOf(a).map((d) => [d.doc, a.reactions!]) : [])),
|
|
230
|
+
);
|
|
231
|
+
// the group's first, its members being who every other write is by; then each app's, by name
|
|
232
|
+
held.sort((a, b) => (a.dir === OWN ? -1 : b.dir === OWN ? 1 : a.name.localeCompare(b.name)));
|
|
233
|
+
if (db !== ":memory:") mkdirSync(dirname(db), { recursive: true });
|
|
234
|
+
// a derived document is kept nowhere: the store holds the others
|
|
235
|
+
const store = await openStore(
|
|
236
|
+
await open(db, engine),
|
|
237
|
+
held.filter((h) => !h.rules.derived),
|
|
238
|
+
);
|
|
239
|
+
const derives = new Map(apps.flatMap((a) => (a.derive ? [[a.document!.doc, a.derive] as const] : [])));
|
|
240
|
+
// A document new to the store is begun from its JSON: a file kept from before the store (in the data
|
|
241
|
+
// folder, or given), or else its seed: the site's own where it names a folder of them, else the app's, the group's
|
|
242
|
+
// the project's own where it gives one (members.json in its apps' folder), else joined's. The file kept from before
|
|
243
|
+
// is then renamed, never deleted, but only when the store is a file that lasts: a store in memory is gone when it
|
|
244
|
+
// stops, and the JSON is still the data. A seed is never renamed.
|
|
245
|
+
const lasts = db !== ":memory:";
|
|
246
|
+
// read first, then taken together in one transaction: one document's seed may link to another's
|
|
247
|
+
const taken: { doc: string; json: Doc; again?: boolean; kept?: string }[] = [];
|
|
248
|
+
const seedOf = async (at: string, doc: string) => {
|
|
249
|
+
for (const file of [seeds && `${seeds}/${doc}.json`, at === OWN && `${dir}/${doc}.json`])
|
|
250
|
+
if (file && (await Bun.file(file).exists())) return file;
|
|
251
|
+
return `${at}/${doc}.json`;
|
|
252
|
+
};
|
|
253
|
+
for (const { dir: at, rules: r } of held) {
|
|
254
|
+
// a static document is its seed: a release's, past the store's version, is taken in place of what was
|
|
255
|
+
if (r.type === "static") {
|
|
256
|
+
const seed = await Bun.file(await seedOf(at, r.doc)).json();
|
|
257
|
+
if (!store.holds(r.doc) || seed.version > store.read(r.doc).version)
|
|
258
|
+
taken.push({ doc: r.doc, json: seed, again: store.holds(r.doc) });
|
|
259
|
+
continue;
|
|
260
|
+
}
|
|
261
|
+
// a document read by member is a query over others' rows: there's nothing of its own to begin
|
|
262
|
+
if (r.derived || r.member || store.holds(r.doc)) continue;
|
|
263
|
+
const before = data[r.doc] ?? `${DATA}/${r.doc}.json`;
|
|
264
|
+
const kept = await Bun.file(before).exists();
|
|
265
|
+
const seed = await seedOf(at, r.doc);
|
|
266
|
+
// a document over tables another of its app seeds (the kitchen, the till's) may have no seed of its own
|
|
267
|
+
const from = Bun.file(kept ? before : seed);
|
|
268
|
+
const json = (await from.exists()) ? await from.json() : { version: 1 };
|
|
269
|
+
taken.push({ doc: r.doc, json, ...(kept ? { kept: before } : {}) });
|
|
270
|
+
}
|
|
271
|
+
store.takeAll(taken);
|
|
272
|
+
for (const { kept } of taken) if (kept && lasts) renameSync(kept, `${kept}.imported`);
|
|
273
|
+
// (a SQLite file's: a Postgres store's vacuum and backups aren't joined's, nor letting its files go); a file nothing
|
|
274
|
+
// names is let go once it's older than the history, and than a week's backups, which may name it still
|
|
275
|
+
const tables = held.filter((h) => !h.rules.derived && !h.rules.member).map((h) => h.rules),
|
|
276
|
+
filesKept = typeof files === "string" ? filesAt(files) : files;
|
|
277
|
+
const kept =
|
|
278
|
+
lasts && engine === "sqlite"
|
|
279
|
+
? upkeep(store.db, backups, console.log, {
|
|
280
|
+
trim: () => store.trim(Date.now() - history * DAY),
|
|
281
|
+
letGo: () => letGo(filesKept, named(store.db, tables), Date.now() - Math.max(history, KEEP) * DAY),
|
|
282
|
+
})
|
|
283
|
+
: null;
|
|
284
|
+
const { land, view, ungranted, ask, read, rulesOf, mayHold, mayOf, groupless, byCode, exists } = writes({
|
|
285
|
+
store,
|
|
286
|
+
rules,
|
|
287
|
+
group: GROUP,
|
|
288
|
+
trusts,
|
|
289
|
+
reacts,
|
|
290
|
+
});
|
|
291
|
+
|
|
292
|
+
// What each page holds beside whole documents, by its topic: a window of one (trip?week=2026-11-02), or a document as
|
|
293
|
+
// a person sees it (`<doc>@<member>`, nobody 0), where that's only some of it (owns) or it's read as each has it;
|
|
294
|
+
// and the version of the last change told to it, which a page subscribing late is sent it at. A page is told a
|
|
295
|
+
// change to it only where it changed: it says the version it follows (`after`), so a page knows one it missed.
|
|
296
|
+
const topics = new Map<string, { doc: string; member?: number; version: number }>();
|
|
297
|
+
/** A page's topic for a document it holds: a window's own, or its person's view, or the document's. */
|
|
298
|
+
const topicOf = (ws: ServerWebSocket<Data>, doc: string) => {
|
|
299
|
+
const r = rulesOf(doc);
|
|
300
|
+
// (held by its root's code, a guest's, it's whole: a window's topic, its own name)
|
|
301
|
+
return (r.sees || r.member) && !byCode(doc) ? `${doc}@${ws.data.who?.member ?? 0}` : doc;
|
|
302
|
+
};
|
|
303
|
+
/** Whether a page holds a part of a document, told what changed of it as a whole: a window, what its person sees, or
|
|
304
|
+
* a document holding only some of its tables' rows (its where's). */
|
|
305
|
+
const isPart = (doc: string, topic: string) => topic !== doc || doc.includes("?") || !!rulesOf(doc).view;
|
|
306
|
+
/** What the pages hold beside whole documents, for a write to work out what's told to each. */
|
|
307
|
+
const pagesHold = (): Held => {
|
|
308
|
+
const windows: string[] = [],
|
|
309
|
+
views: Held["views"] = [];
|
|
310
|
+
for (const [topic, t] of topics) {
|
|
311
|
+
if (!server.subscriberCount(topic)) topics.delete(topic);
|
|
312
|
+
else if (t.member !== undefined) views.push({ topic, doc: t.doc, member: t.member });
|
|
313
|
+
else windows.push(topic);
|
|
314
|
+
}
|
|
315
|
+
return { windows, views };
|
|
316
|
+
};
|
|
317
|
+
/** What landed, published once it has committed: each change to its document's topic (a document seen whole), and
|
|
318
|
+
* what's told to each window and view; and each document derived from one of them, derived again for each page
|
|
319
|
+
* holding it. The one place anything is published: here, once the store's write commits; on Postgres, as each
|
|
320
|
+
* commit is notified. */
|
|
321
|
+
const tell = ({ changes, told }: { changes: Change[]; told: Told }) => {
|
|
322
|
+
const written = new Set(changes.map((change) => docParts(change.doc).name));
|
|
323
|
+
// a page holding a document by a root item's code (an instance, or the root's own), where the root's document
|
|
324
|
+
// changed (its level, its code), asked again whether it may hold it, and refused as at the door if not, before
|
|
325
|
+
// anything's told: told no more
|
|
326
|
+
for (const ws of pages)
|
|
327
|
+
for (const doc of ws.data.docs) {
|
|
328
|
+
const root = !derives.has(doc) && byCode(doc);
|
|
329
|
+
const no = root && written.has(root) && mayHold(doc, ws.data.who?.member ?? null, !(members && rootToken));
|
|
330
|
+
if (no)
|
|
331
|
+
(ws.data.docs.delete(doc),
|
|
332
|
+
ws.unsubscribe(topicOf(ws, doc)),
|
|
333
|
+
forget(ws, doc),
|
|
334
|
+
say(ws, { doc, refused: true, why: no }));
|
|
335
|
+
}
|
|
336
|
+
for (const change of changes) {
|
|
337
|
+
kept?.wrote();
|
|
338
|
+
const r = rulesOf(change.doc);
|
|
339
|
+
if (!r.sees && !r.member && !r.view) server.publish(change.doc, JSON.stringify(change));
|
|
340
|
+
}
|
|
341
|
+
for (const { topic, change } of told) {
|
|
342
|
+
const t = topics.get(topic);
|
|
343
|
+
if (!t) continue;
|
|
344
|
+
server.publish(topic, JSON.stringify({ ...change, after: t.version }));
|
|
345
|
+
t.version = change.version;
|
|
346
|
+
}
|
|
347
|
+
for (const doc of derives.keys())
|
|
348
|
+
if (rulesOf(doc).derived!.some((d) => written.has(d)))
|
|
349
|
+
for (const ws of pages) if (ws.data.docs.has(doc)) derivedTo(ws, doc);
|
|
350
|
+
// what each page's person may do, where the write changed it (an item come or moved, a role gained)
|
|
351
|
+
for (const ws of pages) for (const doc of ws.data.docs) if (!derives.has(doc)) mayTo(ws, doc);
|
|
352
|
+
};
|
|
353
|
+
/** What each page was last sent of each derived document (by its name) and told it may do in each it holds
|
|
354
|
+
* (`may <doc>`): each sent again only when it's changed. */
|
|
355
|
+
const last = new WeakMap<ServerWebSocket<Data>, Map<string, string>>();
|
|
356
|
+
/** Whether what a page is to be sent is new to it: if so, it's kept as what it was sent last. */
|
|
357
|
+
const fresh = (ws: ServerWebSocket<Data>, key: string, text: string) => {
|
|
358
|
+
const sent = last.get(ws) ?? last.set(ws, new Map()).get(ws)!;
|
|
359
|
+
return sent.get(key) !== text && !!sent.set(key, text);
|
|
360
|
+
};
|
|
361
|
+
/** What a page is to be sent of a document afresh, whatever it was sent last. */
|
|
362
|
+
const forget = (ws: ServerWebSocket<Data>, doc: string) => (
|
|
363
|
+
last.get(ws)?.delete(doc),
|
|
364
|
+
last.get(ws)?.delete(`may ${doc}`)
|
|
365
|
+
);
|
|
366
|
+
/** A derived document, as a page's member has it now, sent to the page if it isn't what it was sent last; its
|
|
367
|
+
* version, the sum of the versions of the documents it's derived from. */
|
|
368
|
+
function derivedTo(ws: ServerWebSocket<Data>, doc: string) {
|
|
369
|
+
const value = derives.get(doc)!(read, ws.data.who?.member ?? 0);
|
|
370
|
+
if (!fresh(ws, doc, JSON.stringify(value))) return;
|
|
371
|
+
const version = rulesOf(doc).derived!.reduce((n, d) => n + store.versions(d), 0);
|
|
372
|
+
say(ws, { doc, version, ops: [{ op: "replace", path: "", value }] });
|
|
373
|
+
}
|
|
374
|
+
/** What a person may do in a document they hold (src/write.ts, mayOf): nothing, where the group would refuse them any
|
|
375
|
+
* write (removed, read-only, not signed in), but in a document that's anonymous, which is anyone's, or as a
|
|
376
|
+
* stranger its guest. */
|
|
377
|
+
const mayIn = (doc: string, who: Data["who"]) =>
|
|
378
|
+
groupless(doc, who) || !("refused" in group.write(docParts(doc).base, [], who))
|
|
379
|
+
? mayOf(doc, who?.member ?? null)
|
|
380
|
+
: {};
|
|
381
|
+
/** What a page's person may do in a document, told to the page (`{ doc, may }`) if it isn't what it was told last. */
|
|
382
|
+
function mayTo(ws: ServerWebSocket<Data>, doc: string) {
|
|
383
|
+
const may = mayIn(doc, ws.data.who);
|
|
384
|
+
if (fresh(ws, `may ${doc}`, JSON.stringify(may))) say(ws, { doc, may });
|
|
385
|
+
}
|
|
386
|
+
const write: Write = (doc, ops) => {
|
|
387
|
+
if (docParts(doc).name === GROUP || !store.exists(doc)) throw new Refused(`the server can't write ${doc}`);
|
|
388
|
+
const why = ungranted(doc, ops, null);
|
|
389
|
+
if (why) throw new Refused(why);
|
|
390
|
+
const landed = land([{ doc, ops }], null, null, { held: pagesHold() });
|
|
391
|
+
tell(landed);
|
|
392
|
+
retime();
|
|
393
|
+
return landed.changes[0]!;
|
|
394
|
+
};
|
|
395
|
+
/** A change undone: its inverse, guarded as delta's walk is (refused if a value it changed has been changed
|
|
396
|
+
* since), written as the server's own write, by whoever undoes it, and told as any change is; what the rules
|
|
397
|
+
* over values did as it was made, they undo as it's undone. An undo undone is a redo. Never the group's: its links
|
|
398
|
+
* and its keys aren't put back. */
|
|
399
|
+
const undo = (name: string, version: number, by: number | null = null) => {
|
|
400
|
+
// a window's change is its document's
|
|
401
|
+
const doc = docParts(name).base;
|
|
402
|
+
if (docParts(doc).name === GROUP) throw new Refused("the group's changes aren't undone");
|
|
403
|
+
const ops = store.undoing(doc, version);
|
|
404
|
+
// held to the stories as any write is
|
|
405
|
+
const why = ungranted(doc, ops, null);
|
|
406
|
+
if (why) throw new Refused(why);
|
|
407
|
+
const landed = land([{ doc, ops }], by, null, { undoes: version, held: pagesHold() });
|
|
408
|
+
tell(landed);
|
|
409
|
+
retime();
|
|
410
|
+
return landed.changes[0]!;
|
|
411
|
+
};
|
|
412
|
+
// each app's acts, by name, as its routes are: none named by two
|
|
413
|
+
const acts: Acts = {};
|
|
414
|
+
for (const { app, acts: of = {} } of apps)
|
|
415
|
+
for (const [name, act] of Object.entries(of)) {
|
|
416
|
+
if (name in acts) throw new Error(`${app} and another app both name an act ${name}`);
|
|
417
|
+
acts[name] = act;
|
|
418
|
+
}
|
|
419
|
+
const group = await groupOf({
|
|
420
|
+
rootToken: members ? rootToken : undefined,
|
|
421
|
+
db: store.db,
|
|
422
|
+
keysFile: keys ?? `${DATA}/members.keys.json`,
|
|
423
|
+
lasts,
|
|
424
|
+
read,
|
|
425
|
+
// what each member may hold (asked once the server's made, as each page is told who it is)
|
|
426
|
+
holds: (member) => Object.keys(rules).filter((doc) => doc !== GROUP && !mayRead(doc, member)),
|
|
427
|
+
// a demo's, from this machine alone: asked once the server listens, of each request
|
|
428
|
+
demo: demo ? (req) => fromHere(req, server.requestIP(req)?.address) : undefined,
|
|
429
|
+
// in by their link: the act their invitation names, done for them as them, once, then gone
|
|
430
|
+
accepted: async (who) => {
|
|
431
|
+
const act = (read(GROUP).members as Member[]).find((m) => m.id === who.member)?.act;
|
|
432
|
+
if (!act) return;
|
|
433
|
+
const [name = "", word = ""] = act.split(" ");
|
|
434
|
+
const w = acts[name]?.(who.member, word);
|
|
435
|
+
if (w) await written([{ ...w, why: "accepting an invitation" }], who);
|
|
436
|
+
await written(
|
|
437
|
+
[{ doc: GROUP, ops: [{ op: "remove", path: `/members/${who.member}/act` }], why: "an invitation used" }],
|
|
438
|
+
who,
|
|
439
|
+
);
|
|
440
|
+
},
|
|
441
|
+
});
|
|
442
|
+
|
|
443
|
+
// joined's own (that it's up, and which release and build it is: Railway's health check and the deploy ask; its
|
|
444
|
+
// icon, at the root, where a tab and a phone's home screen ask when a page names none), the
|
|
445
|
+
// group's, then every app's, and no path answered by two; an app's edge is guarded by the group
|
|
446
|
+
const icon = () => new Response(Bun.file(ICON));
|
|
447
|
+
/** Whether a member may read a document: why not, or nothing (as the door and /export ask it). */
|
|
448
|
+
const mayRead = (doc: string, member: number) =>
|
|
449
|
+
derives.has(doc) || exists(doc) ? mayHold(doc, member, false) : `there's no document called ${doc}`;
|
|
450
|
+
/** A document as a member sees it, with its version (a derived one's, the sum of what it's derived from). */
|
|
451
|
+
const asMember = (doc: string, member: number) =>
|
|
452
|
+
derives.has(doc)
|
|
453
|
+
? {
|
|
454
|
+
version: rulesOf(doc).derived!.reduce((n, d) => n + store.versions(d), 0),
|
|
455
|
+
...derives.get(doc)!(read, member),
|
|
456
|
+
}
|
|
457
|
+
: view(doc, member);
|
|
458
|
+
/** The MCP door, for an agent's link (src/mcp.ts): the documents' rules, read and written as a page does. */
|
|
459
|
+
const agents = {
|
|
460
|
+
rules: Object.values(rules).filter((r) => r.doc !== GROUP),
|
|
461
|
+
whoIs: group.whoIs,
|
|
462
|
+
holds: mayRead,
|
|
463
|
+
read: asMember,
|
|
464
|
+
write: (doc: string, ops: Op[], why: string | undefined, who: Who | null) => written([{ doc, ops, why }], who),
|
|
465
|
+
instructions: apps.flatMap((a) => (a.instructions ? [a.instructions.trim()] : [])).join("\n\n"),
|
|
466
|
+
version,
|
|
467
|
+
};
|
|
468
|
+
/** Why someone may not send a file for a document (src/files.ts), or null: they may hold it, and may put a file in
|
|
469
|
+
* it (an add to a collection with a file field, or its replace), as a member by their link or a guest by its code. */
|
|
470
|
+
const mayPut = async (req: Request, doc: string) => {
|
|
471
|
+
if (anotherSite(req)) return "another site";
|
|
472
|
+
const signed = await group.at(req),
|
|
473
|
+
who = signed instanceof Response ? null : signed;
|
|
474
|
+
if (!store.exists(doc)) return `there's no document called ${doc}`;
|
|
475
|
+
return (
|
|
476
|
+
mayHold(doc, who?.member ?? null, !(members && rootToken)) ??
|
|
477
|
+
(putsFile(rulesOf(doc).collections, mayIn(doc, who)) ? null : `you may not put a file in ${docParts(doc).base}`)
|
|
478
|
+
);
|
|
479
|
+
};
|
|
480
|
+
const routes: Routes = {
|
|
481
|
+
"/health": () => new Response("ok"),
|
|
482
|
+
"/version": () => Response.json({ joined: version, build }),
|
|
483
|
+
"/favicon.ico": icon,
|
|
484
|
+
"/apple-touch-icon.png": icon,
|
|
485
|
+
"/apple-touch-icon-precomposed.png": icon,
|
|
486
|
+
...group.routes,
|
|
487
|
+
// everything a member can see, as JSON: each document as they see it, each kind's instances by their key; theirs
|
|
488
|
+
// to keep, or to take elsewhere
|
|
489
|
+
"/export": group.edge((_req, who) => {
|
|
490
|
+
const member = who?.member ?? 0,
|
|
491
|
+
everything: Record<string, unknown> = {};
|
|
492
|
+
for (const r of Object.values(rules)) {
|
|
493
|
+
const docs = r.kind
|
|
494
|
+
? ((asMember(r.kind.doc, member)[r.kind.root] ?? []) as { id: number }[]).map((i) => `${r.doc}:${i.id}`)
|
|
495
|
+
: [r.doc];
|
|
496
|
+
for (const doc of docs) if (!mayRead(doc, member)) everything[doc] = asMember(doc, member);
|
|
497
|
+
}
|
|
498
|
+
return Response.json(everything, { headers: { "content-disposition": 'attachment; filename="joined.json"' } });
|
|
499
|
+
}),
|
|
500
|
+
// the MCP door: an agent's link, for Claude in a chat, reading and writing as a page does (src/mcp.ts)
|
|
501
|
+
"/mcp/:token": door(agents),
|
|
502
|
+
// and where nobody's a member, anyone's, with no link, as a stranger's page is: its writes are anyone's
|
|
503
|
+
...(members ? {} : { "/mcp": door({ ...agents, anyone: true }) }),
|
|
504
|
+
// a file a document names: sent by whoever may put one in it, kept by its hash, and served for good
|
|
505
|
+
...fileRoutes(filesKept, mayPut),
|
|
506
|
+
};
|
|
507
|
+
for (const { app, routes: of = {} } of apps)
|
|
508
|
+
for (const [path, answer] of Object.entries(typeof of === "function" ? of(read, write) : of)) {
|
|
509
|
+
if (path in routes) throw new Error(`${app || "the root"} and another app both answer ${path}`);
|
|
510
|
+
// a page (Bun's bundle of its index.html) is kept at /_page<path>, and served at its own path rendered
|
|
511
|
+
if (typeof answer === "object" && "index" in answer) {
|
|
512
|
+
routes[`/_page${path}`] = answer;
|
|
513
|
+
routes[path] = (req: Request) => rendered(req, path);
|
|
514
|
+
continue;
|
|
515
|
+
}
|
|
516
|
+
routes[path] =
|
|
517
|
+
typeof answer === "function"
|
|
518
|
+
? group.edge(answer)
|
|
519
|
+
: answer instanceof Response
|
|
520
|
+
? answer
|
|
521
|
+
: Object.fromEntries(Object.entries(answer).map(([method, fn]) => [method, group.edge(fn as Handler)]));
|
|
522
|
+
}
|
|
523
|
+
// an app's open routes, anyone's and never guarded: each document read as nobody (owns and sees apply, the group's
|
|
524
|
+
// door doesn't), so each shows only what it picks
|
|
525
|
+
const nobody: Read = (doc) => read(doc, 0);
|
|
526
|
+
for (const { app, open: of = {} } of apps)
|
|
527
|
+
for (const [path, answer] of Object.entries(typeof of === "function" ? of(nobody) : of)) {
|
|
528
|
+
if (path in routes) throw new Error(`${app || "the root"} and another app both answer ${path}`);
|
|
529
|
+
routes[path] = answer;
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
const pages = new Set<ServerWebSocket<Data>>();
|
|
533
|
+
|
|
534
|
+
// A page served with its documents in it: each collection element it holds filled with its items, as the
|
|
535
|
+
// person asking sees them, and each document's version on <body>, so the page subscribes since it and is sent only
|
|
536
|
+
// what's changed after; and the build it's served by (data-build), to know another. A stranger to an invite-only
|
|
537
|
+
// group is served the page as it is, and its note.
|
|
538
|
+
/** Each collection's element, by its tag: its document (an instance's, where the element names one), its
|
|
539
|
+
* items' tag, and their fields. */
|
|
540
|
+
const places = new Map(
|
|
541
|
+
Object.values(rules)
|
|
542
|
+
.filter((r) => !r.derived)
|
|
543
|
+
.flatMap((r) => Object.entries(r.collections).map(([coll, c]) => [c.place, { doc: r.doc, coll, ...c }] as const)),
|
|
544
|
+
);
|
|
545
|
+
/** A page as Bun bundles it (kept at /_page<path>), and the documents it holds: read once live, and each time in
|
|
546
|
+
* development, where it's bundled afresh. */
|
|
547
|
+
const shells = new Map<string, { html: string; docs: string[] }>();
|
|
548
|
+
async function shell(path: string) {
|
|
549
|
+
const kept = shells.get(path);
|
|
550
|
+
if (kept) return kept;
|
|
551
|
+
const html = await (await fetch(new URL(`/_page${path}`, server.url))).text();
|
|
552
|
+
const docs = new Set<string>();
|
|
553
|
+
const finding = new HTMLRewriter();
|
|
554
|
+
for (const [place, { doc }] of places)
|
|
555
|
+
finding.on(place, { element: (el) => void docs.add(el.getAttribute("doc") ?? doc) });
|
|
556
|
+
await finding.transform(new Response(html)).text();
|
|
557
|
+
const page = { html, docs: [...docs].filter((d) => exists(d)) };
|
|
558
|
+
if (production) shells.set(path, page);
|
|
559
|
+
return page;
|
|
560
|
+
}
|
|
561
|
+
const escaped = (s: string) => s.replaceAll("&", "&").replaceAll('"', """).replaceAll("<", "<");
|
|
562
|
+
/** An item as its element, each field an attribute, and what its person may do to it, as the page's applier sets them. */
|
|
563
|
+
const itemHtml = (tag: string, fields: Record<string, Type>, item: Record<string, unknown>, may?: string) =>
|
|
564
|
+
`<${tag} key="${item.id}"${may ? ` may="${escaped(may)}"` : ""}${Object.entries(fields)
|
|
565
|
+
.map(([f, t]) => {
|
|
566
|
+
const a = attribute(t, valueAt(item, f));
|
|
567
|
+
return a === null ? "" : a === "" ? ` ${f}` : ` ${f}="${escaped(a)}"`;
|
|
568
|
+
})
|
|
569
|
+
.join("")}></${tag}>`;
|
|
570
|
+
async function rendered(req: Request, path: string) {
|
|
571
|
+
const { html, docs } = await shell(path);
|
|
572
|
+
const headers = { "content-type": "text/html;charset=utf-8", "cache-control": "private, no-store" };
|
|
573
|
+
const signed = await group.at(req),
|
|
574
|
+
who = signed instanceof Response ? null : signed;
|
|
575
|
+
// a stranger is served the page as it is, but for what's anonymous, which is anyone's; and anyone, only what
|
|
576
|
+
// they may hold (a cook, none of the till's orders)
|
|
577
|
+
const held = docs.filter(
|
|
578
|
+
(d) => (who || !members || rulesOf(d).anonymous) && !mayHold(d, who?.member ?? null, !(members && rootToken)),
|
|
579
|
+
);
|
|
580
|
+
const seen = new Map(held.map((d) => [d, view(d, who?.member ?? 0)]));
|
|
581
|
+
const may = new Map(held.map((d) => [d, mayIn(d, who)]));
|
|
582
|
+
const filling = new HTMLRewriter().on("body", {
|
|
583
|
+
element(el) {
|
|
584
|
+
el.setAttribute("data-build", build);
|
|
585
|
+
for (const [d, { version }] of seen) el.setAttribute(`data-${versionKey(d)}`, String(version));
|
|
586
|
+
},
|
|
587
|
+
});
|
|
588
|
+
for (const [place, { doc, coll, tag, fields, own }] of places)
|
|
589
|
+
filling.on(place, {
|
|
590
|
+
element(el) {
|
|
591
|
+
const name = el.getAttribute("doc") ?? doc,
|
|
592
|
+
d = seen.get(name),
|
|
593
|
+
mine = may.get(name)?.[coll];
|
|
594
|
+
if (mine?.[""]) el.setAttribute("may", mine[""]);
|
|
595
|
+
// a document's own element (<j-hello>) is its one item: each own field an attribute of it
|
|
596
|
+
if (d && own)
|
|
597
|
+
for (const [f, t] of Object.entries(fields)) {
|
|
598
|
+
const a = attribute(t, d[f]);
|
|
599
|
+
if (a !== null) el.setAttribute(f, a);
|
|
600
|
+
}
|
|
601
|
+
const items = own ? undefined : (d?.[coll] as Record<string, unknown>[] | undefined);
|
|
602
|
+
if (items)
|
|
603
|
+
el.append(items.map((i) => itemHtml(tag, fields, i, mine?.[String(i.id)])).join(""), { html: true });
|
|
604
|
+
},
|
|
605
|
+
});
|
|
606
|
+
return filling.transform(new Response(html, { headers }));
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
/** A page's message, answered: a document subscribed to, something asked, or a write. */
|
|
610
|
+
async function answer(ws: ServerWebSocket<Data>, m: Message) {
|
|
611
|
+
const { who } = ws.data;
|
|
612
|
+
// a page subscribes to a document: it's sent whole, then every change to it; a page that had it (back from
|
|
613
|
+
// away) says its version, and is sent the changes since, unless it's too far behind for that, or it holds a part
|
|
614
|
+
// of the document (a window, or what its person sees), which is sent whole, at the version of the last change told
|
|
615
|
+
// to it. A page holding it already asks again with its version, having missed a change: it's sent what it missed;
|
|
616
|
+
// or without, a collection of it put back on the page (another kept it held meanwhile): it's sent whole.
|
|
617
|
+
if (m.subscribe !== undefined) {
|
|
618
|
+
const doc = m.subscribe;
|
|
619
|
+
// a derived document is derived for the page, and sent whole, subscribed again or not
|
|
620
|
+
if (derives.has(doc)) {
|
|
621
|
+
ws.data.docs.add(doc);
|
|
622
|
+
forget(ws, doc);
|
|
623
|
+
return derivedTo(ws, doc);
|
|
624
|
+
}
|
|
625
|
+
if (!exists(doc)) return say(ws, { doc, refused: true, why: `there's no document called ${doc}` });
|
|
626
|
+
// a stranger's page, on a group that's invite-only, holds what's anonymous alone, or an item's own as its guest;
|
|
627
|
+
// a document only some may hold (its where's), those its roles name
|
|
628
|
+
const no = mayHold(doc, ws.data.who?.member ?? null, !(members && rootToken));
|
|
629
|
+
if (no) return say(ws, { doc, refused: true, why: no });
|
|
630
|
+
// a static document is read with its page, and changes only with a release: there's nothing to be told
|
|
631
|
+
if (rulesOf(doc).type === "static")
|
|
632
|
+
return say(ws, { doc, refused: true, why: `${doc} is static: it changes only with a release` });
|
|
633
|
+
const again = ws.data.docs.has(doc);
|
|
634
|
+
ws.data.docs.add(doc);
|
|
635
|
+
const r = rulesOf(doc);
|
|
636
|
+
const topic = topicOf(ws, doc),
|
|
637
|
+
part = isPart(doc, topic);
|
|
638
|
+
ws.subscribe(topic);
|
|
639
|
+
const missed = m.since === undefined || part ? null : store.since(doc, m.since);
|
|
640
|
+
if (missed) for (const c of missed) say(ws, c);
|
|
641
|
+
else {
|
|
642
|
+
const member = ws.data.who?.member ?? 0;
|
|
643
|
+
const { version, ...value } = view(doc, member);
|
|
644
|
+
const t = part
|
|
645
|
+
? (topics.get(topic) ??
|
|
646
|
+
topics
|
|
647
|
+
.set(topic, { doc, ...(topic !== doc || r.view ? { member: topic === doc ? 0 : member } : {}), version })
|
|
648
|
+
.get(topic)!)
|
|
649
|
+
: null;
|
|
650
|
+
say(ws, { doc, version: t?.version ?? version, ops: [{ op: "replace", path: "", value }] });
|
|
651
|
+
}
|
|
652
|
+
// and what its person may do there, told afresh
|
|
653
|
+
forget(ws, doc);
|
|
654
|
+
mayTo(ws, doc);
|
|
655
|
+
return again ? undefined : group.opened(ws, doc);
|
|
656
|
+
}
|
|
657
|
+
// a page unsubscribes from a document (its elements taken off it): it's told it no more
|
|
658
|
+
if (m.unsubscribe !== undefined) {
|
|
659
|
+
if (ws.data.docs.delete(m.unsubscribe) && !derives.has(m.unsubscribe)) ws.unsubscribe(topicOf(ws, m.unsubscribe));
|
|
660
|
+
return void forget(ws, m.unsubscribe);
|
|
661
|
+
}
|
|
662
|
+
if (!m.ops && !m.writes) {
|
|
663
|
+
return say(ws, await group.asked(ws, m as Message & { id: number }));
|
|
664
|
+
}
|
|
665
|
+
// a write of one document, or of several (src/together.ts): each one the page holds, but one the write makes
|
|
666
|
+
const writes = m.writes ?? [{ doc: m.doc ?? "", ops: m.ops!, why: m.why }];
|
|
667
|
+
const away = writes.find((w) => !ws.data.docs.has(w.doc) && !madeBy(w.doc));
|
|
668
|
+
if (away) {
|
|
669
|
+
const why = `this page isn't subscribed to ${docParts(away.doc).base}`;
|
|
670
|
+
return (
|
|
671
|
+
log?.(`write ${docParts(away.doc).base} by ${byOf(who)}: refused, ${why}`),
|
|
672
|
+
say(ws, { refused: m.id, why })
|
|
673
|
+
);
|
|
674
|
+
}
|
|
675
|
+
const w = await written(
|
|
676
|
+
writes.map((w) => ({ ...w, why: w.why?.trim() || undefined })),
|
|
677
|
+
who,
|
|
678
|
+
);
|
|
679
|
+
say(
|
|
680
|
+
ws,
|
|
681
|
+
"why" in w
|
|
682
|
+
? { refused: m.id, why: w.why }
|
|
683
|
+
: { done: m.id, version: w.version, ...(w.ids.length ? { ids: w.ids } : {}) },
|
|
684
|
+
);
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
/** Who wrote, as a write's log line says it (never a link: none is in a why). */
|
|
688
|
+
const byOf = (who: Who | null) =>
|
|
689
|
+
who ? `member ${who.member}${who.agent ? ` (agent ${who.agent.label})` : ""}` : "anyone";
|
|
690
|
+
/** A write, a page's or an agent's at the MCP door: of one document or several (src/together.ts), each as it names
|
|
691
|
+
* it (a window's write is its document's), by who, landed whole or not at all, told, and answered: done, with the
|
|
692
|
+
* version its first part made and the id each item added was given, in order, so the writer needn't match them; or
|
|
693
|
+
* refused, why. Each logs one line. */
|
|
694
|
+
async function written(writes: Part[], who: Who | null): Promise<Written> {
|
|
695
|
+
const doc = writes.map((w) => docParts(w.doc).base).join(" and "),
|
|
696
|
+
by = byOf(who);
|
|
697
|
+
// In the write's transaction, in order, refused at the first that says no: the app's own rules, the grants, and
|
|
698
|
+
// the group's rules (src/write.ts), and, as its rows are written, the tables' constraints; each part's.
|
|
699
|
+
const afters: ((applied: Op[]) => Promise<void>)[] = [];
|
|
700
|
+
const asked = (name: string, ops: Op[], why?: string) => {
|
|
701
|
+
// each part's document one its writer may hold (a where's holds, a visitor's level): one the write makes
|
|
702
|
+
// (board:$1) no page has held
|
|
703
|
+
const no = mayHold(name, who?.member ?? null, !(members && rootToken));
|
|
704
|
+
if (no) throw new Refused(no);
|
|
705
|
+
let after: (applied: Op[]) => Promise<void> = async () => {};
|
|
706
|
+
const asking = ask(name, ops, why, who, (doc, ops) => {
|
|
707
|
+
const write = group.write(doc, ops, who, why);
|
|
708
|
+
if (!("refused" in write)) after = write.after;
|
|
709
|
+
return write;
|
|
710
|
+
});
|
|
711
|
+
afters.push(after);
|
|
712
|
+
return asking;
|
|
713
|
+
};
|
|
714
|
+
// a write lands whole or not at all, with what follows from it, in the store's one transaction; then it's told
|
|
715
|
+
let landed: ReturnType<typeof land>;
|
|
716
|
+
try {
|
|
717
|
+
landed = land(writes, who?.member ?? null, who?.agent?.label ?? null, { asked, held: pagesHold() });
|
|
718
|
+
} catch (e) {
|
|
719
|
+
// refused in words; anything else is the server's, logged, and the writer told it wasn't saved
|
|
720
|
+
if (!(e instanceof Refused)) console.error(`a write to ${doc} failed:`, e);
|
|
721
|
+
const why = e instanceof Refused ? e.message : "That wasn't saved: the server had a problem with it.";
|
|
722
|
+
log?.(`write ${doc} by ${by}: refused, ${why}`);
|
|
723
|
+
return { why };
|
|
724
|
+
}
|
|
725
|
+
tell(landed);
|
|
726
|
+
retime();
|
|
727
|
+
const change = landed.parts[0]!;
|
|
728
|
+
// what follows each part (the group's pages told, a new member's link made), and then the writer's answer:
|
|
729
|
+
// done is all of it done
|
|
730
|
+
for (const [i, after] of afters.entries()) await after(landed.parts[i]!.ops);
|
|
731
|
+
log?.(`write ${doc} by ${by}: done, version ${change.version}`);
|
|
732
|
+
const ids = landed.applied
|
|
733
|
+
.filter((o) => o.op === "add" && parts(o.path).key === "-" && parts(o.path).field === undefined)
|
|
734
|
+
.map((o) => o.value.id as number);
|
|
735
|
+
return { done: true, version: change.version, ids };
|
|
736
|
+
}
|
|
737
|
+
|
|
738
|
+
const server = Bun.serve({
|
|
739
|
+
port,
|
|
740
|
+
// a custom element is defined once a page, so a module run again in place breaks it: reload instead
|
|
741
|
+
development: !production && { hmr: false },
|
|
742
|
+
routes: routes as any,
|
|
743
|
+
// a page's socket, one whatever it holds: it subscribes to its documents once it's open
|
|
744
|
+
async fetch(req, server) {
|
|
745
|
+
const url = new URL(req.url);
|
|
746
|
+
if (url.pathname !== "/ws") return new Response("Not found", { status: 404 });
|
|
747
|
+
if (anotherSite(req)) return new Response("another site", { status: 403 });
|
|
748
|
+
const origin = req.headers.get("origin");
|
|
749
|
+
const signed = await group.at(req);
|
|
750
|
+
// a stranger holds what's anonymous alone, which is anyone's, or an item's own as its guest: with neither,
|
|
751
|
+
// they're refused at the door
|
|
752
|
+
if (signed instanceof Response && !Object.values(rules).some((r) => r.anonymous || r.guests)) return signed;
|
|
753
|
+
const who = signed instanceof Response ? null : signed;
|
|
754
|
+
if (server.upgrade(req, { data: { docs: new Set(), who, origin: origin ?? url.origin } })) return;
|
|
755
|
+
return new Response("upgrade failed", { status: 400 });
|
|
756
|
+
},
|
|
757
|
+
websocket: {
|
|
758
|
+
data: {} as Data,
|
|
759
|
+
// a message is a write, a subscribe or an ask: a megabyte is thousands of events; more closes the socket
|
|
760
|
+
maxPayloadLength: MESSAGE,
|
|
761
|
+
// the page is told the build first, each time it connects: a page served by another reloads
|
|
762
|
+
open(ws) {
|
|
763
|
+
say(ws, { build });
|
|
764
|
+
pages.add(ws);
|
|
765
|
+
group.admit(ws);
|
|
766
|
+
},
|
|
767
|
+
close(ws) {
|
|
768
|
+
pages.delete(ws);
|
|
769
|
+
group.left(ws);
|
|
770
|
+
},
|
|
771
|
+
// a message that isn't one joined reads is refused; one the server fails on is logged and answered, and
|
|
772
|
+
// the server goes on
|
|
773
|
+
async message(ws, text) {
|
|
774
|
+
const m = messageOf(String(text));
|
|
775
|
+
if (typeof m === "string") return say(ws, { refused: null, why: m });
|
|
776
|
+
try {
|
|
777
|
+
await answer(ws, m);
|
|
778
|
+
// a subscribe with an id is answered once it's done: a page woken asks so, to know its socket's still there
|
|
779
|
+
if (m.subscribe !== undefined && m.id !== undefined) say(ws, { done: m.id });
|
|
780
|
+
} catch (e) {
|
|
781
|
+
console.error("a message failed:", e);
|
|
782
|
+
say(ws, { refused: m.id ?? null, why: "The server had a problem with that." });
|
|
783
|
+
}
|
|
784
|
+
},
|
|
785
|
+
},
|
|
786
|
+
});
|
|
787
|
+
// The timed fields' clock (definitions' timed): one timer, for the soonest time of them all. When an item's time
|
|
788
|
+
// comes, the server clears it, as its own write, and what follows from it with it; then looks again, since a
|
|
789
|
+
// reaction may have set it anew (a clock's next tick). One that fails is logged, and tried again in a minute.
|
|
790
|
+
const timed = held.flatMap(({ rules: r }) =>
|
|
791
|
+
Object.entries(r.collections).flatMap(([coll, c]) => (c.timed ? [{ doc: r.doc, coll, field: c.timed }] : [])),
|
|
792
|
+
);
|
|
793
|
+
let clock: ReturnType<typeof setTimeout> | undefined;
|
|
794
|
+
function tick() {
|
|
795
|
+
clearTimeout(clock);
|
|
796
|
+
let soonest = Infinity,
|
|
797
|
+
cleared = false;
|
|
798
|
+
for (const { doc, coll, field } of timed)
|
|
799
|
+
for (const item of read(doc)[coll] as Record<string, any>[]) {
|
|
800
|
+
const at = Date.parse(item[field] ?? "");
|
|
801
|
+
if (!(at <= Date.now())) {
|
|
802
|
+
if (at < soonest) soonest = at;
|
|
803
|
+
continue;
|
|
804
|
+
}
|
|
805
|
+
try {
|
|
806
|
+
tell(
|
|
807
|
+
land([{ doc, ops: [{ op: "remove", path: `/${coll}/${item.id}/${field}` }] }], null, null, {
|
|
808
|
+
held: pagesHold(),
|
|
809
|
+
}),
|
|
810
|
+
);
|
|
811
|
+
cleared = true;
|
|
812
|
+
} catch (e) {
|
|
813
|
+
console.error(`clearing ${coll} ${item.id}'s ${field} failed:`, e);
|
|
814
|
+
soonest = Math.min(soonest, Date.now() + MINUTE);
|
|
815
|
+
}
|
|
816
|
+
}
|
|
817
|
+
if (cleared) return tick();
|
|
818
|
+
if (soonest < Infinity) (clock = setTimeout(tick, Math.min(soonest - Date.now(), LONGEST))).unref();
|
|
819
|
+
}
|
|
820
|
+
/** The clock set again, after a write that may have changed a time. */
|
|
821
|
+
function retime() {
|
|
822
|
+
if (timed.length) tick();
|
|
823
|
+
}
|
|
824
|
+
retime();
|
|
825
|
+
|
|
826
|
+
// stopped, its clock stops too: a time it was waiting for comes to a store that may be closed
|
|
827
|
+
const stop = server.stop.bind(server);
|
|
828
|
+
return Object.assign(server, {
|
|
829
|
+
stop: (closeActive?: boolean) => (clearTimeout(clock), stop(closeActive)),
|
|
830
|
+
apps: apps.map((a) => a.app).filter(Boolean),
|
|
831
|
+
members,
|
|
832
|
+
build,
|
|
833
|
+
// what's answered, without the bundles the pages are rendered from
|
|
834
|
+
paths: Object.keys(routes).filter((p) => !p.startsWith("/_page")),
|
|
835
|
+
tokenOf: group.tokenOf,
|
|
836
|
+
read,
|
|
837
|
+
write,
|
|
838
|
+
undo,
|
|
839
|
+
store,
|
|
840
|
+
upkeep: kept,
|
|
841
|
+
});
|
|
842
|
+
}
|
|
843
|
+
|
|
844
|
+
/** What a server says as it starts: where it is, and the BDFL's link, or that it's open, or has no members. A ROOT_TOKEN
|
|
845
|
+
* long enough to be a secret is never printed (on Railway, what's printed is in the logs); a short
|
|
846
|
+
* one, fine on this machine alone, is, with a warning. */
|
|
847
|
+
export function startUp(server: Awaited<ReturnType<typeof start>>, root = Bun.env.ROOT_TOKEN) {
|
|
848
|
+
const said = [`joined on ${server.url}: ${server.apps.join(", ")}; ${server.paths.join(" ")}`];
|
|
849
|
+
if (!server.members)
|
|
850
|
+
return [
|
|
851
|
+
...said,
|
|
852
|
+
"no members: no story is told as one, so anyone who reaches it may read and write, an agent too, at /mcp",
|
|
853
|
+
];
|
|
854
|
+
if (!root) return [...said, "open: no ROOT_TOKEN, so anyone who reaches it may read and write"];
|
|
855
|
+
const bdfl = `${bdflOf(server.read(GROUP).members as Member[])?.name ?? "The BDFL"}'s link (the BDFL's)`;
|
|
856
|
+
if (root.length >= 32) return [...said, `${bdfl} isn't printed: bun run link <name>, or .railway/root-link`];
|
|
857
|
+
return [
|
|
858
|
+
...said,
|
|
859
|
+
`${bdfl}: ${server.url}auth/${root}`,
|
|
860
|
+
"ROOT_TOKEN is short enough to guess: fine on this machine, never on a site anyone else can reach",
|
|
861
|
+
];
|
|
862
|
+
}
|