@metacensus/library-research 0.11.0 → 0.12.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.
@@ -0,0 +1,78 @@
1
+ import { idPattern, prefixPattern, documentId } from './documents.js';
2
+ const limit = 256 * 1024;
3
+ const json = (status, value, revision) => new Response(JSON.stringify(value), {
4
+ status,
5
+ headers: {
6
+ 'Content-Type': 'application/json',
7
+ 'Cache-Control': 'private, no-cache',
8
+ ...(revision === undefined ? {} : { ETag: `"${revision}"` }),
9
+ },
10
+ });
11
+ const refuse = (status, why) => new Response(why, { status, headers: { 'Content-Type': 'text/plain' } });
12
+ /**
13
+ * The project's document store as service-api-research answers it: the same
14
+ * routes, envelope, id grammar, size limit and conditions, held in memory. The
15
+ * dev host and the test host serve their documents from it.
16
+ */
17
+ export function documentStore(seed = {}, seedWriter = 'test') {
18
+ const docs = new Map();
19
+ let revision = 0;
20
+ for (const [id, { body, writer = seedWriter }] of Object.entries(seed))
21
+ docs.set(documentId(id), { id, writer, revision: ++revision, body });
22
+ /** Every document, sorted by id. */
23
+ const all = () => [...docs.values()].sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
24
+ async function put(request, id, writer) {
25
+ if (!idPattern.test(id))
26
+ return refuse(400, `${id}: not a document id`);
27
+ if (!request.headers.get('Content-Type')?.startsWith('application/json'))
28
+ return refuse(415, 'the body is not application/json');
29
+ const match = request.headers.get('If-Match');
30
+ const none = request.headers.get('If-None-Match');
31
+ if ((match !== null && !/^"\d+"$/.test(match)) ||
32
+ (none !== null && none !== '*'))
33
+ return refuse(400, 'a condition header is malformed');
34
+ const text = await request.text();
35
+ if (new TextEncoder().encode(text).length > limit)
36
+ return refuse(413, `the body is over ${limit} bytes`);
37
+ let body;
38
+ try {
39
+ body = JSON.parse(text);
40
+ }
41
+ catch {
42
+ return refuse(400, 'the body is not valid JSON');
43
+ }
44
+ const held = docs.get(id);
45
+ if ((none !== null && held) ||
46
+ (match !== null && held?.revision !== Number(match.slice(1, -1))))
47
+ return refuse(412, 'a condition does not hold');
48
+ const doc = { id, writer, revision: ++revision, body };
49
+ docs.set(id, doc);
50
+ return json(held ? 200 : 201, doc, doc.revision);
51
+ }
52
+ return {
53
+ /** Answers a request for `/documents[/id]`; `writer` is the session's person. */
54
+ async handle(request, writer) {
55
+ const { pathname, searchParams } = new URL(request.url);
56
+ const id = pathname.match(/\/documents(?:\/([^/]*))?$/)?.[1];
57
+ if (request.method === 'PUT' && id !== undefined)
58
+ return put(request, id, writer);
59
+ if (request.method !== 'GET')
60
+ return refuse(405, 'method not allowed');
61
+ if (id === undefined) {
62
+ const prefix = searchParams.get('prefix') ?? '';
63
+ if (!prefixPattern.test(prefix))
64
+ return refuse(400, `${prefix}: not a document prefix`);
65
+ return json(200, {
66
+ items: all().filter((doc) => doc.id.startsWith(prefix)),
67
+ });
68
+ }
69
+ if (!idPattern.test(id))
70
+ return refuse(400, `${id}: not a document id`);
71
+ const doc = docs.get(id);
72
+ return doc
73
+ ? json(200, doc, doc.revision)
74
+ : refuse(404, 'no such document');
75
+ },
76
+ all,
77
+ };
78
+ }
@@ -0,0 +1,10 @@
1
+ /** A document request the host answered with a status the library does not read as data. */
2
+ export declare class DocumentError extends Error {
3
+ /** The HTTP status: 412 when a condition did not hold, 413 over the size limit. */
4
+ status: number;
5
+ constructor(status: number, message: string);
6
+ }
7
+ export declare const idPattern: RegExp;
8
+ export declare const prefixPattern: RegExp;
9
+ export declare function documentId(id: string): string;
10
+ export declare function documentPrefix(prefix: string): string;
@@ -0,0 +1,22 @@
1
+ /** A document request the host answered with a status the library does not read as data. */
2
+ export class DocumentError extends Error {
3
+ /** The HTTP status: 412 when a condition did not hold, 413 over the size limit. */
4
+ status;
5
+ constructor(status, message) {
6
+ super(message);
7
+ this.name = 'DocumentError';
8
+ this.status = status;
9
+ }
10
+ }
11
+ export const idPattern = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
12
+ export const prefixPattern = /^[A-Za-z0-9._-]*$/;
13
+ export function documentId(id) {
14
+ if (!idPattern.test(id))
15
+ throw new Error(`document id "${id}": must match ${idPattern}`);
16
+ return id;
17
+ }
18
+ export function documentPrefix(prefix) {
19
+ if (!prefixPattern.test(prefix))
20
+ throw new Error(`document prefix "${prefix}": must match ${prefixPattern}`);
21
+ return prefix;
22
+ }
package/dist/host.d.ts ADDED
@@ -0,0 +1,17 @@
1
+ import { type AnyRoute, type ErrorComponentProps } from '@tanstack/react-router';
2
+ import type { Host, Routes } from './types.js';
3
+ export type { Host };
4
+ export { pdfAssets } from './pdf.js';
5
+ declare function Failed({ error, reset }: ErrorComponentProps): import("react").JSX.Element;
6
+ /**
7
+ * The route options of a host's route at `/$project`: the project's `Host`
8
+ * from `useHost`, a resettable error boundary, and a loading state announced
9
+ * to screen readers. Spread into `createRoute`.
10
+ */
11
+ export declare function frame(useHost: () => Host): {
12
+ component: () => import("react").JSX.Element;
13
+ errorComponent: typeof Failed;
14
+ pendingComponent: () => import("react").JSX.Element;
15
+ };
16
+ /** Mounts a project's routes under `parent`, a route at `/$project`; returns `parent`. */
17
+ export declare function mountRoutes(parent: AnyRoute, routes: Routes): import("@tanstack/router-core").Route<any, any, any, any, any, any, any, any, any, any, any, any, any, readonly AnyRoute[], any, any, any, any>;
package/dist/host.js ADDED
@@ -0,0 +1,31 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { Button, Notice } from '@metacensus/library-ui';
3
+ import { useQueryErrorResetBoundary } from '@tanstack/react-query';
4
+ import { Outlet, } from '@tanstack/react-router';
5
+ import { HostContext } from './context.js';
6
+ export { pdfAssets } from './pdf.js';
7
+ function Failed({ error, reset }) {
8
+ const queries = useQueryErrorResetBoundary();
9
+ return (_jsx(Notice, { role: "alert", title: error instanceof Error ? error.message : String(error), children: _jsx(Button, { onClick: () => {
10
+ queries.reset();
11
+ reset();
12
+ }, children: "Try again" }) }));
13
+ }
14
+ /**
15
+ * The route options of a host's route at `/$project`: the project's `Host`
16
+ * from `useHost`, a resettable error boundary, and a loading state announced
17
+ * to screen readers. Spread into `createRoute`.
18
+ */
19
+ export function frame(useHost) {
20
+ return {
21
+ component: function Frame() {
22
+ return (_jsx(HostContext.Provider, { value: useHost(), children: _jsx(Outlet, {}) }));
23
+ },
24
+ errorComponent: Failed,
25
+ pendingComponent: () => _jsx("p", { role: "status", children: "Loading\u2026" }),
26
+ };
27
+ }
28
+ /** Mounts a project's routes under `parent`, a route at `/$project`; returns `parent`. */
29
+ export function mountRoutes(parent, routes) {
30
+ return parent.addChildren(routes(parent));
31
+ }
package/dist/index.d.ts CHANGED
@@ -1,2 +1,3 @@
1
- export type { Corpus, Host, Kind, Location, Paper, Project, Reader, } from './types.js';
2
- export { Link, ResearchProvider, useCorpus, useData, useDatas, useHost, } from './react.js';
1
+ export type { Corpus, Doc, Host, Kind, Paper, Mount, Reader, RouterOf, Routes, } from './types.js';
2
+ export { useCorpus, useData, useDatas, useDocument, useDocuments, useHost, usePrivate, useSaveDocument, } from './react.js';
3
+ export { DocumentError } from './documents.js';
package/dist/index.js CHANGED
@@ -1 +1,2 @@
1
- export { Link, ResearchProvider, useCorpus, useData, useDatas, useHost, } from './react.js';
1
+ export { useCorpus, useData, useDatas, useDocument, useDocuments, useHost, usePrivate, useSaveDocument, } from './react.js';
2
+ export { DocumentError } from './documents.js';
@@ -0,0 +1,14 @@
1
+ import { type AnyRoute } from '@tanstack/react-router';
2
+ /** A host's route at `/$project`, under which a project's routes mount. */
3
+ export declare function createMount(): {
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
+ mount: 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>, "$project", "/$project", string, "/$project", undefined, import("@tanstack/react-router").ResolveParams<"$project">, import("@tanstack/react-router").AnyContext, import("@tanstack/react-router").AnyContext, import("@tanstack/react-router").AnyContext, {}, undefined, unknown, unknown, unknown, unknown, undefined>;
6
+ };
7
+ declare function routerOf<C extends readonly AnyRoute[]>(children: C): import("@tanstack/router-core").RouterCore<import("@tanstack/router-core").Route<import("@tanstack/react-router").Register, any, "/", "/", string, "__root__", undefined, {}, {}, import("@tanstack/react-router").AnyContext, import("@tanstack/react-router").AnyContext, {}, undefined, readonly [import("@tanstack/router-core").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>, "$project", "/$project", string, "/$project", undefined, import("@tanstack/react-router").ResolveParams<"$project">, import("@tanstack/react-router").AnyContext, import("@tanstack/react-router").AnyContext, import("@tanstack/react-router").AnyContext, {}, undefined, C, unknown, unknown, unknown, undefined>], unknown, unknown, unknown, undefined>, "never", false, import("@tanstack/history").RouterHistory, Record<string, any>>;
8
+ /** The parent a project's routes are created against; they type as `/$project/…`. */
9
+ export type Mount = ReturnType<typeof createMount>['mount'];
10
+ /** What `ui/index.tsx` and `ui/local/index.tsx` default-export. */
11
+ export type Routes = (parent: Mount) => readonly AnyRoute[];
12
+ /** A project's `Register`: `router: RouterOf<typeof routes>`. */
13
+ export type RouterOf<R extends Routes> = ReturnType<typeof routerOf<ReturnType<R>>>;
14
+ export {};
package/dist/mount.js ADDED
@@ -0,0 +1,15 @@
1
+ import { createRootRoute, createRoute, createRouter, } from '@tanstack/react-router';
2
+ /** A host's route at `/$project`, under which a project's routes mount. */
3
+ export function createMount() {
4
+ const root = createRootRoute();
5
+ const mount = createRoute({ getParentRoute: () => root, path: '$project' });
6
+ return { root, mount };
7
+ }
8
+ // Only `typeof routerOf` is read: it names the router a project's routes make.
9
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
10
+ function routerOf(children) {
11
+ const { root, mount } = createMount();
12
+ return createRouter({
13
+ routeTree: root.addChildren([mount.addChildren(children)]),
14
+ });
15
+ }
package/dist/papers.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { spawnSync } from 'node:child_process';
2
2
  import { extname } from 'node:path';
