@metacensus/library-research 0.12.1 → 0.14.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 CHANGED
@@ -7,13 +7,13 @@ The research-project contract and its tools
7
7
  A project is this layout, each path fixed, which `npx @metacensus/library-research init` writes into an empty repository:
8
8
 
9
9
  ```
10
- research.json title, data roles and private roles
10
+ research.json title, datasets, private datasets, roles and test people
11
11
  corpus.json sha → paper
12
12
  papers/<sha>.<kind> through LFS
13
13
  ui/package.json depends on @metacensus/library-research, which brings @playwright/test; scripts dev, check and test
14
14
  ui/tsconfig.json extends @metacensus/library-research/tsconfig.json
15
- ui/index.tsx default export: (parent: Mount) => the project's TanStack routes
16
- ui/local/index.tsx optional; the same export for the local-only routes, never shipped; declares no Register
15
+ ui/index.tsx default export: defineProject('<path>', (parent) => the project's TanStack routes)
16
+ ui/local/index.tsx optional; the same export, at the same path, for the local-only routes, never shipped; declares no Register
17
17
  ui/*.test.tsx optional; unit tests on testHost from @metacensus/library-research/testing
18
18
  ui/playwright.config.ts with browser/; export { default } from '@metacensus/library-research/playwright'
19
19
  ui/browser/*.spec.ts optional; test and expect from @metacensus/library-research/playwright
@@ -21,54 +21,61 @@ ui/browser/*.spec.ts optional; test and expect from @metacensus/library-rese
21
21
 
22
22
  From `ui/`:
23
23
 
24
- | Command | Does |
25
- | --------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
26
- | `npm run dev -- [--reader NAME] [--port N]` | serves the routes at `/project/` and `ui/local/`'s at `/local/`, live from the files, as reader `NAME` (else `local`) to a context that names none, under the host's CSP |
27
- | `npm run check` | gates the project, one line per failure, as a host's build does |
28
- | `npx playwright test` | runs `browser/` in Chromium on a dev server; a CSP or axe violation fails its spec unless `violations` lists it |
29
- | `npx library-research add <file> [--title T] [--citation C] [--open]` | adds a paper to `papers/` and `corpus.json` |
30
- | `npx library-research candidate` | runs `check`, then tags a clean `HEAD` on `origin/main` as `<id>-YYYY-MM-DD[.N]`, pushes it, and prints the service's `make pin` line |
24
+ | Command | Does |
25
+ | --------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
26
+ | `npm run dev -- [--reader NAME] [--port N]` | serves the project at `/<path>/` and `ui/local/`'s at `/local/<path>/`, live from the files, as reader `NAME` (else `local`) to a context that names none, under the host's CSP |
27
+ | `npm run check` | gates the project, one line per failure, as a host's build does |
28
+ | `npx playwright test` | runs `browser/` in Chromium on a dev server; a CSP or axe violation fails its spec unless `violations` lists it |
29
+ | `npx library-research add <file> [--title T] [--citation C] [--open]` | adds a paper to `papers/` and `corpus.json` |
30
+ | `npx library-research candidate` | runs `check`, then tags a clean `HEAD` on `origin/main` as `<id>-YYYY-MM-DD[.N]`, pushes it, and prints the service's `make pin` line |
31
31
 
32
32
  ## Rendering
33
33
 
34
34
  A project renders in the browser only: the host is one single-page app and each project is a route of it, with no static build. A project never calls React's `lazy()`, and `check` fails on it; the PDF reader and charting come from `@metacensus/library-ui`.
35
35
 
36
- ## Data roles
36
+ ## Datasets
37
37
 
38
- Each key of research.json's `data` is a role, and `ui/roles.ts` exports `roles`, one Zod schema per role over the role's whole value; a glob role's is a `z.record` keyed by what its wildcard matched. The UI parses with it and `check` fails, one line per record file, on data that does not. A role with no schema fails, and `corpus.json` is no role: library-research's `Corpus` parses it.
38
+ Each key of research.json's `data` is a dataset, and `ui/datasets.ts` exports `datasets`, one Zod schema per dataset over the dataset's whole value; a glob dataset's is a `z.record` keyed by what its wildcard matched. The UI parses with it and `check` fails, one line per record file, on data that does not. A dataset with no schema fails, and `corpus.json` is no dataset: library-research's `Corpus` parses it.
39
39
 
40
40
  ## Private data
41
41
 
42
- `research.json`'s `private` maps a role to a glob holding exactly one `*`, such as `{ "private": { "ask": "research_notes/coauthors/*/questions.json" } }`. What the `*` matches is the page key, and the build emits each match at `/projects/<id>/private/<page>/<role>.json`, never among the shared `data/` files. A host serves that path only to the people who hold the page. A page key matches `^[a-z0-9][a-z0-9-]*$` and a role is in `data` or `private`, not both; `check` fails otherwise, naming the role.
42
+ `research.json`'s `private` maps a dataset to a glob holding exactly one `*`, such as `{ "private": { "ask": "research_notes/coauthors/*/questions.json" } }`. What the `*` matches is the page key, and the build emits each match at `/projects/<id>/private/<page>/<dataset>.json`, never among the shared `data/` files. A host serves that path only to the people who hold the page. A page key matches `^[a-z0-9][a-z0-9-]*$` and a dataset is in `data` or `private`, not both; `check` fails otherwise, naming the dataset.
43
43
 
44
- `usePrivate(role, parse)` returns `{ page: parsed }` for the pages the host names for the person the project is viewed as: none, one or several, and a page not yet built is left out. `Object.values(usePrivate('ask', parse))` is that person's questions. The role's schema in `ui/roles.ts` parses one page's file, and `load` returns the role as `{ page: parsed }`. A host's `private(role)` returns the page-to-URL map.
44
+ `usePrivate(dataset, parse)` returns `{ page: parsed }` for the pages the host names for the person the project is viewed as: none, one or several, and a page not yet built is left out. `Object.values(usePrivate('ask', parse))` is that person's questions. The dataset's schema in `ui/datasets.ts` parses one page's file, and `load` returns the dataset as `{ page: parsed }`. A host's `private(dataset)` returns the page-to-URL map.
45
45
 
46
- In `dev`, a reader's page is the reader's name: `dev --reader hertz` holds `hertz`'s page, another reader's page answers 403, and `testHost`'s `private: { role: { page: json } }` gives the reader the page named as it.
46
+ In `dev` and `testHost`, a reader holds the pages [`people`](#people) gives them, and `testHost`'s `private: { dataset: { page: json } }` holds each page's JSON.
47
47
 
48
- Node loads `ui/roles.ts` by stripping its types: no `enum` or namespace, relative imports end in `.ts`, and `ui/package.json` says `"type": "module"`. Dev tooling reads a project's roles through `load` from `@metacensus/library-research/roles`, which takes the folder holding research.json and returns each role parsed, with `corpus`.
48
+ Node loads `ui/datasets.ts` by stripping its types: no `enum` or namespace, relative imports end in `.ts`, and `ui/package.json` says `"type": "module"`. Dev tooling reads a project's datasets through `load` from `@metacensus/library-research/datasets`, which takes the folder holding research.json and returns each dataset parsed, with `corpus`.
49
+
50
+ ## People
51
+
52
+ `research.json`'s optional `roles` lists the roles a person of the project holds one of, each matching `^[a-z][a-z0-9-]*$`, none repeated: `{ "roles": ["author", "leader"] }`.
53
+
54
+ - `useReader()` returns the host's `reader`, the person the project is viewed as: `{ username, name, role, self }`. `role` is one of `roles`, or null in a project that declares none. `self` is false while the host views the project as a person other than the one signed in.
55
+ - `useMembers()` returns the host's `members`, every person of the project, each `{ username, name, role }`.
56
+
57
+ In `dev` and `testHost`, `research.json`'s optional `people` stands in for production's people.json: it maps a username to `{ name, role, pages }`, `role` and `pages` optional, as `{ "people": { "dan.hertz": { "name": "Hertz", "role": "author", "pages": ["hertz"] } } }`. Every entry is a member. `dev --reader dan.hertz` and `testHost`'s `reader: 'dan.hertz'` serve that person as `reader` with `self` true, holding `hertz`'s page; another page answers 403. In a project that declares `roles`, a reader `people` omits is refused, naming them: by `testHost`, by `dev` before it serves when `--reader` names them, and by a `dev` page read as them, the default `local` included; in one that declares none, such a reader is served with their username as `name`, no role and no pages, and is no member. `check` fails, naming the person, on a role not in `roles`, on a person with no role where the project declares roles, and on a person with a role where it declares none. Production ignores `people`.
49
58
 
50
59
  ## Routes
51
60
 
52
- A project exports its routes, created against the `Mount` its host hands it, a route at `/$project`; the host owns the router. `Register` types the project's own links. A link names its path in full and passes `from="/$project"`, so a wrong path fails to compile and the current `project` carries over:
61
+ A project default-exports `defineProject('<path>', routes)`: its first URL segment, matching `^[a-z0-9][a-z0-9-]*$` and not `projects`, `local` or `pdfjs` (dev and the host reserve them), and its routes created against the `parent` it is handed, a route at that path; the host owns the router. `Register` types the project's own links. A link names its path in full and passes `from="/<path>"`, so a wrong path fails to compile:
53
62
 
54
63
  ```tsx
