@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/dist/host.js CHANGED
@@ -2,9 +2,29 @@ import { jsx as _jsx } from "react/jsx-runtime";
2
2
  import { Button, Notice } from '@metacensus/library-ui';
3
3
  import { useQueryErrorResetBoundary } from '@tanstack/react-query';
4
4
  import { createRoute, Outlet, } from '@tanstack/react-router';
5
- import { DatasetsContext, HostContext } from './context.js';
5
+ import { CollectionsContext, DatasetsContext, HostContext } from './context.js';
6
+ import { checkProjectId } from './project-id.js';
7
+ import { urls } from './urls.js';
6
8
  export { pdfAssets } from './pdf.js';
7
9
  export { projectIdPattern } from './project-id.js';
10
+ /** The `Host` of one project, its URLs built by the one rule every host serves. */
11
+ export function createHost({ project, reader, members, pages, store, sessionLost, origin = location.origin, }) {
12
+ checkProjectId(project, 'project');
13
+ return {
14
+ reader,
15
+ members,
16
+ data: (dataset) => origin + urls.data(project, dataset),
17
+ private: (dataset) => Object.fromEntries(pages.map((page) => [
18
+ page,
19
+ origin + urls.private(project, page, dataset),
20
+ ])),
21
+ paper: (sha) => origin + urls.paper(project, sha),
22
+ collections: () => origin + urls.collections(project),
23
+ collection: (name) => origin + urls.collection(project, name),
24
+ store,
25
+ sessionLost,
26
+ };
27
+ }
8
28
  function Failed({ error, reset }) {
9
29
  const queries = useQueryErrorResetBoundary();
10
30
  return (_jsx(Notice, { role: "alert", title: error instanceof Error ? error.message : String(error), children: _jsx(Button, { onClick: () => {
@@ -29,13 +49,13 @@ export function frame(useHost) {
29
49
  /**
30
50
  * Mounts `project` under `parent` at the path it names, with `options` as the
31
51
  * route's options (`frame(useHost)`, and any `loader` or `head`); returns the
32
- * route. The route's component renders in the project's datasets.
52
+ * route. The route's component renders in the project's datasets and collections.
33
53
  */
34
54
  export function mount(parent, project, options) {
35
55
  const Inner = (options.component ?? Outlet);
36
56
  const route = createRoute({
37
57
  ...options,
38
- component: () => (_jsx(DatasetsContext.Provider, { value: project.datasets, children: _jsx(Inner, {}) })),
58
+ component: () => (_jsx(DatasetsContext.Provider, { value: project.datasets, children: _jsx(CollectionsContext.Provider, { value: project.collections, children: _jsx(Inner, {}) }) })),
39
59
  getParentRoute: () => parent,
40
60
  path: project.path,
41
61
  });
package/dist/index.d.ts CHANGED
@@ -1,5 +1,4 @@
1
- export type { AnyProject, Corpus, Csl, Data, Doc, Edition, Host, Judgment, Kind, Member, Paper, Register, Schema, Mount, Project, Reader, RouterOf, Work, } from './types.js';
1
+ export type { AnyProject, Body, CollectionSchemas, Corpus, Csl, Data, Edition, Host, Item, Judgment, Kind, Member, Paper, Register, Schema, Mount, Project, Reader, RouterOf, Work, WriteRequest, WriteResult, } from './types.js';
2
2
  export { papers } from './corpus.js';
3
3
  export { defineProject } from './mount.js';
4
- export { useCorpus, useData, useDatas, useDocument, useDocuments, useHost, useMembers, usePrivate, useReader, useSaveDocument, } from './react.js';
5
- export { DocumentError } from './documents.js';
4
+ export { useCollection, useCorpus, useData, useDatas, useHost, useMembers, usePrivate, useReader, useWrite, WriteError, } from './react.js';
package/dist/index.js CHANGED
@@ -1,4 +1,3 @@
1
1
  export { papers } from './corpus.js';
2
2
  export { defineProject } from './mount.js';
3
- export { useCorpus, useData, useDatas, useDocument, useDocuments, useHost, useMembers, usePrivate, useReader, useSaveDocument, } from './react.js';
4
- export { DocumentError } from './documents.js';
3
+ export { useCollection, useCorpus, useData, useDatas, useHost, useMembers, usePrivate, useReader, useWrite, WriteError, } from './react.js';
package/dist/mount.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { type AnyRoute } from '@tanstack/react-router';
2
- import type { Schema, Schemas } from './types.js';
2
+ import type { CollectionSchemas, Schema, Schemas } from './types.js';
3
3
  declare function mountRoute<P extends string>(path: P): {
4
4
  root: import("@tanstack/react-router").RootRoute<import("@tanstack/react-router").Register, undefined, {}, import("@tanstack/react-router").AnyContext, import("@tanstack/react-router").AnyContext, {}, undefined, unknown, unknown, unknown, unknown, undefined>;
5
5
  route: import("@tanstack/react-router").Route<unknown, import("@tanstack/react-router").RootRoute<import("@tanstack/react-router").Register, undefined, {}, import("@tanstack/react-router").AnyContext, import("@tanstack/react-router").AnyContext, {}, undefined, unknown, unknown, unknown, unknown, undefined>, P, import("@tanstack/react-router").ResolveFullPath<import("@tanstack/react-router").RootRoute<import("@tanstack/react-router").Register, undefined, {}, import("@tanstack/react-router").AnyContext, import("@tanstack/react-router").AnyContext, {}, undefined, unknown, unknown, unknown, unknown, undefined>, P, import("@tanstack/router-core").RoutePrefix<"/", P>>, string, import("@tanstack/router-core").RoutePrefix<"__root__", P>, undefined, import("@tanstack/react-router").ResolveParams<P>, import("@tanstack/react-router").AnyContext, import("@tanstack/react-router").AnyContext, import("@tanstack/react-router").AnyContext, {}, undefined, unknown, unknown, unknown, unknown, undefined>;
@@ -11,22 +11,25 @@ export type Mount<P extends string> = ReturnType<typeof mountRoute<P>>['route'];
11
11
  export interface Project<P extends string = string, C = readonly AnyRoute[]> {
12
12
  readonly path: P;
13
13
  readonly datasets: Record<string, Schema>;
14
+ readonly collections: Record<string, Schema>;
14
15
  routes(parent: Mount<P>): C;
15
16
  }
16
17
  /** Any project, for a list or a constraint: a `Project<'a'>` is not a `Project<string>`. */
17
18
  export interface AnyProject {
18
19
  readonly path: string;
19
20
  readonly datasets: Record<string, Schema>;
21
+ readonly collections: Record<string, Schema>;
20
22
  routes(parent: never): readonly AnyRoute[];
21
23
  }
22
24
  /**
23
25
  * What `ui/index.tsx` and `ui/local/index.tsx` default-export. `path` is the
24
26
  * project's first URL segment, matching `projectIdPattern` and not
25
- * `projects`, `local` or `pdfjs`, which dev and the host reserve; `routes`
26
- * creates its routes against `parent`; `datasets` is ui/datasets.ts's export,
27
- * which `useData` and `usePrivate` read the schemas from.
27
+ * `projects`, `api`, `local` or `pdfjs`, which dev and the host reserve; `routes`
28
+ * creates its routes against `parent`; `datasets` and `collections` are
29
+ * ui/datasets.ts's exports, which `useData` and `usePrivate`, and
30
+ * `useCollection`, read the schemas from.
28
31
  */
29
- export declare function defineProject<P extends string, const C>(path: P, routes: (parent: Mount<P>) => C, datasets?: Schemas): Project<P, C>;
32
+ export declare function defineProject<P extends string, const C>(path: P, routes: (parent: Mount<P>) => C, datasets?: Schemas, collections?: CollectionSchemas): Project<P, C>;
30
33
  /** A project's `Register`: `router: RouterOf<typeof project>`. */
31
34
  export type RouterOf<R extends AnyProject> = ReturnType<R['routes']> extends infer C extends readonly AnyRoute[] ? ReturnType<typeof routerOf<R['path'], C>> : never;
32
35
  export {};
package/dist/mount.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { createRootRoute, createRoute, createRouter, } from '@tanstack/react-router';
2
2
  import { checkProjectId } from './project-id.js';
3
3
  // First segments that dev and the host serve themselves.
4
- const reserved = ['projects', 'local', 'pdfjs'];
4
+ const reserved = ['projects', 'api', 'local', 'pdfjs'];
5
5
  function mountRoute(path) {
6
6
  const root = createRootRoute();
7
7
  return { root, route: createRoute({ getParentRoute: () => root, path }) };
@@ -17,13 +17,19 @@ function routerOf(path, children) {
17
17
  /**
18
18
  * What `ui/index.tsx` and `ui/local/index.tsx` default-export. `path` is the
19
19
  * project's first URL segment, matching `projectIdPattern` and not
20
- * `projects`, `local` or `pdfjs`, which dev and the host reserve; `routes`
21
- * creates its routes against `parent`; `datasets` is ui/datasets.ts's export,
22
- * which `useData` and `usePrivate` read the schemas from.
20
+ * `projects`, `api`, `local` or `pdfjs`, which dev and the host reserve; `routes`
21
+ * creates its routes against `parent`; `datasets` and `collections` are
22
+ * ui/datasets.ts's exports, which `useData` and `usePrivate`, and
23
+ * `useCollection`, read the schemas from.
23
24
  */
24
- export function defineProject(path, routes, datasets) {
25
+ export function defineProject(path, routes, datasets, collections) {
25
26
  checkProjectId(path, 'project path');
26
27
  if (reserved.includes(path))
27
28
  throw new Error(`project path "${path}" is reserved by dev and the host`);
28
- return { path, routes, datasets: datasets ?? {} };
29
+ return {
30
+ path,
31
+ routes,
32
+ datasets: datasets ?? {},
33
+ collections: collections ?? {},
34
+ };
29
35
  }
@@ -0,0 +1,25 @@
1
+ import type { Host } from './types.js';
2
+ /** One request of `parity`'s run, named the same on every host, and its answer: JSON, or null for a body that is not. */
3
+ export interface Exchange {
4
+ request: string;
5
+ status: number;
6
+ json: unknown;
7
+ }
8
+ /**
9
+ * A fixed run of requests through `host.store` at `host`'s URLs, and their
10
+ * answers: each dataset of `data`; for each private dataset of `private`, each
11
+ * of the reader's pages and the page it maps to, which the reader does not
12
+ * hold; and the collection routes, writes and refusals alike, each request
13
+ * carrying one fault. `collections` names a `document` and a `log` collection
14
+ * the reader may read and write, each accepting `{}` as a body. Reads keep
15
+ * only the run's items, and each `sequence` is its rank within the run, so two
16
+ * hosts' runs compare equal whatever each held before.
17
+ */
18
+ export declare function parity(host: Host, { data, private: held, collections: { document, log }, }: {
19
+ data: string[];
20
+ private: Record<string, string>;
21
+ collections: {
22
+ document: string;
23
+ log: string;
24
+ };
25
+ }): Promise<Exchange[]>;
package/dist/parity.js ADDED
@@ -0,0 +1,70 @@
1
+ import { maxWriteBytes } from './collections.gen.js';
2
+ import { match, urls } from './urls.js';
3
+ /**
4
+ * A fixed run of requests through `host.store` at `host`'s URLs, and their
5
+ * answers: each dataset of `data`; for each private dataset of `private`, each
6
+ * of the reader's pages and the page it maps to, which the reader does not
7
+ * hold; and the collection routes, writes and refusals alike, each request
8
+ * carrying one fault. `collections` names a `document` and a `log` collection
9
+ * the reader may read and write, each accepting `{}` as a body. Reads keep
10
+ * only the run's items, and each `sequence` is its rank within the run, so two
11
+ * hosts' runs compare equal whatever each held before.
12
+ */
13
+ export async function parity(host, { data, private: held, collections: { document, log }, }) {
14
+ const run = `p${Date.now().toString(36)}${Math.random().toString(36).slice(2, 8)}`;
15
+ const exchanges = [];
16
+ const sequences = new Set();
17
+ const send = async (request, url, init) => {
18
+ const response = await host.store(new Request(url, init));
19
+ const text = await response.text();
20
+ let json = null;
21
+ if (response.headers.get('Content-Type')?.startsWith('application/json')) {
22
+ const { items, ...rest } = JSON.parse(text);
23
+ json = JSON.parse(JSON.stringify(items
24
+ ? { ...rest, items: items.filter(({ id }) => id.startsWith(run)) }
25
+ : rest).replaceAll(run, 'run'), (key, value) => {
26
+ if (key === 'sequence' && typeof value === 'number')
27
+ sequences.add(value);
28
+ return value;
29
+ });
30
+ }
31
+ exchanges.push({ request, status: response.status, json });
32
+ };
33
+ const post = (request, body, type = 'application/json') => send(request, host.collections(), {
34
+ method: 'POST',
35
+ headers: { 'Content-Type': type },
36
+ body,
37
+ });
38
+ const write = (request, requestId, collection, id, revision) => post(request, JSON.stringify({
39
+ requestId: `${run}-${requestId}`,
40
+ items: [{ collection, id: `${run}.${id}`, revision, body: {} }],
41
+ }));
42
+ for (const dataset of data)
43
+ await send(`GET data ${dataset}`, host.data(dataset));
44
+ const { origin } = new URL(host.collections());
45
+ const { project } = match(host.collections());
46
+ for (const [dataset, other] of Object.entries(held)) {
47
+ for (const [page, url] of Object.entries(host.private(dataset)))
48
+ await send(`GET private ${dataset} ${page}`, url);
49
+ await send(`GET private ${dataset} ${other}, not the reader's`, origin + urls.private(project, other, dataset));
50
+ }
51
+ await write('POST new', '1', document, 'a', 0);
52
+ await write('POST the same request again', '1', document, 'a', 0);
53
+ await write('POST its request id with other items', '1', document, 'b', 0);
54
+ await write('POST at a stale revision', '2', document, 'a', 0);
55
+ await write('POST at its revision', '3', document, 'a', 1);
56
+ await write('POST a log entry', '4', log, 'e', 0);
57
+ await write('POST the log entry again', '5', log, 'e', 0);
58
+ await send('GET the document collection', host.collection(document));
59
+ await send('GET the log collection', host.collection(log));
60
+ await send('GET an undeclared collection', host.collection(`${run}-none`));
61
+ await send('GET a bad collection name', host.collection('Bad'));
62
+ await post('POST a body not JSON', '{}', 'text/plain');
63
+ await post('POST over the limit', `"${'x'.repeat(maxWriteBytes)}"`);
64
+ await post('POST no items', JSON.stringify({ requestId: run, items: [] }));
65
+ await write('POST to an undeclared collection', '6', `${run}-none`, 'a', 0);
66
+ const rank = [...sequences].sort((a, b) => a - b);
67
+ return JSON.parse(JSON.stringify(exchanges), (key, value) => key === 'sequence' && typeof value === 'number'
68
+ ? rank.indexOf(value) + 1
69
+ : value);
70
+ }
@@ -4,7 +4,7 @@ export default _default;
4
4
  type Violation = `csp ${string} ${string}` | `axe ${string}` | `console ${string}` | `origin ${string}`;
5
5
  export declare const test: import("@playwright/test").TestType<import("@playwright/test").PlaywrightTestArgs & import("@playwright/test").PlaywrightTestOptions & {
6
6
  violations: Violation[];
7
- /** A page in a new context on the dev server, read as `reader`; `null` is signed out. The context takes the project's `contextOptions` and `baseURL`, no other `use` option. */
7
+ /** A page in a new context on the dev server, read as `reader`; `null` is signed out. The context takes the project's `use` options, as `page`'s does. */
8
8
  as: (reader: string | null) => Promise<Page>;
9
9
  }, import("@playwright/test").PlaywrightWorkerArgs & import("@playwright/test").PlaywrightWorkerOptions>;
10
10
  export { expect };
@@ -7,6 +7,10 @@ const server = `const index = require('node:url').pathToFileURL(require.resolve(
7
7
  export default defineConfig({
8
8
  testDir: 'browser',
9
9
  use: { baseURL: process.env.LIBRARY_RESEARCH_URL },
10
+ projects: [
11
+ { name: 'light', use: { colorScheme: 'light' } },
12
+ { name: 'dark', use: { colorScheme: 'dark' } },
13
+ ],
10
14
  webServer: {
11
15
  command: `"${process.execPath}" -e "${server}"`,
12
16
  wait: { stdout: /(?<library_research_url>http:\S+\/)/ },
@@ -49,12 +53,12 @@ export const test = base.extend({
49
53
  await provide(page);
50
54
  await finish(violations);
51
55
  },
52
- as: async ({ browser, baseURL, contextOptions, violations }, provide) => {
56
+ as: async ({ browser, baseURL, violations }, provide) => {
53
57
  const finishers = [];
54
58
  const contexts = [];
55
59
  try {
56
60
  await provide(async (reader) => {
57
- const context = await browser.newContext({ ...contextOptions, baseURL });
61
+ const context = await browser.newContext({ baseURL });
58
62
  contexts.push(context);
59
63
  await context.addCookies([
60
64
  {
package/dist/react.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { DocumentError } from './documents.js';
2
- import type { Corpus, Data, Doc, Host, Member, Reader, Schemas } from './types.js';
1
+ import type { components } from './collections.gen.js';
2
+ import type { Body, CollectionSchemas, Corpus, Data, Host, Item, Member, Reader, Schemas, WriteRequest } from './types.js';
3
3
  /** The `Host` of the project's frame; throws outside `./host`'s `frame`. Stable for the life of the frame. */
4
4
  export declare function useHost(): Host;
5
5
  /** The person the project is viewed as; `self` is false while the host views it as another. */
@@ -28,24 +28,21 @@ export declare function useDatas<const R extends readonly (keyof Schemas)[]>(dat
28
28
  export declare function usePrivate<K extends keyof Schemas>(dataset: K): Record<string, Data<K>>;
29
29
  /** The `corpus` dataset, every work by id, parsed by the library's own schema. */
30
30
  export declare function useCorpus(): Corpus;
31
- /**
32
- * One document of the project, or `null` when none has that id. Suspends while
33
- * it loads; a failed read throws a `DocumentError` to the frame's error
34
- * notice. `parse` runs on the body only and must be pure.
35
- */
36
- export declare function useDocument<T>(id: string, parse: (json: unknown) => T): Doc<T> | null;
37
- /**
38
- * The project's documents whose id starts with `prefix`, sorted by id; every
39
- * save of the project refetches them. `parse` runs on each body and must be pure.
40
- */
41
- export declare function useDocuments<T>(prefix: string, parse: (json: unknown) => T): Doc<T>[];
42
- /**
43
- * Saves a JSON `body` as the document `id`, written by the signed-in person.
44
- * `when` makes the save conditional: `'absent'` refuses (412) if the document
45
- * exists, a revision refuses unless the document is at it; without it the
46
- * save replaces. A failure is the mutation's `error`, a `DocumentError`.
47
- */
48
- export declare function useSaveDocument(id: string): import("@tanstack/react-query").UseMutationResult<Doc<unknown>, DocumentError, {
49
- body: unknown;
50
- when?: "absent" | number;
51
- }, unknown>;
31
+ /** The items of one collection the signed-in person may read, and `refresh` to read them again. */
32
+ export declare function useCollection<K extends keyof CollectionSchemas>(collection: K): {
33
+ items: Item<Body<K>>[];
34
+ refresh: () => Promise<void>;
35
+ };
36
+ /** A write the host refused. */
37
+ export declare class WriteError extends Error {
38
+ status: number;
39
+ /** The store's term for the refusal; absent where the status alone answers, such as 413. */
40
+ code?: components['schemas']['Outcome'];
41
+ /** For `stale` and `exists`, each item in conflict at the revision it holds, to retry from. */
42
+ conflicts: components['schemas']['Item'][];
43
+ constructor(status: number, code: WriteError['code'], conflicts?: WriteError['conflicts']);
44
+ }
45
+ /** Writes items across the project's collections in one atomic request: every item, or none. */
46
+ export declare function useWrite(): import("@tanstack/react-query").UseMutationResult<{
47
+ items: components["schemas"]["Item"][];
48
+ }, WriteError, WriteRequest, unknown>;
package/dist/react.js CHANGED
@@ -1,7 +1,6 @@
1
1
  import { useMutation, useQueryClient, useSuspenseQueries, useSuspenseQuery, } from '@tanstack/react-query';
2
- import { useContext, useMemo, useState } from 'react';
3
- import { DatasetsContext, FetchContext, HostContext } from './context.js';
4
- import { DocumentError, documentId, documentPrefix } from './documents.js';
2
+ import { useContext, useMemo } from 'react';
3
+ import { CollectionsContext, DatasetsContext, HostContext } from './context.js';
5
4
  import * as schema from './schema.js';
6
5
  /** The `Host` of the project's frame; throws outside `./host`'s `frame`. Stable for the life of the frame. */
7
6
  export function useHost() {
@@ -67,7 +66,8 @@ function useFetched(datasets) {
67
66
  const url = host.data(dataset);
68
67
  return {
69
68
  queryKey: ['research', url],
70
- queryFn: () => fetch(url)
69
+ queryFn: () => host
70
+ .store(new Request(url))
71
71
  .then((response) => {
72
72
  if (response.status === 401 || response.status === 403)
73
73
  host.sessionLost();
@@ -121,7 +121,8 @@ export function usePrivate(dataset) {
121
121
  const url = urls[page];
122
122
  return {
123
123
  queryKey: ['research', url],
124
- queryFn: () => fetch(url)
124
+ queryFn: () => host
125
+ .store(new Request(url))
125
126
  .then((response) => {
126
127
  if (response.status === 401 || response.status === 403)
127
128
  host.sessionLost();
@@ -145,97 +146,84 @@ const corpusDataset = ['corpus', (json) => schema.Corpus.parse(json)];
145
146
  export function useCorpus() {
146
147
  return useFetched([corpusDataset])[0];
147
148
  }
148
- /** A fetch whose 401 and 403 are the host's lost session, and whose other failures are a `DocumentError`. */
149
- function useSend() {
149
+ /** The items of one collection the signed-in person may read, and `refresh` to read them again. */
150
+ export function useCollection(collection) {
151
+ const name = String(collection);
152
+ const schemas = useContext(CollectionsContext);
153
+ const parse = Object.hasOwn(schemas, name) ? schemas[name] : undefined;
154
+ if (!parse)
155
+ throw new Error(`collection "${name}": defineProject was given no schema for it`);
150
156
  const host = useHost();
151
- const get = useContext(FetchContext) ?? fetch;
152
- return async (url, init, absent = false) => {
153
- const response = await get(url, init);
154
- if (response.status === 401 || response.status === 403)
155
- host.sessionLost();
156
- if (absent && response.status === 404)
157
- return null;
158
- if (!response.ok)
159
- throw new DocumentError(response.status, `${response.status} from ${url}`);
160
- return response.json();
161
- };
162
- }
163
- /** `parse`, held until `key` changes, so an inline one is not read again on every render. */
164
- function useHeld(key, parse) {
165
- const [held, hold] = useState({ key, parse });
166
- if (held.key !== key)
167
- hold({ key, parse });
168
- return held.parse;
169
- }
170
- const parsed = (parse) => (doc) => {
171
- try {
172
- return { ...doc, body: parse(doc.body) };
173
- }
174
- catch (cause) {
175
- const why = cause instanceof Error ? cause.message : String(cause);
176
- throw new Error(`document "${doc.id}": ${why}`, { cause });
177
- }
178
- };
179
- /**
180
- * One document of the project, or `null` when none has that id. Suspends while
181
- * it loads; a failed read throws a `DocumentError` to the frame's error
182
- * notice. `parse` runs on the body only and must be pure.
183
- */
184
- export function useDocument(id, parse) {
185
- const url = useHost().document(documentId(id));
186
- const send = useSend();
187
- const held = useHeld(url, parse);
188
- const select = useMemo(() => (doc) => doc && parsed(held)(doc), [held]);
189
- return useSuspenseQuery({
190
- queryKey: ['research-document', url],
191
- queryFn: () => send(url, undefined, true),
157
+ const client = useQueryClient();
158
+ const url = host.collection(name);
159
+ const select = useMemo(() => ({ items }) => items.map((item) => {
160
+ try {
161
+ return { ...item, body: parse.parse(item.body) };
162
+ }
163
+ catch (cause) {
164
+ return failed(`collection "${name}" item "${item.id}"`, cause);
165
+ }
166
+ }), [name, parse]);
167
+ const key = ['research-collection', url];
168
+ const { data } = useSuspenseQuery({
169
+ queryKey: key,
170
+ queryFn: () => host
171
+ .store(new Request(url))
172
+ .then((response) => {
173
+ if (response.status === 401 || response.status === 403)
174
+ host.sessionLost();
175
+ if (!response.ok)
176
+ throw new Error(`${response.status} from ${url}`);
177
+ return response.json();
178
+ })
179
+ .catch((cause) => failed(`collection "${name}"`, cause)),
192
180
  select,
193
181
  retry: false,
194
- }).data;
182
+ });
183
+ return {
184
+ items: data,
185
+ refresh: () => client.refetchQueries({ queryKey: key, exact: true }, { throwOnError: true }),
186
+ };
195
187
  }
196
- /**
197
- * The project's documents whose id starts with `prefix`, sorted by id; every
198
- * save of the project refetches them. `parse` runs on each body and must be pure.
199
- */
200
- export function useDocuments(prefix, parse) {
201
- const url = useHost().documents(documentPrefix(prefix));
202
- const send = useSend();
203
- const held = useHeld(url, parse);
204
- const select = useMemo(() => ({ items }) => items.map(parsed(held)), [held]);
205
- return useSuspenseQuery({
206
- queryKey: ['research-documents', url],
207
- queryFn: () => send(url),
208
- select,
209
- retry: false,
210
- }).data;
188
+ /** A write the host refused. */
189
+ export class WriteError extends Error {
190
+ status;
191
+ /** The store's term for the refusal; absent where the status alone answers, such as 413. */
192
+ code;
193
+ /** For `stale` and `exists`, each item in conflict at the revision it holds, to retry from. */
194
+ conflicts;
195
+ constructor(status, code, conflicts = []) {
196
+ super(`write refused: ${code ?? status}`);
197
+ this.name = 'WriteError';
198
+ this.status = status;
199
+ this.code = code;
200
+ this.conflicts = conflicts;
201
+ }
211
202
  }
212
- /**
213
- * Saves a JSON `body` as the document `id`, written by the signed-in person.
214
- * `when` makes the save conditional: `'absent'` refuses (412) if the document
215
- * exists, a revision refuses unless the document is at it; without it the
216
- * save replaces. A failure is the mutation's `error`, a `DocumentError`.
217
- */
218
- export function useSaveDocument(id) {
219
- const url = useHost().document(documentId(id));
220
- const send = useSend();
203
+ /** Writes items across the project's collections in one atomic request: every item, or none. */
204
+ export function useWrite() {
205
+ const host = useHost();
221
206
  const client = useQueryClient();
207
+ const reread = ({ items }) => Promise.all([...new Set(items.map(({ collection }) => String(collection)))].map((name) => client.invalidateQueries({
208
+ queryKey: ['research-collection', host.collection(name)],
209
+ exact: true,
210
+ })));
222
211
  return useMutation({
223
- mutationFn: ({ body, when }) => {
224
- const headers = {
225
- 'Content-Type': 'application/json',
226
- };
227
- if (when === 'absent')
228
- headers['If-None-Match'] = '*';
229
- else if (when !== undefined)
230
- headers['If-Match'] = `"${when}"`;
231
- const text = JSON.stringify(body);
232
- if (text === undefined)
233
- throw new Error(`document "${id}": no JSON body`);
234
- return send(url, { method: 'PUT', headers, body: text });
235
- },
236
- onSuccess: (doc) => {
237
- client.setQueryData(['research-document', url], doc);
238
- return client.invalidateQueries({ queryKey: ['research-documents'] });
212
+ mutationFn: async (request) => {
213
+ const response = await host.store(new Request(host.collections(), {
214
+ method: 'POST',
215
+ headers: { 'Content-Type': 'application/json' },
216
+ body: JSON.stringify(request),
217
+ }));
218
+ if (response.status === 401)
219
+ host.sessionLost();
220
+ const json = (await response.json().catch(() => ({})));
221
+ if (!response.ok)
222
+ throw new WriteError(response.status, json.code, json.conflicts);
223
+ return json;
239
224
  },
225
+ onSuccess: (_, request) => reread(request),
226
+ // A conflict's list is read again, so it shows the revisions the refusal names.
227
+ onError: (error, request) => error.status === 409 ? reread(request) : undefined,
240
228
  });
241
229
  }
package/dist/schema.d.ts CHANGED
@@ -12,4 +12,19 @@ export declare const Research: z.ZodObject<{
12
12
  role: z.ZodOptional<z.ZodString>;
13
13
  pages: z.ZodOptional<z.ZodArray<z.ZodString>>;
14
14
  }, z.core.$strict>>>;
15
+ collections: z.ZodOptional<z.ZodType<{
16
+ [key: string]: {
17
+ mode: "document" | "log";
18
+ body: Record<string, unknown>;
19
+ read: import("./collections.gen.js").components["schemas"]["ReadGrant"][];
20
+ write: import("./collections.gen.js").components["schemas"]["WriteGrant"][];
21
+ };
22
+ }, unknown, z.core.$ZodTypeInternals<{
23
+ [key: string]: {
24
+ mode: "document" | "log";
25
+ body: Record<string, unknown>;
26
+ read: import("./collections.gen.js").components["schemas"]["ReadGrant"][];
27
+ write: import("./collections.gen.js").components["schemas"]["WriteGrant"][];
28
+ };
29
+ }, unknown>>>;
15
30
  }, z.core.$strict>;
package/dist/schema.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { collections } from './collections.gen.js';
1
2
  import { projectIdPattern } from './project-id.js';
2
3
  import { z } from './zod.js';
3
4
  export { Corpus, kinds } from './corpus.js';
@@ -20,6 +21,7 @@ const glob = (stars, rule) => {
20
21
  };
21
22
  const dataGlob = glob(`${other}(?:\\*${other})?`, 'has at most one *');
22
23
  const privateGlob = glob(`${other}\\*${other}`, 'has exactly one *');
24
+ const collectionsSchema = z.fromJSONSchema(collections);
23
25
  export const Research = z
24
26
  .strictObject({
25
27
  title: z.string().min(1),
@@ -39,6 +41,7 @@ export const Research = z
39
41
  pages: z.array(page).optional(),
40
42
  }))
41
43
  .optional(),
44
+ collections: collectionsSchema.optional(),
42
45
  })
43
46
  .superRefine(({ data, private: held = {}, roles, people = {} }, ctx) => {
44
47
  for (const [username, person] of Object.entries(people)) {
@@ -63,4 +66,21 @@ export const Research = z
63
66
  path: ['private', name],
64
67
  message: `dataset "${name}" is in data and private`,
65
68
  });
69
+ })
70
+ // The API's manifest checks: each role a grant names is declared, and each gate is a log.
71
+ .superRefine(({ roles, collections = {} }, ctx) => {
72
+ for (const [name, collection] of Object.entries(collections))
73
+ for (const kind of ['read', 'write'])
74
+ collection[kind].forEach(({ roles: named = [], after }, i) => {
75
+ const issue = (message) => ctx.addIssue({
76
+ code: 'custom',
77
+ path: ['collections', name, kind, i],
78
+ message,
79
+ });
80
+ for (const role of named)
81
+ if (!roles?.includes(role))
82
+ issue(`role "${role}" is not in roles`);
83
+ if (after && collections[after.collection]?.mode !== 'log')
84
+ issue(`gate collection "${after.collection}" is not a log`);
85
+ });
66
86
  });