@metacensus/library-research 0.10.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.
Files changed (50) hide show
  1. package/README.md +99 -13
  2. package/csp.json +10 -0
  3. package/dist/cli.js +1 -1
  4. package/dist/commands/add.js +2 -1
  5. package/dist/commands/candidate.js +12 -1
  6. package/dist/commands/check.js +22 -13
  7. package/dist/commands/dev.js +92 -9
  8. package/dist/commands/init.d.ts +1 -0
  9. package/dist/commands/init.js +131 -0
  10. package/dist/context.d.ts +4 -0
  11. package/dist/context.js +4 -0
  12. package/dist/data.d.ts +22 -0
  13. package/dist/data.js +76 -0
  14. package/dist/dev/host.d.ts +1 -1
  15. package/dist/dev/host.js +38 -41
  16. package/dist/document-store.d.ts +14 -0
  17. package/dist/document-store.js +78 -0
  18. package/dist/documents.d.ts +10 -0
  19. package/dist/documents.js +22 -0
  20. package/dist/host.d.ts +17 -0
  21. package/dist/host.js +31 -0
  22. package/dist/index.d.ts +3 -2
  23. package/dist/index.js +2 -1
  24. package/dist/mount.d.ts +14 -0
  25. package/dist/mount.js +15 -0
  26. package/dist/papers.d.ts +0 -6
  27. package/dist/papers.js +8 -21
  28. package/dist/pdf.d.ts +2 -0
  29. package/dist/pdf.js +2 -0
  30. package/dist/playwright.d.ts +3 -1
  31. package/dist/playwright.js +50 -10
  32. package/dist/react.d.ts +32 -9
  33. package/dist/react.js +170 -36
  34. package/dist/reader.d.ts +2 -0
  35. package/dist/reader.js +2 -0
  36. package/dist/roles.d.ts +7 -5
  37. package/dist/roles.js +103 -36
  38. package/dist/router.d.ts +4 -0
  39. package/dist/router.js +16 -0
  40. package/dist/schema.d.ts +1 -0
  41. package/dist/schema.js +15 -2
  42. package/dist/testing.d.ts +29 -0
  43. package/dist/testing.js +46 -0
  44. package/dist/types.d.ts +22 -12
  45. package/dist/vite-config.js +4 -2
  46. package/dist/vite.js +29 -3
  47. package/package.json +28 -4
  48. package/schema/research.schema.json +11 -0
  49. package/src/virtual.d.ts +2 -2
  50. package/tsconfig.project.json +3 -1
package/dist/react.js CHANGED
@@ -1,33 +1,36 @@
1
- import { jsx as _jsx } from "react/jsx-runtime";
2
- import { useSuspenseQueries } from '@tanstack/react-query';
3
- import { createContext, useContext, useMemo, useRef, } 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
  }
12
+ /** `parse` must be pure: it is read once per role list, not on every render. */
15
13
  export function useData(role, parse) {
16
14
  return useDatas([[role, parse]])[0];
17
15
  }
