File size: 10,660 Bytes
7bc6789
 
 
5084a8e
 
 
 
3da3d2a
 
 
 
 
 
 
 
 
 
 
 
4e9a68f
 
3da3d2a
 
 
 
 
 
6885df8
3da3d2a
 
 
 
 
 
 
 
 
 
 
 
 
 
2c1d035
 
 
5084a8e
2c1d035
5084a8e
 
 
3da3d2a
 
 
 
 
5084a8e
72c1b1a
 
 
 
 
 
 
 
 
5084a8e
 
 
 
 
 
4754d8a
3da3d2a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5084a8e
 
 
3da3d2a
 
 
 
 
 
 
 
 
 
 
 
 
4e9a68f
 
 
 
 
 
3da3d2a
 
4754d8a
 
 
2c1d035
 
 
4754d8a
 
2c1d035
4754d8a
 
3da3d2a
 
4e9a68f
3da3d2a
 
 
 
 
 
 
5084a8e
 
 
2c1d035
4754d8a
 
 
 
 
 
 
 
5084a8e
 
 
 
 
 
 
 
 
 
 
 
 
4e9a68f
 
 
 
3da3d2a
 
 
 
 
5084a8e
2c1d035
 
 
 
 
 
 
3da3d2a
2c1d035
 
 
 
 
 
 
 
 
 
 
 
 
 
f3244ea
2c1d035
3da3d2a
 
 
 
 
 
 
6063b42
5084a8e
2c1d035
 
5084a8e
 
3da3d2a
5084a8e
 
 
 
 
 
 
3da3d2a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
import fs from "node:fs";
import path from "node:path";
import crypto from "node:crypto";
import { createRequire } from "node:module";
const resources = createRequire(import.meta.url)(
  path.join(process.cwd(), "static/reader-resources.js")
);

