@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/LICENSE +21 -0
- package/README.md +239 -2
- package/bin/schema-truth.mjs +4 -0
- package/package.json +39 -4
- package/src/check.mjs +213 -0
- package/src/claims.mjs +252 -0
- package/src/cli.mjs +128 -0
- package/src/errors.mjs +7 -0
- package/src/fetch.mjs +338 -0
- package/src/html.mjs +337 -0
- package/src/jev.mjs +92 -0
- package/src/load.mjs +130 -0
- package/src/report.mjs +190 -0
- package/src/version.mjs +6 -0
package/src/claims.mjs
ADDED
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
// Turns the JSON-LD on a page into claims to check against the visible text: prices, availability, ratings and
|
|
2
|
+
// reviews, authors, dates, headlines, FAQ questions and answers, addresses and phone numbers. A claim names the
|
|
3
|
+
// item it belongs to, the property in plain words, the value as text, and where it sits in the markup.
|
|
4
|
+
import { decodeEntities, fragmentText } from "./html.mjs";
|
|
5
|
+
|
|
6
|
+
export const MAX_VALUE_CHARS = 1_000;
|
|
7
|
+
const MAX_NAME_CHARS = 120;
|
|
8
|
+
|
|
9
|
+
const MONTHS = [
|
|
10
|
+
"January", "February", "March", "April", "May", "June",
|
|
11
|
+
"July", "August", "September", "October", "November", "December",
|
|
12
|
+
];
|
|
13
|
+
|
|
14
|
+
/** Types that are part of an item rather than an item: an offer's price is the price of its product. */
|
|
15
|
+
const PART_TYPES = new Set([
|
|
16
|
+
"Offer", "AggregateOffer", "PriceSpecification", "UnitPriceSpecification", "CompoundPriceSpecification",
|
|
17
|
+
"AggregateRating", "Rating", "Review", "PostalAddress", "ContactPoint", "Question", "Answer",
|
|
18
|
+
]);
|
|
19
|
+
|
|
20
|
+
/** Properties of the page as a whole: identical values are checked once, whichever item they sit on. */
|
|
21
|
+
const PAGE_LEVEL = new Set(["headline", "author", "date published", "date modified"]);
|
|
22
|
+
|
|
23
|
+
const DATES = [
|
|
24
|
+
["datePublished", "date published", false],
|
|
25
|
+
["dateModified", "date modified", false],
|
|
26
|
+
["startDate", "start date", true],
|
|
27
|
+
["endDate", "end date", true],
|
|
28
|
+
];
|
|
29
|
+
|
|
30
|
+
const isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
31
|
+
const asArray = (value) => (value === undefined || value === null ? [] : Array.isArray(value) ? value : [value]);
|
|
32
|
+
|
|
33
|
+
/** "https://schema.org/Product" and "schema:Product" to "Product". */
|
|
34
|
+
function typeNames(node) {
|
|
35
|
+
return asArray(node["@type"])
|
|
36
|
+
.filter((type) => typeof type === "string")
|
|
37
|
+
.map((type) => type.replace(/^https?:\/\/schema\.org\//i, "").replace(/^schema:/i, "").trim())
|
|
38
|
+
.filter(Boolean);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Cuts long text at a word boundary. */
|
|
42
|
+
function cap(text, max) {
|
|
43
|
+
if (text.length <= max) return text;
|
|
44
|
+
const cut = text.slice(0, max - 3);
|
|
45
|
+
const space = cut.lastIndexOf(" ");
|
|
46
|
+
return `${space > max / 2 ? cut.slice(0, space) : cut}...`;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** A JSON-LD value as one line of text: strings decoded and trimmed, numbers as written, {"@value"} unwrapped. */
|
|
50
|
+
function textOf(value) {
|
|
51
|
+
if (typeof value === "string") return decodeEntities(value).replace(/\s+/g, " ").trim();
|
|
52
|
+
if (typeof value === "number" && Number.isFinite(value)) return String(value);
|
|
53
|
+
if (isObject(value) && "@value" in value) return textOf(value["@value"]);
|
|
54
|
+
return "";
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** An ISO 8601 date as "2 March 2026" (with the time for events), so it reads the way pages write dates. */
|
|
58
|
+
export function dateInWords(value, withTime = false) {
|
|
59
|
+
const match = /^(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2}))?/.exec(value);
|
|
60
|
+
if (!match) return value;
|
|
61
|
+
const month = MONTHS[Number(match[2]) - 1];
|
|
62
|
+
const day = Number(match[3]);
|
|
63
|
+
if (!month || day < 1 || day > 31) return value;
|
|
64
|
+
const date = `${day} ${month} ${match[1]}`;
|
|
65
|
+
return withTime && match[4] !== undefined ? `${date}, ${match[4]}:${match[5]}` : date;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** "https://schema.org/InStock" to "in stock". */
|
|
69
|
+
export function availabilityInWords(value) {
|
|
70
|
+
const name = value.replace(/^https?:\/\/schema\.org\//i, "").replace(/^schema:/i, "");
|
|
71
|
+
return name.replace(/([a-z])([A-Z])/g, "$1 $2").toLowerCase();
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** A path inside a block, such as "@graph[1].offers.price". */
|
|
75
|
+
const join = (path, key) => (typeof key === "number" ? `${path}[${key}]` : path ? `${path}.${key}` : key);
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Walks the parsed JSON-LD blocks of one page and returns { claims, types }: the claims in markup order with ids
|
|
79
|
+
* c1, c2 and so on, and the @type of each top-level item. Identical claims (same item, property and value) are kept
|
|
80
|
+
* once with every path where they appear. Items linked by "@id" are followed within the page.
|
|
81
|
+
*/
|
|
82
|
+
export function extractClaims(blocks) {
|
|
83
|
+
const definitions = new Map();
|
|
84
|
+
const referenced = new Set();
|
|
85
|
+
const roots = [];
|
|
86
|
+
const collect = (value, block, path) => {
|
|
87
|
+
if (Array.isArray(value)) return value.forEach((entry, i) => collect(entry, block, join(path, i)));
|
|
88
|
+
if (!isObject(value)) return;
|
|
89
|
+
const keys = Object.keys(value).filter((key) => key !== "@id" && key !== "@type" && key !== "@context");
|
|
90
|
+
if (typeof value["@id"] === "string") {
|
|
91
|
+
if (keys.length === 0) referenced.add(value["@id"]);
|
|
92
|
+
else if (!definitions.has(value["@id"])) definitions.set(value["@id"], { node: value, block, path });
|
|
93
|
+
}
|
|
94
|
+
for (const [key, child] of Object.entries(value)) if (key !== "@context") collect(child, block, join(path, key));
|
|
95
|
+
};
|
|
96
|
+
for (const block of blocks) {
|
|
97
|
+
if (block.data === undefined) continue;
|
|
98
|
+
collect(block.data, block.index, "");
|
|
99
|
+
const tops = Array.isArray(block.data) ? block.data.map((node, i) => [node, `[${i}]`]) : [[block.data, ""]];
|
|
100
|
+
for (const [node, path] of tops) {
|
|
101
|
+
if (!isObject(node)) continue;
|
|
102
|
+
if (Array.isArray(node["@graph"])) node["@graph"].forEach((entry, i) => roots.push({ node: entry, block: block.index, path: join(join(path, "@graph"), i) }));
|
|
103
|
+
if (node["@type"] !== undefined || !Array.isArray(node["@graph"])) roots.push({ node, block: block.index, path });
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
const resolve = (value) => {
|
|
108
|
+
if (!isObject(value) || typeof value["@id"] !== "string") return value;
|
|
109
|
+
const own = Object.keys(value).filter((key) => key !== "@id" && key !== "@type");
|
|
110
|
+
return own.length ? value : definitions.get(value["@id"])?.node ?? value;
|
|
111
|
+
};
|
|
112
|
+
const nameOf = (value) => {
|
|
113
|
+
const node = resolve(value);
|
|
114
|
+
if (typeof node === "string") return textOf(node);
|
|
115
|
+
return isObject(node) ? textOf(node.name) : "";
|
|
116
|
+
};
|
|
117
|
+
const describe = (node) => {
|
|
118
|
+
const name = cap(textOf(node.name) || textOf(node.headline), MAX_NAME_CHARS);
|
|
119
|
+
const type = typeNames(node)[0];
|
|
120
|
+
if (name) return type ? `${name} (${type})` : name;
|
|
121
|
+
return type ?? "";
|
|
122
|
+
};
|
|
123
|
+
|
|
124
|
+
const claims = [];
|
|
125
|
+
const byKey = new Map();
|
|
126
|
+
const add = (item, property, value, block, path, raw) => {
|
|
127
|
+
const text = cap(value, MAX_VALUE_CHARS);
|
|
128
|
+
if (!text) return;
|
|
129
|
+
// A page's headline, author and dates are often repeated on its WebPage node; one check covers both.
|
|
130
|
+
const key = `${PAGE_LEVEL.has(property) ? "" : item}\u0000${property}\u0000${text}`;
|
|
131
|
+
const where = { block, path };
|
|
132
|
+
if (byKey.has(key)) return byKey.get(key).paths.push(where);
|
|
133
|
+
const claim = { id: "", item, property, value: text, paths: [where] };
|
|
134
|
+
if (raw !== undefined && raw !== text) claim.raw = raw;
|
|
135
|
+
byKey.set(key, claim);
|
|
136
|
+
claims.push(claim);
|
|
137
|
+
};
|
|
138
|
+
|
|
139
|
+
const visited = new Set();
|
|
140
|
+
const visit = (value, ctx, block, path) => {
|
|
141
|
+
if (Array.isArray(value)) return value.forEach((entry, i) => visit(entry, ctx, block, join(path, i)));
|
|
142
|
+
if (!isObject(value) || visited.has(value)) return;
|
|
143
|
+
const target = resolve(value);
|
|
144
|
+
if (target !== value) {
|
|
145
|
+
// A reference: follow it only to a part (an offer or a rating, say), which takes its item from here.
|
|
146
|
+
const definition = definitions.get(value["@id"]);
|
|
147
|
+
if (definition && typeNames(target).some((type) => PART_TYPES.has(type))) visit(target, ctx, definition.block, definition.path);
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
visited.add(value);
|
|
151
|
+
const node = value;
|
|
152
|
+
const types = typeNames(node);
|
|
153
|
+
const isPart = types.some((type) => PART_TYPES.has(type));
|
|
154
|
+
const isReview = types.includes("Review");
|
|
155
|
+
// The item a claim is about: this node if it is one, else what it reviews, else the item around it.
|
|
156
|
+
const reviewed = resolve(asArray(node.itemReviewed)[0]);
|
|
157
|
+
const reviewedName = isObject(reviewed) ? describe(reviewed) : "";
|
|
158
|
+
const item = (!isPart && describe(node)) || reviewedName || ctx.item || describe(node) || types[0] || "this page";
|
|
159
|
+
// A part inherits the currency and reviewer of the node around it; a new item starts afresh.
|
|
160
|
+
const here = {
|
|
161
|
+
item,
|
|
162
|
+
currency: textOf(node.priceCurrency) || (isPart ? ctx.currency : ""),
|
|
163
|
+
reviewBy: isPart ? ctx.reviewBy : undefined,
|
|
164
|
+
};
|
|
165
|
+
const at = (key) => join(path, key);
|
|
166
|
+
|
|
167
|
+
// Prices, with the currency of this node or of the offer around it.
|
|
168
|
+
for (const [key, label] of [["price", "price"], ["lowPrice", "lowest price"], ["highPrice", "highest price"]]) {
|
|
169
|
+
const amount = textOf(node[key]);
|
|
170
|
+
if (!amount) continue;
|
|
171
|
+
const priceType = textOf(node.priceType);
|
|
172
|
+
const property = key === "price" && /(ListPrice|StrikethroughPrice)$/i.test(priceType) ? "list price" : label;
|
|
173
|
+
add(item, property, here.currency ? `${amount} ${here.currency}` : amount, block, at(key));
|
|
174
|
+
}
|
|
175
|
+
const availability = textOf(node.availability);
|
|
176
|
+
if (availability) add(item, "availability", availabilityInWords(availability), block, at("availability"), availability);
|
|
177
|
+
|
|
178
|
+
// Ratings: the average for an item, or one reviewer's rating.
|
|
179
|
+
const rating = textOf(node.ratingValue);
|
|
180
|
+
if (rating) {
|
|
181
|
+
const best = textOf(node.bestRating);
|
|
182
|
+
const value = best ? `${rating} out of ${best}` : rating;
|
|
183
|
+
const aggregate = types.includes("AggregateRating") || node.ratingCount !== undefined || node.reviewCount !== undefined;
|
|
184
|
+
const property = ctx.reviewBy ? `rating in the review by ${ctx.reviewBy}` : aggregate ? "average rating" : "rating";
|
|
185
|
+
add(item, property, value, block, at("ratingValue"));
|
|
186
|
+
}
|
|
187
|
+
if (textOf(node.ratingCount)) add(item, "number of ratings", textOf(node.ratingCount), block, at("ratingCount"));
|
|
188
|
+
if (textOf(node.reviewCount)) add(item, "number of reviews", textOf(node.reviewCount), block, at("reviewCount"));
|
|
189
|
+
|
|
190
|
+
const headline = textOf(node.headline);
|
|
191
|
+
if (headline) add(types[0] ?? item, "headline", headline, block, at("headline"));
|
|
192
|
+
|
|
193
|
+
// Authors of the item, or of a review of it. Authors and dates of other parts (answers, offers) are skipped.
|
|
194
|
+
const authors = !isPart || isReview ? asArray(node.author).map(nameOf).filter(Boolean) : [];
|
|
195
|
+
authors.forEach((name) => add(item, isReview ? "review author" : "author", name, block, at("author")));
|
|
196
|
+
if (isReview && authors.length) here.reviewBy = authors[0];
|
|
197
|
+
|
|
198
|
+
if (!isPart) {
|
|
199
|
+
for (const [key, label, withTime] of DATES) {
|
|
200
|
+
const raw = textOf(node[key]);
|
|
201
|
+
if (raw) add(item, label, dateInWords(raw, withTime), block, at(key), raw);
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
// A FAQ or Q&A question and its accepted answers.
|
|
206
|
+
const answers = asArray(node.acceptedAnswer).map(resolve);
|
|
207
|
+
if (types.includes("Question") && answers.some(isObject)) {
|
|
208
|
+
const key = typeof node.name === "string" ? "name" : "text";
|
|
209
|
+
const question = cap(typeof node[key] === "string" ? fragmentText(node[key]) : "", MAX_VALUE_CHARS);
|
|
210
|
+
add(item, "question", question, block, at(key));
|
|
211
|
+
const label = question ? `answer to "${cap(question, MAX_NAME_CHARS)}"` : "answer";
|
|
212
|
+
answers.forEach((answer, i) => {
|
|
213
|
+
if (!isObject(answer)) return;
|
|
214
|
+
const text = typeof answer.text === "string" ? fragmentText(answer.text) : textOf(answer.text);
|
|
215
|
+
const holder = Array.isArray(node.acceptedAnswer) ? join(at("acceptedAnswer"), i) : at("acceptedAnswer");
|
|
216
|
+
add(item, label, text, block, join(holder, "text"));
|
|
217
|
+
});
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
for (const address of asArray(node.address).map(resolve)) {
|
|
221
|
+
const text =
|
|
222
|
+
typeof address === "string"
|
|
223
|
+
? textOf(address)
|
|
224
|
+
: isObject(address)
|
|
225
|
+
? ["streetAddress", "addressLocality", "addressRegion", "postalCode", "addressCountry"]
|
|
226
|
+
.map((key) => (isObject(resolve(address[key])) ? nameOf(address[key]) : textOf(address[key])))
|
|
227
|
+
.filter(Boolean)
|
|
228
|
+
.join(", ")
|
|
229
|
+
: "";
|
|
230
|
+
if (text) add(item, "address", text, block, at("address"));
|
|
231
|
+
}
|
|
232
|
+
const contact = types.includes("ContactPoint") ? textOf(node.contactType) : "";
|
|
233
|
+
for (const phone of asArray(node.telephone).map(textOf).filter(Boolean)) {
|
|
234
|
+
add(item, contact ? `phone number (${contact})` : "phone number", phone, block, at("telephone"));
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
for (const [key, child] of Object.entries(node)) {
|
|
238
|
+
if (key.startsWith("@") && key !== "@graph") continue;
|
|
239
|
+
visit(child, here, block, join(path, key));
|
|
240
|
+
}
|
|
241
|
+
};
|
|
242
|
+
|
|
243
|
+
// Items first, then parts that were only reachable through a reference nobody followed.
|
|
244
|
+
const isReferencedPart = ({ node }) =>
|
|
245
|
+
isObject(node) && referenced.has(node["@id"]) && typeNames(node).some((type) => PART_TYPES.has(type));
|
|
246
|
+
for (const root of roots) if (!isReferencedPart(root)) visit(root.node, {}, root.block, root.path);
|
|
247
|
+
for (const root of roots) visit(root.node, {}, root.block, root.path);
|
|
248
|
+
|
|
249
|
+
claims.forEach((claim, i) => (claim.id = `c${i + 1}`));
|
|
250
|
+
const types = [...new Set(roots.flatMap(({ node }) => (isObject(node) ? typeNames(node) : [])))];
|
|
251
|
+
return { claims, types };
|
|
252
|
+
}
|
package/src/cli.mjs
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
// The command line: parses options, reads the pages, and prints the report, the JSON or the dry run.
|
|
2
|
+
// main() takes its environment, output streams, fetch and page transport as arguments, so tests run it offline.
|
|
3
|
+
import { parseArgs } from "node:util";
|
|
4
|
+
import { DEFAULT_THRESHOLD, DEFAULT_TIMEOUT_SECONDS, planRequests, runPlan } from "./check.mjs";
|
|
5
|
+
import { UserError } from "./errors.mjs";
|
|
6
|
+
import { DEFAULT_MODEL, JevError } from "./jev.mjs";
|
|
7
|
+
import { listInputs, loadPages } from "./load.mjs";
|
|
8
|
+
import { dryRunJson, formatDryRun, formatReport, toJson } from "./report.mjs";
|
|
9
|
+
import { VERSION } from "./version.mjs";
|
|
10
|
+
|
|
11
|
+
export { VERSION };
|
|
12
|
+
|
|
13
|
+
export const USAGE = `Usage: schema-truth <url | page.html | folder>... [options]
|
|
14
|
+
|
|
15
|
+
Checks whether the values in a page's JSON-LD (prices, availability, ratings, reviews, authors, dates, headlines,
|
|
16
|
+
FAQ answers, addresses and phone numbers) are shown in the text a visitor sees.
|
|
17
|
+
|
|
18
|
+
Options:
|
|
19
|
+
--threshold <p> probability needed to call a claim supported or unsupported, above 0.5 and up to 1 (default ${DEFAULT_THRESHOLD})
|
|
20
|
+
--timeout <seconds> time limit for each page and each TypeSafe request (default ${DEFAULT_TIMEOUT_SECONDS})
|
|
21
|
+
--json print JSON instead of the report
|
|
22
|
+
--dry-run read the pages and print the claims and a token estimate; send nothing to TypeSafe
|
|
23
|
+
-h, --help show this help
|
|
24
|
+
-v, --version show the version
|
|
25
|
+
|
|
26
|
+
Environment:
|
|
27
|
+
TYPESAFE_API_KEY your TypeSafe API key (not needed for --dry-run)
|
|
28
|
+
TYPESAFE_MODEL the model to use (default ${DEFAULT_MODEL})
|
|
29
|
+
|
|
30
|
+
Exit codes: 0 no unsupported claim, 1 at least one unsupported claim, 2 an error or a page that could not be read.
|
|
31
|
+
`;
|
|
32
|
+
|
|
33
|
+
function parseOptions(argv) {
|
|
34
|
+
let parsed;
|
|
35
|
+
try {
|
|
36
|
+
parsed = parseArgs({
|
|
37
|
+
args: argv,
|
|
38
|
+
allowPositionals: true,
|
|
39
|
+
options: {
|
|
40
|
+
threshold: { type: "string" },
|
|
41
|
+
timeout: { type: "string" },
|
|
42
|
+
json: { type: "boolean", default: false },
|
|
43
|
+
"dry-run": { type: "boolean", default: false },
|
|
44
|
+
help: { type: "boolean", short: "h", default: false },
|
|
45
|
+
version: { type: "boolean", short: "v", default: false },
|
|
46
|
+
},
|
|
47
|
+
});
|
|
48
|
+
} catch (error) {
|
|
49
|
+
throw new UserError(`${error.message} Run schema-truth --help for the options.`);
|
|
50
|
+
}
|
|
51
|
+
const { values, positionals } = parsed;
|
|
52
|
+
if (values.help || values.version) return { help: values.help, version: values.version };
|
|
53
|
+
if (!positionals.length) {
|
|
54
|
+
throw new UserError("Give at least one URL, saved HTML file or folder to check. Run schema-truth --help for usage.");
|
|
55
|
+
}
|
|
56
|
+
const threshold = values.threshold === undefined ? DEFAULT_THRESHOLD : Number(values.threshold);
|
|
57
|
+
if (!(threshold > 0.5 && threshold <= 1)) {
|
|
58
|
+
throw new UserError(`--threshold must be a number above 0.5 and at most 1, not "${values.threshold}".`);
|
|
59
|
+
}
|
|
60
|
+
const timeoutSeconds = values.timeout === undefined ? DEFAULT_TIMEOUT_SECONDS : Number(values.timeout);
|
|
61
|
+
if (!(timeoutSeconds > 0 && timeoutSeconds <= 600)) {
|
|
62
|
+
throw new UserError(`--timeout must be a number of seconds above 0 and at most 600, not "${values.timeout}".`);
|
|
63
|
+
}
|
|
64
|
+
return { inputs: positionals, threshold, timeoutSeconds, json: values.json, dryRun: values["dry-run"] };
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Runs the tool. Returns the exit code: 0 no unsupported claim, 1 at least one unsupported claim, 2 an error or a
|
|
69
|
+
* page that could not be read.
|
|
70
|
+
*/
|
|
71
|
+
export async function main(argv, io = {}) {
|
|
72
|
+
const {
|
|
73
|
+
env = process.env,
|
|
74
|
+
stdout = process.stdout,
|
|
75
|
+
stderr = process.stderr,
|
|
76
|
+
fetchImpl = globalThis.fetch,
|
|
77
|
+
resolve,
|
|
78
|
+
transport,
|
|
79
|
+
} = io;
|
|
80
|
+
const write = (stream, text) => stream.write(text.endsWith("\n") ? text : `${text}\n`);
|
|
81
|
+
try {
|
|
82
|
+
const options = parseOptions(argv);
|
|
83
|
+
if (options.help || options.version) {
|
|
84
|
+
write(stdout, options.help ? USAGE : VERSION);
|
|
85
|
+
return 0;
|
|
86
|
+
}
|
|
87
|
+
const inputs = listInputs(options.inputs);
|
|
88
|
+
const progress = (verb) =>
|
|
89
|
+
stderr.isTTY ? (done, total) => stderr.write(`\r${verb} ${done} of ${total}${done === total ? "\n" : ""}`) : undefined;
|
|
90
|
+
const pages = await loadPages(inputs, {
|
|
91
|
+
timeoutMs: options.timeoutSeconds * 1000,
|
|
92
|
+
resolve,
|
|
93
|
+
transport,
|
|
94
|
+
onProgress: inputs.some((input) => input.kind === "url") ? progress("read page") : undefined,
|
|
95
|
+
});
|
|
96
|
+
const model = env.TYPESAFE_MODEL?.trim() || DEFAULT_MODEL;
|
|
97
|
+
const meta = { version: VERSION, model };
|
|
98
|
+
const plan = planRequests(pages, { model });
|
|
99
|
+
const unread = pages.some((page) => page.error);
|
|
100
|
+
|
|
101
|
+
if (options.dryRun) {
|
|
102
|
+
write(stdout, options.json ? JSON.stringify(dryRunJson(plan, meta), null, 2) : formatDryRun(plan, meta));
|
|
103
|
+
return unread ? 2 : 0;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
const apiKey = env.TYPESAFE_API_KEY?.trim();
|
|
107
|
+
if (plan.requests.length && !apiKey) {
|
|
108
|
+
throw new UserError(
|
|
109
|
+
"TYPESAFE_API_KEY is not set. Get a key at https://typesafe.ai and export it first, or use --dry-run to see what would be sent.",
|
|
110
|
+
);
|
|
111
|
+
}
|
|
112
|
+
const result = await runPlan(plan, {
|
|
113
|
+
threshold: options.threshold,
|
|
114
|
+
apiKey,
|
|
115
|
+
model,
|
|
116
|
+
timeoutSeconds: options.timeoutSeconds,
|
|
117
|
+
fetchImpl,
|
|
118
|
+
onProgress: progress("request"),
|
|
119
|
+
});
|
|
120
|
+
write(stdout, options.json ? JSON.stringify(toJson(result, meta), null, 2) : formatReport(result));
|
|
121
|
+
if (unread) return 2;
|
|
122
|
+
return result.summary.unsupported > 0 ? 1 : 0;
|
|
123
|
+
} catch (error) {
|
|
124
|
+
const known = error instanceof UserError || error instanceof JevError;
|
|
125
|
+
write(stderr, `schema-truth: ${known ? error.message : `unexpected error: ${error?.message ?? error}`}`);
|
|
126
|
+
return 2;
|
|
127
|
+
}
|
|
128
|
+
}
|