16
+ /** Each parser must be pure: it is read once per role list, not on every render. */
18
17
  export function useDatas(roles) {
19
18
  const host = useHost();
20
- const latest = useRef(roles);
21
- latest.current = roles;
22
- const names = roles.map(([role]) => role);
23
- const selects = useMemo(() => names.map((role, i) => (json) => {
19
+ // The parsers and select functions are kept until the role list changes, so
20
+ // an inline parse does not rerun on every render.
21
+ const key = JSON.stringify(roles.map(([role]) => role));
22
+ const [held, hold] = useState({ key, roles });
23
+ if (held.key !== key)
24
+ hold({ key, roles });
25
+ const names = held.roles.map(([role]) => role);
26
+ const selects = useMemo(() => held.roles.map(([role, parse]) => (json) => {
24
27
  try {
25
- return latest.current[i][1](json);
28
+ return parse(json);
26
29
  }
27
30
  catch (cause) {
28
- return failed(role, cause);
31
+ return failed(`data role "${role}"`, cause);
29
32
  }
30
- }), [JSON.stringify(names)]);
33
+ }), [held]);
31
34
  return useSuspenseQueries({
32
35
  queries: names.map((role, i) => {
33
36
  const url = host.data(role);
@@ -35,39 +38,170 @@ export function useDatas(roles) {
35
38
  queryKey: ['research', url],
36
39
  queryFn: () => fetch(url)
37
40
  .then((response) => {
41
+ if (response.status === 401 || response.status === 403)
42
+ host.sessionLost();
38
43
  if (!response.ok)
39
44
  throw new Error(`${response.status} from ${url}`);
40
45
  return response.json();
41
46
  })
42
- .catch((cause) => failed(role, cause)),
47
+ .catch((cause) => failed(`data role "${role}"`, cause)),
43
48
  select: selects[i],
44
49
  staleTime: Infinity,
45
50
  retry: false,
46
51
  };
47
52
  }),
48
- }).map(({ data }) => data);
53
+ combine: datas,
54
+ });
55
+ }
56
+ // Module-level, so combine reruns only when a result changes.
57
+ const datas = (results) => results.map(({ data }) => data);
58
+ function failed(what, cause) {
59
+ const why = cause instanceof Error ? cause.message : String(cause);
60
+ throw new Error(`${what}: ${why}`, { cause });
49
61
  }
50
- function failed(role, cause) {
51
- const why = cause instanceof Error ? cause.message : cause;
52
- throw new Error(`data role "${role}": ${why}`, { cause });
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
+ });
53
110
  }
54
111
  export function useCorpus() {
55
- return useData('corpus', schema.Corpus.parse);
112
+ return useData('corpus', (json) => schema.Corpus.parse(json));
56
113
  }
57
- export function Link({ to, replace, ...a }) {
58
- const { base, navigate } = useHost();
59
- const onClick = (event) => {
60
- a.onClick?.(event);
61
- if (event.defaultPrevented ||
62
- event.button !== 0 ||
63
- event.metaKey ||
64
- event.ctrlKey ||
65
- event.shiftKey ||
66
- event.altKey ||
67
- (a.target && a.target !== '_self'))
68
- return;
69
- event.preventDefault();
70
- navigate(to, { replace });
114
+ /** A fetch whose 401 and 403 are the host's lost session, and whose other failures are a `DocumentError`. */
115
+ function useSend() {
116
+ const host = useHost();
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();
71
127
  };
72
- return _jsx("a", { ...a, href: base + to, onClick: onClick });
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
+ });
73
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,5 +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
- };
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>>;
package/dist/roles.js CHANGED
@@ -1,42 +1,109 @@
1
- import { globSync, readFileSync } from 'node:fs';
1
+ import { lstatSync, readFileSync } from 'node:fs';
2
2
  import { join } from 'node:path';