3
- import { readCorpus } from './roles.js';
3
+ import { readCorpus } from './data.js';
4
4
  import { kinds } from './schema.js';
5
5
  export function git(root, ...args) {
6
6
  const { status, stdout, stderr, error } = spawnSync('git', args, {
package/dist/pdf.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ /** Where a host serves library-ui's `pdf-assets/`. */
2
+ export declare const pdfAssets = "/pdfjs/";
package/dist/pdf.js ADDED
@@ -0,0 +1,2 @@
1
+ /** Where a host serves library-ui's `pdf-assets/`. */
2
+ export const pdfAssets = '/pdfjs/';
@@ -1,8 +1,10 @@
1
- import { expect } from '@playwright/test';
1
+ import { expect, type Page } from '@playwright/test';
2
2
  declare const _default: import("@playwright/test").PlaywrightTestConfig<{}, {}>;
3
3
  export default _default;
4
4
  type Violation = `csp ${string} ${string}` | `axe ${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. */
8
+ as: (reader: string | null) => Promise<Page>;
7
9
  }, import("@playwright/test").PlaywrightWorkerArgs & import("@playwright/test").PlaywrightWorkerOptions>;
8
10
  export { expect };
@@ -1,5 +1,6 @@
1
1
  import AxeBuilder from '@axe-core/playwright';
2
- import { defineConfig, expect, test as base } from '@playwright/test';
2
+ import { defineConfig, expect, test as base, } from '@playwright/test';
3
+ import { readerCookie } from './reader.js';
3
4
  const report = 'libraryResearchViolation';
4
5
  const sent = 'libraryResearchSent';
5
6
  const server = `const index = require('node:url').pathToFileURL(require.resolve('@metacensus/library-research')); import(new URL('commands/dev.js', index)).then((dev) => dev.default(['--port', '0']))`;
@@ -11,17 +12,53 @@ export default defineConfig({
11
12
  wait: { stdout: /(?<library_research_url>http:\S+\/project\/)/ },
12
13
  },
13
14
  });
15
+ /** Collects a page's CSP and axe violations; the returned function fails on those not listed. */
16
+ async function watch(page) {
17
+ const found = [];
18
+ await page.exposeFunction(report, (v) => found.push(v));
19
+ await page.addInitScript(`window.${sent} = []; document.addEventListener('securitypolicyviolation', (e) => ${sent}.push(${report}('csp ' + e.effectiveDirective + ' ' + e.blockedURI)))`);
20
+ return async (listed) => {
21
+ await page.evaluate(`Promise.all(window.${sent} ?? [])`);
22
+ const axe = await new AxeBuilder({ page }).analyze();
23
+ found.push(...axe.violations.map((v) => `axe ${v.id}`));
24
+ expect(found.filter((v) => !listed.includes(v)), 'unlisted violations').toEqual([]);
25
+ };
26
+ }
14
27
  export const test = base.extend({
15
28
  violations: [[], { option: true }],
16
29
  page: async ({ page, violations }, provide) => {
17
- const found = [];
18
- await page.exposeFunction(report, (v) => found.push(v));
19
- await page.addInitScript(`window.${sent} = []; document.addEventListener('securitypolicyviolation', (e) => ${sent}.push(${report}('csp ' + e.effectiveDirective + ' ' + e.blockedURI)))`);
30
+ const finish = await watch(page);
20
31
  await provide(page);
21
- await page.evaluate(`Promise.all(window.${sent} ?? [])`);
22
- const axe = await new AxeBuilder({ page }).analyze();
23
- found.push(...axe.violations.map((v) => `axe ${v.id}`));
24
- expect(found.filter((v) => !violations.includes(v)), 'unlisted violations').toEqual([]);
32
+ await finish(violations);
33
+ },
34
+ as: async ({ browser, baseURL, contextOptions, violations }, provide) => {
35
+ const finishers = [];
36
+ const contexts = [];
37
+ try {
38
+ await provide(async (reader) => {
39
+ const context = await browser.newContext({ ...contextOptions, baseURL });
40
+ contexts.push(context);
41
+ await context.addCookies([
42
+ {
43
+ name: readerCookie,
44
+ value: encodeURIComponent(reader ?? ''),
45
+ domain: new URL(baseURL).hostname,
46
+ path: '/',
47
+ },
48
+ ]);
49
+ const page = await context.newPage();
50
+ finishers.push(await watch(page));
51
+ return page;
52
+ });
53
+ // Every page is checked, and the first failure is the one thrown.
54
+ const results = await Promise.allSettled(finishers.map((finish) => finish(violations)));
55
+ for (const result of results)
56
+ if (result.status === 'rejected')
57
+ throw result.reason;
58
+ }
59
+ finally {
60
+ await Promise.all(contexts.map((context) => context.close()));
61
+ }
25
62
  },
26
63
  });
27
64
  export { expect };
package/dist/react.d.ts CHANGED
@@ -1,8 +1,5 @@
1
- import { type AnchorHTMLAttributes, type PropsWithChildren } from 'react';
2
- import type { Corpus, Host } from './types.js';
3
- export declare function ResearchProvider({ host, children, }: PropsWithChildren<{
4
- host: Host;
5
- }>): import("react").JSX.Element;
1
+ import { DocumentError } from './documents.js';
2
+ import type { Corpus, Doc, Host } from './types.js';
6
3
  export declare function useHost(): Host;
7
4
  type Role<T = unknown> = readonly [role: string, parse: (json: unknown) => T];
8
5
  /** `parse` must be pure: it is read once per role list, not on every render. */
@@ -11,9 +8,33 @@ export declare function useData<T>(role: string, parse: (json: unknown) => T): T
11
8
  export declare function useDatas<const R extends readonly Role[]>(roles: R): {
12
9
  -readonly [K in keyof R]: R[K] extends Role<infer T> ? T : never;
13
10
  };
11
+ /**
12
+ * The viewed person's pages of a private role, as `{ page: parsed }`: empty
13
+ * when they hold none, a page the host names but the build did not emit left
14
+ * out. `parse` runs on each page's JSON and must be pure. Its cache entry,
15
+ * `{ json } | null`, is not `useData`'s raw JSON, under the same key prefix.
16
+ */
17
+ export declare function usePrivate<T>(role: string, parse: (json: unknown) => T): Record<string, T>;
14
18
  export declare function useCorpus(): Corpus;
15
- export declare const Link: import("react").ForwardRefExoticComponent<{
16
- to: string;
17
- replace?: boolean;
18
- } & Omit<AnchorHTMLAttributes<HTMLAnchorElement>, "href"> & import("react").RefAttributes<HTMLAnchorElement>>;
19
+ /**
20
+ * One document of the project, or `null` when none has that id. Suspends while
21
+ * it loads; a failed read throws a `DocumentError` to the frame's error
22
+ * notice. `parse` runs on the body only and must be pure.
23
+ */
24
+ export declare function useDocument<T>(id: string, parse: (json: unknown) => T): Doc<T> | null;
25
+ /**
26
+ * The project's documents whose id starts with `prefix`, sorted by id; every
27
+ * save of the project refetches them. `parse` runs on each body and must be pure.
28
+ */
29
+ export declare function useDocuments<T>(prefix: string, parse: (json: unknown) => T): Doc<T>[];
30
+ /**
31
+ * Saves a JSON `body` as the document `id`, written by the signed-in person.
32
+ * `when` makes the save conditional: `'absent'` refuses (412) if the document
33
+ * exists, a revision refuses unless the document is at it; without it the
34
+ * save replaces. A failure is the mutation's `error`, a `DocumentError`.
35
+ */
36
+ export declare function useSaveDocument(id: string): import("@tanstack/react-query").UseMutationResult<Doc<unknown>, DocumentError, {
37
+ body: unknown;
38
+ when?: "absent" | number;
39
+ }, unknown>;
19
40
  export {};
package/dist/react.js CHANGED
@@ -1,15 +1,12 @@
1
- import { jsx as _jsx } from "react/jsx-runtime";
2
- import { useSuspenseQueries } from '@tanstack/react-query';
3
- import { createContext, forwardRef, useContext, useMemo, useState, } from 'react';
1
+ import { useMutation, useQueryClient, useSuspenseQueries, useSuspenseQuery, } from '@tanstack/react-query';
2
+ import { useContext, useMemo, useState } from 'react';
3
+ import { FetchContext, HostContext } from './context.js';
4
+ import { DocumentError, documentId, documentPrefix } from './documents.js';
4
5
  import * as schema from './schema.js';
5
- const HostContext = createContext(null);
6
- export function ResearchProvider({ host, children, }) {
7
- return _jsx(HostContext.Provider, { value: host, children: children });
8
- }
9
6
  export function useHost() {
10
7
  const host = useContext(HostContext);
11
8
  if (!host)
12
- throw new Error('useHost outside a ResearchProvider');
9
+ throw new Error('useHost outside the frame of ./host');
13
10
  return host;
14
11
  }
15
12
  /** `parse` must be pure: it is read once per role list, not on every render. */
@@ -31,7 +28,7 @@ export function useDatas(roles) {
31
28
  return parse(json);
32
29
  }
33
30
  catch (cause) {
34
- return failed(role, cause);
31
+ return failed(`data role "${role}"`, cause);
35
32
  }
36
33
  }), [held]);
37
34
  return useSuspenseQueries({
@@ -47,7 +44,7 @@ export function useDatas(roles) {
47
44
  throw new Error(`${response.status} from ${url}`);
48
45
  return response.json();
49
46
  })
50
- .catch((cause) => failed(role, cause)),
47
+ .catch((cause) => failed(`data role "${role}"`, cause)),
51
48
  select: selects[i],
52
49
  staleTime: Infinity,
53
50
  retry: false,
@@ -58,27 +55,153 @@ export function useDatas(roles) {
58
55
  }
59
56
  // Module-level, so combine reruns only when a result changes.
60
57
  const datas = (results) => results.map(({ data }) => data);
61
- function failed(role, cause) {
58
+ function failed(what, cause) {
62
59
  const why = cause instanceof Error ? cause.message : String(cause);
63
- throw new Error(`data role "${role}": ${why}`, { cause });
60
+ throw new Error(`${what}: ${why}`, { cause });
61
+ }
62
+ /**
63
+ * The viewed person's pages of a private role, as `{ page: parsed }`: empty
64
+ * when they hold none, a page the host names but the build did not emit left
65
+ * out. `parse` runs on each page's JSON and must be pure. Its cache entry,
66
+ * `{ json } | null`, is not `useData`'s raw JSON, under the same key prefix.
67
+ */
68
+ export function usePrivate(role, parse) {
69
+ const host = useHost();
70
+ const urls = host.private(role);
71
+ const pages = Object.keys(urls);
72
+ const key = pages.join();
73
+ const held = useHeld(role, parse);
74
+ const selects = useMemo(() => pages.map((page) => (found) => {
75
+ if (!found)
76
+ return null;
77
+ try {
78
+ return { value: held(found.json) };
79
+ }
80
+ catch (cause) {
81
+ return failed(`private role "${role}" page "${page}"`, cause);
82
+ }
83
+ }),
84
+ // The pages are named by `key`.
85
+ // eslint-disable-next-line react-hooks/exhaustive-deps
86
+ [held, key]);
87
+ return useSuspenseQueries({
88
+ queries: pages.map((page, i) => {
89
+ const url = urls[page];
90
+ return {
91
+ queryKey: ['research', url],
92
+ queryFn: () => fetch(url)
93
+ .then((response) => {
94
+ if (response.status === 401 || response.status === 403)
95
+ host.sessionLost();
96
+ if (response.status === 404)
97
+ return null;
98
+ if (!response.ok)
99
+ throw new Error(`${response.status} from ${url}`);
100
+ return response.json().then((json) => ({ json }));
101
+ })
102
+ .catch((cause) => failed(`private role "${role}" page "${page}"`, cause)),
103
+ select: selects[i],
104
+ staleTime: Infinity,
105
+ retry: false,
106
+ };
107
+ }),
108
+ combine: (results) => Object.fromEntries(results.flatMap(({ data }, i) => data ? [[pages[i], data.value]] : [])),
109
+ });
64
110
  }
65
111
  export function useCorpus() {
66
112
  return useData('corpus', (json) => schema.Corpus.parse(json));
67
113
  }
68
- export const Link = forwardRef(function Link({ to, replace, ...a }, ref) {
114
+ /** A fetch whose 401 and 403 are the host's lost session, and whose other failures are a `DocumentError`. */
115
+ function useSend() {
69
116
  const host = useHost();
70
- const onClick = (event) => {
71
- a.onClick?.(event);
72
- if (event.defaultPrevented ||
73
- event.button !== 0 ||
74
- event.metaKey ||
75
- event.ctrlKey ||
76
- event.shiftKey ||
77
- event.altKey ||
78
- (a.target && a.target !== '_self'))
79
- return;
80
- event.preventDefault();
81
- host.navigate(to, { replace });
117
+ const get = useContext(FetchContext) ?? fetch;
118
+ return async (url, init, absent = false) => {
119
+ const response = await get(url, init);
120
+ if (response.status === 401 || response.status === 403)
121
+ host.sessionLost();
122
+ if (absent && response.status === 404)
123
+ return null;
124
+ if (!response.ok)
125
+ throw new DocumentError(response.status, `${response.status} from ${url}`);
126
+ return response.json();
82
127
  };
83
- return _jsx("a", { ...a, ref: ref, href: host.base + to, onClick: onClick });
84
- });
128
+ }
129
+ /** `parse`, held until `key` changes, so an inline one is not read again on every render. */
130
+ function useHeld(key, parse) {
131
+ const [held, hold] = useState({ key, parse });
132
+ if (held.key !== key)
133
+ hold({ key, parse });
134
+ return held.parse;
135
+ }
136
+ const parsed = (parse) => (doc) => {
137
+ try {
138
+ return { ...doc, body: parse(doc.body) };
139
+ }
140
+ catch (cause) {
141
+ const why = cause instanceof Error ? cause.message : String(cause);
142
+ throw new Error(`document "${doc.id}": ${why}`, { cause });
143
+ }
144
+ };
145
+ /**
146
+ * One document of the project, or `null` when none has that id. Suspends while
147
+ * it loads; a failed read throws a `DocumentError` to the frame's error
148
+ * notice. `parse` runs on the body only and must be pure.
149
+ */
150
+ export function useDocument(id, parse) {
151
+ const url = useHost().document(documentId(id));
152
+ const send = useSend();
153
+ const held = useHeld(url, parse);
154
+ const select = useMemo(() => (doc) => doc && parsed(held)(doc), [held]);
155
+ return useSuspenseQuery({
156
+ queryKey: ['research-document', url],
157
+ queryFn: () => send(url, undefined, true),
158
+ select,
159
+ retry: false,
160
+ }).data;
161
+ }
162
+ /**
163
+ * The project's documents whose id starts with `prefix`, sorted by id; every
164
+ * save of the project refetches them. `parse` runs on each body and must be pure.
165
+ */
166
+ export function useDocuments(prefix, parse) {
167
+ const url = useHost().documents(documentPrefix(prefix));
168
+ const send = useSend();
169
+ const held = useHeld(url, parse);
170
+ const select = useMemo(() => ({ items }) => items.map(parsed(held)), [held]);
171
+ return useSuspenseQuery({
172
+ queryKey: ['research-documents', url],
173
+ queryFn: () => send(url),
174
+ select,
175
+ retry: false,
176
+ }).data;
177
+ }
178
+ /**
179
+ * Saves a JSON `body` as the document `id`, written by the signed-in person.
180
+ * `when` makes the save conditional: `'absent'` refuses (412) if the document
181
+ * exists, a revision refuses unless the document is at it; without it the
182
+ * save replaces. A failure is the mutation's `error`, a `DocumentError`.
183
+ */
184
+ export function useSaveDocument(id) {
185
+ const url = useHost().document(documentId(id));
186
+ const send = useSend();
187
+ const client = useQueryClient();
188
+ return useMutation({
189
+ mutationFn: ({ body, when }) => {
190
+ const headers = {
191
+ 'Content-Type': 'application/json',
192
+ };
193
+ if (when === 'absent')
194
+ headers['If-None-Match'] = '*';
195
+ else if (when !== undefined)
196
+ headers['If-Match'] = `"${when}"`;
197
+ const text = JSON.stringify(body);
198
+ if (text === undefined)
199
+ throw new Error(`document "${id}": no JSON body`);
200
+ return send(url, { method: 'PUT', headers, body: text });
201
+ },
202
+ onSuccess: (doc) => {
203
+ client.setQueryData(['research-document', url], doc);
204
+ return client.invalidateQueries({ queryKey: ['research-documents'] });
205
+ },
206
+ });
207
+ }
@@ -0,0 +1,2 @@
1
+ /** The cookie that names the reader of a browser context on a dev server. */
2
+ export declare const readerCookie = "library-research-reader";
package/dist/reader.js ADDED
@@ -0,0 +1,2 @@
1
+ /** The cookie that names the reader of a browser context on a dev server. */
2
+ export const readerCookie = 'library-research-reader';
package/dist/roles.d.ts CHANGED
@@ -1,11 +1,7 @@
1
- /** Reads a project's research.json; each role reads its files when called. */
2
- export declare function project(dir: string): {
3
- title: string;
4
- roles: Record<string, () => unknown>;
5
- };
6
- export declare function readCorpus(dir: string): Record<string, {
7
- kind: "pdf" | "doc" | "docx" | "xls" | "xlsx" | "zip" | "gif" | "jpg" | "tif" | "txt" | "html" | "xml";
8
- title?: string | undefined;
9
- citation?: string | undefined;
10
- open?: true | undefined;
11
- }>;
1
+ /**
2
+ * Reads each data role of the project in `dir`, the folder holding
3
+ * research.json, parsed by its schema in ui/roles.ts, and its corpus. A
4
+ * private role is read as `{ page: parsed }`, its schema parsing one page's
5
+ * file. Throws one line per failure.
6
+ */
7
+ export declare function load(dir: string): Promise<Record<string, unknown>>;