dpp-readiness 0.0.0-stage → 0.1.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/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0 (unreleased)
4
+
5
+ - First release: reads Shopify and WooCommerce product exports (variants grouped, WooCommerce variations matched to parents by ID or SKU, the WooCommerce GTIN column) or a generic CSV/JSON; classifies products into the passport rules that reach them (battery passport from 18 Feb 2027, detergents from 23 Sep 2029, toys from 1 Aug 2030, planned ESPR acts for textiles, tyres, furniture and mattresses, footwear study, EPREL for energy-labelled products) with battery capacity parsing for the 2 kWh threshold; checks GPSR Art. 19 offer information, textile fibre composition and battery listing data; scores ESPR Annex III data readiness; validates GTIN check digits, catches spreadsheet-mangled barcodes and writes GS1 Digital Link URIs; text, Markdown and CSV reports and draft passport JSON per product. Facts checked 4 Dec 2026.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ahmad Zia (https://www.ahmadzia.com)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,112 @@
1
- # Temporary Holding Version
1
+ # dpp-readiness
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ <!-- badges -->
4
+ [![npm](https://img.shields.io/npm/v/dpp-readiness?color=3a7a4e&label=npm)](https://www.npmjs.com/package/dpp-readiness) [![CI](https://github.com/MuhammadAhmadZia/dpp-readiness/actions/workflows/ci.yml/badge.svg)](https://github.com/MuhammadAhmadZia/dpp-readiness/actions/workflows/ci.yml) [![License: MIT](https://img.shields.io/badge/license-MIT-0d2018)](LICENSE) [![Agent skill](https://img.shields.io/badge/agent%20skill-dpp--readiness-c5dfc9)](skills/dpp-readiness/SKILL.md) [![Guide](https://img.shields.io/badge/guide-ahmadzia.com-3a7a4e)](https://www.ahmadzia.com/tools/dpp-readiness)
5
+
6
+ **Find out which EU digital product passport rules reach the products in your store, when, and what your listings already miss under rules that apply today.** Reads a Shopify or WooCommerce product export. No account, no upload, no dependencies beyond Node.
7
+
8
+ ```bash
9
+ npx dpp-readiness products_export.csv --operator operator.json
10
+ ```
11
+
12
+ The EU is moving product information into digital product passports (DPPs): a record per product, reached by a QR code, holding identifiers, materials, compliance documents and repair and recycling information. The framework is the Ecodesign for Sustainable Products Regulation (ESPR, (EU) 2024/1781), and the infrastructure now exists: the EU passport registry went live on 20 July 2026 under Implementing Regulation (EU) 2026/1778, and the first six harmonised passport standards (EN 18216, 18219, 18220, 18221, 18222, 18223) were cited by Implementing Decision (EU) 2026/1736. What each product group must hold comes in separate laws, on different dates. This tool sorts that out for your catalog.
13
+
14
+ ## Which rules, and when
15
+
16
+ | Products | Rule | When | Status (checked 4 Dec 2026) |
17
+ |---|---|---|---|
18
+ | E-bikes, e-scooters and other light electric vehicles (their LMT batteries), home and industrial batteries above 2 kWh, EV batteries | Battery passport, Batteries Regulation (EU) 2023/1542 Art. 77, Annex XIII | **18 February 2027** | Law |
19
+ | Detergents (and surfactants sold to end users) | Detergents Regulation (EU) 2026/405 Art. 21 | 23 September 2029 | Law |
20
+ | Toys | Toy Safety Regulation (EU) 2025/2509 Art. 19; the passport replaces the declaration of conformity | 1 August 2030 | Law |
21
+ | Textiles and apparel | ESPR delegated act | Act indicatively 2027; as a rule, requirements apply no earlier than 18 months later (ESPR Art. 4(4)) | Planned |
22
+ | Tyres | ESPR delegated act | Act indicatively 2027 | Planned |
23
+ | Furniture | ESPR delegated act | Act indicatively 2028 | Planned |
24
+ | Mattresses | ESPR delegated act | Act indicatively 2029 | Planned |
25
+ | Footwear | Not in the 2025-2030 plan | Commission study by end 2027 | Study |
26
+ | Products with an EU energy label | EPREL database instead of a separate passport | Already applies | Law |
27
+
28
+ Planned dates come from the Commission's ESPR and Energy Labelling Working Plan 2025-2030 (COM(2025) 187) and are indicative.
29
+
30
+ ## What it checks in every listing
31
+
32
+ Some of the passport's content is already required in your online offer:
33
+
34
+ - **GPSR Article 19** (since 13 December 2024): every offer to EU consumers must show the manufacturer's name, postal address and electronic address; the EU responsible person if the manufacturer is outside the EU; a product identifier; and the warnings and safety information that go on the product.
35
+ - **Textile fibre names** (Regulation (EU) No 1007/2011 Art. 16): fibre composition with percentages must be available before purchase, online too.
36
+ - **Battery data** for passport batteries: capacity, chemistry and a passport link.
37
+
38
+ And how much of the ESPR Annex III passport data your catalog already holds: a valid GTIN (Annex III point (c) names GTIN under ISO/IEC 15459-6), a commodity (HS/TARIC) code, manufacturer details, the EU operator, the importer's EORI number for imported goods, compliance documents and instructions. That share is the "readiness" percentage.
39
+
40
+ It also validates every barcode (GS1 check digit), catches barcodes a spreadsheet turned into numbers like `4.00638E+12`, and writes a GS1 Digital Link URI for each valid GTIN (`https://id.gs1.org/01/04006381333931`), the kind of web address a passport QR code can carry.
41
+
42
+ ## Step by step
43
+
44
+ **1. Export your products.** Shopify: Products > Export > All products, CSV for Excel or plain CSV. WooCommerce: Products > Export. Any other platform: a CSV with columns such as `title, description, brand, category, gtin, hs_code, country_of_origin, materials`.
45
+
46
+ **2. Describe your suppliers (optional but recommended).** Copy [`examples/operator.json`](examples/operator.json) and fill in each brand's legal name, postal address, email and country, plus your EU responsible person and importer. Without it, every product is reported as missing the manufacturer's address, because product exports do not contain it.
47
+
48
+ **3. Run it.**
49
+
50
+ ```bash
51
+ npx dpp-readiness products_export.csv --operator operator.json --md report.md --csv products.csv --drafts passports/
52
+ ```
53
+
54
+ - `report.md`: the rules that reach your catalog, what to do for each, and the gaps.
55
+ - `products.csv`: one line per product with its rules, readiness and issues.
56
+ - `passports/`: a draft JSON per product with a passport rule, filled from your data, with empty fields for what is still missing. It is a worksheet, not a compliant passport: each delegated act or regulation fixes the real fields and format.
57
+
58
+ The exit code is 1 when a requirement that already applies is missing, so it can run in CI after each catalog import.
59
+
60
+ Try it on the sample store: `npx dpp-readiness examples/shopify-products.csv --operator examples/operator.json`.
61
+
62
+ ## How products are recognised
63
+
64
+ From the title, product type, category and tags (English keywords; Shopify's standard product categories work well). Battery products are decided by stated capacity: storage products above 2 kWh need a passport; products without a stated capacity are flagged so you add it. Check the classification for your catalog in the CSV, especially for mixed or unusual products.
65
+
66
+ ## Limits
67
+
68
+ - Not legal advice. Who must create a passport depends on your role (manufacturer, importer, distributor, marketplace); as a retailer you mostly need the passport to exist and its data in your listing.
69
+ - Planned dates move. The tool says "planned" and "indicative" where no act exists yet. Re-run after new acts are adopted.
70
+ - It reads what your export contains. Data held only in apps or metafields not in the export is not seen.
71
+
72
+ ## Sustainable Development Goals
73
+
74
+ This tool supports **SDG target 12.8** (ensure that people have the relevant information and awareness for sustainable development and lifestyles): it helps small stores publish the material, origin and safety information that passports are designed to carry, and makes listings complete before the passport dates arrive.
75
+
76
+ It also supports **target 12.5** (reduce waste through prevention, recycling and reuse) indirectly, because passports carry the repair, dismantling and recycling information circular business models need, and **target 8.3** (growth of micro, small and medium-sized enterprises): a free check replaces a compliance audit most small sellers cannot afford.
77
+
78
+ What it does not do: it does not create or register passports, and it cannot verify that supplier data is true.
79
+
80
+ ## References
81
+
82
+ - Regulation (EU) 2024/1781 (ESPR), Annex III; Implementing Regulation (EU) 2026/1778 (registry); Implementing Decision (EU) 2026/1736 (harmonised standards).
83
+ - Regulation (EU) 2023/1542 (batteries), Art. 77 and Annexes VI and XIII.
84
+ - Regulation (EU) 2025/2509 (toys), Art. 19; Regulation (EU) 2026/405 (detergents), Art. 21.
85
+ - Regulation (EU) 2023/988 (GPSR), Art. 19; Regulation (EU) No 1007/2011 (textile fibre names), Art. 16.
86
+ - European Commission (2025). Ecodesign for Sustainable Products and Energy Labelling Working Plan 2025-2030, COM(2025) 187.
87
+ - GS1 General Specifications (check digit) and GS1 Digital Link standard.
88
+
89
+ ## License
90
+
91
+ MIT. Built by [Ahmad Zia](https://www.ahmadzia.com).
92
+
93
+ <!-- ahmadzia-links -->
94
+ ## Guide, help and author
95
+
96
+ - **Full guide with examples and FAQs:** [www.ahmadzia.com/tools/dpp-readiness](https://www.ahmadzia.com/tools/dpp-readiness)
97
+ - **Background reading:** [Digital product passport timeline for online sellers](https://www.ahmadzia.com/blog/digital-product-passport-timeline-online-sellers)
98
+ - **All 30 free tools and agent skills:** [ahmadzia.com/tools](https://www.ahmadzia.com/tools) · [ahmadzia.com/skills](https://www.ahmadzia.com/skills)
99
+ - **Want it set up, fixed or tuned for your store?** [Book a free call](https://www.ahmadzia.com/contact)
100
+
101
+ Built by **[Ahmad Zia](https://www.ahmadzia.com)** (Muhammad Ahmad Zia), an AI consultant for ecommerce since 2020 and green AI researcher at the University of Lahore. [Research](https://www.ahmadzia.com/research) · [Google Scholar](https://scholar.google.com/citations?user=sqjdX2EAAAAJ&hl=en) · [ORCID](https://orcid.org/0000-0002-3208-6246) · [LinkedIn](https://www.linkedin.com/in/muhammad-ahmadzia/) · [GitHub](https://github.com/MuhammadAhmadZia)
102
+ <!-- /ahmadzia-links -->
103
+
104
+ ## More compliance and sustainability tools
105
+
106
+ - [green-claims-check](https://github.com/MuhammadAhmadZia/green-claims-check): Find greenwashing risks in your product pages before regulators do
107
+ - [returns-reducer](https://github.com/MuhammadAhmadZia/returns-reducer): Find out why products come back and what to fix first
108
+ - [ai-carbon-report](https://github.com/MuhammadAhmadZia/ai-carbon-report): Turn LLM usage logs into an energy, carbon and water report
109
+ - [green-site-audit](https://github.com/MuhammadAhmadZia/green-site-audit): Measure the carbon footprint of a web page or online store
110
+ - [sdg-alignment](https://github.com/MuhammadAhmadZia/sdg-alignment): Map products, papers and grants to UN SDG targets, with evidence
111
+
112
+ All 30 tools and agent skills: [github.com/MuhammadAhmadZia](https://github.com/MuhammadAhmadZia) · [ahmadzia.com/tools](https://www.ahmadzia.com/tools)
@@ -0,0 +1,38 @@
1
+ #!/usr/bin/env node
2
+ import { mkdir, readFile, writeFile } from 'node:fs/promises';
3
+ import { join } from 'node:path';
4
+ import { analyze, draftPassport, formatCsv, formatMarkdown, formatText, loadProducts } from '../src/index.js';
5
+
6
+ const HELP = `dpp-readiness: which EU digital product passport rules reach your catalog, and what your listings miss today
7
+
8
+ Usage:
9
+ dpp-readiness <products.csv|json> [--operator operator.json] [--md report.md] [--csv products.csv] [--json]
10
+ [--drafts dir] [--resolver https://id.example.com] [--include-drafts]
11
+
12
+ Input: a Shopify or WooCommerce product export, or a generic CSV/JSON (title, description, brand, category, gtin, hs_code, ...).
13
+ --operator: manufacturers' addresses and countries, your EU responsible person and importer (see examples/operator.json).
14
+ Exit code 1 when legal requirements that already apply are missing.`;
15
+
16
+ const args = process.argv.slice(2);
17
+ const opt = (n) => { const i = args.indexOf(n); return i >= 0 ? args[i + 1] : undefined; };
18
+ const file = args.find((a, i) => !a.startsWith('--') && !(i > 0 && args[i - 1].startsWith('--') && !['--json', '--include-drafts'].includes(args[i - 1])));
19
+ if (!file || args.includes('--help')) { console.log(HELP); process.exit(file ? 0 : 2); }
20
+ try {
21
+ const products = await loadProducts(file);
22
+ const op = opt('--operator') ? JSON.parse(await readFile(opt('--operator'), 'utf8')) : {};
23
+ const a = analyze(products, op, { resolver: opt('--resolver'), includeDrafts: args.includes('--include-drafts') });
24
+ if (args.includes('--json')) console.log(JSON.stringify(a, null, 2)); else console.log(formatText(a));
25
+ if (opt('--md')) await writeFile(opt('--md'), formatMarkdown(a));
26
+ if (opt('--csv')) await writeFile(opt('--csv'), formatCsv(a));
27
+ if (opt('--drafts')) {
28
+ await mkdir(opt('--drafts'), { recursive: true });
29
+ const byId = new Map(products.map((p) => [p.id, p]));
30
+ for (const r of a.results.filter((x) => x.regimes.length)) {
31
+ await writeFile(join(opt('--drafts'), `${String(r.id).replace(/[^\w.-]+/g, '_')}.json`), JSON.stringify(draftPassport(byId.get(r.id), r, op), null, 2));
32
+ }
33
+ }
34
+ process.exitCode = a.issues.some((i) => i.level === 'error') ? 1 : 0;
35
+ } catch (e) {
36
+ console.error(`error: ${e.message}`);
37
+ process.exitCode = 2;
38
+ }
@@ -0,0 +1,11 @@
1
+ {
2
+ "manufacturers": {
3
+ "VoltRide": { "name": "VoltRide Technology Co., Ltd.", "address": "88 Industrial Road, Shenzhen, China", "email": "compliance@voltride.example", "country": "CN" },
4
+ "SunCell": { "name": "SunCell GmbH", "address": "Solarstrasse 1, 80331 Munich, Germany", "email": "info@suncell.example", "country": "DE" },
5
+ "CleanCo": { "name": "CleanCo B.V.", "address": "Schoonweg 5, 1011 AB Amsterdam, Netherlands", "email": "service@cleanco.example", "country": "NL" },
6
+ "Atelier Lahore": { "name": "Atelier Lahore (Pvt) Ltd", "address": "12 Mall Road, Lahore 54000, Pakistan", "email": "hello@atelier.example", "country": "PK" },
7
+ "NordHome": { "name": "NordHome AB", "address": "Mobelgatan 3, 111 22 Stockholm, Sweden", "email": "kund@nordhome.example", "country": "SE" }
8
+ },
9
+ "eu_responsible_person": { "name": "EU Rep Services Ltd", "address": "1 Harbour Street, Dublin D02, Ireland", "email": "rp@eurep.example" },
10
+ "importer": { "name": "Example Imports Ltd", "address": "1 Harbour Street, Dublin D02, Ireland", "email": "imports@example.example", "eori": "" }
11
+ }
@@ -0,0 +1,14 @@
1
+ Handle,Title,Body (HTML),Vendor,Product Category,Type,Tags,Published,Option1 Name,Option1 Value,Variant SKU,Variant Grams,Variant Price,Variant Barcode,Status
2
+ city-e-bike,City E-Bike 250W,"<p>Pedelec with 36V 13Ah lithium-ion battery. Warning: charge only with the supplied charger.</p>",VoltRide,Sporting Goods > Outdoor Recreation > Cycling > Bicycles,Electric Bikes,"ebike, commuting",true,Frame,M,VR-EB-M,22000,1299,4006381333931,active
3
+ city-e-bike,,,,,,,,Frame,L,VR-EB-L,22500,1299,5901234123457,active
4
+ power-station-1000,Portable Power Station 1024Wh,"<p>LiFePO4 power station, 1024Wh, 12 kg. Keep away from water.</p>",VoltRide,Electronics > Power > Power Stations,Power Station,,true,Title,Default,VR-PS1000,12000,799,8712345678906,active
5
+ home-battery-5,Home Battery 5.12 kWh,"<p>Wall-mounted solar storage battery for homes.</p>",SunCell,Electronics > Power > Batteries,Home Battery,solar,true,Title,Default,SC-HB5,48000,2490,5012345678900,active
6
+ plush-bear,Plush Teddy Bear,"<p>Super soft teddy for little ones.</p>",HappyToys,Toys & Games > Toys > Stuffed Animals,Plush Toy,kids,true,Title,Default,HT-BEAR,300,19,7612345678901,active
7
+ laundry-liquid,Laundry Liquid Lavender 1.5L,"<p>Concentrated laundry liquid. Warning: keep out of reach of children.</p>",CleanCo,Home & Garden > Household Supplies > Laundry Supplies,Laundry Detergent,,true,Title,Default,CC-LL15,1600,7.5,5601234567892,active
8
+ linen-shirt,Linen Shirt,"<p>Breathable summer shirt. 100% linen.</p>",Atelier Lahore,Apparel & Accessories > Clothing > Shirts & Tops,Shirts,,true,Size,M,AL-LS-M,250,45,4.00638E+12,active
9
+ summer-dress,Summer Dress,"<p>Light and flowing.</p>",Atelier Lahore,Apparel & Accessories > Clothing > Dresses,Dresses,,true,Size,S,AL-SD-S,300,60,,active
10
+ oak-sofa,Oak Frame Sofa,"<p>Three-seater.</p>",NordHome,Furniture > Sofas,Sofa,,true,Title,Default,NH-SOFA,40000,999,8412345678905,active
11
+ foam-mattress,Memory Foam Mattress 160x200,"<p>Medium firm.</p>",NordHome,Furniture > Beds & Accessories > Mattresses,Mattress,,true,Title,Default,NH-MAT,25000,499,3001234567892,active
12
+ runner-sneaker,Runner Sneaker,"<p>Everyday sneaker.</p>",StepUp,Apparel & Accessories > Shoes,Sneakers,,true,Size,42,SU-RS-42,800,89,4801234567897,active
13
+ smart-tv-55,Smart TV 55 inch,"<p>4K television.</p>",Visio,Electronics > Video > Televisions,Television,,true,Title,Default,VS-TV55,15000,549,8991234567891,active
14
+ old-mug,Old Mug,"<p>Ceramic mug.</p>",Atelier Lahore,Home & Garden > Kitchen,Mug,,false,Title,Default,AL-MUG,350,9,,draft
package/package.json CHANGED
@@ -1,6 +1,60 @@
1
1
  {
2
2
  "name": "dpp-readiness",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Find which EU digital product passport rules reach your store's products (battery passport from Feb 2027, toys, detergents, textiles, furniture, tyres, mattresses) and what your listings miss today under the GPSR and textile labelling rules. Reads Shopify and WooCommerce exports, validates GTINs, writes GS1 Digital Link URIs and draft passport data.",
5
+ "type": "module",
6
+ "bin": {
7
+ "dpp-readiness": "bin/dpp-readiness.js"
8
+ },
9
+ "main": "src/index.js",
10
+ "exports": {
11
+ ".": "./src/index.js"
12
+ },
13
+ "files": [
14
+ "bin",
15
+ "src",
16
+ "examples",
17
+ "README.md",
18
+ "LICENSE",
19
+ "CHANGELOG.md"
20
+ ],
21
+ "scripts": {
22
+ "test": "node --test test/*.test.js"
23
+ },
24
+ "engines": {
25
+ "node": ">=18.17"
26
+ },
27
+ "dependencies": {
28
+ "returns-reducer": "^0.1.0"
29
+ },
30
+ "keywords": [
31
+ "digital-product-passport",
32
+ "dpp",
33
+ "espr",
34
+ "ecodesign",
35
+ "battery-passport",
36
+ "gpsr",
37
+ "eu-compliance",
38
+ "shopify",
39
+ "woocommerce",
40
+ "gtin",
41
+ "gs1-digital-link",
42
+ "textile-labelling",
43
+ "toy-safety",
44
+ "sustainability",
45
+ "ecommerce"
46
+ ],
47
+ "author": {
48
+ "name": "Ahmad Zia (Muhammad Ahmad Zia)",
49
+ "url": "https://www.ahmadzia.com"
50
+ },
51
+ "license": "MIT",
52
+ "homepage": "https://www.ahmadzia.com/tools/dpp-readiness",
53
+ "repository": {
54
+ "type": "git",
55
+ "url": "git+https://github.com/MuhammadAhmadZia/dpp-readiness.git"
56
+ },
57
+ "bugs": {
58
+ "url": "https://github.com/MuhammadAhmadZia/dpp-readiness/issues"
59
+ }
60
+ }
package/src/analyze.js ADDED
@@ -0,0 +1,24 @@
1
+ import { checkProduct } from './checks.js';
2
+ import { REGIMES } from './regimes.js';
3
+
4
+ export function analyze(products, op = {}, opts = {}) {
5
+ const list = opts.includeDrafts ? products : products.filter((p) => p.status !== 'draft' && p.status !== 'archived');
6
+ const results = list.map((p) => checkProduct(p, op, opts));
7
+ const byRegime = {};
8
+ for (const r of results) for (const k of r.regimes) (byRegime[k] ||= []).push(r.id);
9
+ const issueCounts = {};
10
+ for (const r of results) for (const i of r.issues) {
11
+ const c = (issueCounts[i.code] ||= { code: i.code, level: i.level, law: i.law, count: 0, example: i.message, products: [] });
12
+ c.count++;
13
+ if (c.products.length < 5) c.products.push(r.title || r.id);
14
+ }
15
+ const order = { error: 0, warning: 1, info: 2 };
16
+ const regimes = Object.entries(byRegime).map(([k, ids]) => ({ id: k, ...REGIMES[k], products: ids.length }))
17
+ .sort((a, b) => (a.status === 'law' ? 0 : 1) - (b.status === 'law' ? 0 : 1) || String(a.applies_from || '9').localeCompare(String(b.applies_from || '9')));
18
+ const avg = results.length ? Math.round(results.reduce((a, r) => a + r.readiness, 0) / results.length) : 0;
19
+ return {
20
+ products: results.length, skipped: products.length - list.length, regimes,
21
+ issues: Object.values(issueCounts).sort((a, b) => order[a.level] - order[b.level] || b.count - a.count),
22
+ readiness_avg: avg, results, checked_on: '2026-12-04',
23
+ };
24
+ }
package/src/checks.js ADDED
@@ -0,0 +1,89 @@
1
+ // Checks per product: what the law asks of an online listing today (GPSR Art. 19 since 13 Dec 2024;
2
+ // textile fibre names, Regulation (EU) No 1007/2011 Art. 16), and how much of the ESPR Annex III passport
3
+ // data the catalog already holds.
4
+ import { classify, REGIMES } from './regimes.js';
5
+ import { digitalLink, looksMangled, validGtin } from './gtin.js';
6
+
7
+ export const EU = new Set(['AT', 'BE', 'BG', 'HR', 'CY', 'CZ', 'DK', 'EE', 'FI', 'FR', 'DE', 'GR', 'HU', 'IE', 'IT', 'LV', 'LT', 'LU', 'MT', 'NL', 'PL', 'PT', 'RO', 'SK', 'SI', 'ES', 'SE']);
8
+ const EMAIL = /[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/i;
9
+ const FIBRE = /\b\d{1,3}\s?%\s*(organic\s+|recycled\s+)?(cotton|polyester|wool|silk|linen|flax|viscose|rayon|elastane|spandex|lycra|nylon|polyamide|acrylic|lyocell|tencel|modal|cashmere|alpaca|mohair|hemp|jute|acetate|cupro|polypropylene|bamboo viscose)\b|\b(cotton|polyester|wool|silk|linen|viscose|elastane|polyamide|acrylic)\s*\d{1,3}\s?%/i;
10
+ const WARNING = /\b(warning|caution|attention|keep (out of reach|away)|not suitable for children|choking hazard|adult supervision|safety (information|instructions)|danger)\b/i;
11
+ const CHEMISTRY = /\b(li-?ion|lithium[- ]ion|lithium|lifepo4|lfp|nmc|nca|lead[- ]acid|agm|gel|nimh|sodium[- ]ion)\b/i;
12
+ const strip = (h) => String(h || '').replace(/<[^>]+>/g, ' ').replace(/&nbsp;/g, ' ').replace(/\s+/g, ' ');
13
+
14
+ function manufacturerFor(p, op) {
15
+ const m = (op.manufacturers || {})[p.manufacturer || p.vendor] || (op.manufacturers || {})[p.vendor] || op.default_manufacturer || null;
16
+ return m ? { name: m.name || p.vendor, address: m.address || '', email: m.email || '', country: (m.country || '').toUpperCase() } : { name: p.manufacturer || p.vendor || '', address: '', email: '', country: '' };
17
+ }
18
+
19
+ export function checkProduct(p, op = {}, { resolver } = {}) {
20
+ const text = strip(`${p.title} ${p.description}`);
21
+ const { regimes, notes, battery_wh } = classify(p);
22
+ const issues = [];
23
+ const add = (level, code, message, law, detail) => issues.push({ level, code, message, law, ...(detail ? { detail } : {}) });
24
+ const m = manufacturerFor(p, op);
25
+ const mEmail = m.email || (text.match(EMAIL) || [''])[0];
26
+ const nonEu = m.country ? !EU.has(m.country) : null;
27
+ const rp = op.eu_responsible_person || null;
28
+
29
+ // GPSR Article 19: what every online offer to EU consumers must show (applies since 13 December 2024)
30
+ const gpsr = 'GPSR (EU) 2023/988 Art. 19';
31
+ if (!m.name) add('error', 'gpsr-manufacturer', 'No manufacturer or brand name.', gpsr);
32
+ if (!m.address || !mEmail) add('error', 'gpsr-manufacturer-contact', 'The manufacturer\'s postal and electronic address are not on file. The offer must show both (add them to the operator file or the listing).', gpsr, `${m.name || 'unknown manufacturer'}: missing ${!m.address && !mEmail ? 'postal and electronic address' : !m.address ? 'postal address' : 'electronic address'}`);
33
+ if (nonEu === true && !(rp?.name && rp?.address && rp?.email)) add('error', 'gpsr-responsible-person', 'Manufacturer outside the EU: the offer must name the EU responsible person with postal and electronic address.', gpsr, `manufacturer country ${m.country}`);
34
+ if (nonEu === null && !(rp?.name)) add('warning', 'gpsr-origin-unknown', 'Manufacturer country unknown: if it is outside the EU, the offer must also name the EU responsible person.', gpsr);
35
+ const gtins = p.variants.map((v) => v.gtin).filter(Boolean);
36
+ if (!gtins.length && !p.variants.some((v) => v.sku)) add('warning', 'gpsr-identifier', 'No barcode or SKU: the offer needs a type or other product identifier.', gpsr);
37
+ if ((regimes.includes('toy_dpp') || regimes.includes('battery_passport') || regimes.includes('detergent_dpp')) && !WARNING.test(text)) add('warning', 'gpsr-warnings', 'No warnings or safety information in the listing. Warnings that go on the product must also appear in the online offer.', gpsr);
38
+
39
+ if (regimes.includes('textiles_espr') && !FIBRE.test(`${text} ${p.materials || ''} ${(p.tags || []).join(' ')}`)) {
40
+ add('error', 'textile-fibres', 'No fibre composition with percentages (for example "95% cotton, 5% elastane"). It must be available before purchase, online too.', 'Regulation (EU) No 1007/2011 Art. 16');
41
+ }
42
+ if (regimes.includes('battery_passport')) {
43
+ if (battery_wh == null) add('warning', 'battery-capacity', 'Battery capacity (Wh, or Ah and V) is not in the listing.', 'Batteries Regulation Annex VI and XIII');
44
+ if (!CHEMISTRY.test(text)) add('warning', 'battery-chemistry', 'Battery chemistry (for example lithium-ion, LiFePO4) is not in the listing.', 'Batteries Regulation Annex VI and XIII');
45
+ if (!p.passport_url) add('info', 'battery-passport-link', 'No battery passport link recorded. From 18 Feb 2027 these batteries need a passport reachable by QR code.', 'Batteries Regulation Art. 77');
46
+ }
47
+
48
+ // ESPR Annex III items a catalog can already hold
49
+ const bad = gtins.filter((g) => !validGtin(g));
50
+ const mangled = gtins.filter(looksMangled);
51
+ if (mangled.length) add('error', 'gtin-mangled', 'Barcodes saved as spreadsheet numbers (like 4.00638E+12): the digits are lost. Re-export with the barcode column formatted as text.', 'ESPR Annex III (c)', mangled.join(' '));
52
+ else if (bad.length) add('warning', 'gtin-invalid', 'Barcodes that fail the GTIN check digit: a typo, or not a GTIN.', 'ESPR Annex III (c)', bad.join(' '));
53
+ const hs = String(p.hs_code || '').replace(/\D/g, '');
54
+ const annex = {
55
+ gtin: gtins.length > 0 && bad.length === 0,
56
+ commodity_code: hs.length >= 6,
57
+ manufacturer: Boolean(m.name && m.address && mEmail),
58
+ eu_operator: nonEu === false || Boolean(rp?.name && rp?.address),
59
+ importer_eori: nonEu === false || Boolean(op.importer?.eori),
60
+ compliance_docs: Boolean(p.doc_url || op.doc_url_template),
61
+ instructions: Boolean(p.manual_url || WARNING.test(text) || op.manual_url_template),
62
+ };
63
+ if (!annex.commodity_code) add('info', 'commodity-code', 'No commodity (HS/TARIC) code. Passports list it, and customs will check passports through the registry.', 'ESPR Annex III (d)');
64
+ if (nonEu && !op.importer?.eori) add('info', 'importer-eori', 'Imported product: the passport will list the importer and its EORI number.', 'ESPR Annex III (j)');
65
+ const have = Object.values(annex).filter(Boolean).length;
66
+ return {
67
+ id: p.id, title: p.title, vendor: p.vendor, regimes, notes, battery_wh, issues,
68
+ readiness: Math.round((100 * have) / Object.keys(annex).length), annex_iii: annex,
69
+ digital_links: [...new Set(gtins.map((g) => digitalLink(g, resolver)).filter(Boolean))],
70
+ };
71
+ }
72
+
73
+ export function draftPassport(p, r, op = {}) {
74
+ const m = manufacturerFor(p, op);
75
+ return {
76
+ _note: 'Draft built from catalog data. Not a compliant digital product passport: the applicable delegated act or regulation sets the required data, granularity and format.',
77
+ product_name: p.title, regimes: r.regimes.map((k) => REGIMES[k].label),
78
+ unique_product_identifier: null, gtin: p.variants.map((v) => v.gtin).filter(validGtin), data_carrier_uri: r.digital_links[0] || null,
79
+ commodity_code: p.hs_code || null, country_of_origin: p.country_of_origin || null,
80
+ manufacturer: { name: m.name || null, postal_address: m.address || null, email: m.email || null, country: m.country || null, unique_operator_identifier: null },
81
+ eu_responsible_operator: op.eu_responsible_person || null,
82
+ importer: op.importer || null,
83
+ compliance_documentation: p.doc_url || (op.doc_url_template ? op.doc_url_template.replace('{id}', p.id) : null),
84
+ instructions_and_safety: p.manual_url || null,
85
+ materials: p.materials || null,
86
+ battery: r.regimes.includes('battery_passport') ? { energy_wh: r.battery_wh, passport_url: p.passport_url || null } : undefined,
87
+ backup_service_provider: null,
88
+ };
89
+ }
package/src/gtin.js ADDED
@@ -0,0 +1,27 @@
1
+ // GTIN check digits (GS1 General Specifications, mod-10 with weights 3 and 1 from the right) and
2
+ // GS1 Digital Link URIs (https://id.gs1.org/01/<GTIN-14>), one ISO/IEC 15459-based identifier scheme.
3
+ export function normalizeGtin(raw) {
4
+ const s = String(raw ?? '').replace(/[\s-]/g, '').replace(/^'/, '');
5
+ if (!/^\d+$/.test(s) || ![8, 12, 13, 14].includes(s.length)) return null;
6
+ return s.padStart(14, '0');
7
+ }
8
+
9
+ export function checkDigit(body) {
10
+ let sum = 0;
11
+ for (let i = body.length - 1, w = 3; i >= 0; i--, w = w === 3 ? 1 : 3) sum += Number(body[i]) * w;
12
+ return (10 - (sum % 10)) % 10;
13
+ }
14
+
15
+ export function validGtin(raw) {
16
+ const g = normalizeGtin(raw);
17
+ if (!g || /^0+$/.test(g)) return false;
18
+ return checkDigit(g.slice(0, 13)) === Number(g[13]);
19
+ }
20
+
21
+ // Shopify exports barcodes from spreadsheets that turned them into numbers like 4.00638E+12.
22
+ export function looksMangled(raw) { return /^\d(\.\d+)?E\+\d+$/i.test(String(raw ?? '').trim()); }
23
+
24
+ export function digitalLink(raw, resolver = 'https://id.gs1.org') {
25
+ if (!validGtin(raw)) return null;
26
+ return `${resolver.replace(/\/$/, '')}/01/${normalizeGtin(raw)}`;
27
+ }
package/src/index.js ADDED
@@ -0,0 +1,6 @@
1
+ export { analyze } from './analyze.js';
2
+ export { checkProduct, draftPassport, EU } from './checks.js';
3
+ export { classify, REGIMES, batteryEnergyWh } from './regimes.js';
4
+ export { validGtin, normalizeGtin, digitalLink, checkDigit, looksMangled } from './gtin.js';
5
+ export { loadProducts, fromRows, detectFormat } from './load.js';
6
+ export { formatText, formatMarkdown, formatCsv } from './report.js';
package/src/load.js ADDED
@@ -0,0 +1,90 @@
1
+ // Products from a Shopify product CSV export, a WooCommerce product CSV export, or a generic CSV/JSON
2
+ // (one row per product or per variant). Variants are grouped into products.
3
+ import { parseCsv, readTable } from 'returns-reducer';
4
+
5
+ const pick = (r, ...names) => {
6
+ for (const n of names) for (const k of Object.keys(r)) if (k.toLowerCase() === n.toLowerCase() && String(r[k]).trim() !== '') return String(r[k]).trim();
7
+ return '';
8
+ };
9
+ const metafield = (r, rx) => {
10
+ for (const [k, v] of Object.entries(r)) if (rx.test(k) && String(v).trim()) return String(v).trim();
11
+ return '';
12
+ };
13
+
14
+ export function detectFormat(rows) {
15
+ const keys = Object.keys(rows[0] || {}).map((k) => k.toLowerCase());
16
+ if (keys.includes('handle') && keys.includes('variant barcode') || keys.includes('body (html)')) return 'shopify';
17
+ if (keys.includes('type') && keys.includes('name') && (keys.includes('short description') || keys.includes('regular price'))) return 'woocommerce';
18
+ return 'generic';
19
+ }
20
+
21
+ export function fromRows(rows, format = detectFormat(rows)) {
22
+ const byKey = new Map();
23
+ const skuToId = new Map();
24
+ for (const r of rows) {
25
+ let key; let base;
26
+ if (format === 'shopify') {
27
+ key = pick(r, 'Handle');
28
+ if (!key) continue;
29
+ base = {
30
+ id: key, title: pick(r, 'Title'), description: pick(r, 'Body (HTML)'), vendor: pick(r, 'Vendor'), type: pick(r, 'Type'),
31
+ category: pick(r, 'Product Category', 'Product category', 'Standard Product Type', 'Google Shopping / Google Product Category'),
32
+ tags: pick(r, 'Tags').split(',').map((t) => t.trim()).filter(Boolean), status: pick(r, 'Status').toLowerCase(),
33
+ hs_code: pick(r, 'HS Code', 'Harmonized System Code') || metafield(r, /hs[_ ]?code|tariff|taric/i),
34
+ country_of_origin: pick(r, 'Country of Origin', 'Country/Region of Origin') || metafield(r, /country.?of.?origin|made.?in/i),
35
+ materials: metafield(r, /material|fabric|composition|fibre|fiber/i), url: '',
36
+ };
37
+ } else if (format === 'woocommerce') {
38
+ const type = pick(r, 'Type').toLowerCase();
39
+ // Parent is "id:123", or the parent's SKU when it has one (WooCommerce product CSV exporter)
40
+ if (type.includes('variation')) {
41
+ const parent = pick(r, 'Parent');
42
+ key = parent.startsWith('id:') ? parent.slice(3) : (skuToId.get(parent) || parent || pick(r, 'ID'));
43
+ } else {
44
+ key = pick(r, 'ID') || pick(r, 'SKU');
45
+ if (pick(r, 'SKU')) skuToId.set(pick(r, 'SKU'), key);
46
+ }
47
+ if (!key) continue;
48
+ base = type.includes('variation') ? {} : {
49
+ id: key, title: pick(r, 'Name'), description: `${pick(r, 'Short description')}\n${pick(r, 'Description')}`.trim(),
50
+ vendor: pick(r, 'Brands', 'Brand'), type: pick(r, 'Categories').split(',').pop()?.trim() || '',
51
+ category: pick(r, 'Categories'), tags: pick(r, 'Tags').split(',').map((t) => t.trim()).filter(Boolean), status: pick(r, 'Published') === '1' ? 'active' : 'draft',
52
+ hs_code: metafield(r, /hs[_ ]?code|tariff|taric/i), country_of_origin: metafield(r, /country.?of.?origin|made.?in/i), materials: metafield(r, /material|fabric|composition/i), url: '',
53
+ };
54
+ if (!byKey.has(key) && type.includes('variation')) { // variation listed before parent: keep a stub
55
+ byKey.set(key, { id: key, title: pick(r, 'Name'), tags: [], variants: [] });
56
+ }
57
+ } else {
58
+ key = pick(r, 'id', 'product_id', 'handle', 'sku', 'title');
59
+ if (!key) continue;
60
+ base = {
61
+ id: key, title: pick(r, 'title', 'name'), description: pick(r, 'description', 'body'), vendor: pick(r, 'brand', 'vendor'),
62
+ manufacturer: pick(r, 'manufacturer'), type: pick(r, 'type', 'product_type'), category: pick(r, 'category', 'google_product_category'),
63
+ tags: pick(r, 'tags').split(',').map((t) => t.trim()).filter(Boolean), hs_code: pick(r, 'hs_code', 'taric', 'commodity_code'),
64
+ country_of_origin: pick(r, 'country_of_origin', 'origin'), materials: pick(r, 'materials', 'material', 'composition', 'fibre_composition'),
65
+ url: pick(r, 'url', 'link'), doc_url: pick(r, 'declaration_of_conformity', 'doc_url'), manual_url: pick(r, 'manual', 'manual_url', 'instructions_url'),
66
+ passport_url: pick(r, 'passport', 'dpp_url', 'battery_passport'),
67
+ };
68
+ }
69
+ const variant = {
70
+ sku: pick(r, 'Variant SKU', 'SKU', 'sku'),
71
+ gtin: pick(r, 'Variant Barcode', 'GTIN, UPC, EAN, or ISBN', 'GTIN, UPC, EAN or ISBN', 'gtin', 'barcode', 'ean', 'upc'),
72
+ weight_g: Number(pick(r, 'Variant Grams')) || (Number(pick(r, 'Weight (kg)', 'weight_kg')) * 1000) || null,
73
+ option: [pick(r, 'Option1 Value'), pick(r, 'Option2 Value'), pick(r, 'Attribute 1 value(s)')].filter(Boolean).join(' / '),
74
+ };
75
+ const p = byKey.get(key) || { variants: [], ...base };
76
+ if (!byKey.has(key)) byKey.set(key, p);
77
+ else for (const [k, v] of Object.entries(base)) if (v && (!p[k] || (Array.isArray(p[k]) && !p[k].length))) p[k] = v;
78
+ const isVariableParent = format === 'woocommerce' && pick(r, 'Type').toLowerCase().split(',').map((x) => x.trim()).includes('variable');
79
+ if (!isVariableParent && (variant.sku || variant.gtin || variant.option)) p.variants.push(variant);
80
+ }
81
+ return [...byKey.values()].map((p) => ({ ...p, options: p.variants.map((v) => v.option).filter(Boolean) }));
82
+ }
83
+
84
+ export async function loadProducts(file, { format } = {}) {
85
+ const data = await readTable(file);
86
+ const rows = Array.isArray(data) ? data : data.products || [];
87
+ return fromRows(rows, format || detectFormat(rows));
88
+ }
89
+
90
+ export { parseCsv };
package/src/regimes.js ADDED
@@ -0,0 +1,92 @@
1
+ // Which EU product-passport rules reach which products, with dates from the legal texts or, where no act
2
+ // exists yet, the Commission's indicative plan. Checked 4 Dec 2026; re-check before relying on a date.
3
+ export const REGIMES = {
4
+ battery_passport: {
5
+ label: 'Battery passport (Batteries Regulation)', status: 'law', applies_from: '2027-02-18',
6
+ source: 'Regulation (EU) 2023/1542, Art. 77 and Annex XIII',
7
+ scope: 'LMT batteries (e-bikes, e-scooters and other light electric vehicles), industrial batteries above 2 kWh (home storage, large power stations) and electric-vehicle batteries placed on the EU market or put into service.',
8
+ action: 'Ask the battery manufacturer or your supplier for the battery passport identifier and QR code. If you import these batteries or the products containing them into the EU, you are the economic operator responsible for it.',
9
+ },
10
+ toy_dpp: {
11
+ label: 'Toy digital product passport (Toy Safety Regulation)', status: 'law', applies_from: '2030-08-01',
12
+ source: 'Regulation (EU) 2025/2509, Art. 19 and Annex VI', scope: 'All toys; the passport replaces the EU declaration of conformity.',
13
+ action: 'Ask manufacturers how they will issue the passport and data carrier; importers and distributors must check it exists before selling.',
14
+ },
15
+ detergent_dpp: {
16
+ label: 'Detergent digital product passport (Detergents Regulation)', status: 'law', applies_from: '2029-09-23',
17
+ source: 'Regulation (EU) 2026/405, Art. 21', scope: 'Detergents, and surfactants sold to end users.',
18
+ action: 'Ask manufacturers for passport plans; refill sales need the label and data carrier too.',
19
+ },
20
+ textiles_espr: {
21
+ label: 'Textiles and apparel (ESPR delegated act)', status: 'planned', indicative: 'Delegated act indicatively 2027; as a rule its requirements apply no earlier than 18 months after it enters into force (ESPR Art. 4(4))',
22
+ source: 'ESPR (EU) 2024/1781; Working Plan 2025-2030, COM(2025) 187', scope: 'Apparel and other textile products in the delegated act once adopted.',
23
+ action: 'Collect fibre composition, origin and supplier data per product now; the act will set the exact passport fields.',
24
+ },
25
+ footwear: {
26
+ label: 'Footwear (not yet planned)', status: 'study', indicative: 'Commission study due by end 2027; not in the 2025-2030 priority list',
27
+ source: 'Working Plan 2025-2030, COM(2025) 187', scope: 'Footwear.', action: 'No passport date yet. Keep identifiers and supplier data tidy.',
28
+ },
29
+ tyres_espr: { label: 'Tyres (ESPR delegated act)', status: 'planned', indicative: 'Delegated act indicatively 2027', source: 'Working Plan 2025-2030, COM(2025) 187', scope: 'Tyres.', action: 'Tyres already need the EU tyre label and EPREL registration; keep the EPREL link with each listing.' },
30
+ furniture_espr: { label: 'Furniture (ESPR delegated act)', status: 'planned', indicative: 'Delegated act indicatively 2028', source: 'Working Plan 2025-2030, COM(2025) 187', scope: 'Furniture.', action: 'Collect material, origin and supplier data per product.' },
31
+ mattresses_espr: { label: 'Mattresses (ESPR delegated act)', status: 'planned', indicative: 'Delegated act indicatively 2029', source: 'Working Plan 2025-2030, COM(2025) 187', scope: 'Mattresses.', action: 'Collect material, origin and supplier data per product.' },
32
+ energy_label: {
33
+ label: 'Energy-labelled product (EPREL instead of a passport)', status: 'law', applies_from: 'already applies',
34
+ source: 'Regulation (EU) 2017/1369; Working Plan 2025-2030 (EPREL as the alternative digital system)',
35
+ scope: 'Appliances, displays, light sources, tyres and other products with an EU energy label.',
36
+ action: 'Show the energy label and product information sheet in the listing; product data lives in EPREL rather than a separate passport.',
37
+ },
38
+ };
39
+
40
+ // Signals per regime. Matched against title, type, category and tags (not the long description, which
41
+ // mentions too much). Capacity and weight decide the battery cases.
42
+ const RX = {
43
+ lmt: /\b(e-?bikes?|electric (bike|bicycle|scooter|moped|skateboard|unicycle)s?|pedelecs?|e-?scooters?|e-?mopeds?|hoverboards?|e-?skateboards?|electric kick ?scooters?|ebike batter(y|ies)|e-?bike batter(y|ies))\b/i,
44
+ storage: /\b(home (battery|storage)|solar (battery|storage|generator)|power ?station|energy storage|battery storage|lifepo4|powerwall|server rack battery|ess battery|storage battery)\b/i,
45
+ ev: /\b(ev batter(y|ies)|electric vehicle batter(y|ies)|traction batter(y|ies))\b/i,
46
+ toy: /\b(toys?|plush(ie|ies)?|stuffed animals?|dolls?|action figures?|building blocks?|lego|board games?|jigsaw|puzzles? for kids|teddy|kids'? (game|play)|rattles?|play ?sets?|toys & games)\b/i,
47
+ detergent: /\b(detergents?|laundry (liquid|powder|pods?|capsules?)|washing[- ]up liquid|dish ?(soap|washing liquid|washer tablets?)|dishwasher (tablets?|detergent|pods?)|fabric softeners?|surface cleaners?|all[- ]purpose cleaners?|multi[- ]surface cleaners?|toilet cleaners?|floor cleaners?|bleach|stain removers?)\b/i,
48
+ textiles: /\b(apparel|clothing|clothes|t-?shirts?|tees?|shirts?|sweatshirts?|polos?|blouses?|dress(es)?|skirts?|jeans|trousers|pants|shorts|jackets?|coats?|hoodies?|sweaters?|jumpers?|cardigans?|knitwear|leggings|socks|underwear|lingerie|bras?|scarf|scarves|shawls?|hijabs?|abayas?|kurtas?|shalwar|kameez|towels?|bed ?sheets?|bedding|duvet covers?|pillow ?cases?|curtains?|textiles?|fabrics?)\b/i,
49
+ footwear: /\b(shoes?|sneakers?|trainers|boots?|sandals?|slippers?|loafers?|heels|footwear|khussa)\b/i,
50
+ tyres: /\b(tyres?|tires?)\b/i,
51
+ mattress: /\b(mattress(es)?|mattress toppers?)\b/i,
52
+ furniture: /\b(furniture|sofas?|couch(es)?|chairs?|tables?|desks?|wardrobes?|cabinets?|bookcases?|shelv(es|ing)|bed frames?|beds|dressers?|sideboards?|stools?|benches)\b/i,
53
+ energy: /\b(washing machines?|washer[- ]dryers?|dishwashers?|fridges?|refrigerators?|freezers?|televisions?|tvs?|monitors?|displays?|light bulbs?|led bulbs?|lamps?|tumble dryers?|ovens?|range hoods?|air conditioners?|heaters?|smartphones?|mobile phones?|tablets?)\b/i,
54
+ };
55
+
56
+ export function batteryEnergyWh(text) {
57
+ const s = String(text || '');
58
+ let best = null;
59
+ for (const m of s.matchAll(/(\d+(?:[.,]\d+)?)\s*(kwh|wh)\b/gi)) {
60
+ const v = parseFloat(m[1].replace(',', '.')) * (m[2].toLowerCase() === 'kwh' ? 1000 : 1);
61
+ if (!best || v > best) best = v;
62
+ }
63
+ if (best == null) {
64
+ const ah = s.match(/(\d+(?:[.,]\d+)?)\s*ah\b/i);
65
+ const v = s.match(/(\d+(?:[.,]\d+)?)\s*v\b/i);
66
+ if (ah && v) best = parseFloat(ah[1].replace(',', '.')) * parseFloat(v[1].replace(',', '.'));
67
+ }
68
+ return best;
69
+ }
70
+
71
+ export function classify(p) {
72
+ const head = [p.title, p.type, p.category, (p.tags || []).join(' ')].filter(Boolean).join(' | ');
73
+ const out = [];
74
+ const notes = [];
75
+ const wh = batteryEnergyWh(`${p.title} ${p.description || ''} ${(p.options || []).join(' ')}`);
76
+ if (RX.lmt.test(head)) { out.push('battery_passport'); notes.push('Light electric vehicle or its battery: LMT battery passport.'); }
77
+ else if (RX.ev.test(head)) out.push('battery_passport');
78
+ else if (RX.storage.test(head)) {
79
+ if (wh != null && wh > 2000) { out.push('battery_passport'); notes.push(`Stated capacity about ${Math.round(wh)} Wh, above 2 kWh.`); }
80
+ else if (wh == null) { out.push('battery_passport'); notes.push('Energy storage product without a stated capacity: it needs a battery passport if it is an industrial battery above 2 kWh. Add the capacity to the listing.'); }
81
+ else notes.push(`Stated capacity about ${Math.round(wh)} Wh, at or below 2 kWh: no battery passport, but other battery rules apply.`);
82
+ }
83
+ if (RX.toy.test(head)) out.push('toy_dpp');
84
+ if (RX.detergent.test(head)) out.push('detergent_dpp');
85
+ if (RX.mattress.test(head)) out.push('mattresses_espr');
86
+ else if (RX.furniture.test(head) && !RX.toy.test(head)) out.push('furniture_espr');
87
+ if (RX.footwear.test(head)) out.push('footwear');
88
+ else if (RX.textiles.test(head) && !RX.toy.test(head)) out.push('textiles_espr');
89
+ if (RX.tyres.test(head)) out.push('tyres_espr', 'energy_label');
90
+ else if (RX.energy.test(head) && !out.includes('furniture_espr')) out.push('energy_label');
91
+ return { regimes: [...new Set(out)], notes, battery_wh: wh };
92
+ }
package/src/report.js ADDED
@@ -0,0 +1,32 @@
1
+ const pct = (n, d) => (d ? `${Math.round((100 * n) / d)}%` : '0%');
2
+
3
+ export function formatText(a) {
4
+ const L = [];
5
+ L.push(`${a.products} products checked${a.skipped ? ` (${a.skipped} drafts or archived skipped)` : ''}. Average passport-data readiness: ${a.readiness_avg}%.`);
6
+ L.push('', 'Rules that reach your catalog (law first, then planned):');
7
+ if (!a.regimes.length) L.push(' None of the product groups with passport rules was recognised. Check categories and product types.');
8
+ for (const r of a.regimes) L.push(` ${String(r.products).padStart(5)} ${r.label}: ${r.status === 'law' ? (/^\d/.test(r.applies_from) ? `applies from ${r.applies_from}` : r.applies_from) : r.indicative} [${r.source}]`);
9
+ L.push('', 'What to fix (errors are legal requirements that already apply):');
10
+ for (const i of a.issues) L.push(` [${i.level}] ${i.count} product(s): ${i.example} (${i.law})${i.products.length ? `\n e.g. ${i.products.slice(0, 3).join('; ')}` : ''}`);
11
+ if (!a.issues.length) L.push(' Nothing found.');
12
+ return L.join('\n');
13
+ }
14
+
15
+ export function formatMarkdown(a) {
16
+ const L = ['# Digital product passport readiness', '', `${a.products} products checked on ${a.checked_on}. Average passport-data readiness: **${a.readiness_avg}%** (share of ESPR Annex III items the catalog already holds).`, '', '## Rules that reach your catalog', '', '| Products | Rule | When | Source |', '|---:|---|---|---|'];
17
+ for (const r of a.regimes) L.push(`| ${r.products} | ${r.label} | ${r.status === 'law' ? r.applies_from : r.indicative} | ${r.source} |`);
18
+ L.push('', '## What to do', '');
19
+ for (const r of a.regimes) L.push(`- **${r.label}:** ${r.action}`);
20
+ L.push('', '## Gaps', '', '| Level | Products | Issue | Law |', '|---|---:|---|---|');
21
+ for (const i of a.issues) L.push(`| ${i.level} | ${i.count} (${pct(i.count, a.products)}) | ${i.example.replace(/\|/g, '/')} | ${i.law} |`);
22
+ L.push('', 'Dates for planned rules are indicative (Commission working plan). Laws and dates checked 4 Dec 2026; this is not legal advice.');
23
+ return L.join('\n');
24
+ }
25
+
26
+ export function formatCsv(a) {
27
+ const esc = (v) => /[",\n]/.test(String(v ?? '')) ? `"${String(v).replace(/"/g, '""')}"` : String(v ?? '');
28
+ const head = ['id', 'title', 'vendor', 'regimes', 'readiness_pct', 'errors', 'warnings', 'issues', 'digital_link'];
29
+ const rows = a.results.map((r) => [r.id, r.title, r.vendor, r.regimes.join(' '), r.readiness, r.issues.filter((i) => i.level === 'error').length,
30
+ r.issues.filter((i) => i.level === 'warning').length, r.issues.map((i) => i.detail ? `${i.code} (${i.detail})` : i.code).join('; '), r.digital_links[0] || '']);
31
+ return [head, ...rows].map((r) => r.map(esc).join(',')).join('\n') + '\n';
32
+ }