55
- export default function routes(parent: Mount) {
56
- const task = createRoute({ getParentRoute: () => parent, path: 'task/$key' })
57
- return [task]
58
- }
64
+ const dpyd = defineProject('dpyd', (parent) => [
65
+ createRoute({ getParentRoute: () => parent, path: 'task/$key' }),
66
+ ])
67
+ export default dpyd
59
68
  declare module '@tanstack/react-router' {
60
69
  interface Register {
61
- router: RouterOf<typeof routes>
70
+ router: RouterOf<typeof dpyd>
62
71
  }
63
72
  }
64
- // <Link from="/$project" to="/$project/task/$key" params={{ key }} />
73
+ // <Link from="/dpyd" to="/dpyd/task/$key" params={{ key }} />
65
74
  ```
66
75
 
67
- A host mounts them with `mountRoutes(route, routes)` from `@metacensus/library-research/host`, `route` being its own route at `/$project`.
68
-
69
- The route also takes `frame(useHost)`, spread into its options: it provides the `Host` that `useHost` returns, shows a resettable error and an announced loading state. A host sets no `defaultPendingComponent` or `defaultErrorComponent` on its router, which would override the frame's for a project's routes. A host serves `@metacensus/library-research/csp.json` as its Content-Security-Policy (directive → sources, adding its own origins and nonces) and `pdfAssets`, `/pdfjs/`, for `configurePdf({ assets })`.
76
+ A host mounts each project with `mount(parent, project, options)` from `@metacensus/library-research/host`: it creates the route at the path the project names, with `options` as the route's options, adds the project's routes, and returns it. Two projects at one path are refused by TanStack's duplicate-route-id check, in development builds only.
70
77
 
71
- `params.project` is `project` or `local` in dev and the project's id in production, so a project never reads it as its id.
78
+ `options` takes `frame(useHost)`, spread in: it provides the `Host` that `useHost` returns, shows a resettable error and an announced loading state. A host sets no `defaultPendingComponent` or `defaultErrorComponent` on its router, which would override the frame's for a project's routes. A host serves `@metacensus/library-research/csp.json` as its Content-Security-Policy (directive → sources, adding its own origins and nonces) and `pdfAssets`, `/pdfjs/`, for `configurePdf({ assets })`.
72
79
 
73
80
  ## Saving
74
81
 
@@ -85,11 +92,11 @@ A project saves JSON documents through its host, as it reads data.
85
92
 
86
93
  ## Testing
87
94
 
88
- `testHost(routes, { data, private, documents, reader, url, sessionLost })` from `@metacensus/library-research/testing` returns `{ element, router, documents }`: a project's routes in the frame and `/$project` mount a real host uses, `data` giving each role's JSON, `reader` the username (default `test`), `documents` the project's saved documents as `{ id: { body, writer? } }`, `url` the path below the project (default `/`). Render `element` with any DOM renderer; `router.state.location` says where the project navigated, and `documents()` what it saved. `init` scaffolds `ui/index.test.tsx` on vitest, jsdom and Testing Library, which a project installs itself.
95
+ `testHost(project, { data, private, documents, people, roles, reader, self, url, sessionLost })` from `@metacensus/library-research/testing` returns `{ element, router, documents }`: the project in the frame and mount a real host uses, at its path, `data` giving each dataset's JSON, `people` and `roles` as research.json's, `reader` the username (default `test`) and the writer of every save, `self` false to view the project as `reader` while signed in as another (default true; `testHost` holds the one identity, so saves are still `reader`'s), `documents` the project's saved documents as `{ id: { body, writer? } }`, `url` the path below the project (default `/`). Render `element` with any DOM renderer; `router.state.location` says where the project navigated, and `documents()` what it saved. `membersOf(research.people)` and `readerOf(research, username, self)` from `./testing` build the `members` and `reader` `testHost` serves, so a fixture reads them from research.json rather than copying them. `init` scaffolds `ui/index.test.tsx` on vitest, jsdom and Testing Library, which a project installs itself.
89
96
 
90
97
  ```tsx
