paperlint 18.2.1 → 18.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/.github/dependabot.yml +17 -0
  2. package/.github/workflows/ci.yml +30 -5
  3. package/CLAUDE.md +2 -1
  4. package/dist/domain/register.d.ts +1 -1
  5. package/dist/domain/register.d.ts.map +1 -1
  6. package/dist/domain/sentences.d.ts +3 -11
  7. package/dist/domain/sentences.d.ts.map +1 -1
  8. package/dist/domain/sentences.js +53 -8
  9. package/dist/domain/sentences.js.map +1 -1
  10. package/dist/eslint-rules/CLAUDE.md.spec.js +2 -2
  11. package/dist/eslint-rules/CLAUDE.md.spec.js.map +1 -1
  12. package/dist/folder-venue-rule.js +1 -1
  13. package/dist/readability.d.ts +12 -9
  14. package/dist/readability.d.ts.map +1 -1
  15. package/dist/readability.js +3 -3
  16. package/dist/readability.js.map +1 -1
  17. package/docs/design/paper-sources.md +1 -1
  18. package/docs/e2e.md +2 -2
  19. package/docs/optional-rules.md +2 -2
  20. package/docs/rules/pdf/body-size.md +1 -1
  21. package/docs/rules/tex/heading-case.md +2 -2
  22. package/docs/rules/tex/max-paragraph-numbers.md +13 -7
  23. package/docs/rules/tex/max-paragraph-words.md +17 -28
  24. package/docs/rules/tex/max-sentence-words.md +3 -2
  25. package/docs/rules/tex/negated-sentences.md +2 -2
  26. package/docs/rules/tex/register.md +1 -1
  27. package/docs/rules/tex/term-before-definition.md +1 -1
  28. package/docs/rules.md +3 -3
  29. package/docs/venues.md +1 -1
  30. package/docs/website.md +61 -5
  31. package/eslint-rules/CLAUDE.md +3 -3
  32. package/eslint-rules/CLAUDE.md.spec.ts +2 -2
  33. package/eslint.config.mjs +15 -4
  34. package/fixtures/real-papers.test.ts +24 -19
  35. package/package.json +4 -5
  36. package/presets/acm-sigconf.jsonc +1 -1
  37. package/presets/aidc-2026.jsonc +4 -4
  38. package/presets/aidc-2026.md +1 -1
  39. package/presets/ase-2026.md +1 -1
  40. package/presets/ieee-conference.jsonc +1 -1
  41. package/presets/msr-2027.jsonc +1 -1
  42. package/presets/neurips-style.jsonc +2 -2
  43. package/presets/neurips-style.md +1 -1
  44. package/presets/sp-2027.md +1 -1
  45. package/presets/venue-profile.schema.json +1 -1
  46. package/scripts/check.ts +9 -1
  47. package/scripts/coverage-config.test.ts +2 -0
  48. package/scripts/grow-real-papers/archive.test.ts +294 -0
  49. package/scripts/grow-real-papers/archive.ts +287 -0
  50. package/scripts/grow-real-papers/collect.test.ts +329 -0
  51. package/scripts/grow-real-papers/collect.ts +316 -0
  52. package/scripts/grow-real-papers/http.test.ts +95 -0
  53. package/scripts/grow-real-papers/http.ts +76 -0
  54. package/scripts/grow-real-papers/main.test.ts +295 -0
  55. package/scripts/grow-real-papers/main.ts +221 -0
  56. package/scripts/grow-real-papers/paper.test.ts +305 -0
  57. package/scripts/grow-real-papers/paper.ts +241 -0
  58. package/scripts/grow-real-papers/rules.test.ts +222 -0
  59. package/scripts/grow-real-papers/rules.ts +250 -0
  60. package/scripts/grow-real-papers/sources.test.ts +275 -0
  61. package/scripts/grow-real-papers/sources.ts +239 -0
  62. package/scripts/grow-real-papers/testkit.ts +79 -0
  63. package/src/domain/register.ts +1 -1
  64. package/src/domain/sentences.test.ts +128 -0
  65. package/src/domain/sentences.ts +60 -11
  66. package/src/folder-venue-rule.test.ts +1 -1
  67. package/src/folder-venue-rule.ts +1 -1
  68. package/src/readability.test.ts +82 -41
  69. package/src/readability.ts +12 -9
  70. package/src/register-bands.test.ts +4 -4
  71. package/src/rule-cases.test.ts +6 -6
