@metacensus/library-research 0.11.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/roles.js CHANGED
@@ -1,50 +1,109 @@
1
- import { globSync, lstatSync, readFileSync, realpathSync } from 'node:fs';
2
- import { join, sep } from 'node:path';
3
- import { Corpus, Research } from './schema.js';
4
- /** Reads a project's research.json; each role reads its files when called. */
5
- export function project(dir) {
6
- const { title, data } = read(dir, 'research.json', Research);
7
- const roles = {
8
- corpus: () => readCorpus(dir),
9
- };
10
- for (const [role, glob] of Object.entries(data))
11
- roles[role] = () => match(dir, glob);
12
- return { title, roles };
13
- }
14
- function match(dir, glob) {
15
- const files = globSync(glob, { cwd: dir }).sort();
16
- if (!files.length)
17
- throw new Error(`${join(dir, glob)}: matches no file`);
18
- const head = glob.indexOf('*');
19
- if (head < 0)
20
- return read(dir, files[0]);
21
- const tail = glob.length - glob.lastIndexOf('*') - 1;
22
- const key = (file) => file.slice(head, file.length - tail).replace(/^[./]+|[./]+$/g, '');
23
- return Object.fromEntries(files.map((file) => [key(file), read(dir, file)]));
24
- }
25
- export function readCorpus(dir) {
26
- return lstatSync(join(dir, 'corpus.json'), { throwIfNoEntry: false })
27
- ? read(dir, 'corpus.json', Corpus)
28
- : {};
1
+ import { lstatSync, readFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
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;
29
27
  }
30
- function read(dir, file, schema) {
31
- const path = join(dir, file);
32
- const fail = (why) => new Error(`${path}: ${why}`);
33
- 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
+ }
34
100
  try {
35
- if (!realpathSync(path).startsWith(realpathSync(dir) + sep))
36
- throw new Error('leads outside the project');
37
- json = JSON.parse(readFileSync(path, 'utf8'));
101
+ loaded.corpus = readCorpus(dir);
38
102
  }
39
- catch (e) {
40
- throw fail(e.message);
103
+ catch (error) {
104
+ failures.push(error.message);
41
105
  }
42
- if (!schema)
43
- return json;
44
- const checked = schema.safeParse(json);
45
- if (!checked.success)
46
- throw fail(checked.error.issues
47
- .map(({ path, message }) => `${path.join('.')}: ${message}`)
48
- .join('; '));
49
- return checked.data;
106
+ if (failures.length)
107
+ throw new Error(failures.join('\n'));
108
+ return loaded;
50
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,27 +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;
14
17
  /** Called each time a data request is answered 401 or 403, so several times for one lost session. */
15
18
  sessionLost(): void;
16
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;
28
+ }
17
29
  export interface Reader {
18
30
  username: string;
19
31
  }
20
- export interface Location {
21
- path: string;
22
- search: string;
23
- hash: string;
24
- }
25
32
  export type Kind = keyof typeof kinds;
26
33
  export type Corpus = z.infer<typeof CorpusSchema>;
27
34
  export type Paper = Corpus[string];
35
+ export type { Mount, RouterOf, Routes } from './mount.js';
@@ -25,6 +25,7 @@ export function hostConfig(root) {
25
25
  '@metacensus/library-ui',
26
26
  '@metacensus/library-ui/pdf',
27
27
  '@tanstack/react-query',
28
+ '@tanstack/react-router',
28
29
  'react-dom/client',
29
30
  'zod',
30
31
  ],
package/dist/vite.js CHANGED
@@ -2,7 +2,7 @@ import { existsSync, readdirSync, readFileSync, realpathSync, statSync, } from '
2
2
  import { basename, dirname, join, relative, resolve, sep } from 'node:path';
3
3
  import { satisfies } from 'semver';
4
4
  import { isCSSRequest, preprocessCSS, searchForWorkspaceRoot, } from 'vite';
5
- import { project } from './roles.js';
5
+ import { project, read } from './data.js';
6
6
  const prefix = 'projects';
7
7
  const dataPath = new RegExp(`^${prefix}/([^/]+)/data/([^/]+)\\.json$`);
8
8
  const virtual = 'virtual:research-projects';
@@ -159,13 +159,22 @@ export function research({ projects, }) {
159
159
  apply: 'build',
160
160
  enforce: 'post',
161
161
  buildStart() {
162
- for (const [slug, dir] of dirs)
163
- for (const [role, json] of Object.entries(project(dir).roles))
162
+ for (const [slug, dir] of dirs) {
163
+ const { roles, pages } = project(dir);
164
+ for (const [role, json] of Object.entries(roles))
164
165
  this.emitFile({
165
166
  type: 'asset',
166
167
  fileName: `${prefix}/${slug}/data/${role}.json`,
167
168
  source: JSON.stringify(json()),
168
169
  });
170
+ for (const [role, held] of Object.entries(pages))
171
+ for (const [page, file] of Object.entries(held()))
172
+ this.emitFile({
173
+ type: 'asset',
174
+ fileName: `${prefix}/${slug}/private/${page}/${role}.json`,
175
+ source: JSON.stringify(read(dir, file)),
176
+ });
177
+ }
169
178
  },
170
179
  buildEnd() {
171
180
  const local = dirs.map(([, dir]) => join(dir, 'ui/local') + sep);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@metacensus/library-research",
3
- "version": "0.11.0",
3
+ "version": "0.12.0",
4
4
  "license": "AGPL-3.0-only",
5
5
  "repository": {
6
6
  "type": "git",
@@ -18,6 +18,19 @@
18
18
  "types": "./dist/index.d.ts",
19
19
  "default": "./dist/index.js"
20
20
  },
21
+ "./host": {
22
+ "types": "./dist/host.d.ts",
23
+ "default": "./dist/host.js"
24
+ },
25
+ "./testing": {
26
+ "types": "./dist/testing.d.ts",
27
+ "default": "./dist/testing.js"
28
+ },
29
+ "./roles": {
30
+ "types": "./dist/roles.d.ts",
31
+ "default": "./dist/roles.js"
32
+ },
33
+ "./csp.json": "./csp.json",
21
34
  "./schema": {
22
35
  "types": "./dist/schema.d.ts",
23
36
  "default": "./dist/schema.js"
@@ -37,6 +50,7 @@
37
50
  "./tsconfig.json": "./tsconfig.project.json"
38
51
  },
39
52
  "files": [
53
+ "csp.json",
40
54
  "dist",
41
55
  "schema",
42
56
  "src/virtual.d.ts",
@@ -56,6 +70,7 @@
56
70
  "peerDependencies": {
57
71
  "@metacensus/library-ui": ">=0.6.0 <1",
58
72
  "@tanstack/react-query": "^5",
73
+ "@tanstack/react-router": "^1",
59
74
  "react": "^18.3.1",
60
75
  "react-dom": "^18.3.1",
61
76
  "vite": "~8.3.8"
@@ -64,6 +79,7 @@
64
79
  "@eslint/js": "^9.39.5",
65
80
  "@metacensus/library-ui": "^0.12.0",
66
81
  "@tanstack/react-query": "^5.108.0",
82
+ "@tanstack/react-router": "^1.170.46",
67
83
  "@types/jsdom": "^30.0.0",
68
84
  "@types/node": "^24.19.2",
69
85
  "@types/semver": "^7.8.0",
@@ -16,6 +16,17 @@
16
16
  "type": "string",
17
17
  "pattern": "^(?!\\/)(?!.*\\.\\.).+$"
18
18
  }
19
+ },
20
+ "private": {
21
+ "type": "object",
22
+ "propertyNames": {
23
+ "type": "string",
24
+ "pattern": "^(?!corpus$)[a-z][A-Za-z0-9]*$"
25
+ },
26
+ "additionalProperties": {
27
+ "type": "string",
28
+ "pattern": "^(?!\\/)(?!.*\\.\\.).+$"
29
+ }
19
30
  }
20
31
  },
21
32
  "required": [
package/src/virtual.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  declare module 'virtual:research-projects' {
2
- import type { Project } from '@metacensus/library-research'
2
+ import type { Routes } from '@metacensus/library-research'
3
3
 
4
- type Root = () => Promise<{ default: Project }>
4
+ type Root = () => Promise<{ default: Routes }>
5
5
  /** `local` only under `vite serve`, where `ui/local/index.tsx` exists. */
6
6
  const projects: Record<string, { title: string; root: Root; local?: Root }>
7
7
  export default projects
@@ -9,6 +9,8 @@
9
9
  "strict": true,
10
10
  "noUncheckedIndexedAccess": true,
11
11
  "isolatedModules": true,
12
+ "allowImportingTsExtensions": true,
13
+ "erasableSyntaxOnly": true,
12
14
  "skipLibCheck": true,
13
15
  "noEmit": true
14
16
  }