91
98
  render(
92
- testHost(routes, { data: { items }, reader: 'ana', url: '/task/7' }).element,
99
+ testHost(dpyd, { data: { items }, reader: 'ana', url: '/task/7' }).element,
93
100
  )
94
101
  ```
95
102
 
@@ -6,7 +6,7 @@ import { join, sep } from 'node:path';
6
6
  import { parseArgs, stripVTControlCharacters } from 'node:util';
7
7
  import { build, mergeConfig } from 'vite';
8
8
  import { checkPapers } from '../papers.js';
9
- import { load } from '../roles.js';
9
+ import { load } from '../datasets.js';
10
10
  import { findRoot } from '../root.js';
11
11
  import { hostConfig } from '../vite-config.js';
12
12
  const tsc = createRequire(import.meta.url).resolve('typescript/bin/tsc');
@@ -9,7 +9,7 @@ import { documentStore } from '../document-store.js';
9
9
  import { paperPath } from '../papers.js';
10
10
  import { project, read, readCorpus } from '../data.js';
11
11
  import { pdfAssets } from '../pdf.js';
12
- import { readerCookie } from '../reader.js';
12
+ import { pagesOf, readerCookie, readerOf } from '../reader.js';
13
13
  import { findRoot } from '../root.js';
14
14
  import { kinds } from '../schema.js';
15
15
  import { hostConfig } from '../vite-config.js';
@@ -51,27 +51,33 @@ export default async function dev(args) {
51
51
  const { values } = parseArgs({
52
52
  args,
53
53
  options: {
54
- reader: { type: 'string', default: 'local' },
54
+ reader: { type: 'string' },
55
55
  port: { type: 'string' },
56
56
  },
57
57
  });
58
58
  const root = findRoot(process.cwd());
59
59
  const local = existsSync(join(root, 'ui/local/index.tsx'));
60
60
  const server = await createServer(mergeConfig(hostConfig(root), {
61
- plugins: [devHost(root, values.reader, local)],
61
+ plugins: [devHost(root, values.reader)],
62
62
  server: {
63
63
  port: values.port === undefined ? undefined : Number(values.port),
64
64
  },
65
65
  }));
66
66
  await server.listen();
67
67
  const [url] = server.resolvedUrls.local;
68
- console.log(`${url}project/`);
68
+ console.log(url);
69
69
  if (local)
70
70
  console.log(`${url}local/`);
71
71
  }
72
- function devHost(root, reader, local) {
73
- const mount = local ? /^\/(project|local)\// : /^\/project\//;
72
+ function devHost(root, named) {
73
+ const reader = named ?? 'local';
74
74
  const real = realpathSync(root);
75
+ const { people, roles } = project(root);
76
+ // Refuses, before serving, a --reader the project's people cannot serve; the
77
+ // default is refused where a page reads as it, so contexts that each name a
78
+ // reader still start.
79
+ if (named !== undefined)
80
+ readerOf({ people, roles }, named, true);
75
81
  const store = documentStore();
76
82
  return {
77
83
  name: 'research:dev',
@@ -81,17 +87,18 @@ function devHost(root, reader, local) {
81
87
  resolveId: (id) => ([entry, css].includes(id) ? '\0' + id : undefined),
82
88
  load(id) {
83
89
  if (id === '\0' + css)
84
- return '@tailwind base;\n@tailwind components;\n@tailwind utilities;\n';
90
+ return '@layer reset, mc;\n@layer reset {\n @tailwind base;\n}\n@tailwind components;\n@tailwind utilities;\n';
85
91
  if (id === '\0' + entry)
86
92
  return [
93
+ // First, so `reset` is ordered below library-ui's `mc`, as the host orders them.
94
+ `import '${css}'`,
87
95
  `import '@metacensus/library-ui/fonts.css'`,
88
96
  `import '@metacensus/library-ui/tokens.css'`,
89
97
  `import '@metacensus/library-ui/styles.css'`,
90
- `import '${css}'`,
91
98
  `import { configurePdf } from '@metacensus/library-ui/pdf'`,
92
99
  `import { start } from ${JSON.stringify(host)}`,
93
100
  `configurePdf({ assets: ${JSON.stringify(pdfAssets)} })`,
94
- `start(${JSON.stringify(reader)})`,
101
+ `start(${JSON.stringify(reader)}, ${JSON.stringify({ people, roles })})`,
95
102
  ].join('\n');
96
103
  },
97
104
  configureServer(server) {
@@ -112,15 +119,13 @@ function devHost(root, reader, local) {
112
119
  server.middlewares.use((req, res, next) => {
113
120
  res.setHeader('Content-Security-Policy', policy);
114
121
  const path = req.url?.split('?')[0];
115
- if (path === '/')
116
- return res.writeHead(302, { Location: '/project/' }).end();
117
122
  // A cookie with an empty value is a signed-out reader; the raw value is
118
123
  // compared, as an encoded name is never empty.
119
124
  const named = cookie(req, readerCookie);
120
125
  if ([data, documents, privates].some((route) => route.test(path ?? '')) &&
121
126
  named === '')
122
127
  return reply(res, 401, { 'Content-Type': 'text/plain' }, 'signed out');
123
- const [, page, role = ''] = path?.match(privates) ?? [];
128
+ const [, page, dataset = ''] = path?.match(privates) ?? [];
124
129
  if (documents.test(path ?? '') || page) {
125
130
  // A cookie that does not decode names no reader.
126
131
  let who = reader;
@@ -141,11 +146,11 @@ function devHost(root, reader, local) {
141
146
  catch {
142
147
  return notFound(res, `${page}: not a page`);
143
148
  }
144
- if (who !== wanted)
149
+ if (!pagesOf(people, who).includes(wanted))
145
150
  return reply(res, 403, { 'Content-Type': 'text/plain' }, 'not yours');
146
- const file = privateFile(root, wanted, role);
151
+ const file = privateFile(root, wanted, dataset);
147
152
  if (!file)
148
- return notFound(res, `project has no private role "${role}" page "${page}"`);
153
+ return notFound(res, `project has no private dataset "${dataset}" page "${page}"`);
149
154
  return send(req, res, Buffer.from(JSON.stringify(read(root, file))), 'application/json');
150
155
  }
151
156
  const asset = path?.startsWith(pdfAssets) && path.slice(pdfAssets.length);
@@ -174,7 +179,7 @@ function devHost(root, reader, local) {
174
179
  });
175
180
  return () => server.middlewares.use((req, res, next) => {
176
181
  const url = req.originalUrl ?? '';
177
- if (req.url !== '/index.html' || !mount.test(url))
182
+ if (req.url !== '/index.html' || url.startsWith('/projects/'))
178
183
  return next();
179
184
  server
180
185
  .transformIndexHtml(url, page)
@@ -184,9 +189,9 @@ function devHost(root, reader, local) {
184
189
  },
185
190
  };
186
191
  }
187
- function privateFile(root, page, role) {
192
+ function privateFile(root, page, dataset) {
188
193
  try {
189
- return project(root).pages[role]?.()[page];
194
+ return project(root).pages[dataset]?.()[page];
190
195
  }
191
196
  catch (error) {
192
197
  if (error.message.endsWith(': matches no file'))
@@ -9,6 +9,11 @@ export default function init(args) {
9
9
  const title = basename(root);
10
10
  if (!/^[\w.-]+$/.test(title))
11
11
  throw new Error(`${title}: not a repository name; use letters, digits, ., - or _`);
12
+ // The project's URL path: the title, lower-cased, in letters, digits and hyphens.
13
+ const path = title
14
+ .toLowerCase()
15
+ .replace(/[^a-z0-9]+/g, '-')
16
+ .replace(/^-|-$/g, '') || 'project';
12
17
  const files = {
13
18
  'research.json': json({ title, data: {} }),
14
19
  'corpus.json': '{}\n',
@@ -76,11 +81,11 @@ jobs:
76
81
  'ui/tsconfig.json': json({
77
82
  extends: '@metacensus/library-research/tsconfig.json',
78
83
  }),
79
- 'ui/index.tsx': `import type { Mount, RouterOf } from '@metacensus/library-research'
84
+ 'ui/index.tsx': `import { defineProject, type RouterOf } from '@metacensus/library-research'
80
85
  import { createRoute } from '@tanstack/react-router'
81
86
 
82
- export default function routes(parent: Mount) {
83
- const index = createRoute({
87
+ const project = defineProject('${path}', (parent) => [
88
+ createRoute({
84
89
  getParentRoute: () => parent,
85
90
  path: '/',
86
91
  component: () => (
@@ -88,13 +93,13 @@ export default function routes(parent: Mount) {
88
93
  <h1>${title}</h1>
89
94
  </main>
90
95
  ),
91
- })
92
- return [index]
93
- }
96
+ }),
97
+ ])
98
+ export default project
94
99
 
95
100
  declare module '@tanstack/react-router' {
96
101
  interface Register {
97
- router: RouterOf<typeof routes>
102
+ router: RouterOf<typeof project>
98
103
  }
99
104
  }
100
105
  `,
