@metacensus/library-research 0.14.0 → 0.15.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.
@@ -12,22 +12,40 @@ export default defineConfig({
12
12
  wait: { stdout: /(?<library_research_url>http:\S+\/)/ },
13
13
  },
14
14
  });
15
- /** Collects a page's CSP and axe violations; the returned function fails on those not listed. */
16
- async function watch(page) {
15
+ /**
16
+ * Collects a page's CSP and axe violations, the console errors its own script logs or throws, and its requests to other origins; the returned function fails on those not listed. A request to another origin is aborted whether or not it is listed.
17
+ */
18
+ async function watch(page, baseURL) {
17
19
  const found = [];
18
20
  await page.exposeFunction(report, (v) => found.push(v));
21
+ // The browser's own console lines (a CSP refusal, a failed load) carry no arguments and are reported, or left to the spec, elsewhere.
22
+ page.on('console', (message) => {
23
+ if (message.type() === 'error' && message.args().length > 0)
24
+ found.push(`console ${message.text()}`);
25
+ });
26
+ page.on('pageerror', (error) => found.push(`console ${error}`));
27
+ await page.context().route('**/*', (route) => {
28
+ const { protocol, origin } = new URL(route.request().url());
29
+ if (!protocol.startsWith('http') || origin === new URL(baseURL).origin)
30
+ return route.fallback();
31
+ found.push(`origin ${origin}`);
32
+ return route.abort('blockedbyclient');
33
+ });
19
34
  await page.addInitScript(`window.${sent} = []; document.addEventListener('securitypolicyviolation', (e) => ${sent}.push(${report}('csp ' + e.effectiveDirective + ' ' + e.blockedURI)))`);
20
35
  return async (listed) => {
21
36
  await page.evaluate(`Promise.all(window.${sent} ?? [])`);
22
- const axe = await new AxeBuilder({ page }).analyze();
37
+ const axe = await new AxeBuilder({ page })
38
+ .withTags(['wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa', 'wcag22aa'])
39
+ .analyze();
23
40
  found.push(...axe.violations.map((v) => `axe ${v.id}`));
24
41
  expect(found.filter((v) => !listed.includes(v)), 'unlisted violations').toEqual([]);
25
42
  };
26
43
  }
27
44
  export const test = base.extend({
45
+ /** What a spec excuses, by entry: `axe <rule>`, `csp <directive> <blocked uri>`, `console <message>` for a console error or uncaught error, `origin <origin>` for a request to another origin (still aborted). */
28
46
  violations: [[], { option: true }],
29
- page: async ({ page, violations }, provide) => {
30
- const finish = await watch(page);
47
+ page: async ({ page, baseURL, violations }, provide) => {
48
+ const finish = await watch(page, baseURL);
31
49
  await provide(page);
32
50
  await finish(violations);
33
51
  },
@@ -47,7 +65,7 @@ export const test = base.extend({
47
65
  },
48
66
  ]);
49
67
  const page = await context.newPage();
50
- finishers.push(await watch(page));
68
+ finishers.push(await watch(page, baseURL));
51
69
  return page;
52
70
  });
53
71
  // Every page is checked, and the first failure is the one thrown.
@@ -0,0 +1,4 @@
1
+ /** What a project's id, its first URL segment and its key in the host's `projects`, matches. */
2
+ export declare const projectIdPattern: RegExp;
3
+ /** Throws unless `id` matches `projectIdPattern`, naming it as `what`. */
4
+ export declare function checkProjectId(id: string, what: string): void;
@@ -0,0 +1,7 @@
1
+ /** What a project's id, its first URL segment and its key in the host's `projects`, matches. */
2
+ export const projectIdPattern = /^[a-z0-9][a-z0-9-]*$/;
3
+ /** Throws unless `id` matches `projectIdPattern`, naming it as `what`. */
4
+ export function checkProjectId(id, what) {
5
+ if (!projectIdPattern.test(id))
6
+ throw new Error(`${what} "${id}" does not match ${projectIdPattern}`);
7
+ }
package/dist/react.d.ts CHANGED
@@ -1,38 +1,32 @@
1
1
  import { DocumentError } from './documents.js';
2
- import type { Corpus, Doc, Host, Member, Reader } from './types.js';
2
+ import type { Corpus, Data, Doc, Host, Member, Reader, Schemas } from './types.js';
3
3
  /** The `Host` of the project's frame; throws outside `./host`'s `frame`. Stable for the life of the frame. */
4
4
  export declare function useHost(): Host;
5
5
  /** The person the project is viewed as; `self` is false while the host views it as another. */
6
6
  export declare function useReader(): Reader;
7
7
  /** Every person of the project, each with their role. */
8
8
  export declare function useMembers(): Member[];
9
- type Dataset<T = unknown> = readonly [
10
- dataset: string,
11
- parse: (json: unknown) => T
12
- ];
13
9
  /**
14
- * One dataset's JSON, parsed by `parse`. Suspends while it loads; a failed
15
- * fetch or parse throws to the frame's error notice, naming the dataset. A 401 or
16
- * 403 also calls `Host.sessionLost`. `parse` must be pure: it is read once per
17
- * dataset list, not on every render.
10
+ * One dataset's JSON, parsed by its schema in `ui/datasets.ts`. Suspends while
11
+ * it loads; a failed fetch or parse throws to the frame's error notice,
12
+ * naming the dataset. A 401 or 403 also calls `Host.sessionLost`.
18
13
  */
19
- export declare function useData<T>(dataset: string, parse: (json: unknown) => T): T;
14
+ export declare function useData<K extends keyof Schemas>(dataset: K): Data<K>;
20
15
  /**
21
- * `useData` for several datasets at once, fetched in parallel: a `[dataset, parse]`
22
- * tuple each, the values returned in the same order and typed by their parsers.
23
- * Each parser must be pure: it is read once per dataset list, not on every render.
16
+ * `useData` for several datasets at once, fetched in parallel: the names in a
17
+ * tuple, the values returned in the same order and typed by their schemas.
24
18
  */
25
- export declare function useDatas<const R extends readonly Dataset[]>(datasets: R): {
26
- -readonly [K in keyof R]: R[K] extends Dataset<infer T> ? T : never;
19
+ export declare function useDatas<const R extends readonly (keyof Schemas)[]>(datasets: R): {
20
+ -readonly [K in keyof R]: R[K] extends keyof Schemas ? Data<R[K]> : never;
27
21
  };
28
22
  /**
29
23
  * The viewed person's pages of a private dataset, as `{ page: parsed }`: empty
30
24
  * when they hold none, a page the host names but the build did not emit left
31
- * out. `parse` runs on each page's JSON and must be pure. Its cache entry,
32
- * `{ json } | null`, is not `useData`'s raw JSON, under the same key prefix.
25
+ * out. Its schema parses each page's JSON. Its cache entry, `{ json } | null`,
26
+ * is not `useData`'s raw JSON, under the same key prefix.
33
27
  */
34
- export declare function usePrivate<T>(dataset: string, parse: (json: unknown) => T): Record<string, T>;
35
- /** The `corpus` dataset, parsed by the library's own schema, through `useData`. */
28
+ export declare function usePrivate<K extends keyof Schemas>(dataset: K): Record<string, Data<K>>;
29
+ /** The `corpus` dataset, every work by id, parsed by the library's own schema. */
36
30
  export declare function useCorpus(): Corpus;
37
31
  /**
38
32
  * One document of the project, or `null` when none has that id. Suspends while
@@ -55,4 +49,3 @@ export declare function useSaveDocument(id: string): import("@tanstack/react-que
55
49
  body: unknown;
56
50
  when?: "absent" | number;
57
51
  }, unknown>;
58
- export {};
package/dist/react.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { useMutation, useQueryClient, useSuspenseQueries, useSuspenseQuery, } from '@tanstack/react-query';
2
2
  import { useContext, useMemo, useState } from 'react';
3
- import { FetchContext, HostContext } from './context.js';
3
+ import { DatasetsContext, FetchContext, HostContext } from './context.js';
4
4
  import { DocumentError, documentId, documentPrefix } from './documents.js';
5
5
  import * as schema from './schema.js';
6
6
  /** The `Host` of the project's frame; throws outside `./host`'s `frame`. Stable for the life of the frame. */
@@ -18,37 +18,50 @@ export function useReader() {
18
18
  export function useMembers() {
19
19
  return useHost().members;
20
20
  }
21
+ /** The schemas `defineProject` registered, as `parse` functions by dataset name. */
22
+ function useParsers() {
23
+ const schemas = useContext(DatasetsContext);
24
+ return (dataset) => {
25
+ const schema = Object.hasOwn(schemas, dataset)
26
+ ? schemas[dataset]
27
+ : undefined;
28
+ if (!schema)
29
+ throw new Error(`dataset "${dataset}": defineProject was given no schema for it`);
30
+ return (json) => schema.parse(json);
31
+ };
32
+ }
21
33
  /**
22
- * One dataset's JSON, parsed by `parse`. Suspends while it loads; a failed
23
- * fetch or parse throws to the frame's error notice, naming the dataset. A 401 or
24
- * 403 also calls `Host.sessionLost`. `parse` must be pure: it is read once per
25
- * dataset list, not on every render.
34
+ * One dataset's JSON, parsed by its schema in `ui/datasets.ts`. Suspends while
35
+ * it loads; a failed fetch or parse throws to the frame's error notice,
36
+ * naming the dataset. A 401 or 403 also calls `Host.sessionLost`.
26
37
  */
27
- export function useData(dataset, parse) {
28
- return useDatas([[dataset, parse]])[0];
38
+ export function useData(dataset) {
39
+ return useDatas([dataset])[0];
29
40
  }
30
41
  /**
31
- * `useData` for several datasets at once, fetched in parallel: a `[dataset, parse]`
32
- * tuple each, the values returned in the same order and typed by their parsers.
33
- * Each parser must be pure: it is read once per dataset list, not on every render.
42
+ * `useData` for several datasets at once, fetched in parallel: the names in a
43
+ * tuple, the values returned in the same order and typed by their schemas.
34
44
  */
35
45
  export function useDatas(datasets) {
46
+ const parser = useParsers();
47
+ return useFetched(datasets.map((dataset) => [String(dataset), parser(String(dataset))]));
48
+ }
49
+ /** Fetches each dataset and parses it; the parsers are those of a project's fixed schemas, so they are read once per dataset list. */
50
+ function useFetched(datasets) {
36
51
  const host = useHost();
37
- // The parsers and select functions are kept until the dataset list changes, so
38
- // an inline parse does not rerun on every render.
39
52
  const key = JSON.stringify(datasets.map(([dataset]) => dataset));
40
- const [held, hold] = useState({ key, datasets });
41
- if (held.key !== key)
42
- hold({ key, datasets });
43
- const names = held.datasets.map(([dataset]) => dataset);
44
- const selects = useMemo(() => held.datasets.map(([dataset, parse]) => (json) => {
53
+ const names = datasets.map(([dataset]) => dataset);
54
+ const selects = useMemo(() => datasets.map(([dataset, parse]) => (json) => {
45
55
  try {
46
56
  return parse(json);
47
57
  }
48
58
  catch (cause) {
49
59
  return failed(`dataset "${dataset}"`, cause);
50
60
  }
51
- }), [held]);
61
+ }),
62
+ // The datasets are named by `key`, and their parsers do not change.
63
+ // eslint-disable-next-line react-hooks/exhaustive-deps
64
+ [key]);
52
65
  return useSuspenseQueries({
53
66
  queries: names.map((dataset, i) => {
54
67
  const url = host.data(dataset);
@@ -80,28 +93,29 @@ function failed(what, cause) {
80
93
  /**
81
94
  * The viewed person's pages of a private dataset, as `{ page: parsed }`: empty
82
95
  * when they hold none, a page the host names but the build did not emit left
83
- * out. `parse` runs on each page's JSON and must be pure. Its cache entry,
84
- * `{ json } | null`, is not `useData`'s raw JSON, under the same key prefix.
96
+ * out. Its schema parses each page's JSON. Its cache entry, `{ json } | null`,
97
+ * is not `useData`'s raw JSON, under the same key prefix.
85
98
  */
86
- export function usePrivate(dataset, parse) {
99
+ export function usePrivate(dataset) {
100
+ const name = String(dataset);
101
+ const parse = useParsers()(name);
87
102
  const host = useHost();
88
- const urls = host.private(dataset);
103
+ const urls = host.private(name);
89
104
  const pages = Object.keys(urls);
90
105
  const key = pages.join();
91
- const held = useHeld(dataset, parse);
92
106
  const selects = useMemo(() => pages.map((page) => (found) => {
93
107
  if (!found)
94
108
  return null;
95
109
  try {
96
- return { value: held(found.json) };
110
+ return { value: parse(found.json) };
97
111
  }
98
112
  catch (cause) {
99
- return failed(`private dataset "${dataset}" page "${page}"`, cause);
113
+ return failed(`private dataset "${name}" page "${page}"`, cause);
100
114
  }
101
115
  }),
102
- // The pages are named by `key`.
116
+ // The pages are named by `key`, and a project's schemas do not change.
103
117
  // eslint-disable-next-line react-hooks/exhaustive-deps
104
- [held, key]);
118
+ [key]);
105
119
  return useSuspenseQueries({
106
120
  queries: pages.map((page, i) => {
107
121
  const url = urls[page];
@@ -117,7 +131,7 @@ export function usePrivate(dataset, parse) {
117
131
  throw new Error(`${response.status} from ${url}`);
118
132
  return response.json().then((json) => ({ json }));
119
133
  })
120
- .catch((cause) => failed(`private dataset "${dataset}" page "${page}"`, cause)),
134
+ .catch((cause) => failed(`private dataset "${name}" page "${page}"`, cause)),
121
135
  select: selects[i],
122
136
  staleTime: Infinity,
123
137
  retry: false,
@@ -126,9 +140,10 @@ export function usePrivate(dataset, parse) {
126
140
  combine: (results) => Object.fromEntries(results.flatMap(({ data }, i) => data ? [[pages[i], data.value]] : [])),
127
141
  });
128
142
  }
129
- /** The `corpus` dataset, parsed by the library's own schema, through `useData`. */
143
+ const corpusDataset = ['corpus', (json) => schema.Corpus.parse(json)];
144
+ /** The `corpus` dataset, every work by id, parsed by the library's own schema. */
130
145
  export function useCorpus() {
131
- return useData('corpus', (json) => schema.Corpus.parse(json));
146
+ return useFetched([corpusDataset])[0];
132
147
  }
133
148
  /** A fetch whose 401 and 403 are the host's lost session, and whose other failures are a `DocumentError`. */
134
149
  function useSend() {
package/dist/schema.d.ts CHANGED
@@ -1,18 +1,7 @@
1
- import { z } from 'zod';
2
- export declare const kinds: {
3
- readonly pdf: "application/pdf";
4
- readonly doc: "application/msword";
5
- readonly docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
6
- readonly xls: "application/vnd.ms-excel";
7
- readonly xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
8
- readonly zip: "application/zip";
9
- readonly gif: "image/gif";
10
- readonly jpg: "image/jpeg";
11
- readonly tif: "image/tiff";
12
- readonly txt: "text/plain";
13
- readonly html: "text/plain";
14
- readonly xml: "text/plain";
15
- };
1
+ import { z } from './zod.js';
2
+ export { Corpus, kinds } from './corpus.js';
3
+ /** A project's id, matching `projectIdPattern`. */
4
+ export declare const ProjectId: z.ZodString;
16
5
  export declare const Research: z.ZodObject<{
17
6
  title: z.ZodString;
18
7
  data: z.ZodRecord<z.ZodString, z.ZodString>;
@@ -24,22 +13,3 @@ export declare const Research: z.ZodObject<{
24
13
  pages: z.ZodOptional<z.ZodArray<z.ZodString>>;
25
14
  }, z.core.$strict>>>;
26
15
  }, z.core.$strict>;
27
- export declare const Corpus: z.ZodRecord<z.ZodString, z.ZodObject<{
28
- kind: z.ZodEnum<{
29
- pdf: "pdf";
30
- doc: "doc";
31
- docx: "docx";
32
- xls: "xls";
33
- xlsx: "xlsx";
34
- zip: "zip";
35
- gif: "gif";
36
- jpg: "jpg";
37
- tif: "tif";
38
- txt: "txt";
39
- html: "html";
40
- xml: "xml";
41
- }>;
42
- title: z.ZodOptional<z.ZodString>;
43
- citation: z.ZodOptional<z.ZodString>;
44
- open: z.ZodOptional<z.ZodLiteral<true>>;
45
- }, z.core.$strict>>;
package/dist/schema.js CHANGED
@@ -1,28 +1,30 @@
1
- import { z } from 'zod';
2
- z.config({ jitless: true });
3
- export const kinds = {
4
- pdf: 'application/pdf',
5
- doc: 'application/msword',
6
- docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
7
- xls: 'application/vnd.ms-excel',
8
- xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
9
- zip: 'application/zip',
10
- gif: 'image/gif',
11
- jpg: 'image/jpeg',
12
- tif: 'image/tiff',
13
- txt: 'text/plain',
14
- html: 'text/plain',
15
- xml: 'text/plain',
16
- };
1
+ import { projectIdPattern } from './project-id.js';
2
+ import { z } from './zod.js';
3
+ export { Corpus, kinds } from './corpus.js';
17
4
  const dataset = z.string().regex(/^(?!corpus$)[a-z][A-Za-z0-9]*$/);
18
- const glob = z.string().regex(/^(?!\/)(?!.*\.\.).+$/);
5
+ /** A project's id, matching `projectIdPattern`. */
6
+ export const ProjectId = z
7
+ .string()
8
+ .regex(projectIdPattern)
9
+ .describe('A project id: lower-case letters, digits and hyphens, not starting with a hyphen');
19
10
  const role = z.string().regex(/^[a-z][a-z0-9-]*$/);
20
11
  const page = z.string().regex(/^[a-z0-9][a-z0-9-]*$/);
12
+ // Relative and without `..`, then `*`s only as `stars` says, and no other glob character.
13
+ const other = String.raw `[^*?[\]{}()!]*`;
14
+ const glob = (stars, rule) => {
15
+ const grammar = `a glob that is relative, has no .., ${rule}, and has none of ?[]{}()!`;
16
+ return z
17
+ .string()
18
+ .regex(new RegExp(`^(?!/)(?!.*\\.\\.)(?=.)${stars}$`), `must be ${grammar}`)
19
+ .describe(grammar);
20
+ };
21
+ const dataGlob = glob(`${other}(?:\\*${other})?`, 'has at most one *');
22
+ const privateGlob = glob(`${other}\\*${other}`, 'has exactly one *');
21
23
  export const Research = z
22
24
  .strictObject({
23
25
  title: z.string().min(1),
24
- data: z.record(dataset, glob),
25
- private: z.record(dataset, glob).optional(),
26
+ data: z.record(dataset, dataGlob),
27
+ private: z.record(dataset, privateGlob).optional(),
26
28
  /** The roles a person of the project holds one of. */
27
29
  roles: z
28
30
  .array(role)
@@ -54,17 +56,11 @@ export const Research = z
54
56
  else if (!roles.includes(person.role))
55
57
  issue(`has role "${person.role}", which is not in roles`);
56
58
  }
57
- for (const [name, pattern] of Object.entries(held)) {
58
- const issue = (message) => ctx.addIssue({ code: 'custom', path: ['private', name], message });
59
+ for (const name of Object.keys(held))
59
60
  if (Object.hasOwn(data, name))
60
- issue(`dataset "${name}" is in data and private`);
61
- if (pattern.split('*').length !== 2 || /[?[\]{}()!]/.test(pattern))
62
- issue(`dataset "${name}": glob "${pattern}" must hold exactly one * and no other glob character`);
63
- }
61
+ ctx.addIssue({
62
+ code: 'custom',
63
+ path: ['private', name],
64
+ message: `dataset "${name}" is in data and private`,
65
+ });
64
66
  });
65
- export const Corpus = z.record(z.string().regex(/^[0-9a-f]{64}$/), z.strictObject({
66
- kind: z.enum(Object.keys(kinds)),
67
- title: z.string().optional(),
68
- citation: z.string().optional(),
69
- open: z.literal(true).optional(),
70
- }));
package/dist/testing.d.ts CHANGED
@@ -32,7 +32,7 @@ export interface TestHostOptions {
32
32
  * the project navigated, and `documents()` what it saved, sorted by id.
33
33
  */
34
34
  export declare function testHost(project: AnyProject, { data, documents, private: held, people, roles, reader, self, url, sessionLost, }?: TestHostOptions): {
35
- element: ReactElement<any, string | import("react").JSXElementConstructor<any>>;
35
+ element: ReactElement<unknown, string | import("react").JSXElementConstructor<any>>;
36
36
  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/react-router").AnyRoute], unknown, unknown, unknown, undefined>, "preserve", false, import("@tanstack/history").RouterHistory, Record<string, any>>;
37
37
  documents: () => import("./types.js").Doc<unknown>[];
38
38
  };
package/dist/types.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import type { z } from 'zod';
2
- import type { Corpus as CorpusSchema, kinds } from './schema.js';
2
+ import type * as corpus from './corpus.js';
3
3
  /**
4
4
  * What a host gives a project: `frame` provides it and `useHost` returns it.
5
5
  * The methods are called during render, so each must be cheap and return the
@@ -36,24 +36,62 @@ export interface Doc<T> {
36
36
  revision: number;
37
37
  body: T;
38
38
  }
39
+ /**
40
+ * What a project declares of itself by augmenting this module:
41
+ * `datasets`, the type of ui/datasets.ts's export, and `roles`, research.json's
42
+ * roles as a union; `load` checks that ui/datasets.ts's `roles` tuple equals
43
+ * research.json's.
44
+ *
45
+ * @example
46
+ * declare module '@metacensus/library-research' {
47
+ * interface Register {
48
+ * datasets: typeof datasets
49
+ * roles: (typeof roles)[number]
50
+ * }
51
+ * }
52
+ */
53
+ export interface Register {
54
+ }
55
+ /** What parses a dataset's JSON: a Zod schema is one. */
56
+ export interface Schema {
57
+ parse(json: unknown): unknown;
58
+ }
59
+ /** The schemas of a project: those of `Register`'s `datasets`, else any by name. */
60
+ export type Schemas = Register extends {
61
+ datasets: infer D;
62
+ } ? D : Record<string, Schema>;
63
+ /** What a dataset's schema parses its JSON to. */
64
+ export type Data<K extends keyof Schemas> = Schemas[K] extends {
65
+ parse(json: unknown): infer T;
66
+ } ? T : unknown;
39
67
  /** A person of the project. */
40
68
  export interface Member {
41
69
  /** The name the host signs them in as. */
42
70
  username: string;
43
71
  /** The name a person reads. */
44
72
  name: string;
45
- /** One of research.json's `roles`; null only in a project that declares none. */
46
- role: string | null;
73
+ /** One of research.json's `roles`: `Register`'s where it declares them; null only in a project that declares none. */
74
+ role: Register extends {
75
+ roles: infer R;
76
+ } ? R : string | null;
47
77
  }
48
78
  /** The person a project is viewed as; `useReader` returns them. */
49
79
  export interface Reader extends Member {
50
80
  /** False while the host views the project as another person than the one signed in. */
51
81
  self: boolean;
52
82
  }
53
- /** A kind of record the schema allows, one of `kinds`' keys. */
54
- export type Kind = keyof typeof kinds;
55
- /** The parsed `corpus` dataset: every paper by sha. */
56
- export type Corpus = z.infer<typeof CorpusSchema>;
57
- /** One paper of the corpus. */
58
- export type Paper = Corpus[string];
83
+ /** A kind of file the schema allows, one of `kinds`' keys. */
84
+ export type Kind = keyof typeof corpus.kinds;
85
+ /** The parsed `corpus` dataset: every work by id. */
86
+ export type Corpus = z.infer<typeof corpus.Corpus>;
87
+ /** One work: its CSL-JSON, its editions, and the fields pending a person. */
88
+ export type Work = z.infer<typeof corpus.Work>;
89
+ /** One edition of a work, holding its files by sha. */
90
+ export type Edition = z.infer<typeof corpus.Edition>;
91
+ /** One held file of an edition. */
92
+ export type Paper = z.infer<typeof corpus.Paper>;
93
+ /** A work's CSL-JSON metadata. */
94
+ export type Csl = z.infer<typeof corpus.Csl>;
95
+ /** What waits on a person: a placeholder's `key`, or a pending CSL field. */
96
+ export type Judgment = ReturnType<typeof corpus.pending>[number];
59
97
  export type { AnyProject, Mount, Project, RouterOf } from './mount.js';
@@ -1,22 +1,12 @@
1
1
  import react from '@vitejs/plugin-react';
2
- import { createRequire } from 'node:module';
3
2
  import { join } from 'node:path';
4
- import tailwind from 'tailwindcss';
5
- import { research, tailwindContent } from './vite.js';
3
+ import { research, tailwind } from './vite.js';
6
4
  export function hostConfig(root) {
7
5
  const projects = { project: root };
8
- const preset = createRequire(import.meta.url)('@metacensus/library-ui/tailwind3');
9
6
  return {
10
7
  root: join(root, 'ui'),
11
8
  configFile: false,
12
- plugins: [react(), research({ projects })],
13
- css: {
14
- postcss: {
15
- plugins: [
16
- tailwind({ presets: [preset], content: tailwindContent(projects) }),
17
- ],
18
- },
19
- },
9
+ plugins: [react(), research({ projects }), tailwind({ projects })],
20
10
  // library-research's modules stay unbundled so the host and the project
21
11
  // share one copy; Vite reads no imports inside node_modules, so theirs are
22
12
  // listed.
package/dist/vite.d.ts CHANGED
@@ -11,5 +11,13 @@ import { type Plugin } from 'vite';
11
11
  export declare function research({ projects, }: {
12
12
  projects: Record<string, string>;
13
13
  }): Plugin[];
14
- /** The Tailwind `content` globs that scan each project's `ui/`, skipping its `node_modules`; spread into the host's config. */
15
- export declare function tailwindContent(projects: Record<string, string>): string[];
14
+ /**
15
+ * Tailwind 4 for a host, as a plugin because a project's path comes from the
16
+ * host's environment, which a stylesheet's literal `@source` cannot hold. A
17
+ * host stylesheet importing `tailwindcss` gains each project's `ui/` as a
18
+ * source; a project stylesheet gains `@reference`s to Tailwind and library-ui's
19
+ * theme, so its `@apply` needs no boilerplate.
20
+ */
21
+ export declare function tailwind({ projects, }: {
22
+ projects: Record<string, string>;
23
+ }): Plugin[];
package/dist/vite.js CHANGED
@@ -1,8 +1,11 @@
1
1
  import { existsSync, readdirSync, readFileSync, realpathSync, statSync, } from 'node:fs';
2
2
  import { basename, dirname, join, relative, resolve, sep } from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
3
4
  import { satisfies } from 'semver';
4
5
  import { isCSSRequest, preprocessCSS, searchForWorkspaceRoot, } from 'vite';
6
+ import tailwindcss from '@tailwindcss/vite';
5
7
  import { project, read } from './data.js';
8
+ import { checkProjectId } from './project-id.js';
6
9
  const prefix = 'projects';
7
10
  const dataPath = new RegExp(`^${prefix}/([^/]+)/data/([^/]+)\\.json$`);
8
11
  const privatePath = new RegExp(`^${prefix}/([^/]+)/private/([^/]+)/([^/]+)\\.json$`);
@@ -66,6 +69,8 @@ export function research({ projects, }) {
66
69
  name: 'research',
67
70
  config(user) {
68
71
  const from = resolve(user.root ?? '');
72
+ for (const slug of Object.keys(projects))
73
+ checkProjectId(slug, 'project');
69
74
  dirs = Object.entries(projects).map(([slug, path]) => [
70
75
  slug,
71
76
  realpathSync(resolve(from, path)),
@@ -297,10 +302,55 @@ export function research({ projects, }) {
297
302
  },
298
303
  ];
299
304
  }
300
- /** The Tailwind `content` globs that scan each project's `ui/`, skipping its `node_modules`; spread into the host's config. */
301
- export function tailwindContent(projects) {
302
- return Object.values(projects).flatMap((path) => [
303
- `${path}/ui/**/*.{ts,tsx}`,
304
- `!${path}/ui/node_modules/**`,
305
- ]);
305
+ /**
306
+ * Tailwind 4 for a host, as a plugin because a project's path comes from the
307
+ * host's environment, which a stylesheet's literal `@source` cannot hold. A
308
+ * host stylesheet importing `tailwindcss` gains each project's `ui/` as a
309
+ * source; a project stylesheet gains `@reference`s to Tailwind and library-ui's
310
+ * theme, so its `@apply` needs no boilerplate.
311
+ */
312
+ export function tailwind({ projects, }) {
313
+ // tailwindcss resolves from library-research, so a project's stylesheet
314
+ // builds with the host's copy wherever the project sits.
315
+ const references = [
316
+ [
317
+ 'tailwindcss',
318
+ fileURLToPath(import.meta.resolve('tailwindcss/index.css')),
319
+ ],
320
+ ['@metacensus/library-ui/theme.css', '@metacensus/library-ui/theme.css'],
321
+ ];
322
+ let dirs = [];
323
+ return [
324
+ {
325
+ name: 'research:tailwind',
326
+ enforce: 'pre',
327
+ configResolved({ root }) {
328
+ dirs = Object.values(projects).map((path) => join(realpathSync(resolve(root, path)), 'ui'));
329
+ },
330
+ transform(code, id) {
331
+ if (!cssCode(id))
332
+ return;
333
+ const file = id.split('?')[0];
334
+ const uses = (target, rules = 'import|reference') => new RegExp(`@(?:${rules})\\s+(['"])${escape(target)}\\1`).test(code);
335
+ const project = dirs.find((dir) => inside(file, dir));
336
+ if (project) {
337
+ if (relative(project, file).split(sep).includes('node_modules'))
338
+ return;
339
+ const lines = references
340
+ .filter(([target]) => !uses(target))
341
+ .map(([, path]) => `@reference ${JSON.stringify(path)};\n`);
342
+ return lines.length
343
+ ? { code: lines.join('') + code, map: null }
344
+ : undefined;
345
+ }
346
+ if (uses('tailwindcss', 'import'))
347
+ return {
348
+ code: code +
349
+ dirs.map((dir) => `\n@source ${JSON.stringify(dir)};`).join(''),
350
+ map: null,
351
+ };
352
+ },
353
+ },
354
+ ...tailwindcss(),
355
+ ];
306
356
  }
package/dist/zod.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ import { z } from 'zod';
2
+ export { z };
package/dist/zod.js ADDED
@@ -0,0 +1,4 @@
1
+ import { z } from 'zod';
2
+ // Before any schema is built: zod picks JIT at construction, and the host's CSP forbids eval.
3
+ z.config({ jitless: true });
4
+ export { z };