const args = Object.fromEntries(
  process.argv
    .slice(2)
    .reduce(
      (items, value, index, all) =>
        value.startsWith("--")
          ? [...items, [value.slice(2), all[index + 1]?.startsWith("--") ? true : all[index + 1]]]
          : items,
      []
    )
);
const sourceRequired = ["reader.html", ...resources.readerFiles];
const required = [...sourceRequired, ...resources.foliateFiles.map(file => `foliate-reader/${file}`)];
// Source smoke assertions, not a substitute for runtime behavior tests.
const behavioral = [
  /\bVoiceOfMLReaderRuntime\s*\.\s*createReaderRuntime\s*\(/,
  /\bVoiceOfMLReaderAdapters\s*\.\s*createAdapterRegistry\s*\(/,
  /\bformatAdapters\s*\.\s*register\s*\(\s*mode\s*,/,
  /\bformatAdapters\s*\.\s*activate\s*\(\s*capability\s*\.\s*mode\s*\)/,
  /\bdisableStream\s*:\s*(?:true|false)\b/,
  /\bnextReaderGeneration\s*\(\s*["']navigation["']\s*\)/
];
const hash = (file) => crypto.createHash("sha256").update(fs.readFileSync(file)).digest("hex");

function assert(condition, message) {
  if (!condition) throw new Error(message);
}

function staticRoot(root, artifact) {
  if (!artifact) return path.join(root, "static");
  return fs.existsSync(path.join(artifact, "static")) ? path.join(artifact, "static") : artifact;
}

function checkBehavior(root) {
  const reader = ["reader.js", ...resources.readerComponentFiles].map(file =>
    fs.readFileSync(path.join(root, "static", file), "utf8")).join("\n").replace(/\breaderContext\./g, "");
  for (const [, dependency] of reader.matchAll(/(?:\/static\/)([^"'\s]+\.(?:js|mjs))/g)) {
    assert(
      required.includes(dependency),
      `Reader dependency missing from inventory: ${dependency}`
    );
  }
  for (const marker of behavioral) {
    assert(marker.test(reader), `missing Reader source behavior in ${root}: ${marker}`);
  }
}

function checkAssets(output, hashed = false) {
  for (const vendor of Object.values(resources.foliateVendors)) {
    const filename = path.join("foliate-reader/vendor", vendor.file);
    assert(hash(path.join(output, filename)) === vendor.sha256,
      `Foliate vendor integrity mismatch: ${filename}`);
  }
  for (const [name, filename] of [["pdf", "pdf.mjs"], ["pdfWorker", "pdf.worker.mjs"]]) {
    assert(hash(path.join(output, "foliate-reader/vendor/pdfjs", filename)) === resources.vendors[name].sha256,
      `Foliate PDF engine mismatch: ${filename}`);
  }
  for (const vendor of Object.values(resources.vendors)) {
    assert(
      hash(path.join(output, vendor.path)) === vendor.sha256,
      `vendor integrity mismatch: ${vendor.path}`
    );
  }
  const files = new Set([...required, "app.js"].map(file => hashed ? currentAsset(output, file) : file));
  for (const file of files) {
    const target = path.join(output, file);
    assert(fs.existsSync(target) && fs.statSync(target).isFile(), `missing Reader asset: ${file}`);
    const shortHash = path.basename(file).match(/\.([0-9a-f]{12})\.(?:js|mjs|css)$/)?.[1];
    if (shortHash) {
      assert(hash(target).startsWith(shortHash), `Reader asset hash mismatch: ${file}`);
    }
    // Vendor internals may contain optional paths; inspect our references to them only.
    if (file.split(path.sep).includes("vendor")) continue;
    const content = fs.readFileSync(target, "utf8");
    const refs = content.matchAll(/(["'])((?:\/(?:search\/)?static\/|\.\.?\/)[^"'\s]+)\1/g);
    for (const [, , url] of refs) {
      const ref = url.split(/[?#]/)[0];
      if (!ref.startsWith("/") && !/\.(?:js|mjs|css|html)$/.test(ref)) continue;
      const relative = ref.startsWith("/")
        ? ref.replace(/^\/(?:search\/)?static\//, "")
        : path.join(path.dirname(file), ref);
      const resolved = path.resolve(output, relative);
      assert(
        resolved.startsWith(`${path.resolve(output)}${path.sep}`),
        `invalid Reader asset: ${url}`
      );
      assert(fs.existsSync(resolved), `unresolved Reader reference in ${file}: ${url}`);
      if (ref.endsWith("/")) {
        assert(
          fs.statSync(resolved).isDirectory() && fs.readdirSync(resolved).length > 0,
          `empty or invalid Reader asset directory: ${url}`
        );
      } else {
        if (hashed && resources.buildFiles("github").includes(relative)) {
          throw new Error(`unversioned build dependency in ${file}: ${url}`);
        }
        files.add(relative);
      }
    }
  }
  for (const directory of ["vendor/cmaps", "vendor/standard_fonts", "vendor/wasm"]) {
    const target = path.join(output, directory);
    assert(
      fs.existsSync(target) &&
        fs.statSync(target).isDirectory() &&
        fs.readdirSync(target).length > 0,
      `missing or empty Reader vendor directory: ${directory}`
    );
  }
  for (const directory of ["foliate-reader/vendor/pdfjs/cmaps", "foliate-reader/vendor/pdfjs/standard_fonts",
    "foliate-reader/vendor/pdfjs/wasm"]) {
    const target = path.join(output, directory);
    assert(fs.existsSync(target) && fs.statSync(target).isDirectory() && fs.readdirSync(target).length > 0,
      `missing or empty Foliate PDF.js directory: ${directory}`);
  }
}

function currentAsset(output, filename) {
  if (!resources.buildFiles("github").includes(filename)) return filename;
  assert(!fs.existsSync(path.join(output, filename)), `obsolete asset alias: ${filename}`);
  const directory = path.dirname(filename), basename = path.basename(filename);
  const extension = path.extname(basename), stem = basename.slice(0, -extension.length);
  const matches = fs.readdirSync(path.join(output, directory)).filter(file => file.startsWith(stem + ".") &&
    file.endsWith(extension) && /^[0-9a-f]{12}$/.test(file.slice(stem.length + 1, -extension.length)));
  assert(matches.length === 1, `expected one current asset: ${filename}`);
  return path.join(directory, matches[0]);
}

function checkProject(root, artifact) {
  const source = path.join(root, "static");
  for (const file of sourceRequired) {
    const target = path.join(source, file);
    assert(
      fs.existsSync(target) && fs.statSync(target).isFile(),
      `missing source Reader file: ${file}`
    );
  }
  checkBehavior(root);
  const output = staticRoot(root, artifact);
  checkAssets(output, !!artifact);
  if (artifact) {
    const project = args.project || (fs.existsSync(path.join(root, "Dockerfile")) ? "hf" : "github");
    for (const file of resources.buildFiles(project)) currentAsset(output, file);
    const shellPath = fs.existsSync(path.join(output, "index.html"))
      ? path.join(output, "index.html") : path.join(output, "../index.html");
    const shell = fs.readFileSync(shellPath, "utf8");
    const scripts = [...shell.matchAll(/<script\b[^>]*\bsrc="([^"]+)"/g)].map(match => match[1]);
    assert(scripts.length === 1 && /\/app\.[0-9a-f]{12}\.js$/.test(scripts[0]),
      "search shell must load one hashed app bundle");
    const app = fs.readFileSync(path.join(output, currentAsset(output, "app.js")), "utf8");
    const swPath = fs.existsSync(path.join(output, "sw.js"))
      ? path.join(output, "sw.js")
      : path.join(output, "../sw.js");
    const sw = fs.readFileSync(swPath, "utf8");
    assert(
      !/VoiceOfMLReaderResources\.(?:shellAssets|engineAssets)\(/.test(app),
      "unexpanded Reader warming inventory"
    );
    assert(
      !/VoiceOfMLReaderResources\.runtimePaths\(/.test(sw),
      "unexpanded Reader cache inventory"
    );
  }
  const manifest = [
    ...sourceRequired.map(file => `${file}:${hash(path.join(source, file))}`),
    ...resources.foliateFiles.map(file => `foliate-reader/${file}:${hash(path.join(output, "foliate-reader", file))}`)
  ].join("\n");
  return crypto.createHash("sha256").update(manifest).digest("hex");
}

function crossCheck(githubRoot, hfRoot) {
  const exact = [
    "reader-resources.js",
    "reader/core/reader-store.js",
    "reader/pdf/reader-pdf-text.js",
    "reader/search/workers/reader-pdf-book-search-worker.mjs",
    "reader/search/reader-pdf-book-search.mjs",
    "search/search-session.js",
    "search/download-controller.js",
    "search/reader-navigation.js",
    "reader.css",
    "reader/core/reader-request-manager.js",
    "reader/formats/reader-chapter-repository.js",
    "reader/ui/reader-scroll-anchor.js",
    "reader/formats/reader-section-virtualizer.js",
    "reader/core/reader-runtime.js",
    "reader/formats/reader-format-adapters.js",
    "reader/core/reader-security.js",
    "reader/search/reader-search-controller.mjs",
    "reader/search/reader-dom-search.mjs",
    "reader/formats/reader-image-loader.mjs",
    "reader/reader-components.mjs",
    "reader/ui/reader-document-styles.mjs",
    "reader/core/reader-diagnostics.mjs", "reader/core/reader-lifecycle.mjs", "reader/ui/reader-bookmarks.mjs",
    "reader/formats/reader-media-format.mjs", "reader/core/reader-document-loader.mjs", "reader/formats/reader-html-format.mjs",
    "reader/formats/reader-text-format.mjs", "reader/formats/reader-chapter-format.mjs",
    "reader/pdf/pdf-worker-wrapper.mjs"
  ];
  for (const file of exact) {
    assert(
      hash(path.join(githubRoot, "static", file)) === hash(path.join(hfRoot, "static", file)),
      `cross-project drift: ${file}`
    );
  }
  for (const file of ["compose_app.mjs", "copy_reader_vendor.mjs", "fetch_foliate_reader.mjs", "foliate-local.patch.b64", "check_reader_release.mjs"]) {
    assert(
      hash(path.join(githubRoot, "scripts/build", file)) === hash(path.join(hfRoot, "scripts/build", file)),
      `cross-project drift: scripts/build/${file}`
    );
  }
  for (const root of [githubRoot, hfRoot]) checkBehavior(root);
  const vectors = "tests/reader-contract-vectors.json";
  if (fs.existsSync(path.join(githubRoot, vectors)) && fs.existsSync(path.join(hfRoot, vectors))) {
    assert(
      hash(path.join(githubRoot, vectors)) === hash(path.join(hfRoot, vectors)),
      "cross-project drift: Reader contract vectors"
    );
  }
}

try {
  if (args.cross) {
    crossCheck(path.resolve(args["github-root"]), path.resolve(args["hf-root"]));
    console.log("reader cross-project release gate ok");
  } else {
    const root = path.resolve(args.root || ".");
    const identity = checkProject(
      root,
      args["artifact-root"] ? path.resolve(args["artifact-root"]) : null
    );
    console.log(`reader release gate ok ${identity}`);
  }
} catch (error) {
  console.error(`reader release gate failed: ${error.message}`);
  process.exitCode = 1;
}