@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.
@@ -0,0 +1,190 @@
1
+ export const collections = {
2
+ "type": "object",
3
+ "description": "The collections section of a project's manifest, by collection name.\n\nOnly the project's members are ever allowed: a person who is not a member is refused `forbidden`, and a request with no session is refused `unauthenticated`.\n\nA manifest that fails one of these checks is refused whole:\n- each role a grant names is one the project declares;\n- each gate's collection exists and is a `log`;\n- each `body` compiles as JSON Schema.\n",
4
+ "propertyNames": {
5
+ "type": "string",
6
+ "pattern": "^[a-z][a-z0-9-]{0,63}$"
7
+ },
8
+ "additionalProperties": {
9
+ "type": "object",
10
+ "description": "A set of items, each keyed by (writer, id) within the collection. Only an item's writer writes it, so no one can take an id another person is using.\n\nA collection allows a person when any one of its grants holds; an empty list allows no one. A grant holds when all of its conditions hold.\n",
11
+ "additionalProperties": false,
12
+ "required": [
13
+ "mode",
14
+ "body",
15
+ "read",
16
+ "write"
17
+ ],
18
+ "properties": {
19
+ "mode": {
20
+ "type": "string",
21
+ "enum": [
22
+ "document",
23
+ "log"
24
+ ],
25
+ "description": "`document`: a write names the item's expected revision, `0` for a new item, and is refused `stale` unless the item is at that revision. A read returns each item's current revision. Earlier revisions stay stored and count toward the quota, but are never served.\n\n`log`: an entry is written once, at expected revision `0`; any other expected revision is `stale`. A second write of the same (writer, id) is refused `exists`. A read returns every entry, so the log is its writer's history, and no entry is replaced or deleted.\n"
26
+ },
27
+ "body": {
28
+ "type": "object",
29
+ "description": "A JSON Schema, draft 2020-12, that every item body written to the collection must satisfy. It holds no external `$ref`, and `format` is an annotation only."
30
+ },
31
+ "read": {
32
+ "type": "array",
33
+ "description": "The grants that allow a read. A read returns, in the store's sequence order, the items the person may read, which are those for which some grant holds; a member is never refused a read, and may be served nothing.\n",
34
+ "items": {
35
+ "type": "object",
36
+ "description": "A rule allowing a read. It holds when each condition it names holds, and names at least one.",
37
+ "additionalProperties": false,
38
+ "minProperties": 1,
39
+ "properties": {
40
+ "own": {
41
+ "type": "boolean",
42
+ "const": true,
43
+ "description": "The reader wrote the item."
44
+ },
45
+ "roles": {
46
+ "type": "array",
47
+ "minItems": 1,
48
+ "description": "The person's role in the project is one of these. The roles are the ones the project's research.json declares.",
49
+ "items": {
50
+ "type": "string"
51
+ }
52
+ },
53
+ "members": {
54
+ "type": "boolean",
55
+ "const": true,
56
+ "description": "The person opens the project: a member, an admin or a super admin."
57
+ },
58
+ "after": {
59
+ "type": "object",
60
+ "description": "Names one entry of a `log` collection in the same project: the entry with this `id` in this `collection`.\n\nThe first entry with that id opens the gate, whoever wrote it, provided the collection's write grants allowed that writer. Until then every grant that names the gate fails.\n\nA gate never closes: a log entry is never replaced or deleted, and the gate names only a log.\n",
61
+ "additionalProperties": false,
62
+ "required": [
63
+ "collection",
64
+ "id"
65
+ ],
66
+ "properties": {
67
+ "collection": {
68
+ "type": "string",
69
+ "pattern": "^[a-z][a-z0-9-]{0,63}$"
70
+ },
71
+ "id": {
72
+ "type": "string",
73
+ "pattern": "^[A-Za-z0-9][A-Za-z0-9._:-]{0,199}$"
74
+ }
75
+ }
76
+ }
77
+ }
78
+ }
79
+ },
80
+ "write": {
81
+ "type": "array",
82
+ "description": "The grants that allow a write. A write is refused `forbidden` for an item the person may not write.",
83
+ "items": {
84
+ "type": "object",
85
+ "description": "A rule allowing a write. It holds when each condition it names holds, and names at least one.",
86
+ "additionalProperties": false,
87
+ "minProperties": 1,
88
+ "properties": {
89
+ "roles": {
90
+ "type": "array",
91
+ "minItems": 1,
92
+ "description": "The person's role in the project is one of these. The roles are the ones the project's research.json declares.",
93
+ "items": {
94
+ "type": "string"
95
+ }
96
+ },
97
+ "members": {
98
+ "type": "boolean",
99
+ "const": true,
100
+ "description": "The person opens the project: a member, an admin or a super admin."
101
+ },
102
+ "after": {
103
+ "type": "object",
104
+ "description": "Names one entry of a `log` collection in the same project: the entry with this `id` in this `collection`.\n\nThe first entry with that id opens the gate, whoever wrote it, provided the collection's write grants allowed that writer. Until then every grant that names the gate fails.\n\nA gate never closes: a log entry is never replaced or deleted, and the gate names only a log.\n",
105
+ "additionalProperties": false,
106
+ "required": [
107
+ "collection",
108
+ "id"
109
+ ],
110
+ "properties": {
111
+ "collection": {
112
+ "type": "string",
113
+ "pattern": "^[a-z][a-z0-9-]{0,63}$"
114
+ },
115
+ "id": {
116
+ "type": "string",
117
+ "pattern": "^[A-Za-z0-9][A-Za-z0-9._:-]{0,199}$"
118
+ }
119
+ }
120
+ }
121
+ }
122
+ }
123
+ }
124
+ }
125
+ }
126
+ };
127
+ export const writeRequest = {
128
+ "type": "object",
129
+ "additionalProperties": false,
130
+ "required": [
131
+ "requestId",
132
+ "items"
133
+ ],
134
+ "properties": {
135
+ "requestId": {
136
+ "type": "string",
137
+ "minLength": 1,
138
+ "maxLength": 128
139
+ },
140
+ "items": {
141
+ "type": "array",
142
+ "minItems": 1,
143
+ "maxItems": 100,
144
+ "items": {
145
+ "type": "object",
146
+ "additionalProperties": false,
147
+ "required": [
148
+ "collection",
149
+ "id",
150
+ "revision",
151
+ "body"
152
+ ],
153
+ "properties": {
154
+ "collection": {
155
+ "type": "string",
156
+ "pattern": "^[a-z][a-z0-9-]{0,63}$"
157
+ },
158
+ "id": {
159
+ "type": "string",
160
+ "pattern": "^[A-Za-z0-9][A-Za-z0-9._:-]{0,199}$"
161
+ },
162
+ "revision": {
163
+ "type": "integer",
164
+ "format": "int64",
165
+ "minimum": 0
166
+ },
167
+ "body": {
168
+ "x-go-type": "json.RawMessage",
169
+ "x-go-type-import": {
170
+ "path": "encoding/json"
171
+ }
172
+ }
173
+ }
174
+ }
175
+ }
176
+ }
177
+ };
178
+ export const collectionName = {
179
+ "type": "string",
180
+ "pattern": "^[a-z][a-z0-9-]{0,63}$"
181
+ };
182
+ export const status = {
183
+ "unauthenticated": 401,
184
+ "forbidden": 403,
185
+ "invalid": 400,
186
+ "stale": 409,
187
+ "exists": 409,
188
+ "full": 507
189
+ };
190
+ export const maxWriteBytes = 1048576;
@@ -6,21 +6,18 @@ import { fileURLToPath } from 'node:url';
6
6
  import { parseArgs } from 'node:util';
