@mscode-pl/feed-lint 0.0.0-stage → 0.1.1
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 +282 -2
- package/dist/cli/colors.d.ts +13 -0
- package/dist/cli/colors.js +23 -0
- package/dist/cli/config.d.ts +11 -0
- package/dist/cli/config.js +59 -0
- package/dist/cli/format.d.ts +23 -0
- package/dist/cli/format.js +129 -0
- package/dist/cli/input.d.ts +3 -0
- package/dist/cli/input.js +27 -0
- package/dist/cli/main.d.ts +2 -0
- package/dist/cli/main.js +151 -0
- package/dist/core/fixes.d.ts +1 -0
- package/dist/core/fixes.js +41 -0
- package/dist/core/gtin.d.ts +5 -0
- package/dist/core/gtin.js +22 -0
- package/dist/core/lint.d.ts +19 -0
- package/dist/core/lint.js +46 -0
- package/dist/core/parse.d.ts +33 -0
- package/dist/core/parse.js +188 -0
- package/dist/core/report.d.ts +28 -0
- package/dist/core/report.js +29 -0
- package/dist/core/urls.d.ts +23 -0
- package/dist/core/urls.js +114 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.js +5 -0
- package/dist/mcp/server.d.ts +19 -0
- package/dist/mcp/server.js +118 -0
- package/dist/mcp/tools.d.ts +74 -0
- package/dist/mcp/tools.js +124 -0
- package/dist/rules/ceneo.d.ts +7 -0
- package/dist/rules/ceneo.js +222 -0
- package/dist/rules/google.d.ts +5 -0
- package/dist/rules/google.js +278 -0
- package/dist/rules/text.d.ts +5 -0
- package/dist/rules/text.js +21 -0
- package/package.json +63 -6
package/dist/cli/main.js
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { readFileSync } from 'node:fs';
|
|
3
|
+
import { writeFile } from 'node:fs/promises';
|
|
4
|
+
import { parseArgs } from 'node:util';
|
|
5
|
+
import { lintFeed, RULES } from '../core/lint.js';
|
|
6
|
+
import { painter } from './colors.js';
|
|
7
|
+
import { CONFIG_FILE, FAIL_ON, loadConfig } from './config.js';
|
|
8
|
+
import { FORMATS, formatFromPath, onlyErrors, render } from './format.js';
|
|
9
|
+
import { openInput, USER_AGENT } from './input.js';
|
|
10
|
+
const HELP = `Usage: feed-lint <files or URLs...> [options]
|
|
11
|
+
feed-lint mcp Start an MCP server on stdio for AI agents
|
|
12
|
+
|
|
13
|
+
Checks Google Merchant (RSS, Atom) and Ceneo XML product feeds before you
|
|
14
|
+
upload them. Files may be gzipped (.gz).
|
|
15
|
+
|
|
16
|
+
Options:
|
|
17
|
+
-i, --ignore <list> Rules to skip, e.g. google/identifiers,ceneo/brand
|
|
18
|
+
--check-urls Also request product links and images
|
|
19
|
+
--url-limit <n> Unique URLs to check per feed, 0 for all (default: 200)
|
|
20
|
+
-f, --format <type> ${FORMATS.join(', ')} (default: text)
|
|
21
|
+
-o, --output <file> Also save the report; format follows the extension
|
|
22
|
+
(.json, .md, anything else is plain text)
|
|
23
|
+
--verbose Show more examples and links to the specification
|
|
24
|
+
-q, --quiet Report errors only
|
|
25
|
+
--fail-on <level> ${FAIL_ON.join(', ')} (default: error)
|
|
26
|
+
--config <file> Config file (default: ${CONFIG_FILE} if present)
|
|
27
|
+
--stdin Read the feed from stdin
|
|
28
|
+
--rules List all rules
|
|
29
|
+
-v, --version Print version
|
|
30
|
+
-h, --help Show this help
|
|
31
|
+
|
|
32
|
+
Examples:
|
|
33
|
+
feed-lint google.xml
|
|
34
|
+
feed-lint https://shop.example/feed/ceneo.xml --check-urls
|
|
35
|
+
feed-lint feeds/*.xml -o feed-report.md
|
|
36
|
+
curl -s https://shop.example/google.xml | feed-lint --stdin --format json`;
|
|
37
|
+
const list = (value) => value
|
|
38
|
+
?.split(',')
|
|
39
|
+
.map((s) => s.trim())
|
|
40
|
+
.filter(Boolean);
|
|
41
|
+
function version() {
|
|
42
|
+
return JSON.parse(readFileSync(new URL('../../package.json', import.meta.url), 'utf8')).version;
|
|
43
|
+
}
|
|
44
|
+
function listRules() {
|
|
45
|
+
const width = Math.max(...Object.keys(RULES).map((r) => r.length));
|
|
46
|
+
return Object.entries(RULES)
|
|
47
|
+
.map(([rule, info]) => `${rule.padEnd(width)} ${info.level.padEnd(7)} ${info.title}`)
|
|
48
|
+
.join('\n');
|
|
49
|
+
}
|
|
50
|
+
async function main() {
|
|
51
|
+
if (process.argv[2] === 'mcp' && process.argv.length === 3) {
|
|
52
|
+
const { serve } = await import('../mcp/server.js');
|
|
53
|
+
await serve();
|
|
54
|
+
return 0;
|
|
55
|
+
}
|
|
56
|
+
const { values, positionals } = parseArgs({
|
|
57
|
+
allowPositionals: true,
|
|
58
|
+
options: {
|
|
59
|
+
ignore: { type: 'string', short: 'i' },
|
|
60
|
+
'check-urls': { type: 'boolean' },
|
|
61
|
+
'url-limit': { type: 'string' },
|
|
62
|
+
verbose: { type: 'boolean', default: false },
|
|
63
|
+
quiet: { type: 'boolean', short: 'q', default: false },
|
|
64
|
+
format: { type: 'string', short: 'f', default: 'text' },
|
|
65
|
+
output: { type: 'string', short: 'o' },
|
|
66
|
+
'fail-on': { type: 'string' },
|
|
67
|
+
config: { type: 'string' },
|
|
68
|
+
stdin: { type: 'boolean', default: false },
|
|
69
|
+
rules: { type: 'boolean', default: false },
|
|
70
|
+
version: { type: 'boolean', short: 'v' },
|
|
71
|
+
help: { type: 'boolean', short: 'h' },
|
|
72
|
+
},
|
|
73
|
+
});
|
|
74
|
+
if (values.help) {
|
|
75
|
+
console.log(HELP);
|
|
76
|
+
return 0;
|
|
77
|
+
}
|
|
78
|
+
if (values.version) {
|
|
79
|
+
console.log(version());
|
|
80
|
+
return 0;
|
|
81
|
+
}
|
|
82
|
+
if (values.rules) {
|
|
83
|
+
console.log(listRules());
|
|
84
|
+
return 0;
|
|
85
|
+
}
|
|
86
|
+
const config = await loadConfig(values.config);
|
|
87
|
+
const inputs = positionals.length ? positionals : (config.feeds ?? []);
|
|
88
|
+
if (!inputs.length && !values.stdin) {
|
|
89
|
+
console.log(HELP);
|
|
90
|
+
return 2;
|
|
91
|
+
}
|
|
92
|
+
const format = values.format;
|
|
93
|
+
if (!FORMATS.includes(format)) {
|
|
94
|
+
console.error(`Unknown format "${values.format}". Use ${FORMATS.join(', ')}.`);
|
|
95
|
+
return 2;
|
|
96
|
+
}
|
|
97
|
+
const failOn = (values['fail-on'] ?? config.failOn ?? 'error');
|
|
98
|
+
if (!FAIL_ON.includes(failOn)) {
|
|
99
|
+
console.error(`Unknown --fail-on "${failOn}". Use ${FAIL_ON.join(', ')}.`);
|
|
100
|
+
return 2;
|
|
101
|
+
}
|
|
102
|
+
const urlLimit = values['url-limit'] !== undefined ? Number(values['url-limit']) : config.urlLimit;
|
|
103
|
+
if (urlLimit !== undefined && (!Number.isInteger(urlLimit) || urlLimit < 0)) {
|
|
104
|
+
console.error(`--url-limit must be a whole number, 0 for all.`);
|
|
105
|
+
return 2;
|
|
106
|
+
}
|
|
107
|
+
const ignore = list(values.ignore) ?? config.ignore ?? [];
|
|
108
|
+
const unknown = ignore.filter((r) => !RULES[r]);
|
|
109
|
+
if (unknown.length) {
|
|
110
|
+
console.error(`Unknown rule ${unknown.join(', ')}. Run feed-lint --rules for the list.`);
|
|
111
|
+
return 2;
|
|
112
|
+
}
|
|
113
|
+
const options = {
|
|
114
|
+
ignore,
|
|
115
|
+
checkUrls: (values['check-urls'] ?? config.checkUrls) ? { limit: urlLimit, userAgent: USER_AGENT } : false,
|
|
116
|
+
};
|
|
117
|
+
let results = [];
|
|
118
|
+
const sources = values.stdin ? ['<stdin>'] : inputs;
|
|
119
|
+
for (const feed of sources) {
|
|
120
|
+
try {
|
|
121
|
+
const chunks = feed === '<stdin>' ? process.stdin : await openInput(feed);
|
|
122
|
+
results.push({ feed, ...(await lintFeed(chunks, options)) });
|
|
123
|
+
}
|
|
124
|
+
catch (error) {
|
|
125
|
+
results.push({ feed, format: undefined, records: 0, errors: 1, warnings: 0, results: [], fatal: error.message });
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
if (values.quiet)
|
|
129
|
+
results = onlyErrors(results);
|
|
130
|
+
console.log(render(results, format, { verbose: values.verbose }));
|
|
131
|
+
if (values.output) {
|
|
132
|
+
await writeFile(values.output, render(results, formatFromPath(values.output), { paint: painter(false), verbose: true }));
|
|
133
|
+
if (format === 'text')
|
|
134
|
+
console.log(`Report saved to ${values.output}`);
|
|
135
|
+
}
|
|
136
|
+
if (results.some((r) => r.fatal))
|
|
137
|
+
return 2;
|
|
138
|
+
const errors = results.reduce((n, r) => n + r.errors, 0);
|
|
139
|
+
const warnings = results.reduce((n, r) => n + r.warnings, 0);
|
|
140
|
+
if (failOn === 'error' && errors)
|
|
141
|
+
return 1;
|
|
142
|
+
if (failOn === 'warning' && (errors || warnings))
|
|
143
|
+
return 1;
|
|
144
|
+
return 0;
|
|
145
|
+
}
|
|
146
|
+
main().then((code) => {
|
|
147
|
+
process.exitCode = code;
|
|
148
|
+
}, (error) => {
|
|
149
|
+
console.error(error instanceof Error ? error.message : String(error));
|
|
150
|
+
process.exitCode = 2;
|
|
151
|
+
});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function fixFor(rule: string): string;
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
const FIXES = {
|
|
2
|
+
'xml/parse': 'Fix the XML at the reported line. Usually an unescaped & or < in a value: escape it (&, <) or wrap the value in <![CDATA[...]]>.',
|
|
3
|
+
'xml/format-unknown': 'Google feeds start with <rss> (with xmlns:g="http://base.google.com/ns/1.0") or <feed>; Ceneo feeds start with <offers>.',
|
|
4
|
+
'google/duplicate-id': 'Every product needs its own g:id. Check the export for joins that repeat a product (for example one row per category or warehouse) and use the variant SKU as the id.',
|
|
5
|
+
'google/identifiers': 'Send g:gtin (EAN) when the product has one. Without a GTIN send g:brand and g:mpn. For own-brand, handmade or custom products with neither, set g:identifier_exists to "no".',
|
|
6
|
+
'google/identifier-exists-misused': 'Remove g:identifier_exists or set it to "yes"; the product has a valid GTIN.',
|
|
7
|
+
'google/gtin-checksum': 'The last digit of the GTIN does not match. Copy the GTIN from the packaging or the supplier; never generate one.',
|
|
8
|
+
'google/gtin-format': 'Use 8, 12, 13 or 14 digits. Convert ISBN-10 to ISBN-13 and UPC-E to UPC-A. Leave g:gtin out when there is none.',
|
|
9
|
+
'google/gtin-restricted': 'Prefixes 2, 02 and 04 are for in-store codes and 05, 98, 99 for coupons. Use the manufacturer GTIN or leave g:gtin out.',
|
|
10
|
+
'google/price-format': 'Write the price as a number with a dot and an ISO 4217 code: 1299.99 PLN. No thousands separators, no "zł".',
|
|
11
|
+
'google/sale-price': 'g:sale_price must be lower than g:price and use the same currency. Drop g:sale_price when there is no sale.',
|
|
12
|
+
'google/availability-value': 'Use in_stock, out_of_stock, preorder or backorder.',
|
|
13
|
+
'google/brand-placeholder': 'Leave g:brand empty when the product has no brand; placeholders get the product disapproved.',
|
|
14
|
+
'google/color-value': 'Use color names in the language of the feed, e.g. "Czarny" or "Czarny/Biały" for several. Map internal color codes to names in the export.',
|
|
15
|
+
'google/all-caps': 'Write titles and descriptions in sentence case; all caps reads as spam and may be disapproved.',
|
|
16
|
+
'google/promo-text': 'Move "free shipping", discounts and "!!" out of the title. Use g:sale_price and shipping settings instead.',
|
|
17
|
+
'google/html-in-text': 'Strip HTML tags from g:title and g:description; Google shows them as plain text.',
|
|
18
|
+
'google/http': 'Serve product pages and images over https.',
|
|
19
|
+
'google/image-url-ascii': 'Percent-encode spaces and non-ASCII characters in image URLs (encodeURI does this).',
|
|
20
|
+
'ceneo/avail-value': 'Use 1 (ships within 24 h), 3, 7, 14, 90 (made to order), 99 (check in store) or 110 (pre-order).',
|
|
21
|
+
'ceneo/price-format': 'Write the price as a number with a dot: 1299.99. No currency, no thousands separators.',
|
|
22
|
+
'ceneo/cat-generic': 'Send the full category path from your shop, e.g. "Dom i ogród/Ogród/Pompy". Do not use temporary categories like "Promocja".',
|
|
23
|
+
'ceneo/desc-cdata': 'Wrap the description in <![CDATA[ ... ]]> so Ceneo reads the HTML as text.',
|
|
24
|
+
'ceneo/desc-html': 'Keep to p, h2, h3, br, ol, ul, li, i, b, strong, em. Remove links, div, span, tables and inline styles.',
|
|
25
|
+
'ceneo/ean': 'Send the 8 or 13 digit EAN from the packaging as <a name="Kod EAN">. Remove the attribute when there is no EAN.',
|
|
26
|
+
'ceneo/brand': 'Add <a name="Marka">Brand</a> (or "Producent") to <attrs>; Ceneo uses it to match the offer to a product.',
|
|
27
|
+
'ceneo/gpsr-reference': 'List the producer or person in <responsibleProducers> or <responsiblePersons> as <p id="..."> before the offers, and use that id in the attribute.',
|
|
28
|
+
'url/unreachable': 'Fix or remove products whose page or image does not load; Google and Ceneo reject them.',
|
|
29
|
+
'url/redirect': 'Put the final URL in the feed. Redirects slow crawling and break if the target changes.',
|
|
30
|
+
};
|
|
31
|
+
export function fixFor(rule) {
|
|
32
|
+
if (FIXES[rule])
|
|
33
|
+
return FIXES[rule];
|
|
34
|
+
if (/\/missing-/.test(rule))
|
|
35
|
+
return 'Add the missing field to every product; products without it are rejected.';
|
|
36
|
+
if (/-length$/.test(rule))
|
|
37
|
+
return 'Shorten the value to the limit; longer values are cut or rejected.';
|
|
38
|
+
if (/-value$/.test(rule))
|
|
39
|
+
return 'Use one of the values listed in the rule title or the linked specification.';
|
|
40
|
+
return 'See the linked specification for the accepted format.';
|
|
41
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export declare const GTIN_LENGTHS: number[];
|
|
2
|
+
export declare const normalizeGtin: (value: string) => string;
|
|
3
|
+
export declare function validCheckDigit(digits: string): boolean;
|
|
4
|
+
export type GtinProblem = 'format' | 'checksum' | 'restricted' | 'coupon';
|
|
5
|
+
export declare function checkGtin(value: string, lengths?: number[]): GtinProblem | undefined;
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
export const GTIN_LENGTHS = [8, 12, 13, 14];
|
|
2
|
+
export const normalizeGtin = (value) => value.replace(/[\s-]/g, '');
|
|
3
|
+
// GS1 check digit: weights 3 and 1 alternate from the digit next to the check digit.
|
|
4
|
+
export function validCheckDigit(digits) {
|
|
5
|
+
let sum = 0;
|
|
6
|
+
for (let i = digits.length - 2, weight = 3; i >= 0; i--, weight = 4 - weight)
|
|
7
|
+
sum += Number(digits[i]) * weight;
|
|
8
|
+
return (10 - (sum % 10)) % 10 === Number(digits[digits.length - 1]);
|
|
9
|
+
}
|
|
10
|
+
export function checkGtin(value, lengths = GTIN_LENGTHS) {
|
|
11
|
+
const digits = normalizeGtin(value);
|
|
12
|
+
if (!/^\d+$/.test(digits) || !lengths.includes(digits.length))
|
|
13
|
+
return 'format';
|
|
14
|
+
if (!validCheckDigit(digits))
|
|
15
|
+
return 'checksum';
|
|
16
|
+
const as13 = digits.length === 14 ? digits.slice(1) : digits.padStart(13, '0');
|
|
17
|
+
if (digits.length > 8 && /^(?:2|02|04)/.test(as13))
|
|
18
|
+
return 'restricted';
|
|
19
|
+
if (digits.length > 8 && /^(?:05|98|99)/.test(as13))
|
|
20
|
+
return 'coupon';
|
|
21
|
+
return undefined;
|
|
22
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { type Chunks, type FeedFormat } from './parse.js';
|
|
2
|
+
import { type RuleInfo, type RuleResult } from './report.js';
|
|
3
|
+
import { type UrlCheckOptions, type UrlStats } from './urls.js';
|
|
4
|
+
export declare const RULES: Record<string, RuleInfo>;
|
|
5
|
+
export interface LintOptions {
|
|
6
|
+
ignore?: string[];
|
|
7
|
+
maxSamples?: number;
|
|
8
|
+
checkUrls?: boolean | UrlCheckOptions;
|
|
9
|
+
}
|
|
10
|
+
export interface LintResult {
|
|
11
|
+
format: FeedFormat | undefined;
|
|
12
|
+
records: number;
|
|
13
|
+
errors: number;
|
|
14
|
+
warnings: number;
|
|
15
|
+
results: RuleResult[];
|
|
16
|
+
urls?: UrlStats;
|
|
17
|
+
}
|
|
18
|
+
export declare function lintFeed(chunks: Chunks, options?: LintOptions): Promise<LintResult>;
|
|
19
|
+
export declare function summarize(format: FeedFormat | undefined, records: number, results: RuleResult[]): LintResult;
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { CENEO_RULES, ceneoChecker, ceneoFileChecks } from '../rules/ceneo.js';
|
|
2
|
+
import { GOOGLE_RULES, googleChecker } from '../rules/google.js';
|
|
3
|
+
import { parseFeed } from './parse.js';
|
|
4
|
+
import { Collector } from './report.js';
|
|
5
|
+
import { URL_RULES, UrlCollector } from './urls.js';
|
|
6
|
+
const XML_RULES = {
|
|
7
|
+
'xml/parse': { level: 'error', title: 'The file is not valid XML', url: 'https://www.w3.org/TR/xml/' },
|
|
8
|
+
'xml/format-unknown': {
|
|
9
|
+
level: 'error',
|
|
10
|
+
title: 'Not a Google Merchant (<rss>, <feed>) or Ceneo (<offers>) feed',
|
|
11
|
+
url: 'https://github.com/mscode-pl/feed-lint#formats',
|
|
12
|
+
},
|
|
13
|
+
'xml/encoding': { level: 'error', title: 'Unsupported encoding in the XML declaration', url: 'https://www.w3.org/TR/xml/#charencoding' },
|
|
14
|
+
};
|
|
15
|
+
export const RULES = { ...XML_RULES, ...GOOGLE_RULES, ...CENEO_RULES, ...URL_RULES };
|
|
16
|
+
const CHECKERS = {
|
|
17
|
+
google: googleChecker,
|
|
18
|
+
ceneo: ceneoChecker,
|
|
19
|
+
};
|
|
20
|
+
export async function lintFeed(chunks, options = {}) {
|
|
21
|
+
const collector = new Collector(RULES, new Set(options.ignore), options.maxSamples ?? 20);
|
|
22
|
+
let check;
|
|
23
|
+
const urlOptions = typeof options.checkUrls === 'object' ? options.checkUrls : {};
|
|
24
|
+
const urls = options.checkUrls ? new UrlCollector(urlOptions.limit ?? 200) : undefined;
|
|
25
|
+
const parsed = await parseFeed(chunks, (record, info, state) => {
|
|
26
|
+
check ??= CHECKERS[info.format](collector.report, state);
|
|
27
|
+
check(record);
|
|
28
|
+
urls?.add(record, info.format, info.root === 'feed');
|
|
29
|
+
});
|
|
30
|
+
check?.end?.();
|
|
31
|
+
if (parsed.info?.format === 'ceneo')
|
|
32
|
+
ceneoFileChecks(parsed.info, collector.report);
|
|
33
|
+
for (const error of parsed.errors) {
|
|
34
|
+
const rule = error.kind === 'format' ? 'xml/format-unknown' : error.kind === 'encoding' ? 'xml/encoding' : 'xml/parse';
|
|
35
|
+
collector.report(rule, { line: error.line, detail: error.message });
|
|
36
|
+
}
|
|
37
|
+
let stats;
|
|
38
|
+
if (urls && !parsed.errors.length) {
|
|
39
|
+
stats = await urls.check(collector.report, urlOptions);
|
|
40
|
+
}
|
|
41
|
+
return { ...summarize(parsed.info?.format, parsed.records, collector.list()), ...(stats ? { urls: stats } : {}) };
|
|
42
|
+
}
|
|
43
|
+
export function summarize(format, records, results) {
|
|
44
|
+
const sum = (level) => results.filter((r) => r.level === level).reduce((n, r) => n + r.count, 0);
|
|
45
|
+
return { format, records, errors: sum('error'), warnings: sum('warning'), results };
|
|
46
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
export declare const GOOGLE_NS = "http://base.google.com/ns/1.0";
|
|
2
|
+
export type FeedFormat = 'google' | 'ceneo';
|
|
3
|
+
export interface XmlNode {
|
|
4
|
+
name: string;
|
|
5
|
+
attrs: Record<string, string>;
|
|
6
|
+
text: string;
|
|
7
|
+
cdata: boolean;
|
|
8
|
+
line: number;
|
|
9
|
+
children: XmlNode[];
|
|
10
|
+
google?: boolean;
|
|
11
|
+
}
|
|
12
|
+
export interface FeedInfo {
|
|
13
|
+
format: FeedFormat;
|
|
14
|
+
root: string;
|
|
15
|
+
rootAttrs: Record<string, string>;
|
|
16
|
+
rootLine: number;
|
|
17
|
+
encoding: string | undefined;
|
|
18
|
+
googleNamespace: string | undefined;
|
|
19
|
+
}
|
|
20
|
+
export interface ParseError {
|
|
21
|
+
kind: 'xml' | 'format' | 'encoding';
|
|
22
|
+
line: number;
|
|
23
|
+
message: string;
|
|
24
|
+
}
|
|
25
|
+
export interface ParseResult {
|
|
26
|
+
info: FeedInfo | undefined;
|
|
27
|
+
errors: ParseError[];
|
|
28
|
+
records: number;
|
|
29
|
+
responsibleProducers: Set<string>;
|
|
30
|
+
responsiblePersons: Set<string>;
|
|
31
|
+
}
|
|
32
|
+
export type Chunks = AsyncIterable<Uint8Array | string> | Iterable<Uint8Array | string>;
|
|
33
|
+
export declare function parseFeed(chunks: Chunks, onRecord: (record: XmlNode, info: FeedInfo, result: ParseResult) => void): Promise<ParseResult>;
|
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
import sax from 'sax';
|
|
2
|
+
export const GOOGLE_NS = 'http://base.google.com/ns/1.0';
|
|
3
|
+
const RECORD = { google: new Set(['item', 'entry']), ceneo: new Set(['o']) };
|
|
4
|
+
function sniffEncoding(head) {
|
|
5
|
+
if (head[0] === 0xef && head[1] === 0xbb && head[2] === 0xbf)
|
|
6
|
+
return { label: 'utf-8', skip: 3 };
|
|
7
|
+
if (head[0] === 0xff && head[1] === 0xfe)
|
|
8
|
+
return { label: 'utf-16le', skip: 2 };
|
|
9
|
+
if (head[0] === 0xfe && head[1] === 0xff)
|
|
10
|
+
return { label: 'utf-16be', skip: 2 };
|
|
11
|
+
const start = new TextDecoder('latin1').decode(head.subarray(0, 512));
|
|
12
|
+
const declared = start.match(/^\s*<\?xml[^>]*\bencoding\s*=\s*["']([^"']+)["']/)?.[1];
|
|
13
|
+
return { label: declared ?? 'utf-8', skip: 0 };
|
|
14
|
+
}
|
|
15
|
+
function decoderFor(label) {
|
|
16
|
+
try {
|
|
17
|
+
return new TextDecoder(label, { fatal: true });
|
|
18
|
+
}
|
|
19
|
+
catch {
|
|
20
|
+
return undefined;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
function concat(a, b) {
|
|
24
|
+
const out = new Uint8Array(a.length + b.length);
|
|
25
|
+
out.set(a);
|
|
26
|
+
out.set(b, a.length);
|
|
27
|
+
return out;
|
|
28
|
+
}
|
|
29
|
+
export async function parseFeed(chunks, onRecord) {
|
|
30
|
+
const result = {
|
|
31
|
+
info: undefined,
|
|
32
|
+
errors: [],
|
|
33
|
+
records: 0,
|
|
34
|
+
responsibleProducers: new Set(),
|
|
35
|
+
responsiblePersons: new Set(),
|
|
36
|
+
};
|
|
37
|
+
const parser = sax.parser(true, { xmlns: true, position: true, strictEntities: true });
|
|
38
|
+
const stack = [];
|
|
39
|
+
let record;
|
|
40
|
+
let gpsrList;
|
|
41
|
+
let stopped = false;
|
|
42
|
+
let tagLine = 1;
|
|
43
|
+
let declaredEncoding;
|
|
44
|
+
const fail = (message, line = parser.line + 1, kind = 'xml') => {
|
|
45
|
+
result.errors.push({ kind, line, message });
|
|
46
|
+
stopped = true;
|
|
47
|
+
};
|
|
48
|
+
parser.onerror = (error) => {
|
|
49
|
+
// One broken tag makes sax report follow-on errors; only the first one is real.
|
|
50
|
+
if (stopped)
|
|
51
|
+
return;
|
|
52
|
+
const message = error.message.split('\n')[0];
|
|
53
|
+
fail(message.charAt(0).toUpperCase() + message.slice(1));
|
|
54
|
+
};
|
|
55
|
+
parser.onprocessinginstruction = (pi) => {
|
|
56
|
+
if (pi.name === 'xml')
|
|
57
|
+
declaredEncoding = pi.body.match(/encoding\s*=\s*["']([^"']+)["']/)?.[1];
|
|
58
|
+
};
|
|
59
|
+
parser.onopentagstart = () => {
|
|
60
|
+
tagLine = parser.line + 1;
|
|
61
|
+
};
|
|
62
|
+
parser.onopentag = (tag) => {
|
|
63
|
+
if (stopped)
|
|
64
|
+
return;
|
|
65
|
+
const t = tag;
|
|
66
|
+
const attrs = {};
|
|
67
|
+
for (const a of Object.values(t.attributes))
|
|
68
|
+
attrs[a.name] = a.value;
|
|
69
|
+
if (!result.info) {
|
|
70
|
+
const root = t.local;
|
|
71
|
+
const format = root === 'rss' || root === 'feed' ? 'google' : root === 'offers' ? 'ceneo' : undefined;
|
|
72
|
+
if (!format) {
|
|
73
|
+
fail(`Unknown feed format: root element <${t.name}>. Expected <rss> or <feed> (Google Merchant) or <offers> (Ceneo).`, tagLine, 'format');
|
|
74
|
+
return;
|
|
75
|
+
}
|
|
76
|
+
result.info = {
|
|
77
|
+
format,
|
|
78
|
+
root,
|
|
79
|
+
rootAttrs: attrs,
|
|
80
|
+
rootLine: tagLine,
|
|
81
|
+
encoding: declaredEncoding,
|
|
82
|
+
googleNamespace: t.ns?.g,
|
|
83
|
+
};
|
|
84
|
+
stack.push({ name: root, attrs, text: '', cdata: false, line: tagLine, children: [] });
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
const info = result.info;
|
|
88
|
+
// Google fields count with or without the g: prefix, and under a wrongly declared g: namespace.
|
|
89
|
+
const google = info.format === 'google' && (t.uri === GOOGLE_NS || t.prefix === 'g');
|
|
90
|
+
const name = google || (info.format === 'google' && t.prefix === '') ? t.local : t.name;
|
|
91
|
+
const node = { name, attrs, text: '', cdata: false, line: tagLine, children: [] };
|
|
92
|
+
if (google)
|
|
93
|
+
node.google = true;
|
|
94
|
+
if (record) {
|
|
95
|
+
stack[stack.length - 1].children.push(node);
|
|
96
|
+
}
|
|
97
|
+
else if (RECORD[info.format].has(name)) {
|
|
98
|
+
record = node;
|
|
99
|
+
}
|
|
100
|
+
else if (info.format === 'ceneo' && (name === 'responsibleProducers' || name === 'responsiblePersons')) {
|
|
101
|
+
gpsrList = name === 'responsibleProducers' ? result.responsibleProducers : result.responsiblePersons;
|
|
102
|
+
}
|
|
103
|
+
else if (gpsrList && name === 'p' && attrs.id) {
|
|
104
|
+
gpsrList.add(attrs.id);
|
|
105
|
+
}
|
|
106
|
+
stack.push(node);
|
|
107
|
+
};
|
|
108
|
+
const addText = (text, cdata) => {
|
|
109
|
+
if (stopped || !record)
|
|
110
|
+
return;
|
|
111
|
+
const node = stack[stack.length - 1];
|
|
112
|
+
node.text += text;
|
|
113
|
+
if (cdata)
|
|
114
|
+
node.cdata = true;
|
|
115
|
+
};
|
|
116
|
+
parser.ontext = (text) => addText(text, false);
|
|
117
|
+
parser.oncdata = (text) => addText(text, true);
|
|
118
|
+
parser.onclosetag = () => {
|
|
119
|
+
if (stopped)
|
|
120
|
+
return;
|
|
121
|
+
const node = stack.pop();
|
|
122
|
+
if (node && node === record) {
|
|
123
|
+
result.records++;
|
|
124
|
+
onRecord(record, result.info, result);
|
|
125
|
+
record = undefined;
|
|
126
|
+
}
|
|
127
|
+
else if (node && (node.name === 'responsibleProducers' || node.name === 'responsiblePersons')) {
|
|
128
|
+
gpsrList = undefined;
|
|
129
|
+
}
|
|
130
|
+
};
|
|
131
|
+
let decoder;
|
|
132
|
+
let head;
|
|
133
|
+
const decode = (bytes, stream) => {
|
|
134
|
+
try {
|
|
135
|
+
return decoder.decode(bytes, { stream });
|
|
136
|
+
}
|
|
137
|
+
catch {
|
|
138
|
+
fail(`The bytes do not match the declared encoding (${decoder.encoding}); the file is probably saved in another encoding.`, parser.line + 1, 'encoding');
|
|
139
|
+
return undefined;
|
|
140
|
+
}
|
|
141
|
+
};
|
|
142
|
+
const start = (bytes) => {
|
|
143
|
+
const { label, skip } = sniffEncoding(bytes);
|
|
144
|
+
decoder = decoderFor(label);
|
|
145
|
+
if (!decoder) {
|
|
146
|
+
fail(`Unsupported encoding "${label}" in the XML declaration.`, 1, 'encoding');
|
|
147
|
+
return undefined;
|
|
148
|
+
}
|
|
149
|
+
return decode(bytes.subarray(skip), true);
|
|
150
|
+
};
|
|
151
|
+
for await (const chunk of chunks) {
|
|
152
|
+
if (stopped)
|
|
153
|
+
break;
|
|
154
|
+
let text;
|
|
155
|
+
if (typeof chunk === 'string') {
|
|
156
|
+
text = chunk;
|
|
157
|
+
}
|
|
158
|
+
else if (decoder) {
|
|
159
|
+
text = decode(chunk, true);
|
|
160
|
+
}
|
|
161
|
+
else {
|
|
162
|
+
// The XML declaration may be split across small chunks (stdin, slow HTTP), so wait for enough of it.
|
|
163
|
+
head = head ? concat(head, chunk) : chunk;
|
|
164
|
+
if (head.length < 512 && !new TextDecoder('latin1').decode(head).includes('?>'))
|
|
165
|
+
continue;
|
|
166
|
+
text = start(head);
|
|
167
|
+
head = undefined;
|
|
168
|
+
}
|
|
169
|
+
if (text === undefined)
|
|
170
|
+
break;
|
|
171
|
+
parser.write(text);
|
|
172
|
+
}
|
|
173
|
+
if (!stopped && head) {
|
|
174
|
+
const text = start(head);
|
|
175
|
+
if (text !== undefined)
|
|
176
|
+
parser.write(text);
|
|
177
|
+
}
|
|
178
|
+
if (!stopped && decoder) {
|
|
179
|
+
const rest = decode(new Uint8Array(), false);
|
|
180
|
+
if (rest)
|
|
181
|
+
parser.write(rest);
|
|
182
|
+
}
|
|
183
|
+
if (!stopped)
|
|
184
|
+
parser.close();
|
|
185
|
+
if (!result.info && !result.errors.length)
|
|
186
|
+
result.errors.push({ kind: 'format', line: 1, message: 'The file is empty or has no root element.' });
|
|
187
|
+
return result;
|
|
188
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
export type Level = 'error' | 'warning';
|
|
2
|
+
export interface RuleInfo {
|
|
3
|
+
level: Level;
|
|
4
|
+
title: string;
|
|
5
|
+
url: string;
|
|
6
|
+
}
|
|
7
|
+
export interface Sample {
|
|
8
|
+
line: number;
|
|
9
|
+
id?: string;
|
|
10
|
+
detail?: string;
|
|
11
|
+
}
|
|
12
|
+
export interface RuleResult extends RuleInfo {
|
|
13
|
+
rule: string;
|
|
14
|
+
count: number;
|
|
15
|
+
samples: Sample[];
|
|
16
|
+
}
|
|
17
|
+
export interface Report {
|
|
18
|
+
(rule: string, sample: Sample): void;
|
|
19
|
+
}
|
|
20
|
+
export declare class Collector {
|
|
21
|
+
private readonly rules;
|
|
22
|
+
private readonly ignore;
|
|
23
|
+
private readonly maxSamples;
|
|
24
|
+
private readonly results;
|
|
25
|
+
constructor(rules: Record<string, RuleInfo>, ignore: Set<string>, maxSamples: number);
|
|
26
|
+
readonly report: Report;
|
|
27
|
+
list(): RuleResult[];
|
|
28
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
export class Collector {
|
|
2
|
+
rules;
|
|
3
|
+
ignore;
|
|
4
|
+
maxSamples;
|
|
5
|
+
results = new Map();
|
|
6
|
+
constructor(rules, ignore, maxSamples) {
|
|
7
|
+
this.rules = rules;
|
|
8
|
+
this.ignore = ignore;
|
|
9
|
+
this.maxSamples = maxSamples;
|
|
10
|
+
}
|
|
11
|
+
report = (rule, sample) => {
|
|
12
|
+
if (this.ignore.has(rule))
|
|
13
|
+
return;
|
|
14
|
+
const info = this.rules[rule];
|
|
15
|
+
if (!info)
|
|
16
|
+
throw new Error(`Unknown rule ${rule}`);
|
|
17
|
+
let result = this.results.get(rule);
|
|
18
|
+
if (!result)
|
|
19
|
+
this.results.set(rule, (result = { rule, ...info, count: 0, samples: [] }));
|
|
20
|
+
result.count++;
|
|
21
|
+
if (result.samples.length < this.maxSamples)
|
|
22
|
+
result.samples.push(sample);
|
|
23
|
+
};
|
|
24
|
+
list() {
|
|
25
|
+
// An XML error makes every other result partial, so it always comes first.
|
|
26
|
+
const rank = (r) => (r.rule.startsWith('xml/') ? 0 : r.level === 'error' ? 1 : 2);
|
|
27
|
+
return [...this.results.values()].sort((a, b) => rank(a) - rank(b) || b.count - a.count || a.rule.localeCompare(b.rule));
|
|
28
|
+
}
|
|
29
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { FeedFormat, XmlNode } from './parse.js';
|
|
2
|
+
import type { Report, RuleInfo } from './report.js';
|
|
3
|
+
export declare const URL_RULES: Record<string, RuleInfo>;
|
|
4
|
+
export interface UrlCheckOptions {
|
|
5
|
+
limit?: number;
|
|
6
|
+
concurrency?: number;
|
|
7
|
+
timeoutMs?: number;
|
|
8
|
+
userAgent?: string;
|
|
9
|
+
fetch?: typeof fetch;
|
|
10
|
+
}
|
|
11
|
+
export interface UrlStats {
|
|
12
|
+
total: number;
|
|
13
|
+
checked: number;
|
|
14
|
+
}
|
|
15
|
+
export declare class UrlCollector {
|
|
16
|
+
private readonly limit;
|
|
17
|
+
private readonly urls;
|
|
18
|
+
private readonly overflow;
|
|
19
|
+
constructor(limit?: number);
|
|
20
|
+
add(record: XmlNode, format: FeedFormat, atom?: boolean): void;
|
|
21
|
+
private put;
|
|
22
|
+
check(report: Report, options?: UrlCheckOptions): Promise<UrlStats>;
|
|
23
|
+
}
|