@metacensus/library-research 0.15.0 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -7,7 +7,7 @@ The research-project contract and its tools
7
7
  A project is this layout, each path fixed, which `npx @metacensus/library-research init` writes into an empty repository:
8
8
 
9
9
  ```
10
- research.json title, datasets, private datasets, roles and test people
10
+ research.json title, datasets, private datasets, roles, test people and collections
11
11
  corpus.json works by DOI or citation key: CSL-JSON, editions, papers by sha
12
12
  papers/<sha>.<kind> through LFS
13
13
  ui/package.json depends on @metacensus/library-research, which brings @playwright/test; scripts dev, check and test
@@ -25,7 +25,7 @@ From `ui/`:
25
25
  | --------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
26
26
  | `npm run dev -- [--reader NAME] [--port N]` | serves the project at `/<path>/` and `ui/local/`'s at `/local/<path>/`, live from the files, as reader `NAME` (else `local`) to a context that names none, under the host's CSP |
27
27
  | `npm run check` | gates the project, one line per failure, as a host's build does |
28
- | `npx playwright test` | runs `browser/` in Chromium on a dev server; a CSP, WCAG 2.2, console-error or other-origin violation fails its spec unless `violations` lists it |
28
+ | `npx playwright test` | runs `browser/` in Chromium, light and dark, on a dev server; a CSP, WCAG 2.2, console-error or other-origin violation fails its spec unless `violations` lists it |
29
29
  | `npx library-research add <file> [--title T] [--citation C] [--open]` | adds a paper to `papers/` and `corpus.json` |
30
30
  | `npx library-research reshape` | rewrites a legacy `corpus.json`, one sha per paper, as works under placeholder keys, and prints what waits on a person |
31
31
  | `npx library-research candidate` | runs `check`, then tags a clean `HEAD` on `origin/main` as `<id>-YYYY-MM-DD[.N]`, pushes it, and prints the service's `make pin` line |
@@ -60,7 +60,7 @@ A glob in `data` is relative, holds no `..`, at most one `*` and none of `?[]{}(
60
60
 
61
61
  ## Private data
62
62
 
63
- `research.json`'s `private` maps a dataset to a glob holding exactly one `*` and otherwise the `data` grammar, such as `{ "private": { "ask": "research_notes/coauthors/*/questions.json" } }`. What the `*` matches is the page key, and the build emits each match at `/projects/<id>/private/<page>/<dataset>.json`, never among the shared `data/` files. A host serves that path only to the people who hold the page. A page key matches `^[a-z0-9][a-z0-9-]*$` and a dataset is in `data` or `private`, not both; `check` fails otherwise, naming the dataset.
63
+ `research.json`'s `private` maps a dataset to a glob holding exactly one `*` and otherwise the `data` grammar, such as `{ "private": { "ask": "research_notes/coauthors/*/questions.json" } }`. What the `*` matches is the page key, and the build emits each match at the host's `private(dataset)` URL (see [Routes](#routes)), never among the shared `data/` files. A host serves that path only to the people who hold the page. A page key matches `^[a-z0-9][a-z0-9-]*$` and a dataset is in `data` or `private`, not both; `check` fails otherwise, naming the dataset.
64
64
 
65
65
  `usePrivate(dataset)` returns `{ page: parsed }` for the pages the host names for the person the project is viewed as: none, one or several, and a page not yet built is left out. `Object.values(usePrivate('ask'))` is that person's questions. The dataset's schema in `ui/datasets.ts` parses one page's file, and `load` returns the dataset as `{ page: parsed }`. A host's `private(dataset)` returns the page-to-URL map.
66
66
 
@@ -77,9 +77,34 @@ Node loads `ui/datasets.ts` by stripping its types: no `enum` or namespace, rela
77
77
 
78
78
  In `dev` and `testHost`, `research.json`'s optional `people` stands in for production's people.json: it maps a username to `{ name, role, pages }`, `role` and `pages` optional, as `{ "people": { "dan.hertz": { "name": "Hertz", "role": "author", "pages": ["hertz"] } } }`. Every entry is a member. `dev --reader dan.hertz` and `testHost`'s `reader: 'dan.hertz'` serve that person as `reader` with `self` true, holding `hertz`'s page; another page answers 403. In a project that declares `roles`, a reader `people` omits is refused, naming them: by `testHost`, by `dev` before it serves when `--reader` names them, and by a `dev` page read as them, the default `local` included; in one that declares none, such a reader is served with their username as `name`, no role and no pages, and is no member. `check` fails, naming the person, on a role not in `roles`, on a person with no role where the project declares roles, and on a person with a role where it declares none. Production ignores `people`.
79
79
 
80
+ ## Collections
81
+
82
+ `research.json`'s optional `collections` declares the project's collections in the API's `Collections` schema, by name: each a `mode`, a JSON Schema `body`, and `read` and `write` grants, as `{ "collections": { "reviews": { "mode": "log", "body": { "type": "object" }, "read": [{ "own": true }], "write": [{ "roles": ["author"] }] } } }`. `check` fails on a declaration off that schema, on a grant naming a role `roles` does not declare, and on a gate whose collection is not a `log`, as the API refuses such a manifest.
83
+
84
+ `ui/datasets.ts` exports `collections`, one Zod schema per collection over an item's body, registered as `Register['collections']` and passed to `defineProject` as its fourth argument. Once `ui/datasets.ts` exports `collections`, `check` fails, one line per collection, on a collection one of the two lacks, or on a schema whose JSON Schema (`z.toJSONSchema`, without `$schema`) is not research.json's `body`, printing the one it expects:
85
+
86
+ ```ts
87
+ // ui/datasets.ts
88
+ export const collections = { reviews: z.object({ text: z.string() }) }
89
+ declare module '@metacensus/library-research' {
90
+ interface Register {
91
+ collections: typeof collections
92
+ }
93
+ }
94
+ ```
95
+
96
+ - `useCollection('reviews')` returns `{ items, refresh }`: the items the signed-in person may read, each `{ collection, writer, id, revision, sequence, body }` at its current revision, in write order, the body parsed by its schema. It suspends while it loads; a failed read or parse throws to the frame's error notice, naming the collection and the item. `refresh()` reads it again, and rejects when that read fails.
97
+ - `useWrite()` is a mutation taking `{ requestId, items: [{ collection, id, revision, body }] }`, which writes every item or none, each `body` typed by its `collection`. `revision` is the item's current revision, or `0` for a new one; a retry of the same write reuses its `requestId`, and a new write takes a new one. A write, and a write refused 409, read each collection it names again.
98
+ - A refused write is the mutation's `error`, a `WriteError` with its status and a code (`stale`, `exists`, `forbidden`, `invalid`, `full` or `unauthenticated`; absent for 413 and 415); `stale` and `exists` carry `conflicts` at their current revisions.
99
+ - An item is keyed by its writer and id, so an id is the writer's alone. The `writer` is the signed-in person, set by the store.
100
+ - A 401 on either hook, and a read's 403, call `Host.sessionLost`; a write's 403 is a refused grant.
101
+ - `dev` and `testHost` serve one in-memory store with the API's checks and outcomes, which `make check` runs every scenario of the API's `api/scenarios/` through; a restart empties it. In a project without `people`, the reader is its one member.
102
+
103
+ `contract/` is service-api-research pinned at a commit. `make contract` clones it and rewrites `src/collections.gen.ts`, the types of the two collection routes and of the schemas they and `Collections` reach, and `test/scenario.gen.ts`, the scenarios' types; both are committed, and `make generated`, in `check`, fails when either differs. Moving the pin is `git -C contract checkout <sha>`, then `make contract`, in one PR.
104
+
80
105
  ## Routes
81
106
 
82
- A project default-exports `defineProject('<path>', routes, datasets)`: its first URL segment, a project id matching `^[a-z0-9][a-z0-9-]*$` (`projectIdPattern` from `@metacensus/library-research/host`, and `schema/project-id.schema.json`) and not `projects`, `local` or `pdfjs` (dev and the host reserve them), and its routes created against the `parent` it is handed, a route at that path; the host owns the router. `Register` types the project's own links. A link names its path in full and passes `from="/<path>"`, so a wrong path fails to compile:
107
+ A project default-exports `defineProject('<path>', routes, datasets, collections)`: its first URL segment, a project id matching `^[a-z0-9][a-z0-9-]*$` (`projectIdPattern` from `@metacensus/library-research/host`, and `schema/project-id.schema.json`) and not `projects`, `api`, `local` or `pdfjs` (dev and the host reserve them), and its routes created against the `parent` it is handed, a route at that path; the host owns the router. `Register` types the project's own links. A link names its path in full and passes `from="/<path>"`, so a wrong path fails to compile:
83
108
 
84
109
  ```tsx
85
110
  const dpyd = defineProject('dpyd', (parent) => [
@@ -96,26 +121,23 @@ declare module '@tanstack/react-router' {
96
121
 
97
122
  A host mounts each project with `mount(parent, project, options)` from `@metacensus/library-research/host`: it creates the route at the path the project names, with `options` as the route's options, adds the project's routes, and returns it. Two projects at one path are refused by TanStack's duplicate-route-id check, in development builds only.
98
123
 
99
- A host builds with `research({ projects })` and `tailwind({ projects })` from `@metacensus/library-research/vite`, `projects` mapping each project's id to its directory: `plugins: [react(), research({ projects }), tailwind({ projects })]`. It builds with library-research's `tailwindcss` and `@tailwindcss/vite`, and carries neither of its own. The host's stylesheet opens with `@layer theme, base, mc, components, utilities;`, then `@import "tailwindcss";` and `@import "@metacensus/library-ui/theme.css";`; each project's `ui/` becomes a source of the stylesheet a module or `index.html` loads, not of one reached through a nested CSS `@import`. A project's stylesheets `@apply` Tailwind's and library-ui's utilities as they are.
100
-
101
- `options` takes `frame(useHost)`, spread in: it provides the `Host` that `useHost` returns, shows a resettable error and an announced loading state. A host sets no `defaultPendingComponent` or `defaultErrorComponent` on its router, which would override the frame's for a project's routes. A host serves `@metacensus/library-research/csp.json` as its Content-Security-Policy (directive → sources, adding its own origins and nonces) and `pdfAssets`, `/pdfjs/`, for `configurePdf({ assets })`.
124
+ A host builds with `research({ projects })` and `tailwind({ projects })` from `@metacensus/library-research/vite`, `projects` mapping each project's id to its directory: `plugins: [react(), research({ projects }), tailwind({ projects })]`. It builds with library-research's `tailwindcss` and `@tailwindcss/vite`, and carries neither of its own. The host's stylesheet opens with `@layer theme, base, mc, components, utilities;`, then `@import "tailwindcss";` and `@import "@metacensus/library-ui/theme.css";`; each project's `ui/` becomes a source of the stylesheet a module or `index.html` loads, not of one reached through a nested CSS `@import`. The same stylesheet paints `body` with library-ui's `--mc-ground` and `--mc-ink`, so a page reads as its readers see it in either color scheme. A project's stylesheets `@apply` Tailwind's and library-ui's utilities as they are.
102
125
 
103
- ## Saving
126
+ `options` takes `frame(useHost)`, spread in: it provides the `Host` that `useHost` returns, shows a resettable error and an announced loading state. `createHost({ project, reader, members, pages, store, sessionLost, origin })` from `./host` builds that `Host`: `pages` the viewed person's private pages, `origin` what the URLs are under (default `location.origin`). Every hook fetches through `store`. The URLs are one rule, each segment `encodeURIComponent`ed:
104
127
 
105
- A project saves JSON documents through its host, as it reads data.
128
+ | `Host` field | URL |
129
+ | ------------------ | --------------------------------------------------- |
130
+ | `data(dataset)` | `/projects/{project}/data/{dataset}.json` |
131
+ | `private(dataset)` | `/projects/{project}/private/{page}/{dataset}.json` |
132
+ | `paper(sha)` | `/api/papers/{project}/{sha}` |
133
+ | `collections()` | `/api/projects/{project}/collections` |
134
+ | `collection(name)` | `/api/projects/{project}/collections/{name}` |
106
135
 
107
- - `useDocument(id, parse)` returns `{ id, writer, revision, body }`, or `null`.
108
- - `useDocuments(prefix, parse)` lists the documents whose id starts with `prefix`.
109
- - `useSaveDocument(id)` is a mutation taking `{ body, when }`. `when` is `'absent'` (refuse if the document exists) or a `revision` (refuse unless the document is at it).
110
- - A refused save, a 412 or a 413, is the mutation's `error`: a `DocumentError` with its `status`.
111
- - Ids match `^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$`; a body is at most 256 KiB.
112
- - The `writer` is the signed-in person, set by the store.
113
- - A host's `document(id)` and `documents(prefix)` return the URLs of the store's routes.
114
- - `dev` keeps one in-memory store for every reader; a restart empties it.
136
+ A host sets no `defaultPendingComponent` or `defaultErrorComponent` on its router, which would override the frame's for a project's routes. A host serves `@metacensus/library-research/csp.json` as its Content-Security-Policy (directive → sources, adding its own origins and nonces) and `pdfAssets`, `/pdfjs/`, for `configurePdf({ assets })`.
115
137
 
116
138
  ## Testing
117
139
 
118
- `testHost(project, { data, private, documents, people, roles, reader, self, url, sessionLost })` from `@metacensus/library-research/testing` returns `{ element, router, documents }`: the project in the frame and mount a real host uses, at its path, `data` giving each dataset's JSON, `people` and `roles` as research.json's, `reader` the username (default `test`) and the writer of every save, `self` false to view the project as `reader` while signed in as another (default true; `testHost` holds the one identity, so saves are still `reader`'s), `documents` the project's saved documents as `{ id: { body, writer? } }`, `url` the path below the project (default `/`). Render `element` with any DOM renderer; `router.state.location` says where the project navigated, and `documents()` what it saved. `membersOf(research.people)` and `readerOf(research, username, self)` from `./testing` build the `members` and `reader` `testHost` serves, so a fixture reads them from research.json rather than copying them. `init` scaffolds `ui/index.test.tsx` on vitest, jsdom and Testing Library, which a project installs itself.
140
+ `testHost(project, { data, private, collections, items, people, roles, reader, self, url, sessionLost })` from `@metacensus/library-research/testing` returns `{ element, router, host, items }`: the project in the frame and mount a real host uses, at its path, its `Host` built by `createHost` over an in-memory store, `data` giving each dataset's JSON (a dataset it omits answers 404), `people`, `roles` and `collections` as research.json's, `reader` the username (default `test`) and the writer of every write, `self` false to view the project as `reader` while signed in as another (default true; `testHost` holds the one identity, so writes are still `reader`'s), `items` the items the project starts with as `[{ collection, id, body, writer? }]`, written in order, a refused one throwing, `url` the path below the project (default `/`). Render `element` with any DOM renderer; `router.state.location` says where the project navigated, and `items()` each current item's `{ collection, writer, id, revision, sequence }`, in write order. `parity(host, { data, private, collections: { document, log } })` from `./testing` runs a fixed set of requests through `host.store`, writing to a `document` and a `log` collection the reader may read and write, each accepting `{}` as a body, and returns the answers, which two hosts serving the same files return equally. `membersOf(research.people)` and `readerOf(research, username, self)` from `./testing` build the `members` and `reader` `testHost` serves, so a fixture reads them from research.json rather than copying them. `init` scaffolds `ui/index.test.tsx` on vitest, jsdom and Testing Library, which a project installs itself.
119
141
 
120
142
  ```tsx
121
143
  render(
@@ -123,7 +145,7 @@ render(
123
145
  )
124
146
  ```
125
147
 
126
- One dev server serves several readers: a browser context names its reader by the cookie `library-research-reader`, and an empty one is signed out, so data answers 401 and the host reports the session lost. In a browser spec, `as(reader)` opens a page in a new context read as `reader` (`null` signed out), each checked for CSP and axe violations as `page` is. That context takes the project's `contextOptions` and `baseURL`, no other `use` option. A leftover `library-research-reader` cookie in a browser overrides `--reader`:
148
+ One dev server serves several readers: a browser context names its reader by the cookie `library-research-reader`, and an empty one is signed out, so data answers 401 and the host reports the session lost. In a browser spec, `as(reader)` opens a page in a new context read as `reader` (`null` signed out), each checked for CSP and axe violations as `page` is. The context takes the project's `use` options, as `page`'s does. A leftover `library-research-reader` cookie in a browser overrides `--reader`:
127
149
 
128
150
  ```ts
129
151
  test('a leader sees what an author saved', async ({ as }) => {
@@ -0,0 +1,31 @@
1
+ import { type Collections, type components } from './collections.gen.js';
2
+ import type { Route } from './urls.js';
3
+ type Schemas = components['schemas'];
4
+ type Item = Schemas['Item'];
5
+ type Outcome = Schemas['Outcome'];
6
+ /** How a request ended: for `ok` and `replayed`, the items written or read; for `stale` and `exists`, those in conflict. */
7
+ export interface Answer {
8
+ outcome: Outcome;
9
+ items: Item[];
10
+ }
11
+ /**
12
+ * A project's collections as service-api-research serves them, held in
13
+ * memory: its checks in their order, its outcomes, and its answers to a
14
+ * request `match` reads as a collection route. `people` are the project's
15
+ * members, each with their role; a person `undefined` holds no session.
16
+ */
17
+ export declare function collectionStore({ collections, people, }: {
18
+ collections?: Collections;
19
+ people?: Record<string, {
20
+ role?: string;
21
+ }>;
22
+ }): {
23
+ write: (person: string | undefined, request: unknown) => Answer;
24
+ read: (person: string | undefined, collection: string) => Answer | undefined;
25
+ handle(request: Request, route: Extract<Route, {
26
+ route: "collections" | "collection";
27
+ }>, person: string | undefined): Promise<Response>;
28
+ /** Every current item, in sequence order. */
29
+ items: () => Item[];
30
+ };
31
+ export {};
@@ -0,0 +1,174 @@
1
+ import { collectionName, maxWriteBytes, status, writeRequest, } from './collections.gen.js';
2
+ import { z } from './zod.js';
3
+ const WriteRequest = z.fromJSONSchema(writeRequest);
4
+ const namePattern = new RegExp(collectionName.pattern);
5
+ /** `value` as JSON with every object's keys sorted, so equal values print alike. */
6
+ const canonical = (value) => JSON.stringify(value, (_, v) => typeof v === 'object' && v !== null && !Array.isArray(v)
7
+ ? Object.fromEntries(Object.entries(v).sort(([a], [b]) => (a < b ? -1 : 1)))
8
+ : v);
9
+ const json = (code, value) => new Response(value === undefined ? null : JSON.stringify(value), {
10
+ status: code,
11
+ headers: {
12
+ 'Cache-Control': 'private, no-cache',
13
+ ...(value === undefined ? {} : { 'Content-Type': 'application/json' }),
14
+ },
15
+ });
16
+ /** An answer as the API sends it: 201 for a write's `ok`, 200 for a read or a replay, else `Error` at its status. */
17
+ const respond = ({ outcome, items }, written) => outcome === 'ok' || outcome === 'replayed'
18
+ ? json(outcome === 'ok' && written ? 201 : 200, { items })
19
+ : json(status[outcome], {
20
+ code: outcome,
21
+ ...(items.length ? { conflicts: items } : {}),
22
+ });
23
+ /**
24
+ * A project's collections as service-api-research serves them, held in
25
+ * memory: its checks in their order, its outcomes, and its answers to a
26
+ * request `match` reads as a collection route. `people` are the project's
27
+ * members, each with their role; a person `undefined` holds no session.
28
+ */
29
+ export function collectionStore({ collections = {}, people = {}, }) {
30
+ const stored = [];
31
+ const requests = new Map();
32
+ const bodies = Object.fromEntries(Object.entries(collections).map(([named, { body }]) => [
33
+ named,
34
+ z.fromJSONSchema(body),
35
+ ]));
36
+ const refuse = (outcome, items = []) => ({ outcome, items });
37
+ const admit = (person) => person === undefined
38
+ ? refuse('unauthenticated')
39
+ : Object.hasOwn(people, person)
40
+ ? undefined
41
+ : refuse('forbidden');
42
+ // A grant's conditions, for `person`; `members` holds for every member.
43
+ const holds = ({ roles, after }, person) => {
44
+ const role = people[person]?.role;
45
+ return ((!roles || (role !== undefined && roles.includes(role))) &&
46
+ (!after ||
47
+ stored.some((it) => it.collection === after.collection && it.id === after.id)));
48
+ };
49
+ const current = (collection, writer, id) => stored
50
+ .filter((it) => it.collection === collection && it.writer === writer && it.id === id)
51
+ .at(-1);
52
+ const shown = (it) => {
53
+ const item = { ...it };
54
+ delete item.body;
55
+ return item;
56
+ };
57
+ const latest = (keep) => {
58
+ const found = new Map();
59
+ for (const it of stored)
60
+ if (keep(it))
61
+ found.set(canonical([it.collection, it.writer, it.id]), it);
62
+ return [...found.values()].sort((a, b) => a.sequence - b.sequence);
63
+ };
64
+ function write(person, request) {
65
+ const refused = admit(person);
66
+ if (refused)
67
+ return refused;
68
+ const writer = person;
69
+ const parsed = WriteRequest.safeParse(request);
70
+ if (!parsed.success)
71
+ return refuse('invalid');
72
+ const { requestId, items } = parsed.data;
73
+ const named = new Set();
74
+ for (const { collection, id } of items) {
75
+ const key = canonical([collection, id]);
76
+ if (!Object.hasOwn(collections, collection) || named.has(key))
77
+ return refuse('invalid');
78
+ named.add(key);
79
+ }
80
+ const digest = canonical(items);
81
+ const replay = requests.get(canonical([writer, requestId]));
82
+ if (replay)
83
+ return replay.digest === digest
84
+ ? { outcome: 'replayed', items: replay.items }
85
+ : refuse('exists');
86
+ if (!items.every(({ collection }) => collections[collection].write.some((grant) => holds(grant, writer))))
87
+ return refuse('forbidden');
88
+ if (!items.every(({ collection, body }) => bodies[collection].safeParse(body).success))
89
+ return refuse('invalid');
90
+ const conflicts = [];
91
+ let refusal;
92
+ for (const { collection, id, revision } of items) {
93
+ const have = current(collection, writer, id)?.revision ?? 0;
94
+ const log = collections[collection].mode === 'log';
95
+ const stale = log ? revision !== 0 : revision !== have;
96
+ if (stale)
97
+ refusal = 'stale';
98
+ else if (log && have !== 0)
99
+ refusal ??= 'exists';
100
+ else
101
+ continue;
102
+ if (have !== 0)
103
+ conflicts.push({ collection, writer, id, revision: have });
104
+ }
105
+ if (refusal)
106
+ return refuse(refusal, conflicts);
107
+ const written = items.map(({ collection, id, revision, body }) => {
108
+ const item = {
109
+ collection,
110
+ writer,
111
+ id,
112
+ revision: revision + 1,
113
+ sequence: stored.length + 1,
114
+ body,
115
+ };
116
+ stored.push(item);
117
+ return shown(item);
118
+ });
119
+ requests.set(canonical([writer, requestId]), { digest, items: written });
120
+ return { outcome: 'ok', items: written };
121
+ }
122
+ /** `collection`'s items `person` may read, each at its current revision; undefined when the project declares no such collection. */
123
+ function read(person, collection) {
124
+ const refused = admit(person);
125
+ if (refused)
126
+ return refused;
127
+ if (!namePattern.test(collection))
128
+ return refuse('invalid');
129
+ if (!Object.hasOwn(collections, collection))
130
+ return;
131
+ const grants = collections[collection].read.filter((grant) => holds(grant, person));
132
+ const all = grants.some((grant) => !grant.own);
133
+ const own = grants.some((grant) => grant.own);
134
+ return {
135
+ outcome: 'ok',
136
+ items: latest((it) => it.collection === collection &&
137
+ (all || (own && it.writer === person))),
138
+ };
139
+ }
140
+ return {
141
+ write,
142
+ read,
143
+ async handle(request, route, person) {
144
+ if (route.route === 'collection') {
145
+ if (request.method !== 'GET')
146
+ return json(405);
147
+ const answer = read(person, route.collection);
148
+ return answer ? respond(answer, false) : json(404);
149
+ }
150
+ if (request.method !== 'POST')
151
+ return json(405);
152
+ // In service-api-research's middleware order: the media type, then the session.
153
+ const type = request.headers.get('Content-Type')?.split(';')[0]?.trim();
154
+ if (type?.toLowerCase() !== 'application/json')
155
+ return json(415);
156
+ const refused = admit(person);
157
+ if (refused)
158
+ return respond(refused, true);
159
+ const text = await request.text();
160
+ if (new TextEncoder().encode(text).length > maxWriteBytes)
161
+ return json(413);
162
+ let body;
163
+ try {
164
+ body = JSON.parse(text);
165
+ }
166
+ catch {
167
+ return respond(refuse('invalid'), true);
168
+ }
169
+ return respond(write(person, body), true);
170
+ },
171
+ /** Every current item, in sequence order. */
172
+ items: () => latest(() => true).map(shown),
173
+ };
174
+ }
@@ -0,0 +1,309 @@
1
+ import type { JSONSchema } from 'zod/v4/core';
2
+ export declare const collections: JSONSchema.JSONSchema;
3
+ export declare const writeRequest: JSONSchema.JSONSchema;
4
+ export declare const collectionName: {
5
+ readonly type: "string";
6
+ readonly pattern: "^[a-z][a-z0-9-]{0,63}$";
7
+ };
8
+ export declare const status: {
9
+ readonly unauthenticated: 401;
10
+ readonly forbidden: 403;
11
+ readonly invalid: 400;
12
+ readonly stale: 409;
13
+ readonly exists: 409;
14
+ readonly full: 507;
15
+ };
16
+ export declare const maxWriteBytes = 1048576;
17
+ export type Collections = components['schemas']['Collections'];
18
+ export interface paths {
19
+ "/api/projects/{project}/collections": {
20
+ parameters: {
21
+ query?: never;
22
+ header?: never;
23
+ path?: never;
24
+ cookie?: never;
25
+ };
26
+ get?: never;
27
+ put?: never;
28
+ post: operations["writeItems"];
29
+ delete?: never;
30
+ options?: never;
31
+ head?: never;
32
+ patch?: never;
33
+ trace?: never;
34
+ };
35
+ "/api/projects/{project}/collections/{collection}": {
36
+ parameters: {
37
+ query?: never;
38
+ header?: never;
39
+ path?: never;
40
+ cookie?: never;
41
+ };
42
+ get: operations["readItems"];
43
+ put?: never;
44
+ post?: never;
45
+ delete?: never;
46
+ options?: never;
47
+ head?: never;
48
+ patch?: never;
49
+ trace?: never;
50
+ };
51
+ }
52
+ export type webhooks = Record<string, never>;
53
+ export interface components {
54
+ schemas: {
55
+ WriteRequest: {
56
+ requestId: string;
57
+ items: components["schemas"]["WriteItem"][];
58
+ };
59
+ WriteItem: {
60
+ collection: components["schemas"]["CollectionName"];
61
+ id: components["schemas"]["ItemID"];
62
+ /** Format: int64 */
63
+ revision: number;
64
+ body: unknown;
65
+ };
66
+ CollectionName: string;
67
+ ItemID: string;
68
+ WriteResult: {
69
+ items: components["schemas"]["Item"][];
70
+ };
71
+ Item: {
72
+ collection: components["schemas"]["CollectionName"];
73
+ writer: string;
74
+ id: components["schemas"]["ItemID"];
75
+ /** Format: int64 */
76
+ revision: number;
77
+ /** Format: int64 */
78
+ sequence?: number;
79
+ body?: unknown;
80
+ };
81
+ Error: {
82
+ code: components["schemas"]["Outcome"];
83
+ conflicts?: components["schemas"]["Item"][];
84
+ };
85
+ /** @enum {string} */
86
+ Outcome: "ok" | "replayed" | "unauthenticated" | "forbidden" | "invalid" | "stale" | "exists" | "full";
87
+ ItemList: {
88
+ items: components["schemas"]["Item"][];
89
+ };
90
+ /**
91
+ * @description The collections section of a project's manifest, by collection name.
92
+ *
93
+ * Only the project's members are ever allowed: a person who is not a member is refused `forbidden`, and a request with no session is refused `unauthenticated`.
94
+ *
95
+ * A manifest that fails one of these checks is refused whole:
96
+ * - each role a grant names is one the project declares;
97
+ * - each gate's collection exists and is a `log`;
98
+ * - each `body` compiles as JSON Schema.
99
+ */
100
+ Collections: {
101
+ [key: string]: components["schemas"]["Collection"];
102
+ };
103
+ /**
104
+ * @description A set of items, each keyed by (writer, id) within the collection. Only an item's writer writes it, so no one can take an id another person is using.
105
+ *
106
+ * A collection allows a person when any one of its grants holds; an empty list allows no one. A grant holds when all of its conditions hold.
107
+ */
108
+ Collection: {
109
+ /**
110
+ * @description `document`: a write names the item's expected revision, `0` for a new item, and is refused `stale` unless the item is at that revision. A read returns each item's current revision. Earlier revisions stay stored and count toward the quota, but are never served.
111
+ *
112
+ * `log`: an entry is written once, at expected revision `0`; any other expected revision is `stale`. A second write of the same (writer, id) is refused `exists`. A read returns every entry, so the log is its writer's history, and no entry is replaced or deleted.
113
+ * @enum {string}
114
+ */
115
+ mode: "document" | "log";
116
+ /** @description A JSON Schema, draft 2020-12, that every item body written to the collection must satisfy. It holds no external `$ref`, and `format` is an annotation only. */
117
+ body: Record<string, unknown>;
118
+ /** @description The grants that allow a read. A read returns, in the store's sequence order, the items the person may read, which are those for which some grant holds; a member is never refused a read, and may be served nothing. */
119
+ read: components["schemas"]["ReadGrant"][];
120
+ /** @description The grants that allow a write. A write is refused `forbidden` for an item the person may not write. */
121
+ write: components["schemas"]["WriteGrant"][];
122
+ };
123
+ /** @description A rule allowing a read. It holds when each condition it names holds, and names at least one. */
124
+ ReadGrant: {
125
+ /**
126
+ * @description The reader wrote the item.
127
+ * @constant
128
+ */
129
+ own?: true;
130
+ roles?: components["schemas"]["GrantRoles"];
131
+ /**
132
+ * @description The person opens the project: a member, an admin or a super admin.
133
+ * @constant
134
+ */
135
+ members?: true;
136
+ after?: components["schemas"]["Gate"];
137
+ };
138
+ /** @description The person's role in the project is one of these. The roles are the ones the project's research.json declares. */
139
+ GrantRoles: string[];
140
+ /**
141
+ * @description Names one entry of a `log` collection in the same project: the entry with this `id` in this `collection`.
142
+ *
143
+ * The first entry with that id opens the gate, whoever wrote it, provided the collection's write grants allowed that writer. Until then every grant that names the gate fails.
144
+ *
145
+ * A gate never closes: a log entry is never replaced or deleted, and the gate names only a log.
146
+ */
147
+ Gate: {
148
+ collection: components["schemas"]["CollectionName"];
149
+ id: components["schemas"]["ItemID"];
150
+ };
151
+ /** @description A rule allowing a write. It holds when each condition it names holds, and names at least one. */
152
+ WriteGrant: {
153
+ roles?: components["schemas"]["GrantRoles"];
154
+ /**
155
+ * @description The person opens the project: a member, an admin or a super admin.
156
+ * @constant
157
+ */
158
+ members?: true;
159
+ after?: components["schemas"]["Gate"];
160
+ };
161
+ };
162
+ responses: never;
163
+ parameters: {
164
+ ProjectID: string;
165
+ };
166
+ requestBodies: never;
167
+ headers: never;
168
+ pathItems: never;
169
+ }
170
+ export type $defs = Record<string, never>;
171
+ export interface operations {
172
+ writeItems: {
173
+ parameters: {
174
+ query?: never;
175
+ header?: never;
176
+ path: {
177
+ project: components["parameters"]["ProjectID"];
178
+ };
179
+ cookie?: never;
180
+ };
181
+ requestBody: {
182
+ content: {
183
+ "application/json": components["schemas"]["WriteRequest"];
184
+ };
185
+ };
186
+ responses: {
187
+ 200: {
188
+ headers: {
189
+ [name: string]: unknown;
190
+ };
191
+ content: {
192
+ "application/json": components["schemas"]["WriteResult"];
193
+ };
194
+ };
195
+ 201: {
196
+ headers: {
197
+ [name: string]: unknown;
198
+ };
199
+ content: {
200
+ "application/json": components["schemas"]["WriteResult"];
201
+ };
202
+ };
203
+ 400: {
204
+ headers: {
205
+ [name: string]: unknown;
206
+ };
207
+ content: {
208
+ "application/json": components["schemas"]["Error"];
209
+ };
210
+ };
211
+ 401: {
212
+ headers: {
213
+ [name: string]: unknown;
214
+ };
215
+ content: {
216
+ "application/json": components["schemas"]["Error"];
217
+ };
218
+ };
219
+ 403: {
220
+ headers: {
221
+ [name: string]: unknown;
222
+ };
223
+ content: {
224
+ "application/json": components["schemas"]["Error"];
225
+ };
226
+ };
227
+ 409: {
228
+ headers: {
229
+ [name: string]: unknown;
230
+ };
231
+ content: {
232
+ "application/json": components["schemas"]["Error"];
233
+ };
234
+ };
235
+ 413: {
236
+ headers: {
237
+ [name: string]: unknown;
238
+ };
239
+ content?: never;
240
+ };
241
+ 415: {
242
+ headers: {
243
+ [name: string]: unknown;
244
+ };
245
+ content?: never;
246
+ };
247
+ 507: {
248
+ headers: {
249
+ [name: string]: unknown;
250
+ };
251
+ content: {
252
+ "application/json": components["schemas"]["Error"];
253
+ };
254
+ };
255
+ };
256
+ };
257
+ readItems: {
258
+ parameters: {
259
+ query?: never;
260
+ header?: never;
261
+ path: {
262
+ project: components["parameters"]["ProjectID"];
263
+ collection: components["schemas"]["CollectionName"];
264
+ };
265
+ cookie?: never;
266
+ };
267
+ requestBody?: never;
268
+ responses: {
269
+ 200: {
270
+ headers: {
271
+ [name: string]: unknown;
272
+ };
273
+ content: {
274
+ "application/json": components["schemas"]["ItemList"];
275
+ };
276
+ };
277
+ 400: {
278
+ headers: {
279
+ [name: string]: unknown;
280
+ };
281
+ content: {
282
+ "application/json": components["schemas"]["Error"];
283
+ };
284
+ };
285
+ 401: {
286
+ headers: {
287
+ [name: string]: unknown;
288
+ };
289
+ content: {
290
+ "application/json": components["schemas"]["Error"];
291
+ };
292
+ };
293
+ 403: {
294
+ headers: {
295
+ [name: string]: unknown;
296
+ };
297
+ content: {
298
+ "application/json": components["schemas"]["Error"];
299
+ };
300
+ };
301
+ 404: {
302
+ headers: {
303
+ [name: string]: unknown;
304
+ };
305
+ content?: never;
306
+ };
307
+ };
308
+ };
309
+ }