7
7
  import { createServer, mergeConfig } from 'vite';
8
8
  import { papers as held } from '../corpus.js';
9
- import { documentStore } from '../document-store.js';
9
+ import { collectionStore } from '../collection-store.js';
10
10
  import { paperPath } from '../papers.js';
11
11
  import { project, read, readCorpus } from '../data.js';
12
12
  import { pdfAssets } from '../pdf.js';
13
13
  import { pagesOf, readerCookie, readerOf } from '../reader.js';
14
14
  import { findRoot } from '../root.js';
15
15
  import { kinds } from '../schema.js';
16
+ import { match, routed } from '../urls.js';
16
17
  import { hostConfig } from '../vite-config.js';
17
18
  const entry = 'virtual:research-host';
18
19
  const css = `${entry}.css`;
19
20
  const host = fileURLToPath(new URL('../dev/host.js', import.meta.url));
20
- const data = /^\/projects\/project\/data\//;
21
- const privates = /^\/projects\/project\/private\/([^/]+)\/([^/]+)\.json$/;
22
- const documents = /^\/projects\/project\/documents(\/[^/]*)?$/;
23
- const papers = /^\/projects\/project\/papers\/([^/]+)$/;
24
21
  const assetTypes = {
25
22
  '.js': 'text/javascript',
26
23
  '.mjs': 'text/javascript',
@@ -73,13 +70,17 @@ export default async function dev(args) {
73
70
  function devHost(root, named) {
74
71
  const reader = named ?? 'local';
75
72
  const real = realpathSync(root);
76
- const { people, roles } = project(root);
73
+ const { people, roles, collections } = project(root);
77
74
  // Refuses, before serving, a --reader the project's people cannot serve; the
78
75
  // default is refused where a page reads as it, so contexts that each name a
79
76
  // reader still start.
80
77
  if (named !== undefined)
81
78
  readerOf({ people, roles }, named, true);
82
- const store = documentStore();
79
+ // Without people, the reader is the one member, as in testHost.
80
+ const store = collectionStore({
81
+ collections,
82
+ people: people ?? { [reader]: {} },
83
+ });
83
84
  return {
84
85
  name: 'research:dev',
85
86
  // Before research:serve, so a signed-out reader's data requests are refused first.
@@ -107,8 +108,8 @@ function devHost(root, named) {
107
108
  ].join('\n');
108
109
  },
109
110
  configureServer(server) {
110
- // The project's documents, shared by every reader, written as the cookie names.
111
- const document = async (req, res, writer) => {
111
+ // The project's collections, shared by every reader, as the cookie names them.
112
+ const collection = async (req, res, route, person) => {
112
113
  const chunks = [];
113
114
  for await (const chunk of req)
114
115
  chunks.push(chunk);
@@ -118,47 +119,44 @@ function devHost(root, named) {
118
119
  body: ['GET', 'HEAD'].includes(req.method)
119
120
  ? undefined
120
121
  : Buffer.concat(chunks),
121
- }), writer);
122
+ }), route, person);
122
123
  reply(res, answer.status, Object.fromEntries(answer.headers), Buffer.from(await answer.arrayBuffer()));
123
124
  };
