@hamzaahmadaslam/schema-truth 0.0.0-stage → 1.0.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/src/jev.mjs ADDED
@@ -0,0 +1,92 @@
1
+ // A small client for TypeSafe's System One API (Jev). Copy this file into a tool as src/jev.mjs.
2
+ // API: POST https://api.typesafe.ai/v1/systemone { model, state, questions } -> { model, answers, usage }
3
+ // The key comes from TYPESAFE_API_KEY and is only ever sent in the Authorization header.
4
+
5
+ export const JEV_ENDPOINT = "https://api.typesafe.ai/v1/systemone";
6
+ export const DEFAULT_MODEL = "jev-latest";
7
+
8
+ export class JevError extends Error {
9
+ constructor(message, status) {
10
+ super(message);
11
+ this.name = "JevError";
12
+ this.status = status;
13
+ }
14
+ }
15
+
16
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
17
+
18
+ /**
19
+ * Asks Jev the `questions` about `state`. Retries 429 and 529 up to `retries` times with exponential backoff
20
+ * (honouring retry-after), times out each attempt after `timeoutMs`, and throws a JevError with a plain message
21
+ * otherwise. `fetchImpl` is injectable so tests never touch the network.
22
+ */
23
+ export async function askJev(state, questions, options = {}) {
24
+ const {
25
+ apiKey = process.env.TYPESAFE_API_KEY,
26
+ model = process.env.TYPESAFE_MODEL || DEFAULT_MODEL,
27
+ timeoutMs = 10_000,
28
+ retries = 3,
29
+ fetchImpl = globalThis.fetch,
30
+ } = options;
31
+ if (!apiKey || !apiKey.trim()) {
32
+ throw new JevError("TYPESAFE_API_KEY is not set. Get a key at https://typesafe.ai and export it first.", 0);
33
+ }
34
+ const body = JSON.stringify({ model, state, questions });
35
+ for (let attempt = 0; ; attempt++) {
36
+ let res;
37
+ try {
38
+ res = await fetchImpl(JEV_ENDPOINT, {
39
+ method: "POST",
40
+ headers: { authorization: `Bearer ${apiKey.trim()}`, "content-type": "application/json" },
41
+ body,
42
+ signal: AbortSignal.timeout(timeoutMs),
43
+ });
44
+ } catch (error) {
45
+ if (attempt < retries) {
46
+ await sleep(500 * 2 ** attempt);
47
+ continue;
48
+ }
49
+ throw new JevError(`Could not reach TypeSafe: ${error?.name === "TimeoutError" ? "timed out" : error?.message}`, 0);
50
+ }
51
+ if (res.ok) {
52
+ const data = await res.json();
53
+ if (!data || typeof data.answers !== "object") throw new JevError("TypeSafe answered without answers.", res.status);
54
+ return data;
55
+ }
56
+ if ((res.status === 429 || res.status === 529) && attempt < retries) {
57
+ const after = Number(res.headers.get("retry-after"));
58
+ await sleep(Number.isFinite(after) && after > 0 ? after * 1000 : 500 * 2 ** attempt);
59
+ continue;
60
+ }
61
+ const detail = await res.text().catch(() => "");
62
+ const reason =
63
+ res.status === 401
64
+ ? "the API key was refused"
65
+ : res.status === 422
66
+ ? `the request was invalid: ${detail.slice(0, 300)}`
67
+ : res.status === 429
68
+ ? "rate limited; try again later"
69
+ : res.status === 529
70
+ ? "TypeSafe is overloaded; try again later"
71
+ : `HTTP ${res.status}`;
72
+ throw new JevError(`TypeSafe error: ${reason}`, res.status);
73
+ }
74
+ }
75
+
76
+ /** Question helpers (the shapes in reference/typesafe/api.md). */
77
+ export const noul = (instructions, criteria) => ({ type: "noul", instructions, ...(criteria ? { criteria } : {}) });
78
+ export const choice = (instructions, options) => ({ type: "choice", instructions, criteria: options });
79
+ export const score = (instructions, levels) => ({ type: "score", instructions, criteria: levels });
80
+
81
+ /** A fetch stand-in for tests: answers each request with `respond(body)` (a plain object) or an error status. */
82
+ export function fixtureFetch(respond) {
83
+ const calls = [];
84
+ const fetchImpl = async (url, init) => {
85
+ const body = JSON.parse(init.body);
86
+ calls.push({ url, body, headers: init.headers });
87
+ const out = await respond(body, calls.length);
88
+ if (typeof out === "number") return new Response(JSON.stringify({ error: "fixture" }), { status: out });
89
+ return new Response(JSON.stringify(out), { status: 200, headers: { "content-type": "application/json" } });
90
+ };
91
+ return { fetchImpl, calls };
92
+ }
package/src/load.mjs ADDED
@@ -0,0 +1,130 @@
1
+ // Reads the input: URLs to fetch, saved HTML files, or folders of them. Each becomes a page with its JSON-LD, its
2
+ // visible text and its claims, or with the reason it could not be read.
3
+ import { readdirSync, readFileSync, statSync } from "node:fs";
4
+ import path from "node:path";
5
+ import { extractClaims } from "./claims.mjs";
6
+ import { UserError } from "./errors.mjs";
7
+ import { DEFAULT_TIMEOUT_MS, fetchPage, FetchError, parseHttpUrl } from "./fetch.mjs";
8
+ import { decodeHtml, parseHtml, readJsonLd } from "./html.mjs";
9
+ import { USER_AGENT } from "./version.mjs";
10
+
11
+ export const HTML_EXTENSIONS = [".html", ".htm", ".xhtml"];
12
+ const CONCURRENCY = 4;
13
+
14
+ /** "https://...", "http://..." and any other "scheme://" count as URLs; everything else is a path. */
15
+ export const isUrl = (arg) => /^[a-z][a-z0-9+.-]+:\/\//i.test(arg);
16
+
17
+ const isHtmlPath = (file) => HTML_EXTENSIONS.includes(path.extname(file).toLowerCase());
18
+
19
+ /** Every HTML file below `root`, skipping node_modules and folders whose names start with a dot, in path order. */
20
+ export function listHtmlFiles(root) {
21
+ const found = [];
22
+ const walk = (dir) => {
23
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
24
+ if (entry.name.startsWith(".") || entry.name === "node_modules") continue;
25
+ const full = path.join(dir, entry.name);
26
+ if (entry.isDirectory()) walk(full);
27
+ else if (entry.isFile() && isHtmlPath(entry.name)) found.push(full);
28
+ }
29
+ };
30
+ walk(root);
31
+ return found
32
+ .map((full) => ({ full, relative: path.relative(root, full).split(path.sep).join("/") }))
33
+ .sort((a, b) => (a.relative < b.relative ? -1 : a.relative > b.relative ? 1 : 0));
34
+ }
35
+
36
+ /**
37
+ * Turns the command line arguments into a list of inputs in order: { kind: "url", source } or
38
+ * { kind: "file", source, full }. A folder given alone names its pages relative to itself; alongside other inputs,
39
+ * with the folder in front. Missing paths and non-HTML files are usage errors.
40
+ */
41
+ export function listInputs(args) {
42
+ const inputs = [];
43
+ for (const arg of args) {
44
+ if (isUrl(arg)) {
45
+ try {
46
+ parseHttpUrl(arg);
47
+ } catch (error) {
48
+ throw new UserError(`${arg}: ${error.message}.`);
49
+ }
50
+ inputs.push({ kind: "url", source: arg });
51
+ continue;
52
+ }
53
+ let stat;
54
+ try {
55
+ stat = statSync(arg);
56
+ } catch {
57
+ const looksLikeHost = /^(?:www\.|[\w-]+(?:\.[\w-]+)+\/)/i.test(arg);
58
+ throw new UserError(
59
+ `Cannot read ${arg}: there is no such file or folder.${looksLikeHost ? " For a web page, start the URL with https://." : ""}`,
60
+ );
61
+ }
62
+ if (stat.isDirectory()) {
63
+ const files = listHtmlFiles(arg);
64
+ if (!files.length) throw new UserError(`${arg} has no ${HTML_EXTENSIONS.join(", ")} files.`);
65
+ const prefix = args.length === 1 ? "" : `${arg.split(path.sep).join("/").replace(/\/+$/, "")}/`;
66
+ for (const { full, relative } of files) inputs.push({ kind: "file", source: `${prefix}${relative}`, full });
67
+ } else if (isHtmlPath(arg)) {
68
+ inputs.push({ kind: "file", source: args.length === 1 ? path.basename(arg) : arg.split(path.sep).join("/"), full: arg });
69
+ } else {
70
+ throw new UserError(`${arg} is not a URL, an HTML file (${HTML_EXTENSIONS.join(", ")}) or a folder.`);
71
+ }
72
+ }
73
+ return inputs;
74
+ }
75
+
76
+ /**
77
+ * What the tool knows about one page: its JSON-LD blocks (parsed or not), the types at the top of the markup, its
78
+ * visible text and the claims to check.
79
+ */
80
+ export function readPage(source, html, extra = {}) {
81
+ const { text, blocks } = parseHtml(html);
82
+ const parsed = readJsonLd(blocks);
83
+ const { claims, types } = extractClaims(parsed);
84
+ return { source, ...extra, error: null, blocks: parsed, types, text, claims };
85
+ }
86
+
87
+ /** Runs `worker` over `items`, at most `limit` at a time, keeping the order; starts nothing new after a failure. */
88
+ export async function mapLimit(items, limit, worker) {
89
+ const results = new Array(items.length);
90
+ let next = 0;
91
+ let failed = false;
92
+ const lanes = Array.from({ length: Math.min(limit, items.length) }, async () => {
93
+ while (!failed && next < items.length) {
94
+ const index = next++;
95
+ try {
96
+ results[index] = await worker(items[index], index);
97
+ } catch (error) {
98
+ failed = true;
99
+ throw error;
100
+ }
101
+ }
102
+ });
103
+ await Promise.all(lanes);
104
+ return results;
105
+ }
106
+
107
+ /**
108
+ * Loads every input: reads files, fetches URLs (four at a time). A URL that cannot be fetched becomes a page with an
109
+ * `error` instead of stopping the run. `resolve` and `transport` are passed to fetchPage for tests.
110
+ */
111
+ export async function loadPages(inputs, options = {}) {
112
+ const { timeoutMs = DEFAULT_TIMEOUT_MS, resolve, transport, onProgress } = options;
113
+ let done = 0;
114
+ return mapLimit(inputs, CONCURRENCY, async (input) => {
115
+ let page;
116
+ if (input.kind === "file") {
117
+ page = readPage(input.source, decodeHtml(readFileSync(input.full)), { kind: "file", url: null });
118
+ } else {
119
+ try {
120
+ const fetched = await fetchPage(input.source, { timeoutMs, resolve, transport, userAgent: USER_AGENT });
121
+ page = readPage(input.source, decodeHtml(fetched.body, fetched.contentType), { kind: "url", url: fetched.url });
122
+ } catch (error) {
123
+ if (!(error instanceof FetchError)) throw error;
124
+ page = { source: input.source, kind: "url", url: null, error: error.message, blocks: [], types: [], text: "", claims: [] };
125
+ }
126
+ }
127
+ onProgress?.(++done, inputs.length);
128
+ return page;
129
+ });
130
+ }
package/src/report.mjs ADDED
@@ -0,0 +1,190 @@
1
+ // Formats results for people (the report, the dry run) and for programs (JSON). Every word printed comes from the
2
+ // pages or from the fixed text in this file; Jev returns only probabilities.
3
+ import { estimatePlan, estimateTokens, QUESTION } from "./check.mjs";
4
+
5
+ export const POLICY_URL = "https://developers.google.com/search/docs/appearance/structured-data/sd-policies";
6
+ const ORDER = ["unsupported", "review", "supported"];
7
+ const LIST_LIMIT = 20;
8
+
9
+ const count = (n) => n.toLocaleString("en-US");
10
+ const plural = (n, word) => `${count(n)} ${word}${n === 1 ? "" : "s"}`;
11
+ const p2 = (value) => (value === null ? " - " : value.toFixed(2));
12
+ const round6 = (value) => Math.round(value * 1e6) / 1e6;
13
+
14
+ /** Text on one line, cut at a word boundary. */
15
+ export function preview(text, max = 90) {
16
+ const flat = text.replace(/\s+/g, " ").trim();
17
+ if (flat.length <= max) return flat;
18
+ const cut = flat.slice(0, max - 3);
19
+ const space = cut.lastIndexOf(" ");
20
+ return `${space > max / 2 ? cut.slice(0, space) : cut}...`;
21
+ }
22
+
23
+ const where = ({ block, path }) => `block ${block}${path ? `, ${path}` : ""}`;
24
+
25
+ /** "1 JSON-LD block (Product)", with the blocks that are not valid JSON called out. */
26
+ function describeMarkup(page) {
27
+ if (!page.blocks.length) return "no JSON-LD";
28
+ const invalid = page.blocks.filter((block) => block.error).length;
29
+ const types = page.types.length ? ` (${page.types.join(", ")})` : "";
30
+ return `${plural(page.blocks.length, "JSON-LD block")}${types}${invalid ? `, ${invalid} not valid JSON` : ""}`;
31
+ }
32
+
33
+ function invalidLines(page) {
34
+ return page.blocks
35
+ .filter((block) => block.error)
36
+ .map((block) =>
37
+ block.error === "empty"
38
+ ? ` block ${block.index} (line ${block.line}) is empty`
39
+ : ` block ${block.index} (line ${block.line}) is not valid JSON; its claims were not checked`,
40
+ );
41
+ }
42
+
43
+ function pageLines(page) {
44
+ const lines = ["", page.source];
45
+ if (page.url && page.url !== page.source) lines.push(` fetched from ${page.url}`);
46
+ if (page.error) return [...lines, ` not read: ${page.error}`];
47
+ const tally = ORDER.map((verdict) => [verdict, page.claims.filter((claim) => claim.verdict === verdict).length])
48
+ .filter(([, n]) => n)
49
+ .map(([verdict, n]) => `${verdict} ${n}`)
50
+ .join(", ");
51
+ const claims = page.claims.length ? `${plural(page.claims.length, "claim")}: ${tally}` : "no claims to check";
52
+ lines.push(` ${describeMarkup(page)}; ${claims}`, ...invalidLines(page));
53
+ if (page.claims.length && !page.text) {
54
+ lines.push(" no visible text in the HTML; if a script builds the page, save it from a browser and check the file");
55
+ }
56
+ for (const verdict of ORDER) {
57
+ for (const claim of page.claims.filter((entry) => entry.verdict === verdict)) {
58
+ lines.push(` ${verdict.padEnd(11)} ${p2(claim.probability)} ${claim.property}: ${preview(claim.value)}`);
59
+ if (verdict !== "supported") lines.push(`${" ".repeat(21)}${claim.item}; ${where(claim.paths[0])}`);
60
+ }
61
+ }
62
+ return lines;
63
+ }
64
+
65
+ /** The human-readable report: counts, then every page with its claims, the doubtful ones first. */
66
+ export function formatReport(result) {
67
+ const { summary, usage, threshold } = result;
68
+ const lines = [
69
+ `schema-truth: ${plural(summary.claims, "claim")} on ${plural(summary.pages, "page")}`,
70
+ usage.requests
71
+ ? `Model ${result.model}, ${plural(usage.requests, "request")}, ${count(usage.input_tokens)} input tokens, threshold ${threshold}`
72
+ : `Nothing to ask TypeSafe, threshold ${threshold}`,
73
+ "",
74
+ `supported ${summary.supported} unsupported ${summary.unsupported} review ${summary.review}` +
75
+ (summary.pages_not_read ? ` pages not read ${summary.pages_not_read}` : ""),
76
+ ];
77
+ for (const page of result.pages) lines.push(...pageLines(page));
78
+ const low = round6(1 - threshold);
79
+ const notes = [];
80
+ if (summary.supported) notes.push(`supported: the visible text shows the value (probability at or above ${threshold}).`);
81
+ if (summary.unsupported) {
82
+ notes.push(
83
+ `unsupported: the visible text does not show it (probability at or below ${low}). Google asks that structured`,
84
+ " data describe only content visible to readers of the page:",
85
+ ` ${POLICY_URL}`,
86
+ );
87
+ }
88
+ if (summary.review) notes.push("review: Jev was not sure either way, or had no text to read. Check these on the page yourself.");
89
+ if (notes.length) lines.push("", ...notes);
90
+ return `${lines.join("\n")}\n`;
91
+ }
92
+
93
+ const claimJson = (claim) => ({
94
+ id: claim.id,
95
+ item: claim.item,
96
+ property: claim.property,
97
+ value: claim.value,
98
+ ...(claim.raw !== undefined ? { raw: claim.raw } : {}),
99
+ paths: claim.paths,
100
+ });
101
+
102
+ function pageJson(page) {
103
+ return {
104
+ source: page.source,
105
+ url: page.url,
106
+ error: page.error,
107
+ jsonld_blocks: page.blocks.length,
108
+ invalid_blocks: page.blocks.filter((block) => block.error).map(({ index, line, error }) => ({ block: index, line, error })),
109
+ types: page.types,
110
+ visible_text_tokens: estimateTokens(page.text),
111
+ };
112
+ }
113
+
114
+ /** The report as JSON: every page and claim, its verdict and the raw probability. */
115
+ export function toJson(result, meta) {
116
+ return {
117
+ tool: "schema-truth",
118
+ version: meta.version,
119
+ threshold: result.threshold,
120
+ model: result.model,
121
+ summary: result.summary,
122
+ usage: result.usage,
123
+ pages: result.pages.map((page) => ({
124
+ ...pageJson(page),
125
+ parts: page.parts,
126
+ claims: page.claims.map((claim) => ({
127
+ ...claimJson(claim),
128
+ probability: claim.probability,
129
+ verdict: claim.verdict,
130
+ reason: claim.reason,
131
+ })),
132
+ })),
133
+ };
134
+ }
135
+
136
+ /** What --dry-run prints: each page's markup and claims, the requests and the token estimate. */
137
+ export function formatDryRun(plan, meta) {
138
+ const estimate = estimatePlan(plan);
139
+ const claims = plan.pages.reduce((sum, page) => sum + page.claims.length, 0);
140
+ const lines = ["Dry run: nothing was sent to TypeSafe.", "", `${plural(claims, "claim")} on ${plural(plan.pages.length, "page")}`];
141
+ const shown = plan.pages.slice(0, LIST_LIMIT);
142
+ const width = Math.max(...shown.map((page) => page.source.length));
143
+ for (const page of shown) {
144
+ const detail = page.error
145
+ ? `not read: ${page.error}`
146
+ : `${describeMarkup(page)}, ${plural(page.claims.length, "claim")}, visible text about ${plural(estimateTokens(page.text), "token")}`;
147
+ lines.push(` ${page.source.padEnd(width)} ${detail}`);
148
+ }
149
+ if (plan.pages.length > shown.length) lines.push(` and ${plural(plan.pages.length - shown.length, "more page")}`);
150
+ lines.push(
151
+ "",
152
+ `${plural(plan.requests.length, "request")} to ${meta.model}, about ${count(estimate.tokens)} input tokens`,
153
+ );
154
+ const listed = shown.filter((page) => page.claims.length);
155
+ if (listed.length) {
156
+ lines.push("", "Each claim is one yes/no question (noul), asked against the page's visible text:", ` ${QUESTION}`);
157
+ for (const page of listed) {
158
+ lines.push("", `${page.source}`);
159
+ for (const claim of page.claims) lines.push(` ${claim.id.padEnd(4)} ${claim.property}: ${preview(claim.value, 70)} [${claim.item}]`);
160
+ }
161
+ }
162
+ lines.push("", "Run with --dry-run --json to see every request body, including the visible text.");
163
+ return `${lines.join("\n")}\n`;
164
+ }
165
+
166
+ /** What --dry-run --json prints: the pages, their claims and every request body exactly as it would be sent. */
167
+ export function dryRunJson(plan, meta) {
168
+ const estimate = estimatePlan(plan);
169
+ return {
170
+ tool: "schema-truth",
171
+ version: meta.version,
172
+ dry_run: true,
173
+ model: meta.model,
174
+ summary: {
175
+ pages: plan.pages.length,
176
+ pages_not_read: plan.pages.filter((page) => page.error).length,
177
+ claims: plan.pages.reduce((sum, page) => sum + page.claims.length, 0),
178
+ requests: plan.requests.length,
179
+ },
180
+ estimated_input_tokens: estimate.tokens,
181
+ pages: plan.pages.map((page) => ({ ...pageJson(page), claims: page.claims.map(claimJson) })),
182
+ requests: plan.requests.map((request, i) => ({
183
+ source: request.page.source,
184
+ part: request.part + 1,
185
+ claims: request.claims.map((claim) => claim.id),
186
+ estimated_tokens: estimate.perRequest[i],
187
+ body: request.body,
188
+ })),
189
+ };
190
+ }
@@ -0,0 +1,6 @@
1
+ import { readFileSync } from "node:fs";
2
+
3
+ export const VERSION = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
4
+
5
+ /** Sent with every page request, so site owners can see what fetched their page. */
6
+ export const USER_AGENT = `schema-truth/${VERSION} (+https://github.com/hamzaahmadaslam/schema-truth)`;