@@ -102,12 +107,12 @@ declare module '@tanstack/react-router' {
102
107
  import { testHost } from '@metacensus/library-research/testing'
103
108
  import { cleanup, render, screen } from '@testing-library/react'
104
109
  import { afterEach, test } from 'vitest'
105
- import routes from './index.tsx'
110
+ import project from './index.tsx'
106
111
 
107
112
  afterEach(cleanup)
108
113
 
109
114
  test('the root renders', async () => {
110
- render(testHost(routes).element)
115
+ render(testHost(project).element)
111
116
  await screen.findByRole('heading', { level: 1 })
112
117
  })
113
118
  `,
package/dist/data.d.ts CHANGED
@@ -1,13 +1,19 @@
1
1
  import { z } from 'zod';
2
- /** Reads a project's research.json; each role reads its files when called. */
2
+ /** Reads a project's research.json; each dataset reads its files when called. */
3
3
  export declare function project(dir: string): {
4
4
  title: string;
5
- roles: Record<string, () => unknown>;
5
+ datasets: Record<string, () => unknown>;
6
6
  pages: Record<string, () => Record<string, string>>;
7
+ people: Record<string, {
8
+ name: string;
9
+ role?: string | undefined;
10
+ pages?: string[] | undefined;
11
+ }> | undefined;
12
+ roles: string[] | undefined;
7
13
  };
8
- /** The files a private role's glob matches, by the page each names; throws on a key a page cannot have. */
9
- export declare function privatePages(dir: string, role: string, glob: string): Record<string, string>;
10
- /** The files a role's glob matches; a wildcard keys each by what it matched. */
14
+ /** The files a private dataset's glob matches, by the page each names; throws on a key a page cannot have. */
15
+ export declare function privatePages(dir: string, dataset: string, glob: string): Record<string, string>;
16
+ /** The files a dataset's glob matches; a wildcard keys each by what it matched. */
11
17
  export declare function files(dir: string, glob: string): {
12
18
  keyed: boolean;
13
19
  entries: [file: string, key: string][];
package/dist/data.js CHANGED
@@ -1,36 +1,36 @@
1
1
  import { globSync, lstatSync, readFileSync, realpathSync } from 'node:fs';
2
2
  import { join, sep } from 'node:path';
3
3
  import { Corpus, Research } from './schema.js';
4
- /** Reads a project's research.json; each role reads its files when called. */
4
+ /** Reads a project's research.json; each dataset reads its files when called. */
5
5
  export function project(dir) {
6
- const { title, data, private: held = {}, } = read(dir, 'research.json', Research);
7
- const roles = {
6
+ const { title, data, private: held = {}, people, roles, } = read(dir, 'research.json', Research);
7
+ const datasets = {
8
8
  corpus: () => readCorpus(dir),
9
9
  };
10
- for (const [role, glob] of Object.entries(data))
11
- roles[role] = () => match(dir, files(dir, glob));
10
+ for (const [dataset, glob] of Object.entries(data))
11
+ datasets[dataset] = () => match(dir, files(dir, glob));
12
12
  const pages = {};
13
- for (const [role, glob] of Object.entries(held))
14
- pages[role] = () => privatePages(dir, role, glob);
15
- return { title, roles, pages };
13
+ for (const [dataset, glob] of Object.entries(held))
14
+ pages[dataset] = () => privatePages(dir, dataset, glob);
15
+ return { title, datasets, pages, people, roles };
16
16
  }
17
- /** The files a private role's glob matches, by the page each names; throws on a key a page cannot have. */
18
- export function privatePages(dir, role, glob) {
17
+ /** The files a private dataset's glob matches, by the page each names; throws on a key a page cannot have. */
18
+ export function privatePages(dir, dataset, glob) {
19
19
  const { entries } = files(dir, glob);
20
20
  const bad = entries.filter(([, key]) => !/^[a-z0-9][a-z0-9-]*$/.test(key));
21
21
  if (bad.length)
22
22
  throw new Error(bad
23
- .map(([file, key]) => `${join(dir, file)}: private role "${role}": page "${key}" is not [a-z0-9][a-z0-9-]*`)
23
+ .map(([file, key]) => `${join(dir, file)}: private dataset "${dataset}": page "${key}" is not [a-z0-9][a-z0-9-]*`)
24
24
  .join('\n'));
25
25
  const pages = {};
26
26
  for (const [file, key] of entries) {
27
27
  if (Object.hasOwn(pages, key))
28
- throw new Error(`private role "${role}": page "${key}" matched by ${pages[key]} and ${file}`);
28
+ throw new Error(`private dataset "${dataset}": page "${key}" matched by ${pages[key]} and ${file}`);
29
29
  pages[key] = file;
30
30
  }
31
31
  return pages;
32
32
  }
33
- /** The files a role's glob matches; a wildcard keys each by what it matched. */
33
+ /** The files a dataset's glob matches; a wildcard keys each by what it matched. */
34
34
  export function files(dir, glob) {
35
35
  const found = globSync(glob, { cwd: dir }).sort();
36
36
  if (!found.length)
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Reads each dataset of the project in `dir`, the folder holding
3
+ * research.json, parsed by its schema in ui/datasets.ts, and its corpus. A
4
+ * private dataset 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>>;
@@ -3,8 +3,8 @@ import { join } from 'node:path';
3
3
  import { pathToFileURL } from 'node:url';
4
4
  import { files, match, privatePages, read, readCorpus } from './data.js';
5
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. */
6
+ const schemaFile = 'ui/datasets.ts';
7
+ /** The `datasets` ui/datasets.ts exports, which Node loads by stripping its types. */
8
8
  async function schemas(dir) {
9
9
  const path = join(dir, schemaFile);
10
10
  if (!lstatSync(path, { throwIfNoEntry: false }))
@@ -13,22 +13,21 @@ async function schemas(dir) {
13
13
  const { type } = JSON.parse(readFileSync(manifest, 'utf8'));
14
14
  if (type !== 'module')
15
15
  throw new Error(`${manifest}: needs "type": "module" for ${schemaFile}`);
16
- let roles;
16
+ let datasets;
17
17
  try {
18
- roles = (await import(pathToFileURL(path).href))
19
- .roles;
18
+ datasets = (await import(pathToFileURL(path).href)).datasets;
20
19
  }
21
20
  catch (error) {
22
21
  throw new Error(`${path}: ${error.message.split('\n')[0]}`);
23
22
  }
24
- if (typeof roles !== 'object' || !roles)
25
- throw new Error(`${path}: exports no roles object`);
26
- return roles;
23
+ if (typeof datasets !== 'object' || !datasets)
24
+ throw new Error(`${path}: exports no datasets object`);
25
+ return datasets;
27
26
  }
28
27
  /**
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
28
+ * Reads each dataset of the project in `dir`, the folder holding
29
+ * research.json, parsed by its schema in ui/datasets.ts, and its corpus. A
30
+ * private dataset is read as `{ page: parsed }`, its schema parsing one page's
32
31
  * file. Throws one line per failure.
33
32
  */
34
33
  export async function load(dir) {
@@ -36,21 +35,21 @@ export async function load(dir) {
36
35
  const found = await schemas(dir);
37
36
  const loaded = {};
38
37
  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)) {
38
+ for (const dataset of Object.keys(found))
39
+ if (!Object.hasOwn(data, dataset) && !Object.hasOwn(held, dataset))
40
+ failures.push(`${join(dir, schemaFile)}: schema for "${dataset}", which research.json does not name`);
41
+ for (const [dataset, glob] of Object.entries(data)) {
43
42
  try {
44
43
  const matched = files(dir, glob);
45
44
  const value = match(dir, matched);
46
- const schema = Object.hasOwn(found, role) ? found[role] : undefined;
45
+ const schema = Object.hasOwn(found, dataset) ? found[dataset] : undefined;
47
46
  if (typeof schema?.safeParse !== 'function') {
48
- failures.push(`${role}: no schema in ${schemaFile}`);
47
+ failures.push(`${dataset}: no schema in ${schemaFile}`);
49
48
  continue;
50
49
  }
51
50
  const parsed = schema.safeParse(value);
52
51
  if (parsed.success)
53
- loaded[role] = parsed.data;
52
+ loaded[dataset] = parsed.data;
54
53
  else {
55
54
  const byPlace = new Map();
56
55
  for (const { path, message } of parsed.error.issues) {
@@ -65,33 +64,33 @@ export async function load(dir) {
65
64
  ]);
66
65
  }
67
66
  for (const [place, issues] of byPlace)
68
- failures.push(`${place}: ${role}: ${issues.join('; ')}`);
67
+ failures.push(`${place}: ${dataset}: ${issues.join('; ')}`);
69
68
  }
70
69
  }
71
70
  catch (error) {
72
71
  failures.push(error.message);
73
72
  }
74
73
  }
75
- for (const [role, glob] of Object.entries(held)) {
74
+ for (const [dataset, glob] of Object.entries(held)) {
76
75
  try {
77
- const schema = Object.hasOwn(found, role) ? found[role] : undefined;
76
+ const schema = Object.hasOwn(found, dataset) ? found[dataset] : undefined;
78
77
  if (typeof schema?.safeParse !== 'function') {
79
- failures.push(`${role}: no schema in ${schemaFile}`);
78
+ failures.push(`${dataset}: no schema in ${schemaFile}`);
80
79
  continue;
81
80
  }
82
81
  const pages = {};
83
- for (const [page, file] of Object.entries(privatePages(dir, role, glob))) {
82
+ for (const [page, file] of Object.entries(privatePages(dir, dataset, glob))) {
84
83
  const parsed = schema.safeParse(read(dir, file));
85
84
  if (parsed.success)
86
85
  pages[page] = parsed.data;
87
86
  else
88
- failures.push(`${join(dir, file)}: ${role}: ${parsed
87
+ failures.push(`${join(dir, file)}: ${dataset}: ${parsed
89
88
  .error.issues.map(({ path, message }) => path.length
90
89
  ? `${path.map(String).join('.')}: ${message}`
91
90
  : message)
92
91
  .join('; ')}`);
93
92
  }
94
- loaded[role] = pages;
93
+ loaded[dataset] = pages;
95
94
  }