@@ -0,0 +1,294 @@
1
+ /**
2
+ * The source archive: reading the e-print, choosing what a paper keeps and where, and the record
3
+ * of what was staged. The archives are built in memory by `testkit.ts`.
4
+ */
5
+ import { gzipSync } from "node:zlib";
6
+ import { describe, expect, test } from "vitest";
7
+ import {
8
+ jsonOf,
9
+ recordOf,
10
+ sha256,
11
+ stagingPlan,
12
+ toplevelOf,
13
+ unpack,
14
+ untar,
15
+ } from "./archive.ts";
16
+ import { file, mainTex, tar, tarGz, text } from "./testkit.ts";
17
+
18
+ const paths = (fs: readonly { path: string }[]) => fs.map((f) => f.path);
19
+
20
+ describe("unpack", () => {
21
+ test("keeps regular files at safe paths, under their long names", () => {
22
+ const files = untar(
23
+ tar([
24
+ { name: "./main.tex", body: "m" },
25
+ { name: "sec.tex", prefix: "ACL2026", body: "s" },
26
+ {
27
+ name: "././@LongLink",
28
+ type: "L",
29
+ body: `${"d/".repeat(60)}long.tex\0`,
30
+ },
31
+ { name: "truncated", body: "l" },
32
+ {
33
+ name: "PaxHeader/short.bib",
34
+ type: "x",
35
+ body: "30 path=pax/named.bib\n",
36
+ },
37
+ { name: "short.bib", body: "p" },
38
+ { name: "PaxHeader/nul.sty", type: "x", body: "20 mtime=1700000000\n" },
39
+ { name: "nul.sty", type: "\0", body: "n" },
40
+ { name: "../escape.tex", body: "e" },
41
+ { name: "/abs.tex", body: "a" },
42
+ { name: "./", body: "" },
43
+ { name: "link.tex", type: "2" },
44
+ { name: "figs", type: "5" },
45
+ ]),
46
+ );
47
+ // Guards: prefix and long names applied; links, directories and paths that leave the archive dropped.
48
+ expect(paths(files)).toEqual([
49
+ "main.tex",
50
+ "ACL2026/sec.tex",
51
+ `${"d/".repeat(60)}long.tex`,
52
+ "pax/named.bib",
53
+ "nul.sty",
54
+ ]);
55
+ // Guards: a stream cut before the end-of-archive blocks still ends.
56
+ expect(
57
+ untar(tar([{ name: "a.tex", body: "a" }]).subarray(0, 1024)),
58
+ ).toEqual([{ path: "a.tex", bytes: Buffer.from("a") }]);
59
+ });
60
+
61
+ test("a gzipped tar, a lone gzipped .tex, a PDF and a broken gzip", () => {
62
+ const archive = unpack(tarGz([{ name: "x/main.tex", body: "t" }]));
63
+ // Guards: a tar's files.
64
+ expect(archive.ok && paths(archive.files)).toEqual(["x/main.tex"]);
65
+ // Guards: one gzipped file is the main file.
66
+ expect(unpack(gzipSync(Buffer.from("tex")))).toEqual({
67
+ ok: true,
68
+ files: [{ path: "main.tex", bytes: Buffer.from("tex") }],
69
+ });
70
+ // Guards: a PDF-only submission is rejected by name.
71
+ expect(unpack(Buffer.from("%PDF-1.5"))).toEqual({
72
+ ok: false,
73
+ reason: "no source: not gzip (PDF-only submission)",
74
+ });
75
+ // Guards: gzip magic over garbage is rejected, not thrown.
76
+ expect(unpack(Buffer.from([0x1f, 0x8b, 1, 2, 3]))).toEqual({
77
+ ok: false,
78
+ reason: "unreadable source: Error: unknown compression method",
79
+ });
80
+ });
81
+ });
82
+
83
+ describe("unpack — a tar this reader does not take", () => {
84
+ test("a tar without the ustar mark (old V7 format) is rejected, not staged as one .tex", () => {
85
+ const v7 = Buffer.from(
86
+ tar([{ name: "main.tex", body: "\\begin{document}" }]),
87
+ );
88
+ v7.fill(0, 257, 263);
89
+ expect(unpack(gzipSync(v7))).toEqual({
90
+ ok: false,
91
+ reason: "unreadable source: binary data, not a ustar tar",
92
+ });
93
+ });
94
+ });
95
+
96
+ describe("the top-level file", () => {
97
+ test.each([
98
+ [
99
+ "00README.json names it",
100
+ [
101
+ file(
102
+ "00README.json",
103
+ '{"sources":[{"usage":"toplevel","filename":"ACL2026/main.tex"}]}',
104
+ ),
105
+ ],
106
+ "ACL2026/main.tex",
107
+ ],
108
+ [
109
+ "00README.json without a toplevel",
110
+ [file("00README.json", '{"sources":[{"filename":"a.tex"}]}')],
111
+ null,
112
+ ],
113
+ ["00README.json that is not JSON", [file("00README.json", "{")], null],
114
+ [
115
+ "a legacy 00README.XXX",
116
+ [file("00README.XXX", "sub/ms.tex toplevelfile\n")],
117
+ "sub/ms.tex",
118
+ ],
119
+ [
120
+ "a legacy 00README without one",
121
+ [file("00README.XXX", "nostamp\n")],
122
+ null,
123
+ ],
124
+ ["no 00README", [file("main.tex", "")], null],
125
+ ])("%s", (_, files, named) => {
126
+ // Guards: what arXiv compiles first, as its own README says.
127
+ expect(toplevelOf(files)).toBe(named);
128
+ });
129
+
130
+ test("jsonOf: JSON, or undefined", () => {
131
+ // Guards: both halves of the parse.
132
+ expect([jsonOf("[1]"), jsonOf("{")]).toEqual([[1], undefined]);
133
+ });
134
+ });
135
+
136
+ describe("the staging plan", () => {
137
+ test("a main file in a subfolder is staged from the archive root, every input kept", () => {
138
+ // The defect the code review found in the 2026-11-20 run: staging from the main file's folder
139
+ // dropped `sections/intro.tex`, which arXiv resolves from the root.
140
+ const files = [
141
+ file(
142
+ "00README.json",
143
+ '{"sources":[{"usage":"toplevel","filename":"ACL2026/main.tex"}]}',
144
+ ),
145
+ file("ACL2026/main.tex", mainTex("\\input{sections/intro}")),
146
+ file("ACL2026/main.bbl", "bbl"),
147
+ file("sections/intro.tex", "Intro."),
148
+ file("acl.sty", "sty"),
149
+ file("figs/plot.pdf", "pdf"),
150
+ ];
151
+ const plan = stagingPlan(files);
152
+ // Guards: every text file at its path from the root; only the main file and its .bbl renamed.
153
+ expect(plan.ok && { ...plan, staged: paths(plan.staged) }).toEqual({
154
+ ok: true,
155
+ main: "ACL2026/main.tex",
156
+ mainText: mainTex("\\input{sections/intro}"),
157
+ mainCandidates: 1,
158
+ staged: ["paper.tex", "paper.bbl", "sections/intro.tex", "acl.sty"],
159
+ renames: [
160
+ "ACL2026/main.tex to paper.tex",
161
+ "ACL2026/main.bbl to paper.bbl",
162
+ ],
163
+ edits: [],
164
+ size: mainTex("\\input{sections/intro}").length + 3 + 6 + 3,
165
+ });
166
+ });
167
+
168
+ test("without a README: main/paper/ms first, else the largest candidate", () => {
169
+ const named = stagingPlan([
170
+ file("big.tex", mainTex("x".repeat(100))),
171
+ file("ms.tex", mainTex("")),
172
+ file("notmain.tex", "\\documentclass{article} % \\begin{document}"),
173
+ ]);
174
+ // Guards: a conventional name beats size; a file whose \begin{document} is commented out is no candidate.
175
+ expect(named.ok && [named.main, named.mainCandidates]).toEqual([
176
+ "ms.tex",
177
+ 2,
178
+ ]);
179
+ const largest = stagingPlan([
180
+ file("a.tex", mainTex("")),
181
+ file("b.tex", mainTex("longer")),
182
+ ]);
183
+ // Guards: else the largest.
184
+ expect(largest.ok && largest.main).toBe("b.tex");
185
+ // Guards: no candidate at all is a rejection.
186
+ expect(stagingPlan([file("a.bib", "")])).toEqual({
187
+ ok: false,
188
+ reason: "no main .tex found",
189
+ });
190
+ });
191
+ });
192
+
193
+ describe("renaming the main file", () => {
194
+ test("a wrapper's \\input of the main file is rewritten to paper", () => {
195
+ const plan = stagingPlan([
196
+ file("00README.XXX", "doc.tex toplevelfile"),
197
+ file("doc.tex", mainTex("body")),
198
+ file("wrap.tex", "\\input{doc}\\include{doc.tex}\\input{other}"),
199
+ file("paper.tex.bak", "dropped"),
200
+ ]);
201
+ // Guards: each rewrite noted, the wrapper's bytes changed, other inputs untouched.
202
+ expect(
203
+ plan.ok && {
204
+ edits: plan.edits,
205
+ wrap: plan.staged.filter((f) => f.path === "wrap.tex").map(text),
206
+ },
207
+ ).toEqual({
208
+ edits: [
209
+ "\\input{doc} to \\input{paper}",
210
+ "\\include{doc.tex} to \\include{paper.tex}",
211
+ ],
212
+ wrap: ["\\input{paper}\\include{paper.tex}\\input{other}"],
213
+ });
214
+ const already = stagingPlan([
215
+ file("paper.tex", mainTex("")),
216
+ file("w.tex", "\\input{paper}"),
217
+ ]);
218
+ // Guards: a main file already called paper.tex needs no rename and no edit.
219
+ expect(already.ok && [already.renames, already.edits]).toEqual([[], []]);
220
+ });
221
+ });
222
+
223
+ describe("renaming the main file onto a file the archive already has", () => {
224
+ test("an archive with its own paper.tex or paper.bbl besides another main is rejected", () => {
225
+ const readme = file("00README.XXX", "main.tex toplevelfile");
226
+ // Guards: two files would be staged as paper.tex, and one would be lost.
227
+ expect(
228
+ stagingPlan([
229
+ readme,
230
+ file("main.tex", mainTex("")),
231
+ file("paper.tex", "x"),
232
+ ]),
233
+ ).toEqual({ ok: false, reason: "two files would be staged as paper.tex" });
234
+ // Guards: the same for the .bbl.
235
+ expect(
236
+ stagingPlan([
237
+ readme,
238
+ file("main.tex", mainTex("")),
239
+ file("main.bbl", ""),
240
+ file("paper.bbl", ""),
241
+ ]),
242
+ ).toEqual({ ok: false, reason: "two files would be staged as paper.bbl" });
243
+ });
244
+ });
245
+
246
+ describe("record-by-hand.json", () => {
247
+ test("paper.tex, root class and style files, then inputs depth first, hashed", () => {
248
+ const staged = [
249
+ file(
250
+ "paper.tex",
251
+ mainTex(
252
+ "\\input{./a}\\include{b.tex}\\input{a}% \\input{c}\n\\input{gone}",
253
+ ),
254
+ ),
255
+ file("a.tex", "\\input{sub/d}"),
256
+ file("sub/d.tex", "d"),
257
+ file("b.tex", "b"),
258
+ file("c.tex", "c"),
259
+ file("z.sty", "z"),
260
+ file("acl.cls", "k"),
261
+ file("styles/nested.sty", "n"),
262
+ ];
263
+ const hash = (p: string) =>
264
+ sha256(staged.find((f) => f.path === p)?.bytes ?? new Uint8Array());
265
+ const order = [
266
+ "paper.tex",
267
+ "acl.cls",
268
+ "z.sty",
269
+ "a.tex",
270
+ "sub/d.tex",
271
+ "b.tex",
272
+ ];
273
+ // Guards: the order and roles a reader audits, no repeat, a commented or missing input left out.
274
+ expect(recordOf(staged)).toEqual({
275
+ schema: 1,
276
+ inputs: [
277
+ { path: "paper.tex", role: "body" },
278
+ { path: "acl.cls", role: "preamble" },
279
+ { path: "z.sty", role: "preamble" },
280
+ { path: "a.tex", role: "body" },
281
+ { path: "sub/d.tex", role: "body" },
282
+ { path: "b.tex", role: "body" },
283
+ ],
284
+ written: [],
285
+ bibdata: [],
286
+ bibtex: { ran: false },
287
+ sha256: Object.fromEntries(order.map((p) => [p, hash(p)])),
288
+ });
289
+ // Guards: a staging without paper.tex records it as empty.
290
+ expect(recordOf([]).sha256).toEqual({
291
+ "paper.tex": sha256(new Uint8Array()),
292
+ });
293
+ });
294
+ });
@@ -0,0 +1,287 @@
1
+ /**
2
+ * An arXiv source archive, read in memory and never executed: `unpack` turns the e-print's bytes
3
+ * into files, `stagingPlan` decides which files a paper keeps and where, `recordOf` writes the
4
+ * `record-by-hand.json` of what was staged. arXiv compiles from the archive's ROOT (its
5
+ * `00README.json` names the top-level file, e.g. `ACL2026/main.tex`), so every kept file keeps its
6
+ * path from the root and only the main file moves, to `paper.tex`. No I/O.
7
+ */
8
+ import { createHash } from "node:crypto";
9
+ import { gunzipSync } from "node:zlib";
10
+ import { z } from "zod";
11
+ import { stripComments, TEXT_EXT, type Verdict } from "./rules.ts";
12
+
13
+ export type ArchiveFile = Readonly<{ path: string; bytes: Uint8Array }>;
14
+
15
+ const latin1 = (b: Uint8Array): string => Buffer.from(b).toString("latin1");
16
+ const cString = (b: Uint8Array, at: number, len: number): string =>
17
+ latin1(b.subarray(at, at + len)).replace(/\0.*$/s, "");
18
+
19
+ /** A path inside the archive, or null for one that would leave it (absolute, or `..`). */
20
+ const safePath = (p: string): string | null => {
21
+ const parts = p
22
+ .replace(/^(\.\/)+/, "")
23
+ .split("/")
24
+ .filter((s) => s !== "" && s !== ".");
25
+ return p.startsWith("/") || parts.includes("..") || parts.length === 0
26
+ ? null
27
+ : parts.join("/");
28
+ };
29
+
30
+ type TarEntry = Readonly<{
31
+ name: string;
32
+ type: string;
33
+ body: Uint8Array;
34
+ next: number;
35
+ }>;
36
+
37
+ /** The tar entry whose header starts at `at`, or null at the end of the archive. */
38
+ const entryAt = (tar: Uint8Array, at: number): TarEntry | null => {
39
+ if (at + 512 > tar.length || tar[at] === 0) return null;
40
+ const head = tar.subarray(at, at + 512);
41
+ const size = parseInt(cString(head, 124, 12).trim(), 8);
42
+ const prefix = cString(head, 345, 155);
43
+ return {
44
+ name: (prefix === "" ? "" : `${prefix}/`) + cString(head, 0, 100),
45
+ type: latin1(head.subarray(156, 157)),
46
+ body: tar.subarray(at + 512, at + 512 + size),
47
+ next: at + 512 + Math.ceil(size / 512) * 512,
48
+ };
49
+ };
50
+
51
+ /** The name a GNU long-name (`L`) or pax (`x`) entry gives the entry after it. */
52
+ const nameForNext = (e: TarEntry): string | null =>
53
+ e.type === "L"
54
+ ? cString(e.body, 0, e.body.length)
55
+ : e.type === "x"
56
+ ? (/(?:^|\n)\d+ path=([^\n]*)\n/.exec(latin1(e.body))?.[1] ?? null)
57
+ : null;
58
+
59
+ /** The regular files of a tar stream; links, directories and unsafe paths are left out. */
60
+ export function untar(
61
+ tar: Uint8Array,
62
+ at = 0,
63
+ longName: string | null = null,
64
+ ): readonly ArchiveFile[] {
65
+ const e = entryAt(tar, at);
66
+ if (e === null) return [];
67
+ const regular = e.type === "0" || e.type === "\0";
68
+ const path = regular ? safePath(longName ?? e.name) : null;
69
+ return [
70
+ ...(path === null ? [] : [{ path, bytes: e.body }]),
71
+ ...untar(tar, e.next, nameForNext(e)),
72
+ ];
73
+ }
74
+
75
+ /** The e-print's files: a gzipped tar, or one gzipped `.tex` (named `main.tex`). */
76
+ export function unpack(
77
+ bytes: Uint8Array,
78
+ ): Verdict<{ files: readonly ArchiveFile[] }> {
79
+ if (bytes[0] !== 0x1f || bytes[1] !== 0x8b)
80
+ return { ok: false, reason: "no source: not gzip (PDF-only submission)" };
81
+ try {
82
+ const raw = gunzipSync(bytes);
83
+ if (latin1(raw.subarray(257, 262)) === "ustar")
84
+ return { ok: true, files: untar(raw) };
85
+ // A NUL byte is no TeX: an older tar with no ustar mark, which this reader does not take.
86
+ return raw.includes(0)
87
+ ? { ok: false, reason: "unreadable source: binary data, not a ustar tar" }
88
+ : { ok: true, files: [{ path: "main.tex", bytes: raw }] };
89
+ } catch (e) {
90
+ return {
91
+ ok: false,
92
+ reason: `unreadable source: ${String(e).slice(0, 80)}`,
93
+ };
94
+ }
95
+ }
96
+
97
+ const ext = (p: string): string => {
98
+ const m = /\.([^./]+)$/.exec(p);
99
+ return m === null ? "" : String(m[1]).toLowerCase();
100
+ };
101
+
102
+ const ReadmeSchema = z.object({
103
+ sources: z.array(
104
+ z.object({ usage: z.string().optional(), filename: z.string() }),
105
+ ),
106
+ });
107
+
108
+ /** JSON text as a value, or undefined when it is not JSON. */
109
+ export const jsonOf = (text: string): unknown => {
110
+ try {
111
+ return JSON.parse(text);
112
+ } catch {
113
+ return undefined;
114
+ }
115
+ };
116
+
117
+ /** The top-level file the archive's `00README.json` (or legacy `00README.XXX`) names, if any. */
118
+ export function toplevelOf(files: readonly ArchiveFile[]): string | null {
119
+ const json = files.find((f) => f.path === "00README.json");
120
+ if (json !== undefined) {
121
+ const readme = ReadmeSchema.safeParse(jsonOf(latin1(json.bytes)));
122
+ return readme.success
123
+ ? (readme.data.sources.find((s) => s.usage === "toplevel")?.filename ??
124
+ null)
125
+ : null;
126
+ }
127
+ const legacy = files.find((f) => /^00README/i.test(f.path));
128
+ return legacy === undefined
129
+ ? null
130
+ : (/(\S+\.tex)\s+toplevelfile/i.exec(latin1(legacy.bytes))?.[1] ?? null);
131
+ }
132
+
133
+ /** What a paper keeps of its archive, and every change made on the way. */
134
+ export type StagingPlan = Readonly<{
135
+ /** The main file's path in the archive. */
136
+ main: string;
137
+ mainText: string;
138
+ /** How many files could be the main one (a `\documentclass` and a `\begin{document}`). */
139
+ mainCandidates: number;
140
+ /** Every kept file at its staged path: the main one at `paper.tex`, the rest where they were. */
141
+ staged: readonly ArchiveFile[];
142
+ /** «a to b», for each renamed file. */
143
+ renames: readonly string[];
144
+ /** «a to b», for each `\input` of the main file that was rewritten to `paper`. */
145
+ edits: readonly string[];
146
+ /** Bytes of the staged text sources. */
147
+ size: number;
148
+ }>;
149
+
150
+ const escape = (s: string): string => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
151
+
152
+ const isMain = (f: ArchiveFile): boolean => {
153
+ const t = stripComments(latin1(f.bytes));
154
+ return (
155
+ ext(f.path) === "tex" &&
156
+ t.includes("\\documentclass") &&
157
+ t.includes("\\begin{document}")
158
+ );
159
+ };
160
+
161
+ /** The one `00README` names, else one called main, paper or ms, else the largest candidate. */
162
+ const pickMain = (
163
+ mains: readonly ArchiveFile[],
164
+ named: string | null,
165
+ ): ArchiveFile | undefined =>
166
+ mains.find((f) => f.path === named) ??
167
+ mains.find((f) => /(^|\/)(main|paper|ms)\.tex$/.test(f.path)) ??
168
+ mains.toSorted((a, b) => b.bytes.length - a.bytes.length)[0];
169
+
170
+ /** Rewrites an `\input`/`\include` of the main file to `paper`, noting each «from to to». */
171
+ const pointAtPaper = (
172
+ f: ArchiveFile,
173
+ stem: string,
174
+ ): Readonly<{ bytes: Uint8Array; edits: readonly string[] }> => {
175
+ if (ext(f.path) !== "tex" || stem === "paper")
176
+ return { bytes: f.bytes, edits: [] };
177
+ const re = new RegExp(
178
+ `\\\\(input|include)\\{${escape(stem)}(\\.tex|\\.bbl)?\\}`,
179
+ "g",
180
+ );
181
+ const text = latin1(f.bytes);
182
+ const edits = [...text.matchAll(re)].map(
183
+ (m) => `${m[0]} to \\${String(m[1])}{paper${m[2] ?? ""}}`,
184
+ );
185
+ return {
186
+ bytes: Buffer.from(text.replace(re, "\\$1{paper$2}"), "latin1"),
187
+ edits,
188
+ };
189
+ };
190
+
191
+ /** A rename target the archive already holds: staging both would drop one of the two files. */
192
+ const takenTwice = (staged: readonly { path: string }[]): string | undefined =>
193
+ ["paper.tex", "paper.bbl"].find(
194
+ (p) => staged.filter((f) => f.path === p).length > 1,
195
+ );
196
+
197
+ /**
198
+ * Every text source of the archive, kept at its path from the root; the main file becomes
199
+ * `paper.tex`, the `.bbl` beside it with its stem `paper.bbl`, and an `\input` of the main file
200
+ * (rare: a wrapper) is rewritten to `paper`.
201
+ */
202
+ export function stagingPlan(
203
+ files: readonly ArchiveFile[],
204
+ ): Verdict<StagingPlan> {
205
+ const mains = files.filter(isMain);
206
+ const pick = pickMain(mains, toplevelOf(files));
207
+ if (pick === undefined) return { ok: false, reason: "no main .tex found" };
208
+ const stem = pick.path.replace(/\.tex$/, "");
209
+ const target = (p: string): string =>
210
+ p === pick.path ? "paper.tex" : p === `${stem}.bbl` ? "paper.bbl" : p;
211
+ const kept = files.filter((f) => TEXT_EXT.has(ext(f.path)));
212
+ const staged = kept.map((f) => ({
213
+ path: target(f.path),
214
+ ...pointAtPaper(f, stem),
215
+ }));
216
+ const taken = takenTwice(staged);
217
+ if (taken !== undefined)
218
+ return { ok: false, reason: `two files would be staged as ${taken}` };
219
+ return {
220
+ ok: true,
221
+ main: pick.path,
222
+ mainText: latin1(pick.bytes),
223
+ mainCandidates: mains.length,
224
+ staged: staged.map((f) => ({ path: f.path, bytes: f.bytes })),
225
+ renames: kept
226
+ .filter((f) => target(f.path) !== f.path)
227
+ .map((f) => `${f.path} to ${target(f.path)}`),
228
+ edits: staged.flatMap((x) => x.edits),
229
+ size: staged.reduce((n, f) => n + f.bytes.length, 0),
230
+ };
231
+ }
232
+
233
+ export const sha256 = (b: Uint8Array): string =>
234
+ createHash("sha256").update(b).digest("hex");
235
+
236
+ const INPUT = /\\(?:input|include)\s*\{([^}]+)\}/g;
237
+
238
+ /** The `.tex` files reached from `file`, depth first in source order, after those in `seen`. */
239
+ const reached = (
240
+ byPath: ReadonlyMap<string, Uint8Array>,
241
+ file: string,
242
+ seen: readonly string[],
243
+ ): readonly string[] =>
244
+ [
245
+ ...stripComments(latin1(byPath.get(file) ?? new Uint8Array())).matchAll(
246
+ INPUT,
247
+ ),
248
+ ].reduce<readonly string[]>((acc, m) => {
249
+ const n = String(m[1]).trim().replace(/^\.\//, "");
250
+ const hit = [n, `${n}.tex`].find((x) => ext(x) === "tex" && byPath.has(x));
251
+ return hit === undefined || acc.includes(hit)
252
+ ? acc
253
+ : reached(byPath, hit, [...acc, hit]);
254
+ }, seen);
255
+
256
+ /**
257
+ * `record-by-hand.json`, NOT TeX's answer: `paper.tex`, the class and style files at the root in
258
+ * name order, then each `\input`/`\include` reached from `paper.tex`, depth first in source order,
259
+ * every one hashed over the staged bytes. A staging without `paper.tex` records it as empty.
260
+ */
261
+ export function recordOf(staged: readonly ArchiveFile[]) {
262
+ const byPath = new Map(staged.map((f) => [f.path, f.bytes]));
263
+ const preamble = staged
264
+ .map((f) => f.path)
265
+ .filter((p) => !p.includes("/") && ["cls", "sty"].includes(ext(p)))
266
+ .toSorted();
267
+ const inputs = [
268
+ { path: "paper.tex", role: "body" },
269
+ ...preamble.map((path) => ({ path, role: "preamble" })),
270
+ ...reached(byPath, "paper.tex", ["paper.tex"])
271
+ .slice(1)
272
+ .map((path) => ({ path, role: "body" })),
273
+ ];
274
+ return {
275
+ schema: 1,
276
+ inputs,
277
+ written: [],
278
+ bibdata: [],
279
+ bibtex: { ran: false },
280
+ sha256: Object.fromEntries(
281
+ inputs.map((i) => [
282
+ i.path,
283
+ sha256(byPath.get(i.path) ?? new Uint8Array()),
284
+ ]),
285
+ ),
286
+ };
287
+ }