3
- import { z } from 'zod';
4
- import { Corpus, Research } from './schema.js';
5
- /** Reads a project's research.json; each role reads its files when called. */
6
- export function project(dir) {
7
- const { title, data } = read(dir, 'research.json', Research);
8
- const roles = {
9
- corpus: () => read(dir, 'corpus.json', Corpus),
10
- };
11
- for (const [role, glob] of Object.entries(data))
12
- roles[role] = () => match(dir, glob);
13
- return { title, roles };
14
- }
15
- function match(dir, glob) {
16
- const files = globSync(glob, { cwd: dir }).sort();
17
- if (!files.length)
18
- throw new Error(`${join(dir, glob)}: matches no file`);
19
- const head = glob.indexOf('*');
20
- if (head < 0)
21
- return read(dir, files[0]);
22
- const tail = glob.length - glob.lastIndexOf('*') - 1;
23
- const key = (file) => file.slice(head, file.length - tail).replace(/^[./]+|[./]+$/g, '');
24
- return Object.fromEntries(files.map((file) => [key(file), read(dir, file)]));
3
+ import { pathToFileURL } from 'node:url';
4
+ import { files, match, privatePages, read, readCorpus } from './data.js';
5
+ import { Research } from './schema.js';
6
+ const schemaFile = 'ui/roles.ts';
7
+ /** The `roles` ui/roles.ts exports, which Node loads by stripping its types. */
8
+ async function schemas(dir) {
9
+ const path = join(dir, schemaFile);
10
+ if (!lstatSync(path, { throwIfNoEntry: false }))
11
+ return {};
12
+ const manifest = join(dir, 'ui/package.json');
13
+ const { type } = JSON.parse(readFileSync(manifest, 'utf8'));
14
+ if (type !== 'module')
15
+ throw new Error(`${manifest}: needs "type": "module" for ${schemaFile}`);
16
+ let roles;
17
+ try {
18
+ roles = (await import(pathToFileURL(path).href))
19
+ .roles;
20
+ }
21
+ catch (error) {
22
+ throw new Error(`${path}: ${error.message.split('\n')[0]}`);
23
+ }
24
+ if (typeof roles !== 'object' || !roles)
25
+ throw new Error(`${path}: exports no roles object`);
26
+ return roles;
25
27
  }
26
- function read(dir, file, schema) {
27
- const path = join(dir, file);
28
- const fail = (why) => new Error(`${path}: ${why}`);
29
- let json;
28
+ /**
29
+ * Reads each data role of the project in `dir`, the folder holding
30
+ * research.json, parsed by its schema in ui/roles.ts, and its corpus. A
31
+ * private role is read as `{ page: parsed }`, its schema parsing one page's
32
+ * file. Throws one line per failure.
33
+ */
34
+ export async function load(dir) {
35
+ const { data, private: held = {} } = read(dir, 'research.json', Research);
36
+ const found = await schemas(dir);
37
+ const loaded = {};
38
+ const failures = [];
39
+ for (const role of Object.keys(found))
40
+ if (!Object.hasOwn(data, role) && !Object.hasOwn(held, role))
41
+ failures.push(`${join(dir, schemaFile)}: schema for "${role}", which research.json does not name`);
42
+ for (const [role, glob] of Object.entries(data)) {
43
+ try {
44
+ const matched = files(dir, glob);
45
+ const value = match(dir, matched);
46
+ const schema = Object.hasOwn(found, role) ? found[role] : undefined;
47
+ if (typeof schema?.safeParse !== 'function') {
48
+ failures.push(`${role}: no schema in ${schemaFile}`);
49
+ continue;
50
+ }
51
+ const parsed = schema.safeParse(value);
52
+ if (parsed.success)
53
+ loaded[role] = parsed.data;
54
+ else {
55
+ const byPlace = new Map();
56
+ for (const { path, message } of parsed.error.issues) {
57
+ const entry = matched.keyed
58
+ ? matched.entries.find(([, key]) => key === String(path[0]))
59
+ : matched.entries[0];
60
+ const rest = entry && matched.keyed ? path.slice(1) : path;
61
+ const place = join(dir, entry?.[0] ?? glob);
62
+ byPlace.set(place, [
63
+ ...(byPlace.get(place) ?? []),
64
+ rest.length ? `${rest.map(String).join('.')}: ${message}` : message,
65
+ ]);
66
+ }
67
+ for (const [place, issues] of byPlace)
68
+ failures.push(`${place}: ${role}: ${issues.join('; ')}`);
69
+ }
70
+ }
71
+ catch (error) {
72
+ failures.push(error.message);
73
+ }
74
+ }
75
+ for (const [role, glob] of Object.entries(held)) {
76
+ try {
77
+ const schema = Object.hasOwn(found, role) ? found[role] : undefined;
78
+ if (typeof schema?.safeParse !== 'function') {
79
+ failures.push(`${role}: no schema in ${schemaFile}`);
80
+ continue;
81
+ }
82
+ const pages = {};
83
+ for (const [page, file] of Object.entries(privatePages(dir, role, glob))) {
84
+ const parsed = schema.safeParse(read(dir, file));
85
+ if (parsed.success)
86
+ pages[page] = parsed.data;
87
+ else
88
+ failures.push(`${join(dir, file)}: ${role}: ${parsed
89
+ .error.issues.map(({ path, message }) => path.length
90
+ ? `${path.map(String).join('.')}: ${message}`
91
+ : message)
92
+ .join('; ')}`);
93
+ }
94
+ loaded[role] = pages;
95
+ }
96
+ catch (error) {
97
+ failures.push(error.message);
98
+ }
99
+ }
30
100
  try {
31
- json = JSON.parse(readFileSync(path, 'utf8'));
101
+ loaded.corpus = readCorpus(dir);
32
102
  }
33
- catch (e) {
34
- throw fail(e.message);
103
+ catch (error) {
104
+ failures.push(error.message);
35
105
  }
36
- if (!schema)
37
- return json;
38
- const checked = schema.safeParse(json);
39
- if (!checked.success)
40
- throw fail(z.prettifyError(checked.error));
41
- return checked.data;
106
+ if (failures.length)
107
+ throw new Error(failures.join('\n'));
108
+ return loaded;
42
109
  }
@@ -0,0 +1,4 @@
1
+ import { type RouterHistory } from '@tanstack/react-router';
2
+ import type { Host, Routes } from './types.js';
3
+ /** A project's routes under `/$project`, in the frame a real host uses; shared by the dev host and the test host. */
4
+ export declare function projectRouter(routes: Routes, useHost: () => Host, history?: RouterHistory): 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<any, any, any, any, any, any, any, any, any, any, any, any, any, readonly import("@tanstack/react-router").AnyRoute[], any, any, any, any>], unknown, unknown, unknown, undefined>, "preserve", false, RouterHistory, Record<string, any>>;
package/dist/router.js ADDED
@@ -0,0 +1,16 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { Notice } from '@metacensus/library-ui';
3
+ import { createRouter } from '@tanstack/react-router';
4
+ import { frame, mountRoutes } from './host.js';
5
+ import { createMount } from './mount.js';
6
+ /** A project's routes under `/$project`, in the frame a real host uses; shared by the dev host and the test host. */
7
+ export function projectRouter(routes, useHost, history) {
8
+ const { root, mount } = createMount();
9
+ mount.update(frame(useHost));
10
+ return createRouter({
11
+ routeTree: root.addChildren([mountRoutes(mount, routes)]),
12
+ history,
13
+ trailingSlash: 'preserve',
14
+ defaultNotFoundComponent: () => _jsx(Notice, { role: "alert", title: "Not found" }),
15
+ });
16
+ }
package/dist/schema.d.ts CHANGED
@@ -16,6 +16,7 @@ export declare const kinds: {
16
16
  export declare const Research: z.ZodObject<{
17
17
  title: z.ZodString;
18
18
  data: z.ZodRecord<z.ZodString, z.ZodString>;
19
+ private: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
19
20
  }, z.core.$strict>;
20
21
  export declare const Corpus: z.ZodRecord<z.ZodString, z.ZodObject<{
21
22
  kind: z.ZodEnum<{
package/dist/schema.js CHANGED
@@ -14,9 +14,22 @@ export const kinds = {
14
14
  html: 'text/plain',
15
15
  xml: 'text/plain',
16
16
  };
17
- export const Research = z.strictObject({
17
+ const role = z.string().regex(/^(?!corpus$)[a-z][A-Za-z0-9]*$/);
18
+ const glob = z.string().regex(/^(?!\/)(?!.*\.\.).+$/);
19
+ export const Research = z
20
+ .strictObject({
18
21
  title: z.string().min(1),
19
- data: z.record(z.string().regex(/^(?!corpus$)[a-z][A-Za-z0-9]*$/), z.string().regex(/^(?!\/)(?!.*\.\.).+$/)),
22
+ data: z.record(role, glob),
23
+ private: z.record(role, glob).optional(),
24
+ })
25
+ .superRefine(({ data, private: held = {} }, ctx) => {
26
+ for (const [name, pattern] of Object.entries(held)) {
27
+ const issue = (message) => ctx.addIssue({ code: 'custom', path: ['private', name], message });
28
+ if (Object.hasOwn(data, name))
29
+ issue(`role "${name}" is in data and private`);
30
+ if (pattern.split('*').length !== 2 || /[?[\]{}()!]/.test(pattern))
31
+ issue(`role "${name}": glob "${pattern}" must hold exactly one * and no other glob character`);
32
+ }
20
33
  });
21
34
  export const Corpus = z.record(z.string().regex(/^[0-9a-f]{64}$/), z.strictObject({
22
35
  kind: z.enum(Object.keys(kinds)),
@@ -0,0 +1,29 @@
1
+ import type { ReactElement } from 'react';
2
+ import type { Routes } from './types.js';
3
+ export interface TestHostOptions {
4
+ /** Each data role's JSON value, parsed by the project's own schema. */
5
+ data?: Record<string, unknown>;
6
+ /** Each private role's pages, `{ role: { page: JSON } }`; the reader's page is the one named as the reader. */
7
+ private?: Record<string, Record<string, unknown>>;
8
+ /** Each document the project starts with, by id; `writer` defaults to the reader. */
9
+ documents?: Record<string, {
10
+ body: unknown;
11
+ writer?: string;
12
+ }>;
13
+ /** The reader's username. */
14
+ reader?: string;
15
+ /** The path below the project, with search and hash. */
16
+ url?: string;
17
+ /** Called as `Host.sessionLost` is. */
18
+ sessionLost?: () => void;
19
+ }
20
+ /**
21
+ * A project's routes rendered through the frame and the `/$project` mount a
22
+ * real host uses. Render `element` with any DOM renderer; `router` says where
23
+ * the project navigated, and `documents()` what it saved, sorted by id.
24
+ */
25
+ export declare function testHost(routes: Routes, { data, documents, private: held, reader, url, sessionLost, }?: TestHostOptions): {
26
+ element: ReactElement<any, string | import("react").JSXElementConstructor<any>>;
27
+ router: 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<any, any, any, any, any, any, any, any, any, any, any, any, any, readonly import("@tanstack/react-router").AnyRoute[], any, any, any, any>], unknown, unknown, unknown, undefined>, "preserve", false, import("@tanstack/history").RouterHistory, Record<string, any>>;
28
+ documents: () => import("./types.js").Doc<unknown>[];
29
+ };
@@ -0,0 +1,46 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
3
+ import { createMemoryHistory, RouterProvider } from '@tanstack/react-router';
4
+ import { FetchContext } from './context.js';
5
+ import { documentStore } from './document-store.js';
6
+ import { projectRouter } from './router.js';
7
+ const origin = 'http://test.invalid';
8
+ /**
9
+ * A project's routes rendered through the frame and the `/$project` mount a
10
+ * real host uses. Render `element` with any DOM renderer; `router` says where
11
+ * the project navigated, and `documents()` what it saved, sorted by id.
12
+ */
13
+ export function testHost(routes, { data = {}, documents = {}, private: held = {}, reader = 'test', url = '/', sessionLost = () => { }, } = {}) {
14
+ const store = documentStore(documents, reader);
15
+ const memory = (input, init) => store.handle(new Request(new URL(input instanceof Request ? input.url : input, origin), init), reader);
16
+ const host = {
17
+ reader: { username: reader },
18
+ data(role) {
19
+ if (!Object.hasOwn(data, role) || data[role] === undefined)
20
+ throw new Error(`testHost: no data for role "${role}"`);
21
+ return `data:application/json,${encodeURIComponent(JSON.stringify(data[role]))}`;
22
+ },
23
+ private: (role) => Object.hasOwn(held[role] ?? {}, reader)
24
+ ? {
25
+ [reader]: `data:application/json,${encodeURIComponent(JSON.stringify(held[role][reader]))}`,
26
+ }
27
+ : {},
28
+ paper: (sha) => `/papers/${sha}`,
29
+ document: (id) => `${origin}/documents/${id}`,
30
+ documents: (prefix) => `${origin}/documents?prefix=${prefix}`,
31
+ sessionLost,
32
+ };
33
+ const router = projectRouter(routes, () => host, createMemoryHistory({ initialEntries: [`/project${url}`] }));
34
+ // react-router 1.170.46 reads this in Matches before router-core 1.171.39 sets it.
35
+ // Delete once react-router and router-core are bumped to versions that agree.
36
+ Object.assign(router, { _rendered: [] });
37
+ // Infinite, so no gc timer holds a test runner's process open.
38
+ const client = new QueryClient({
39
+ defaultOptions: {
40
+ queries: { gcTime: Infinity },
41
+ mutations: { gcTime: Infinity },
42
+ },
43
+ });
44
+ const element = (_jsx(QueryClientProvider, { client: client, children: _jsx(FetchContext.Provider, { value: memory, children: _jsx(RouterProvider, { router: router }) }) }));
45
+ return { element, router, documents: store.all };
46
+ }
package/dist/types.d.ts CHANGED
@@ -1,25 +1,35 @@
1
- import type { ComponentType } from 'react';
2
1
  import type { z } from 'zod';
3
2
  import type { Corpus as CorpusSchema, kinds } from './schema.js';
4
- export type Project = ComponentType;
5
3
  export interface Host {
6
4
  reader: Reader;
7
- base: string;
8
- location: Location;
9
- navigate(to: string, options?: {
10
- replace?: boolean;
11
- }): void;
12
5
  data(role: string): string;
6
+ /** The viewed person's pages of a private role: page key to URL; empty when they hold none. */
7
+ private(role: string): Record<string, string>;
13
8
  paper(sha: string): string;
9
+ /**
10
+ * The URL of one document of this project: a GET reads it, a PUT writes it
11
+ * as the signed-in person. `id` matches `^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$`,
12
+ * so the URL needs no encoding.
13
+ */
14
+ document(id: string): string;
15
+ /** The URL a GET lists the project's documents at, those whose id starts with `prefix`, sorted by id. */
16
+ documents(prefix: string): string;
17
+ /** Called each time a data request is answered 401 or 403, so several times for one lost session. */
18
+ sessionLost(): void;
19
+ }
20
+ /** A stored document: what the store records beside the project's `body`. */
21
+ export interface Doc<T> {
22
+ id: string;
23
+ /** The person signed in when it was saved; never the person a reader views the project as. */
24
+ writer: string;
25
+ /** The project's write counter at the save, so it orders every save; `useSaveDocument`'s `when` takes it. */
26
+ revision: number;
27
+ body: T;
14
28
  }
15
29
  export interface Reader {
16
30
  username: string;
17
31
  }
18
- export interface Location {
19
- path: string;
20
- search: string;
21
- hash: string;
22
- }
23
32
  export type Kind = keyof typeof kinds;
24
33
  export type Corpus = z.infer<typeof CorpusSchema>;
25
34
  export type Paper = Corpus[string];
35
+ export type { Mount, RouterOf, Routes } from './mount.js';
@@ -17,13 +17,15 @@ export function hostConfig(root) {
17
17
  ],
18
18
  },
19
19
  },
20
- // The kit's modules stay unbundled so the host and the project share one
21
- // copy; Vite reads no imports inside node_modules, so theirs are listed.
20
+ // library-research's modules stay unbundled so the host and the project
21
+ // share one copy; Vite reads no imports inside node_modules, so theirs are
22
+ // listed.
22
23
  optimizeDeps: {
23
24
  include: [
24
25
  '@metacensus/library-ui',
25
26
  '@metacensus/library-ui/pdf',
26
27
  '@tanstack/react-query',
28
+ '@tanstack/react-router',
27
29
  'react-dom/client',
28
30
  'zod',
29
31
  ],