96
95
  catch (error) {
97
96
  failures.push(error.message);
@@ -1 +1,8 @@
1
- export declare function start(username: string): Promise<void>;
1
+ import { type People } from '../reader.js';
2
+ /** research.json's `people` and `roles`. */
3
+ type Cast = {
4
+ people?: People;
5
+ roles?: string[];
6
+ };
7
+ export declare function start(username: string, cast: Cast): Promise<void>;
8
+ export {};
package/dist/dev/host.js CHANGED
@@ -5,36 +5,36 @@ 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 { readerCookie } from '../reader.js';
8
+ import { membersOf, pagesOf, readerCookie, readerOf, } from '../reader.js';
9
9
  import { projectRouter } from '../router.js';
10
10
  const project = projects.project;
11
- const load = window.location.pathname.startsWith('/local/')
12
- ? project.local
13
- : project.root;
14
- const Reader = createContext({ username: '', lost: () => { } });
11
+ const Reader = createContext({ username: '', cast: {}, lost: () => { } });
15
12
  function useHost() {
16
- const { username, lost } = useContext(Reader);
13
+ const { username, cast, lost } = useContext(Reader);
17
14
  return useMemo(() => ({
18
- reader: { username },
19
- data: (role) => `/projects/project/data/${role}.json`,
20
- private: (role) => ({
21
- [username]: `/projects/project/private/${encodeURIComponent(username)}/${role}.json`,
22
- }),
15
+ // A signed-out context is no one, refused by its first request's 401.
16
+ reader: readerOf(username ? cast : {}, username, true),
17
+ 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
23
  paper: (sha) => `/projects/project/papers/${sha}`,
24
24
  document: (id) => `/projects/project/documents/${id}`,
25
25
  documents: (prefix) => `/projects/project/documents?prefix=${prefix}`,
26
26
  sessionLost: lost,
27
- }), [username, lost]);
27
+ }), [username, cast, lost]);
28
28
  }
