@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 +41 -19
- package/dist/collection-store.d.ts +31 -0
- package/dist/collection-store.js +174 -0
- package/dist/collections.gen.d.ts +309 -0
- package/dist/collections.gen.js +190 -0
- package/dist/commands/dev.js +40 -41
- package/dist/context.d.ts +2 -2
- package/dist/context.js +2 -2
- package/dist/corpus.d.ts +8 -8
- package/dist/data.d.ts +8 -0
- package/dist/data.js +2 -2
- package/dist/datasets.d.ts +3 -1
- package/dist/datasets.js +39 -6
- package/dist/dev/host.js +6 -9
- package/dist/host.d.ts +15 -2
- package/dist/host.js +23 -3
- package/dist/index.d.ts +2 -3
- package/dist/index.js +1 -2
- package/dist/mount.d.ts +8 -5
- package/dist/mount.js +12 -6
- package/dist/parity.d.ts +25 -0
- package/dist/parity.js +70 -0
- package/dist/playwright.d.ts +1 -1
- package/dist/playwright.js +6 -2
- package/dist/react.d.ts +20 -23
- package/dist/react.js +77 -89
- package/dist/schema.d.ts +15 -0
- package/dist/schema.js +20 -0
- package/dist/testing.d.ts +25 -10
- package/dist/testing.js +64 -26
- package/dist/types.d.ts +43 -22
- package/dist/urls.d.ts +35 -0
- package/dist/urls.js +58 -0
- package/dist/vite.d.ts +3 -2
- package/dist/vite.js +26 -22
- package/package.json +9 -2
- package/schema/research.schema.json +126 -0
- package/dist/document-store.d.ts +0 -14
- package/dist/document-store.js +0 -78
- package/dist/documents.d.ts +0 -10
- package/dist/documents.js +0 -22
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,
|
|
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,
|
|
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,
|
|
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`
|
|
27
|
-
* which `useData` and `usePrivate
|
|
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`
|
|
22
|
-
* which `useData` and `usePrivate
|
|
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 {
|
|
29
|
+
return {
|
|
30
|
+
path,
|
|
31
|
+
routes,
|
|
32
|
+
datasets: datasets ?? {},
|
|
33
|
+
collections: collections ?? {},
|
|
34
|
+
};
|
|
29
35
|
}
|
package/dist/parity.d.ts
ADDED
|
@@ -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
|
+
}
|
package/dist/playwright.d.ts
CHANGED
|
@@ -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 `
|
|
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 };
|
package/dist/playwright.js
CHANGED
|
@@ -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,
|
|
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({
|
|
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 {
|
|
2
|
-
import type { Corpus, Data,
|
|
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
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
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
|
|
3
|
-
import {
|
|
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: () =>
|
|
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: () =>
|
|
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
|
-
/**
|
|
149
|
-
function
|
|
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
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
}
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
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
|
-
})
|
|
182
|
+
});
|
|
183
|
+
return {
|
|
184
|
+
items: data,
|
|
185
|
+
refresh: () => client.refetchQueries({ queryKey: key, exact: true }, { throwOnError: true }),
|
|
186
|
+
};
|
|
195
187
|
}
|
|
196
|
-
/**
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
*/
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
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
|
-
|
|
214
|
-
|
|
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: (
|
|
224
|
-
const
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
const
|
|
232
|
-
if (
|
|
233
|
-
throw new
|
|
234
|
-
return
|
|
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
|
});
|