124
125
  server.middlewares.use((req, res, next) => {
125
126
  res.setHeader('Content-Security-Policy', policy);
126
- const path = req.url?.split('?')[0];
127
- // A cookie with an empty value is a signed-out reader; the raw value is
128
- // compared, as an encoded name is never empty.
127
+ const path = req.url?.split('?')[0] ?? '';
128
+ const route = match(req.url ?? '');
129
+ if (route?.project !== 'project' && routed(path))
130
+ return notFound(res, `${path}: not a route of this project`);
131
+ // A cookie with an empty value is a signed-out reader, as an encoded
132
+ // name is never empty; one that does not decode names no reader.
129
133
  const named = cookie(req, readerCookie);
130
- if ([data, documents, privates].some((route) => route.test(path ?? '')) &&
131
- named === '')
134
+ let who = reader;
135
+ try {
136
+ if (named !== undefined)
137
+ who = decodeURIComponent(named) || undefined;
138
+ }
139
+ catch {
140
+ who = undefined;
141
+ }
142
+ // The store answers a signed-out reader as the API does.
143
+ if (route?.route === 'collections' || route?.route === 'collection')
144
+ return void collection(req, res, route, who).catch(next);
145
+ if (route && route.route !== 'paper' && named === '')
132
146
  return reply(res, 401, { 'Content-Type': 'text/plain' }, 'signed out');
133
- const [, page, dataset = ''] = path?.match(privates) ?? [];
134
- if (documents.test(path ?? '') || page) {
135
- // A cookie that does not decode names no reader.
136
- let who = reader;
137
- try {
138
- if (named !== undefined)
139
- who = decodeURIComponent(named);
140
- }
141
- catch {
147
+ if (route?.route === 'private') {
148
+ if (who === undefined)
142
149
  return reply(res, 401, { 'Content-Type': 'text/plain' }, 'signed out');
143
- }
144
- if (!page)
145
- return void document(req, res, who).catch(next);
146
150
  // A page is its reader's alone, as the server gates it; view-as is no gate.
147
- let wanted = page;
148
- try {
149
- wanted = decodeURIComponent(page);
150
- }
151
- catch {
152
- return notFound(res, `${page}: not a page`);
153
- }
154
- if (!pagesOf(people, who).includes(wanted))
151
+ const { page, dataset } = route;
152
+ if (!pagesOf(people, who).includes(page))
155
153
  return reply(res, 403, { 'Content-Type': 'text/plain' }, 'not yours');
156
- const file = privateFile(root, wanted, dataset);
154
+ const file = privateFile(root, page, dataset);
157
155
  if (!file)
158
156
  return notFound(res, `project has no private dataset "${dataset}" page "${page}"`);
159
157
  return send(req, res, Buffer.from(JSON.stringify(read(root, file))), 'application/json');
160
158
  }
161
- const asset = path?.startsWith(pdfAssets) && path.slice(pdfAssets.length);
159
+ const asset = path.startsWith(pdfAssets) && path.slice(pdfAssets.length);
162
160
  if (asset) {
163
161
  const file = pdfAsset(asset);
164
162
  if (!file)
@@ -166,9 +164,9 @@ function devHost(root, named) {
166
164
  const type = assetTypes[extname(file)] ?? 'application/octet-stream';
167
165
  return send(req, res, readFileSync(file), type);
168
166
  }
169
- const sha = path?.match(papers)?.[1];
170
- if (!sha)
167
+ if (route?.route !== 'paper')
171
168
  return next();
169
+ const { sha } = route;
172
170
  const kind = held(readCorpus(root)).get(sha)?.paper.kind;
173
171
  if (!kind)
174
172
  return notFound(res, `${sha}: not in corpus.json`);
@@ -184,7 +182,7 @@ function devHost(root, named) {
184
182
  });
185
183
  return () => server.middlewares.use((req, res, next) => {
186
184
  const url = req.originalUrl ?? '';
187
- if (req.url !== '/index.html' || url.startsWith('/projects/'))
185
+ if (req.url !== '/index.html' || routed(url))
188
186
  return next();
189
187
  server
190
188
  .transformIndexHtml(url, page)
@@ -196,7 +194,8 @@ function devHost(root, named) {
196
194
  }
197
195
  function privateFile(root, page, dataset) {
198
196
  try {
199
- return project(root).pages[dataset]?.()[page];
197
+ const { pages } = project(root);
198
+ return Object.hasOwn(pages, dataset) ? pages[dataset]()[page] : undefined;
200
199
  }
201
200
  catch (error) {
202
201
  if (error.message.endsWith(': matches no file'))
package/dist/context.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import type { Host, Schema } from './types.js';
2
2
  export declare const HostContext: import("react").Context<Host | null>;
3
- /** Where the document hooks fetch from; the test host sets its in-memory store, a host leaves the global. */
4
- export declare const FetchContext: import("react").Context<typeof fetch | null>;
5
3
  /** The schemas `defineProject` was given, which `useData` and `usePrivate` look a dataset up in. */
6
4
  export declare const DatasetsContext: import("react").Context<Record<string, Schema>>;
5
+ /** The schemas `defineProject` was given, which `useCollection` parses a collection's bodies by. */
6
+ export declare const CollectionsContext: import("react").Context<Record<string, Schema>>;
package/dist/context.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { createContext } from 'react';
2
2
  export const HostContext = createContext(null);
3
- /** Where the document hooks fetch from; the test host sets its in-memory store, a host leaves the global. */
4
- export const FetchContext = createContext(null);
5
3
  /** The schemas `defineProject` was given, which `useData` and `usePrivate` look a dataset up in. */
6
4
  export const DatasetsContext = createContext({});
5
+ /** The schemas `defineProject` was given, which `useCollection` parses a collection's bodies by. */
6
+ export const CollectionsContext = createContext({});
package/dist/corpus.d.ts CHANGED
@@ -42,6 +42,10 @@ type Variables<K extends string, T extends z.ZodType> = {
42
42
  };
43
43
  declare const base: {
44
44
  type: z.ZodOptional<z.ZodEnum<{
45
+ document: "document";
46
+ collection: "collection";
47
+ dataset: "dataset";
48
+ map: "map";
45
49
  article: "article";
46
50
  "article-journal": "article-journal";
47
51
  "article-magazine": "article-magazine";
@@ -51,9 +55,6 @@ declare const base: {
51
55
  broadcast: "broadcast";
52
56
  chapter: "chapter";
53
57
  classic: "classic";
54
- collection: "collection";
55
- dataset: "dataset";
56
- document: "document";
57
58
  entry: "entry";
58
59
  "entry-dictionary": "entry-dictionary";
59
60
  "entry-encyclopedia": "entry-encyclopedia";
@@ -65,7 +66,6 @@ declare const base: {
65
66
  legal_case: "legal_case";
66
67
  legislation: "legislation";
67
68
  manuscript: "manuscript";
68
- map: "map";
69
69
  motion_picture: "motion_picture";
70
70
  musical_score: "musical_score";
71
71
  pamphlet: "pamphlet";
@@ -156,6 +156,8 @@ export declare const Work: z.ZodObject<{
156
156
  pending: z.ZodOptional<z.ZodArray<z.ZodEnum<{
157
157
  number: "number";
158
158
  type: "type";
159
+ page: "page";
160
+ status: "status";
159
161
  event: "event";
160
162
  author: "author";
161
163
  chair: "chair";
@@ -197,7 +199,6 @@ export declare const Work: z.ZodObject<{
197
199
  issue: "issue";
198
200
  "number-of-pages": "number-of-pages";
199
201
  "number-of-volumes": "number-of-volumes";
200
- page: "page";
201
202
  "page-first": "page-first";
202
203
  part: "part";
203
204
  printing: "printing";
@@ -245,7 +246,6 @@ export declare const Work: z.ZodObject<{
245
246
  section: "section";
246
247
  shortTitle: "shortTitle";
247
248
  source: "source";
248
- status: "status";
249
249
  title: "title";
250
250
  "title-short": "title-short";
251
251
  URL: "URL";
@@ -281,6 +281,8 @@ export declare const Corpus: z.ZodRecord<z.ZodUnion<readonly [z.ZodString, z.Zod
281
281
  pending: z.ZodOptional<z.ZodArray<z.ZodEnum<{
282
282
  number: "number";
283
283
  type: "type";
284
+ page: "page";
285
+ status: "status";
284
286
  event: "event";
285
287
  author: "author";
286
288
  chair: "chair";
@@ -322,7 +324,6 @@ export declare const Corpus: z.ZodRecord<z.ZodUnion<readonly [z.ZodString, z.Zod
322
324
  issue: "issue";
323
325
  "number-of-pages": "number-of-pages";
324
326
  "number-of-volumes": "number-of-volumes";
325
- page: "page";
326
327
  "page-first": "page-first";
327
328
  part: "part";
328
329
  printing: "printing";
@@ -370,7 +371,6 @@ export declare const Corpus: z.ZodRecord<z.ZodUnion<readonly [z.ZodString, z.Zod
370
371
  section: "section";
371
372
  shortTitle: "shortTitle";
372
373
  source: "source";
373
- status: "status";
374
374
  title: "title";
375
375
  "title-short": "title-short";
376
376
  URL: "URL";
package/dist/data.d.ts CHANGED
@@ -11,6 +11,14 @@ export declare function project(dir: string): {
11
11
  pages?: string[] | undefined;
12
12
  }> | undefined;
13
13
  roles: string[] | undefined;
14
+ collections: {
15
+ [key: string]: {
16
+ mode: "document" | "log";
17
+ body: Record<string, unknown>;
18
+ read: import("./collections.gen.js").components["schemas"]["ReadGrant"][];
19
+ write: import("./collections.gen.js").components["schemas"]["WriteGrant"][];
20
+ };
21
+ } | undefined;
14
22
  };
15
23
  /** The files a private dataset's glob matches, by the page each names; throws on a key a page cannot have. */
16
24
  export declare function privatePages(dir: string, dataset: string, glob: string): Record<string, string>;
package/dist/data.js CHANGED
@@ -4,7 +4,7 @@ import { LegacyCorpus } from './corpus.js';
4
4
  import { Corpus, Research } from './schema.js';
5
5
  /** Reads a project's research.json; each dataset reads its files when called. */
6
6
  export function project(dir) {
7
- const { title, data, private: held = {}, people, roles, } = read(dir, 'research.json', Research);
7
+ const { title, data, private: held = {}, people, roles, collections, } = read(dir, 'research.json', Research);
8
8
  const datasets = {
9
9
  corpus: () => readCorpus(dir),
10
10
  };
@@ -13,7 +13,7 @@ export function project(dir) {
13
13
  const pages = {};
14
14
  for (const [dataset, glob] of Object.entries(held))
15
15
  pages[dataset] = () => privatePages(dir, dataset, glob);
16
- return { title, datasets, pages, people, roles };
16
+ return { title, datasets, pages, people, roles, collections };
17
17
  }
18
18
  /** The files a private dataset's glob matches, by the page each names; throws on a key a page cannot have. */
19
19
  export function privatePages(dir, dataset, glob) {
@@ -3,6 +3,8 @@
3
3
  * research.json, parsed by its schema in ui/datasets.ts, and its corpus. A
4
4
  * private dataset is read as `{ page: parsed }`, its schema parsing one page's
5
5
  * file. A `roles` that ui/datasets.ts exports, the tuple `Register` types
6
- * roles from, must equal research.json's. Throws one line per failure.
6
+ * roles from, must equal research.json's; a `collections` it exports must
7
+ * name research.json's collections, each schema's JSON Schema equal to its
8
+ * `body`. Throws one line per failure.
7
9
  */
8
10
  export declare function load(dir: string): Promise<Record<string, unknown>>;
package/dist/datasets.js CHANGED
@@ -1,10 +1,12 @@
1
1
  import { lstatSync, readFileSync } from 'node:fs';
2
2
  import { join } from 'node:path';
3
3
  import { pathToFileURL } from 'node:url';
4
+ import { isDeepStrictEqual } from 'node:util';
4
5
  import { files, match, privatePages, read, readCorpus } from './data.js';
5
6
  import { Research } from './schema.js';
7
+ import { z } from './zod.js';
6
8
  const schemaFile = 'ui/datasets.ts';
7
- /** The `datasets` and `roles` ui/datasets.ts exports, which Node loads by stripping its types. */
9
+ /** The `datasets`, `roles` and `collections` ui/datasets.ts exports, which Node loads by stripping its types. */
8
10
  async function schemas(dir) {
9
11
  const path = join(dir, schemaFile);
10
12
  if (!lstatSync(path, { throwIfNoEntry: false }))
@@ -20,10 +22,37 @@ async function schemas(dir) {
20
22
  catch (error) {
21
23
  throw new Error(`${path}: ${error.message.split('\n')[0]}`);
22
24
  }
23
- const { datasets, roles } = exported;
25
+ const { datasets, roles, collections } = exported;
24
26
  if (typeof datasets !== 'object' || !datasets)
25
27
  throw new Error(`${path}: exports no datasets object`);
26
- return { datasets: datasets, roles };
28
+ return { datasets: datasets, roles, collections };
29
+ }
30
+ /** One line per collection whose schema in `typed` does not hold research.json's `body`, or that one of the two lacks. */
31
+ function collectionFailures(file, typed, declared) {
32
+ if (typeof typed !== 'object' || !typed)
33
+ return [`${file}: collections is not an object of schemas`];
34
+ const schemas = typed;
35
+ const failures = Object.keys(schemas)
36
+ .filter((name) => !Object.hasOwn(declared, name))
37
+ .map((name) => `${file}: schema for collection "${name}", which research.json does not declare`);
38
+ for (const [name, { body }] of Object.entries(declared)) {
39
+ if (!Object.hasOwn(schemas, name)) {
40
+ failures.push(`${file}: no schema for collection "${name}"`);
41
+ continue;
42
+ }
43
+ let expected;
44
+ try {
45
+ expected = z.toJSONSchema(schemas[name]);
46
+ delete expected.$schema;
47
+ }
48
+ catch (error) {
49
+ failures.push(`${file}: collection "${name}": ${error.message}`);
50
+ continue;
51
+ }
52
+ if (!isDeepStrictEqual(expected, body))
53
+ failures.push(`${file}: collection "${name}": research.json's body differs from its schema, which is ${JSON.stringify(expected)}`);
54
+ }
55
+ return failures;
27
56
  }
28
57
  const sameRoles = (typed, roles) => Array.isArray(typed) &&
29
58
  typed.length === roles.length &&
@@ -33,15 +62,19 @@ const sameRoles = (typed, roles) => Array.isArray(typed) &&
33
62
  * research.json, parsed by its schema in ui/datasets.ts, and its corpus. A
34
63
  * private dataset is read as `{ page: parsed }`, its schema parsing one page's
35
64
  * file. A `roles` that ui/datasets.ts exports, the tuple `Register` types
36
- * roles from, must equal research.json's. Throws one line per failure.
65
+ * roles from, must equal research.json's; a `collections` it exports must
66
+ * name research.json's collections, each schema's JSON Schema equal to its
67
+ * `body`. Throws one line per failure.
37
68
  */
38
69
  export async function load(dir) {
39
- const { data, private: held = {}, roles = [], } = read(dir, 'research.json', Research);
40
- const { datasets: found, roles: typed } = await schemas(dir);
70
+ const { data, private: held = {}, roles = [], collections = {}, } = read(dir, 'research.json', Research);
71
+ const { datasets: found, roles: typed, collections: typedCollections, } = await schemas(dir);
41
72
  const loaded = {};
42
73
  const failures = [];
43
74
  if (typed !== undefined && !sameRoles(typed, roles))
44
75
  failures.push(`${join(dir, schemaFile)}: roles ${JSON.stringify(typed)} differ from research.json's ${JSON.stringify(roles)}`);
76
+ if (typedCollections !== undefined)
77
+ failures.push(...collectionFailures(join(dir, schemaFile), typedCollections, collections));
45
78
  for (const dataset of Object.keys(found))
46
79
  if (!Object.hasOwn(data, dataset) && !Object.hasOwn(held, dataset))
47
80
  failures.push(`${join(dir, schemaFile)}: schema for "${dataset}", which research.json does not name`);
package/dist/dev/host.js CHANGED
@@ -5,24 +5,21 @@ import { RouterProvider } from '@tanstack/react-router';
5
5
  import { createContext, useContext, useMemo, useState } from 'react';
6
6
  import { createRoot } from 'react-dom/client';
7
7
  import projects from 'virtual:research-projects';
8
+ import { createHost } from '../host.js';
8
9
  import { membersOf, pagesOf, readerCookie, readerOf, } from '../reader.js';
9
10
  import { projectRouter } from '../router.js';
10
11
  const project = projects.project;
11
12
  const Reader = createContext({ username: '', cast: {}, lost: () => { } });
12
13
  function useHost() {
13
14
  const { username, cast, lost } = useContext(Reader);
14
- return useMemo(() => ({
15
+ return useMemo(() => createHost({
16
+ project: 'project',
15
17
  // A signed-out context is no one, refused by its first request's 401.
16
18
  reader: readerOf(username ? cast : {}, username, true),
17
19
  members: membersOf(cast.people),
18
- data: (dataset) => `/projects/project/data/${dataset}.json`,
19
- private: (dataset) => Object.fromEntries(pagesOf(cast.people, username).map((page) => [
20
- page,
21
- `/projects/project/private/${encodeURIComponent(page)}/${dataset}.json`,
22
- ])),
23
- paper: (sha) => `/projects/project/papers/${sha}`,
24
- document: (id) => `/projects/project/documents/${id}`,
25
- documents: (prefix) => `/projects/project/documents?prefix=${prefix}`,
20
+ pages: pagesOf(cast.people, username),
21
+ // The dev server answers with its one collectionStore, shared by every browser context.
22
+ store: (request) => fetch(request),
26
23
  sessionLost: lost,
27
24
  }), [username, cast, lost]);
28
25
  }
package/dist/host.d.ts CHANGED
@@ -1,9 +1,22 @@
1
1
  import { type AnyRoute, type ErrorComponentProps } from '@tanstack/react-router';
2
2
  import type { AnyProject } from './mount.js';
3
- import type { Host } from './types.js';
3
+ import type { Host, Member, Reader } from './types.js';
4
4
  export type { Host };
5
5
  export { pdfAssets } from './pdf.js';
6
6
  export { projectIdPattern } from './project-id.js';
7
+ /** The `Host` of one project, its URLs built by the one rule every host serves. */
8
+ export declare function createHost({ project, reader, members, pages, store, sessionLost, origin, }: {
9
+ /** The project's id, matching `projectIdPattern`. */
10
+ project: string;
11
+ reader: Reader;
12
+ members: Member[];
13
+ /** The viewed person's private pages. */
14
+ pages: string[];
15
+ store: (request: Request) => Promise<Response>;
16
+ sessionLost: () => void;
17
+ /** What the URLs are under; Node's `Request` refuses a relative URL. */
18
+ origin?: string;
19
+ }): Host;
7
20
  declare function Failed({ error, reset }: ErrorComponentProps): import("react").JSX.Element;
8
21
  /**
9
22
  * The route options of a project's mount: the project's `Host` from
@@ -18,6 +31,6 @@ export declare function frame(useHost: () => Host): {
18
31
  /**
19
32
  * Mounts `project` under `parent` at the path it names, with `options` as the
20
33
  * route's options (`frame(useHost)`, and any `loader` or `head`); returns the
21
- * route. The route's component renders in the project's datasets.
34
+ * route. The route's component renders in the project's datasets and collections.
22
35
  */
23
36
  export declare function mount(parent: AnyRoute, project: AnyProject, options: Partial<Omit<AnyRoute['options'], 'getParentRoute' | 'path'>>): AnyRoute;