29
- function App({ username, router }) {
29
+ function App({ username, cast, router, }) {
30
30
  const [lost, setLost] = useState(false);
31
- const value = useMemo(() => ({ username, lost: () => setLost(true) }), [username]);
31
+ const value = useMemo(() => ({ username, cast, lost: () => setLost(true) }), [username, cast]);
32
32
  if (lost)
33
33
  return (_jsx(Notice, { role: "alert", title: "Your session ended", children: _jsx(Button, { onClick: () => window.location.reload(), children: "Reload" }) }));
34
34
  return (_jsx(Reader.Provider, { value: value, children: _jsx(RouterProvider, { router: router }) }));
35
35
  }
36
36
  /** The reader the browser context names by cookie, else `username`. */
37
- function readerOf(username) {
37
+ function readerName(username) {
38
38
  const named = document.cookie
39
39
  .split('; ')
40
40
  .find((cookie) => cookie.startsWith(`${readerCookie}=`));
@@ -42,9 +42,18 @@ function readerOf(username) {
42
42
  ? username
43
43
  : decodeURIComponent(named.slice(readerCookie.length + 1));
44
44
  }
45
- export async function start(username) {
45
+ export async function start(username, cast) {
46
46
  document.title = project.title;
47
- const { default: routes } = await load();
48
- const router = projectRouter(routes, useHost);
49
- createRoot(document.getElementById('root')).render(_jsx(QueryClientProvider, { client: new QueryClient(), children: _jsx(App, { username: readerOf(username), router: router }) }));
47
+ const local = window.location.pathname.startsWith('/local/');
48
+ const { default: shown } = await (local ? project.local : project.root)();
49
+ if (local) {
50
+ const { default: root } = await project.root();
51
+ if (shown.path !== root.path)
52
+ throw new Error(`ui/local/index.tsx's path "${shown.path}" is not ui/index.tsx's "${root.path}"`);
53
+ }
54
+ const base = local ? '/local' : '';
55
+ if (window.location.pathname === `${base}/`)
56
+ window.history.replaceState(null, '', `${base}/${shown.path}/`);
57
+ const router = projectRouter(shown, useHost, undefined, base || undefined);
58
+ createRoot(document.getElementById('root')).render(_jsx(QueryClientProvider, { client: new QueryClient(), children: _jsx(App, { username: readerName(username), cast: cast, router: router }) }));
50
59
  }