@vicacha-devs/medusa-plugin-barcode 0.0.0-stage → 0.0.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/.medusa/server/src/admin/index.cjs +3960 -0
- package/.medusa/server/src/admin/index.js +3938 -0
- package/.medusa/server/src/api/admin/barcodes/[barcode]/route.js +43 -0
- package/.medusa/server/src/api/admin/barcodes/batch/route.js +9 -0
- package/.medusa/server/src/api/admin/barcodes/bulk-generate/route.js +9 -0
- package/.medusa/server/src/api/admin/barcodes/cache/route.js +25 -0
- package/.medusa/server/src/api/admin/barcodes/count-sessions/[id]/apply/route.js +13 -0
- package/.medusa/server/src/api/admin/barcodes/count-sessions/[id]/scan/route.js +13 -0
- package/.medusa/server/src/api/admin/barcodes/count-sessions/route.js +27 -0
- package/.medusa/server/src/api/admin/barcodes/create-from-barcode/route.js +9 -0
- package/.medusa/server/src/api/admin/barcodes/lookup/route.js +12 -0
- package/.medusa/server/src/api/admin/barcodes/print/route.js +11 -0
- package/.medusa/server/src/api/admin/barcodes/route.js +27 -0
- package/.medusa/server/src/api/admin/barcodes/scan/route.js +23 -0
- package/.medusa/server/src/api/admin/barcodes/tags/[id]/route.js +28 -0
- package/.medusa/server/src/api/admin/barcodes/tags/route.js +25 -0
- package/.medusa/server/src/api/admin/barcodes/templates/route.js +40 -0
- package/.medusa/server/src/api/admin/plugin/route.js +4 -0
- package/.medusa/server/src/api/admin/variants/barcode/[code]/route.js +28 -0
- package/.medusa/server/src/api/middlewares.js +73 -0
- package/.medusa/server/src/api/store/barcodes/[code]/route.js +28 -0
- package/.medusa/server/src/api/store/barcodes/[code]/verify/route.js +20 -0
- package/.medusa/server/src/api/store/plugin/route.js +4 -0
- package/.medusa/server/src/api/store/variants/barcode/[code]/route.js +28 -0
- package/.medusa/server/src/api/validators.js +173 -0
- package/.medusa/server/src/hooks/index.js +202 -0
- package/.medusa/server/src/index.js +5 -0
- package/.medusa/server/src/jobs/purge-expired-barcode-cache.js +10 -0
- package/.medusa/server/src/modules/barcode/index.js +16 -0
- package/.medusa/server/src/modules/barcode/migrations/Migration20260522000000.js +165 -0
- package/.medusa/server/src/modules/barcode/models/index.js +162 -0
- package/.medusa/server/src/modules/barcode/operations/context.js +2 -0
- package/.medusa/server/src/modules/barcode/operations/data-service.js +10 -0
- package/.medusa/server/src/modules/barcode/operations/generation.js +33 -0
- package/.medusa/server/src/modules/barcode/operations/index.js +9 -0
- package/.medusa/server/src/modules/barcode/operations/labels.js +57 -0
- package/.medusa/server/src/modules/barcode/operations/lookup.js +135 -0
- package/.medusa/server/src/modules/barcode/operations/maintenance.js +37 -0
- package/.medusa/server/src/modules/barcode/operations/stock-count.js +129 -0
- package/.medusa/server/src/modules/barcode/operations/tags.js +298 -0
- package/.medusa/server/src/modules/barcode/providers/index.js +721 -0
- package/.medusa/server/src/modules/barcode/service.js +161 -0
- package/.medusa/server/src/modules/barcode/types.js +21 -0
- package/.medusa/server/src/modules/barcode/utils/barcode-parser.js +399 -0
- package/.medusa/server/src/modules/barcode/utils/label-printer.js +533 -0
- package/.medusa/server/src/modules/barcode/utils/normalize-product.js +443 -0
- package/.medusa/server/src/modules/barcode/utils/security.js +114 -0
- package/.medusa/server/src/modules/barcode/utils/svg-renderer.js +492 -0
- package/.medusa/server/src/rbac.js +130 -0
- package/.medusa/server/src/sdk/index.js +164 -0
- package/.medusa/server/src/subscribers/product-created.js +34 -0
- package/.medusa/server/src/types/index.js +2 -0
- package/.medusa/server/src/ui/index.js +138 -0
- package/.medusa/server/src/workflows/apply-inventory-count.js +68 -0
- package/.medusa/server/src/workflows/batch-barcode-import.js +153 -0
- package/.medusa/server/src/workflows/bulk-generate-variant-barcodes.js +143 -0
- package/.medusa/server/src/workflows/generate-barcode-tag.js +44 -0
- package/.medusa/server/src/workflows/helpers.js +15 -0
- package/.medusa/server/src/workflows/index.js +7 -0
- package/.medusa/server/src/workflows/lookup-and-create-product.js +215 -0
- package/.medusa/server/src/workflows/scan-inventory-count.js +15 -0
- package/LICENSE +21 -0
- package/README.md +844 -2
- package/package.json +129 -3
- package/src/__tests__/barcode.spec.ts +836 -0
- package/src/__tests__/medusa-shim.mjs +331 -0
- package/src/__tests__/register-ts-resolver.mjs +135 -0
- package/src/admin/README.md +134 -0
- package/src/admin/components/barcode-studio-header.tsx +73 -0
- package/src/admin/components/batch-import-section.tsx +99 -0
- package/src/admin/components/dynamic-qr-tag-drawer-form.tsx +230 -0
- package/src/admin/components/dynamic-qr-tag-form.tsx +129 -0
- package/src/admin/components/dynamic-qr-tags-table.tsx +136 -0
- package/src/admin/components/gtin-lookup-section.tsx +155 -0
- package/src/admin/components/index.tsx +14 -0
- package/src/admin/components/label-designer-section.tsx +151 -0
- package/src/admin/components/label-output-section.tsx +63 -0
- package/src/admin/components/overview-cards.tsx +98 -0
- package/src/admin/components/product-barcode-card.tsx +127 -0
- package/src/admin/components/providers-cache-table.tsx +61 -0
- package/src/admin/components/providers-overview-section.tsx +49 -0
- package/src/admin/components/rbac-guard.tsx +153 -0
- package/src/admin/components/stock-take-scanner-section.tsx +116 -0
- package/src/admin/components/stock-take-sessions-section.tsx +109 -0
- package/src/admin/hooks/use-barcode-studio.ts +466 -0
- package/src/admin/hooks/use-product-barcodes.ts +139 -0
- package/src/admin/i18n/README.md +130 -0
- package/src/admin/i18n/index.ts +36 -0
- package/src/admin/i18n/json/ar.json +157 -0
- package/src/admin/i18n/json/de.json +157 -0
- package/src/admin/i18n/json/en.json +157 -0
- package/src/admin/i18n/json/es.json +157 -0
- package/src/admin/i18n/json/fr.json +157 -0
- package/src/admin/i18n/json/it.json +157 -0
- package/src/admin/i18n/json/nl.json +157 -0
- package/src/admin/i18n/json/pl.json +157 -0
- package/src/admin/i18n/json/pt.json +157 -0
- package/src/admin/i18n/json/tr.json +157 -0
- package/src/admin/routes/barcodes/lookup/page.tsx +75 -0
- package/src/admin/routes/barcodes/page.tsx +212 -0
- package/src/admin/routes/barcodes/print/page.tsx +67 -0
- package/src/admin/routes/barcodes/providers/page.tsx +66 -0
- package/src/admin/routes/barcodes/stock-take/page.tsx +74 -0
- package/src/admin/routes/barcodes/tags/@create/page.tsx +56 -0
- package/src/admin/routes/barcodes/tags/page.tsx +72 -0
- package/src/admin/tsconfig.json +20 -0
- package/src/admin/vite-env.d.ts +1 -0
- package/src/admin/widgets/product-barcode-widget.tsx +43 -0
- package/src/api/README.md +117 -0
- package/src/api/admin/barcodes/[barcode]/route.ts +64 -0
- package/src/api/admin/barcodes/batch/route.ts +12 -0
- package/src/api/admin/barcodes/bulk-generate/route.ts +12 -0
- package/src/api/admin/barcodes/cache/route.ts +35 -0
- package/src/api/admin/barcodes/count-sessions/[id]/apply/route.ts +17 -0
- package/src/api/admin/barcodes/count-sessions/[id]/scan/route.ts +17 -0
- package/src/api/admin/barcodes/count-sessions/route.ts +43 -0
- package/src/api/admin/barcodes/create-from-barcode/route.ts +16 -0
- package/src/api/admin/barcodes/lookup/route.ts +19 -0
- package/src/api/admin/barcodes/print/route.ts +18 -0
- package/src/api/admin/barcodes/route.ts +36 -0
- package/src/api/admin/barcodes/scan/route.ts +32 -0
- package/src/api/admin/barcodes/tags/[id]/route.ts +41 -0
- package/src/api/admin/barcodes/tags/route.ts +36 -0
- package/src/api/admin/barcodes/templates/route.ts +51 -0
- package/src/api/admin/plugin/route.ts +5 -0
- package/src/api/admin/variants/barcode/[code]/route.ts +36 -0
- package/src/api/middlewares.ts +91 -0
- package/src/api/store/barcodes/[code]/route.ts +43 -0
- package/src/api/store/barcodes/[code]/verify/route.ts +35 -0
- package/src/api/store/plugin/route.ts +5 -0
- package/src/api/store/variants/barcode/[code]/route.ts +36 -0
- package/src/api/validators.ts +217 -0
- package/src/hooks/index.ts +270 -0
- package/src/index.ts +4 -0
- package/src/jobs/README.md +54 -0
- package/src/jobs/purge-expired-barcode-cache.ts +18 -0
- package/src/links/README.md +44 -0
- package/src/modules/README.md +85 -0
- package/src/modules/barcode/index.ts +18 -0
- package/src/modules/barcode/migrations/Migration20260522000000.ts +225 -0
- package/src/modules/barcode/models/index.ts +168 -0
- package/src/modules/barcode/operations/context.ts +14 -0
- package/src/modules/barcode/operations/data-service.ts +10 -0
- package/src/modules/barcode/operations/generation.ts +57 -0
- package/src/modules/barcode/operations/index.ts +8 -0
- package/src/modules/barcode/operations/labels.ts +90 -0
- package/src/modules/barcode/operations/lookup.ts +202 -0
- package/src/modules/barcode/operations/maintenance.ts +53 -0
- package/src/modules/barcode/operations/stock-count.ts +217 -0
- package/src/modules/barcode/operations/tags.ts +425 -0
- package/src/modules/barcode/providers/index.ts +958 -0
- package/src/modules/barcode/service.ts +243 -0
- package/src/modules/barcode/types.ts +297 -0
- package/src/modules/barcode/utils/barcode-parser.ts +453 -0
- package/src/modules/barcode/utils/label-printer.ts +641 -0
- package/src/modules/barcode/utils/normalize-product.ts +524 -0
- package/src/modules/barcode/utils/security.ts +136 -0
- package/src/modules/barcode/utils/svg-renderer.ts +574 -0
- package/src/providers/README.md +105 -0
- package/src/rbac.ts +144 -0
- package/src/sdk/index.ts +253 -0
- package/src/subscribers/README.md +73 -0
- package/src/subscribers/product-created.ts +45 -0
- package/src/types/index.ts +1 -0
- package/src/types/medusa-ui.d.ts +118 -0
- package/src/ui/index.tsx +311 -0
- package/src/workflows/README.md +56 -0
- package/src/workflows/apply-inventory-count.ts +115 -0
- package/src/workflows/batch-barcode-import.ts +218 -0
- package/src/workflows/bulk-generate-variant-barcodes.ts +214 -0
- package/src/workflows/generate-barcode-tag.ts +85 -0
- package/src/workflows/helpers.ts +21 -0
- package/src/workflows/index.ts +6 -0
- package/src/workflows/lookup-and-create-product.ts +298 -0
- package/src/workflows/scan-inventory-count.ts +45 -0
- package/tsconfig.json +40 -0
|
@@ -0,0 +1,958 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
BarcodeLookupChainResult,
|
|
3
|
+
BarcodeModuleOptions,
|
|
4
|
+
BarcodeSymbology,
|
|
5
|
+
EnrichmentStrategy,
|
|
6
|
+
NormalizedBarcodeProduct,
|
|
7
|
+
ProviderConfig,
|
|
8
|
+
ProviderLookupOutcome,
|
|
9
|
+
} from "../types"
|
|
10
|
+
import { parseBarcode } from "../utils/barcode-parser"
|
|
11
|
+
import {
|
|
12
|
+
mergeNormalizedProducts,
|
|
13
|
+
normalizeStringArray,
|
|
14
|
+
parseDimensionMm,
|
|
15
|
+
parseWeightGrams,
|
|
16
|
+
} from "../utils/normalize-product"
|
|
17
|
+
import { validateExternalImageUrl } from "../utils/security"
|
|
18
|
+
|
|
19
|
+
const DEFAULT_USER_AGENT = "MedusaPluginBarcode/1.0 (+https://medusajs.com)"
|
|
20
|
+
|
|
21
|
+
export abstract class BaseBarcodeProvider {
|
|
22
|
+
abstract readonly name: string
|
|
23
|
+
readonly priority: number
|
|
24
|
+
readonly timeout: number
|
|
25
|
+
readonly retries: number
|
|
26
|
+
protected readonly apiKey?: string
|
|
27
|
+
protected readonly baseUrl?: string
|
|
28
|
+
|
|
29
|
+
constructor(config: ProviderConfig = {}) {
|
|
30
|
+
this.priority = config.priority ?? 50
|
|
31
|
+
this.timeout = config.timeout ?? 5000
|
|
32
|
+
this.retries = config.retries ?? 1
|
|
33
|
+
this.apiKey = config.apiKey
|
|
34
|
+
this.baseUrl = config.baseUrl
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
abstract lookup(
|
|
38
|
+
barcode: string,
|
|
39
|
+
format: BarcodeSymbology
|
|
40
|
+
): Promise<NormalizedBarcodeProduct | null>
|
|
41
|
+
|
|
42
|
+
supportsFormat(_format: BarcodeSymbology): boolean {
|
|
43
|
+
return true
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
protected async fetchJson<T = Record<string, unknown>>(
|
|
47
|
+
url: string,
|
|
48
|
+
init: RequestInit = {}
|
|
49
|
+
): Promise<T | null> {
|
|
50
|
+
const maxAttempts = Math.max(0, this.retries)
|
|
51
|
+
for (let attempt = 0; attempt <= maxAttempts; attempt++) {
|
|
52
|
+
const controller = new AbortController()
|
|
53
|
+
const timer = setTimeout(() => controller.abort(), this.timeout)
|
|
54
|
+
try {
|
|
55
|
+
const headers = new Headers(init.headers || {})
|
|
56
|
+
if (!headers.has("User-Agent")) {
|
|
57
|
+
headers.set("User-Agent", DEFAULT_USER_AGENT)
|
|
58
|
+
}
|
|
59
|
+
if (!headers.has("Accept")) {
|
|
60
|
+
headers.set("Accept", "application/json")
|
|
61
|
+
}
|
|
62
|
+
const response = await fetch(url, {
|
|
63
|
+
...init,
|
|
64
|
+
headers,
|
|
65
|
+
signal: controller.signal,
|
|
66
|
+
})
|
|
67
|
+
if (!response.ok) {
|
|
68
|
+
const isRetryable = response.status === 429 || response.status >= 500
|
|
69
|
+
if (isRetryable && attempt < maxAttempts) {
|
|
70
|
+
await new Promise((r) => setTimeout(r, 50 * 2 ** attempt))
|
|
71
|
+
continue
|
|
72
|
+
}
|
|
73
|
+
return null
|
|
74
|
+
}
|
|
75
|
+
return (await response.json()) as T
|
|
76
|
+
} catch {
|
|
77
|
+
if (attempt < maxAttempts) {
|
|
78
|
+
await new Promise((r) => setTimeout(r, 50 * 2 ** attempt))
|
|
79
|
+
continue
|
|
80
|
+
}
|
|
81
|
+
return null
|
|
82
|
+
} finally {
|
|
83
|
+
clearTimeout(timer)
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
return null
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Shared Open*Facts family base provider (OpenFoodFacts, OpenBeautyFacts, OpenPetFoodFacts, OpenProductsFacts)
|
|
92
|
+
*/
|
|
93
|
+
abstract class BaseOpenFactsProvider extends BaseBarcodeProvider {
|
|
94
|
+
protected abstract readonly defaultDomain: string
|
|
95
|
+
protected readonly country?: string
|
|
96
|
+
|
|
97
|
+
constructor(config: ProviderConfig = {}) {
|
|
98
|
+
super(config)
|
|
99
|
+
this.country = config.country?.trim() || undefined
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
async lookup(
|
|
103
|
+
barcode: string,
|
|
104
|
+
_format: BarcodeSymbology
|
|
105
|
+
): Promise<NormalizedBarcodeProduct | null> {
|
|
106
|
+
const resolvedDomain =
|
|
107
|
+
this.country && !this.baseUrl
|
|
108
|
+
? this.defaultDomain.replace(
|
|
109
|
+
/^https:\/\/world\./i,
|
|
110
|
+
`https://${encodeURIComponent(this.country.toLowerCase())}.`
|
|
111
|
+
)
|
|
112
|
+
: this.defaultDomain
|
|
113
|
+
const host = this.baseUrl || resolvedDomain
|
|
114
|
+
const url = `${host.replace(/\/$/, "")}/api/v2/product/${encodeURIComponent(
|
|
115
|
+
barcode
|
|
116
|
+
)}.json`
|
|
117
|
+
|
|
118
|
+
const data = await this.fetchJson<{
|
|
119
|
+
status?: number
|
|
120
|
+
product?: Record<string, unknown>
|
|
121
|
+
}>(url)
|
|
122
|
+
|
|
123
|
+
if (!data || data.status !== 1 || !data.product) {
|
|
124
|
+
return null
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
const p = data.product
|
|
128
|
+
const name =
|
|
129
|
+
(p.product_name as string) ||
|
|
130
|
+
(p.product_name_en as string) ||
|
|
131
|
+
(p.generic_name as string) ||
|
|
132
|
+
""
|
|
133
|
+
if (!name.trim()) {
|
|
134
|
+
return null
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
const images = normalizeStringArray([
|
|
138
|
+
p.image_url,
|
|
139
|
+
p.image_front_url,
|
|
140
|
+
p.image_ingredients_url,
|
|
141
|
+
p.image_nutrition_url,
|
|
142
|
+
]).filter((img) => Boolean(validateExternalImageUrl(img)))
|
|
143
|
+
|
|
144
|
+
const categories =
|
|
145
|
+
typeof p.categories === "string"
|
|
146
|
+
? p.categories
|
|
147
|
+
.split(",")
|
|
148
|
+
.map((c) => c.trim())
|
|
149
|
+
.filter(Boolean)
|
|
150
|
+
: normalizeStringArray(p.categories_tags)
|
|
151
|
+
|
|
152
|
+
const labels =
|
|
153
|
+
typeof p.labels === "string"
|
|
154
|
+
? p.labels
|
|
155
|
+
.split(",")
|
|
156
|
+
.map((l) => l.trim())
|
|
157
|
+
.filter(Boolean)
|
|
158
|
+
: normalizeStringArray(p.labels_tags)
|
|
159
|
+
|
|
160
|
+
let weightGrams: number | null = null
|
|
161
|
+
if (
|
|
162
|
+
typeof p.product_quantity === "number" &&
|
|
163
|
+
Number.isFinite(p.product_quantity)
|
|
164
|
+
) {
|
|
165
|
+
weightGrams = p.product_quantity
|
|
166
|
+
} else if (typeof p.product_quantity === "string") {
|
|
167
|
+
const parsed = Number.parseFloat(p.product_quantity)
|
|
168
|
+
if (Number.isFinite(parsed)) {
|
|
169
|
+
weightGrams = parsed
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
if (weightGrams === null) {
|
|
173
|
+
weightGrams = parseWeightGrams(p.quantity)
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
const brands =
|
|
177
|
+
typeof p.brands === "string"
|
|
178
|
+
? p.brands.split(",")[0]?.trim() || null
|
|
179
|
+
: null
|
|
180
|
+
|
|
181
|
+
return {
|
|
182
|
+
barcode,
|
|
183
|
+
barcode_type: _format,
|
|
184
|
+
name: name.trim(),
|
|
185
|
+
description:
|
|
186
|
+
(
|
|
187
|
+
(p.generic_name as string) ||
|
|
188
|
+
(p.ingredients_text as string) ||
|
|
189
|
+
""
|
|
190
|
+
).trim() || null,
|
|
191
|
+
brand: brands,
|
|
192
|
+
manufacturer: (p.manufacturing_places as string) || null,
|
|
193
|
+
categories,
|
|
194
|
+
labels,
|
|
195
|
+
images,
|
|
196
|
+
weight: weightGrams,
|
|
197
|
+
weight_unit: weightGrams !== null ? "g" : null,
|
|
198
|
+
dimensions: null,
|
|
199
|
+
quantity_label: (p.quantity as string) || null,
|
|
200
|
+
ingredients: (p.ingredients_text as string) || null,
|
|
201
|
+
nutrition:
|
|
202
|
+
p.nutriments && typeof p.nutriments === "object"
|
|
203
|
+
? (p.nutriments as Record<string, unknown>)
|
|
204
|
+
: null,
|
|
205
|
+
country_of_origin: (p.countries as string) || null,
|
|
206
|
+
suggested_price: null,
|
|
207
|
+
currency_code: null,
|
|
208
|
+
isbn: null,
|
|
209
|
+
authors: [],
|
|
210
|
+
publisher: null,
|
|
211
|
+
published_date: null,
|
|
212
|
+
page_count: null,
|
|
213
|
+
provider: this.name,
|
|
214
|
+
raw_data: p,
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
export class OpenFoodFactsProvider extends BaseOpenFactsProvider {
|
|
220
|
+
readonly name = "openfoodfacts"
|
|
221
|
+
protected readonly defaultDomain = "https://world.openfoodfacts.org"
|
|
222
|
+
constructor(config: ProviderConfig = {}) {
|
|
223
|
+
super({ priority: 10, ...config })
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
export class OpenBeautyFactsProvider extends BaseOpenFactsProvider {
|
|
228
|
+
readonly name = "openbeautyfacts"
|
|
229
|
+
protected readonly defaultDomain = "https://world.openbeautyfacts.org"
|
|
230
|
+
constructor(config: ProviderConfig = {}) {
|
|
231
|
+
super({ priority: 20, ...config })
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
export class OpenPetFoodFactsProvider extends BaseOpenFactsProvider {
|
|
236
|
+
readonly name = "openpetfoodfacts"
|
|
237
|
+
protected readonly defaultDomain = "https://world.openpetfoodfacts.org"
|
|
238
|
+
constructor(config: ProviderConfig = {}) {
|
|
239
|
+
super({ priority: 25, ...config })
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
export class OpenProductsFactsProvider extends BaseOpenFactsProvider {
|
|
244
|
+
readonly name = "openproductsfacts"
|
|
245
|
+
protected readonly defaultDomain = "https://world.openproductsfacts.org"
|
|
246
|
+
constructor(config: ProviderConfig = {}) {
|
|
247
|
+
super({ priority: 30, ...config })
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/**
|
|
252
|
+
* Google Books API provider (prioritized automatically for ISBN-13 978/979 prefixes)
|
|
253
|
+
*/
|
|
254
|
+
export class GoogleBooksProvider extends BaseBarcodeProvider {
|
|
255
|
+
readonly name = "googlebooks"
|
|
256
|
+
|
|
257
|
+
constructor(config: ProviderConfig = {}) {
|
|
258
|
+
super({ priority: 15, ...config })
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
supportsFormat(format: BarcodeSymbology): boolean {
|
|
262
|
+
return format === "isbn13" || format === "ean13"
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
async lookup(
|
|
266
|
+
barcode: string,
|
|
267
|
+
format: BarcodeSymbology
|
|
268
|
+
): Promise<NormalizedBarcodeProduct | null> {
|
|
269
|
+
if (
|
|
270
|
+
!barcode.startsWith("978") &&
|
|
271
|
+
!barcode.startsWith("979") &&
|
|
272
|
+
format !== "isbn13"
|
|
273
|
+
) {
|
|
274
|
+
return null
|
|
275
|
+
}
|
|
276
|
+
const host = this.baseUrl || "https://www.googleapis.com/books/v1/volumes"
|
|
277
|
+
const keyParam = this.apiKey
|
|
278
|
+
? `&key=${encodeURIComponent(this.apiKey)}`
|
|
279
|
+
: ""
|
|
280
|
+
const url = `${host}?q=isbn:${encodeURIComponent(barcode)}${keyParam}`
|
|
281
|
+
|
|
282
|
+
const data = await this.fetchJson<{
|
|
283
|
+
totalItems?: number
|
|
284
|
+
items?: Array<{ volumeInfo?: Record<string, unknown> }>
|
|
285
|
+
}>(url)
|
|
286
|
+
|
|
287
|
+
const info = data?.items?.[0]?.volumeInfo
|
|
288
|
+
if (!info || typeof info.title !== "string" || !info.title.trim()) {
|
|
289
|
+
return null
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
const subtitle =
|
|
293
|
+
typeof info.subtitle === "string" ? `: ${info.subtitle}` : ""
|
|
294
|
+
const imageLinks =
|
|
295
|
+
(info.imageLinks as Record<string, string> | undefined) || {}
|
|
296
|
+
const images = normalizeStringArray([
|
|
297
|
+
imageLinks.thumbnail?.replace(/^http:\/\//i, "https://"),
|
|
298
|
+
imageLinks.smallThumbnail?.replace(/^http:\/\//i, "https://"),
|
|
299
|
+
]).filter((img) => Boolean(validateExternalImageUrl(img)))
|
|
300
|
+
|
|
301
|
+
const authors = normalizeStringArray(info.authors)
|
|
302
|
+
const categories = normalizeStringArray(info.categories)
|
|
303
|
+
|
|
304
|
+
return {
|
|
305
|
+
barcode,
|
|
306
|
+
barcode_type: "isbn13",
|
|
307
|
+
name: `${info.title.trim()}${subtitle}`,
|
|
308
|
+
description:
|
|
309
|
+
typeof info.description === "string" ? info.description : null,
|
|
310
|
+
brand:
|
|
311
|
+
typeof info.publisher === "string"
|
|
312
|
+
? info.publisher
|
|
313
|
+
: authors[0] || null,
|
|
314
|
+
manufacturer: typeof info.publisher === "string" ? info.publisher : null,
|
|
315
|
+
categories,
|
|
316
|
+
images,
|
|
317
|
+
weight: null,
|
|
318
|
+
weight_unit: null,
|
|
319
|
+
dimensions: null,
|
|
320
|
+
quantity_label:
|
|
321
|
+
typeof info.pageCount === "number" ? `${info.pageCount} pages` : null,
|
|
322
|
+
ingredients: null,
|
|
323
|
+
nutrition: null,
|
|
324
|
+
country_of_origin:
|
|
325
|
+
typeof info.language === "string" ? info.language : null,
|
|
326
|
+
suggested_price: null,
|
|
327
|
+
currency_code: null,
|
|
328
|
+
isbn: barcode,
|
|
329
|
+
authors,
|
|
330
|
+
publisher: typeof info.publisher === "string" ? info.publisher : null,
|
|
331
|
+
published_date:
|
|
332
|
+
typeof info.publishedDate === "string" ? info.publishedDate : null,
|
|
333
|
+
page_count: typeof info.pageCount === "number" ? info.pageCount : null,
|
|
334
|
+
provider: this.name,
|
|
335
|
+
raw_data: info,
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
/**
|
|
341
|
+
* OpenLibrary API provider (Free, keyless ISBN / book metadata)
|
|
342
|
+
*/
|
|
343
|
+
export class OpenLibraryProvider extends BaseBarcodeProvider {
|
|
344
|
+
readonly name = "openlibrary"
|
|
345
|
+
|
|
346
|
+
constructor(config: ProviderConfig = {}) {
|
|
347
|
+
super({ priority: 18, ...config })
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
supportsFormat(format: BarcodeSymbology): boolean {
|
|
351
|
+
return format === "isbn13" || format === "ean13"
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
async lookup(
|
|
355
|
+
barcode: string,
|
|
356
|
+
format: BarcodeSymbology
|
|
357
|
+
): Promise<NormalizedBarcodeProduct | null> {
|
|
358
|
+
if (
|
|
359
|
+
!barcode.startsWith("978") &&
|
|
360
|
+
!barcode.startsWith("979") &&
|
|
361
|
+
format !== "isbn13"
|
|
362
|
+
) {
|
|
363
|
+
return null
|
|
364
|
+
}
|
|
365
|
+
const bibKey = `ISBN:${barcode}`
|
|
366
|
+
const host = this.baseUrl || "https://openlibrary.org/api/books"
|
|
367
|
+
const url = `${host}?bibkeys=${encodeURIComponent(
|
|
368
|
+
bibKey
|
|
369
|
+
)}&format=json&jscmd=data`
|
|
370
|
+
|
|
371
|
+
const data =
|
|
372
|
+
await this.fetchJson<Record<string, Record<string, unknown>>>(url)
|
|
373
|
+
const book = data?.[bibKey]
|
|
374
|
+
if (!book || typeof book.title !== "string" || !book.title.trim()) {
|
|
375
|
+
return null
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
const cover = (book.cover as Record<string, string> | undefined) || {}
|
|
379
|
+
const images = normalizeStringArray([
|
|
380
|
+
cover.large,
|
|
381
|
+
cover.medium,
|
|
382
|
+
cover.small,
|
|
383
|
+
]).filter((img) => Boolean(validateExternalImageUrl(img)))
|
|
384
|
+
|
|
385
|
+
const authors = Array.isArray(book.authors)
|
|
386
|
+
? book.authors
|
|
387
|
+
.map((a) =>
|
|
388
|
+
a && typeof a === "object" && "name" in a ? String(a.name) : ""
|
|
389
|
+
)
|
|
390
|
+
.filter(Boolean)
|
|
391
|
+
: []
|
|
392
|
+
|
|
393
|
+
const publishers = Array.isArray(book.publishers)
|
|
394
|
+
? book.publishers
|
|
395
|
+
.map((p) =>
|
|
396
|
+
p && typeof p === "object" && "name" in p ? String(p.name) : ""
|
|
397
|
+
)
|
|
398
|
+
.filter(Boolean)
|
|
399
|
+
: []
|
|
400
|
+
|
|
401
|
+
const subjects = Array.isArray(book.subjects)
|
|
402
|
+
? book.subjects
|
|
403
|
+
.map((s) =>
|
|
404
|
+
s && typeof s === "object" && "name" in s ? String(s.name) : ""
|
|
405
|
+
)
|
|
406
|
+
.filter(Boolean)
|
|
407
|
+
.slice(0, 8)
|
|
408
|
+
: []
|
|
409
|
+
|
|
410
|
+
return {
|
|
411
|
+
barcode,
|
|
412
|
+
barcode_type: "isbn13",
|
|
413
|
+
name: book.title.trim(),
|
|
414
|
+
description: typeof book.notes === "string" ? book.notes : null,
|
|
415
|
+
brand: publishers[0] || authors[0] || null,
|
|
416
|
+
manufacturer: publishers[0] || null,
|
|
417
|
+
categories: subjects,
|
|
418
|
+
images,
|
|
419
|
+
weight: null,
|
|
420
|
+
weight_unit: null,
|
|
421
|
+
dimensions: null,
|
|
422
|
+
quantity_label:
|
|
423
|
+
typeof book.number_of_pages === "number"
|
|
424
|
+
? `${book.number_of_pages} pages`
|
|
425
|
+
: null,
|
|
426
|
+
ingredients: null,
|
|
427
|
+
nutrition: null,
|
|
428
|
+
country_of_origin: null,
|
|
429
|
+
suggested_price: null,
|
|
430
|
+
currency_code: null,
|
|
431
|
+
isbn: barcode,
|
|
432
|
+
authors,
|
|
433
|
+
publisher: publishers[0] || null,
|
|
434
|
+
published_date:
|
|
435
|
+
typeof book.publish_date === "string" ? book.publish_date : null,
|
|
436
|
+
page_count:
|
|
437
|
+
typeof book.number_of_pages === "number" ? book.number_of_pages : null,
|
|
438
|
+
provider: this.name,
|
|
439
|
+
raw_data: book,
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
/**
|
|
445
|
+
* Brocade.io Open GTIN Database provider (Free, keyless general product catalog)
|
|
446
|
+
*/
|
|
447
|
+
export class BrocadeProvider extends BaseBarcodeProvider {
|
|
448
|
+
readonly name = "brocade"
|
|
449
|
+
|
|
450
|
+
constructor(config: ProviderConfig = {}) {
|
|
451
|
+
super({ priority: 35, ...config })
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
async lookup(
|
|
455
|
+
barcode: string,
|
|
456
|
+
format: BarcodeSymbology
|
|
457
|
+
): Promise<NormalizedBarcodeProduct | null> {
|
|
458
|
+
const host = this.baseUrl || "https://www.brocade.io/api/items"
|
|
459
|
+
const url = `${host.replace(/\/$/, "")}/${encodeURIComponent(barcode)}`
|
|
460
|
+
|
|
461
|
+
const data = await this.fetchJson<Record<string, unknown>>(url)
|
|
462
|
+
if (!data || typeof data.name !== "string" || !data.name.trim()) {
|
|
463
|
+
return null
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
return {
|
|
467
|
+
barcode,
|
|
468
|
+
barcode_type: format,
|
|
469
|
+
name: data.name.trim(),
|
|
470
|
+
description: typeof data.properties === "string" ? data.properties : null,
|
|
471
|
+
brand: typeof data.brand_name === "string" ? data.brand_name : null,
|
|
472
|
+
manufacturer:
|
|
473
|
+
typeof data.brand_name === "string" ? data.brand_name : null,
|
|
474
|
+
categories: [],
|
|
475
|
+
images: [],
|
|
476
|
+
weight: null,
|
|
477
|
+
weight_unit: null,
|
|
478
|
+
dimensions: null,
|
|
479
|
+
quantity_label: typeof data.size === "string" ? data.size : null,
|
|
480
|
+
ingredients: null,
|
|
481
|
+
nutrition: null,
|
|
482
|
+
country_of_origin: null,
|
|
483
|
+
suggested_price: null,
|
|
484
|
+
currency_code: null,
|
|
485
|
+
isbn: null,
|
|
486
|
+
authors: [],
|
|
487
|
+
publisher: null,
|
|
488
|
+
published_date: null,
|
|
489
|
+
page_count: null,
|
|
490
|
+
provider: this.name,
|
|
491
|
+
raw_data: data,
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
/**
|
|
497
|
+
* UPCitemdb API provider (supports free trial endpoint or paid v1 endpoint with API key)
|
|
498
|
+
*/
|
|
499
|
+
export class UpcItemDbProvider extends BaseBarcodeProvider {
|
|
500
|
+
readonly name = "upcitemdb"
|
|
501
|
+
|
|
502
|
+
constructor(config: ProviderConfig = {}) {
|
|
503
|
+
super({ priority: 40, ...config })
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
async lookup(
|
|
507
|
+
barcode: string,
|
|
508
|
+
format: BarcodeSymbology
|
|
509
|
+
): Promise<NormalizedBarcodeProduct | null> {
|
|
510
|
+
const endpoint = this.apiKey
|
|
511
|
+
? `${this.baseUrl || "https://api.upcitemdb.com/prod/v1"}/lookup?upc=${encodeURIComponent(
|
|
512
|
+
barcode
|
|
513
|
+
)}`
|
|
514
|
+
: `${
|
|
515
|
+
this.baseUrl || "https://api.upcitemdb.com/prod/trial"
|
|
516
|
+
}/lookup?upc=${encodeURIComponent(barcode)}`
|
|
517
|
+
|
|
518
|
+
const headers: Record<string, string> = {}
|
|
519
|
+
if (this.apiKey) {
|
|
520
|
+
headers.user_key = this.apiKey
|
|
521
|
+
headers.key_type = "3scale"
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
const data = await this.fetchJson<{
|
|
525
|
+
code?: string
|
|
526
|
+
items?: Array<Record<string, unknown>>
|
|
527
|
+
}>(endpoint, { headers })
|
|
528
|
+
|
|
529
|
+
const item = data?.items?.[0]
|
|
530
|
+
if (!item || typeof item.title !== "string" || !item.title.trim()) {
|
|
531
|
+
return null
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
const images = normalizeStringArray(item.images).filter((img) =>
|
|
535
|
+
Boolean(validateExternalImageUrl(img))
|
|
536
|
+
)
|
|
537
|
+
const categories =
|
|
538
|
+
typeof item.category === "string"
|
|
539
|
+
? item.category
|
|
540
|
+
.split(">")
|
|
541
|
+
.map((c) => c.trim())
|
|
542
|
+
.filter(Boolean)
|
|
543
|
+
: []
|
|
544
|
+
|
|
545
|
+
const lowestPrice =
|
|
546
|
+
typeof item.lowest_recorded_price === "number"
|
|
547
|
+
? item.lowest_recorded_price
|
|
548
|
+
: null
|
|
549
|
+
|
|
550
|
+
const weightGrams = parseWeightGrams(item.weight || item.size)
|
|
551
|
+
const parsedDims = parseDimensionMm(item.dimension)
|
|
552
|
+
|
|
553
|
+
return {
|
|
554
|
+
barcode,
|
|
555
|
+
barcode_type: format,
|
|
556
|
+
name: item.title.trim(),
|
|
557
|
+
description:
|
|
558
|
+
typeof item.description === "string" ? item.description.trim() : null,
|
|
559
|
+
brand: typeof item.brand === "string" ? item.brand.trim() : null,
|
|
560
|
+
manufacturer: typeof item.brand === "string" ? item.brand.trim() : null,
|
|
561
|
+
categories,
|
|
562
|
+
images,
|
|
563
|
+
weight: weightGrams,
|
|
564
|
+
weight_unit: weightGrams !== null ? "g" : null,
|
|
565
|
+
length: parsedDims.length,
|
|
566
|
+
width: parsedDims.width,
|
|
567
|
+
height: parsedDims.height,
|
|
568
|
+
dimensions: typeof item.dimension === "string" ? item.dimension : null,
|
|
569
|
+
quantity_label: typeof item.size === "string" ? item.size : null,
|
|
570
|
+
ingredients: null,
|
|
571
|
+
nutrition: null,
|
|
572
|
+
country_of_origin: null,
|
|
573
|
+
suggested_price: lowestPrice,
|
|
574
|
+
currency_code:
|
|
575
|
+
typeof item.currency === "string" && item.currency
|
|
576
|
+
? item.currency.toUpperCase()
|
|
577
|
+
: "USD",
|
|
578
|
+
isbn: typeof item.isbn === "string" ? item.isbn : null,
|
|
579
|
+
authors: [],
|
|
580
|
+
publisher: typeof item.publisher === "string" ? item.publisher : null,
|
|
581
|
+
published_date: null,
|
|
582
|
+
page_count: null,
|
|
583
|
+
provider: this.name,
|
|
584
|
+
raw_data: item,
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
/**
|
|
590
|
+
* EAN-Search.org commercial API provider (requires API token)
|
|
591
|
+
*/
|
|
592
|
+
export class EanSearchProvider extends BaseBarcodeProvider {
|
|
593
|
+
readonly name = "eansearch"
|
|
594
|
+
|
|
595
|
+
constructor(config: ProviderConfig = {}) {
|
|
596
|
+
super({ priority: 60, ...config })
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
async lookup(
|
|
600
|
+
barcode: string,
|
|
601
|
+
format: BarcodeSymbology
|
|
602
|
+
): Promise<NormalizedBarcodeProduct | null> {
|
|
603
|
+
if (!this.apiKey) {
|
|
604
|
+
return null
|
|
605
|
+
}
|
|
606
|
+
const host = this.baseUrl || "https://api.ean-search.org/api"
|
|
607
|
+
const url = `${host}?token=${encodeURIComponent(
|
|
608
|
+
this.apiKey
|
|
609
|
+
)}&op=barcode-lookup&format=json&ean=${encodeURIComponent(barcode)}`
|
|
610
|
+
|
|
611
|
+
const data = await this.fetchJson<Array<Record<string, unknown>>>(url)
|
|
612
|
+
const item = Array.isArray(data) ? data[0] : null
|
|
613
|
+
if (!item || typeof item.name !== "string" || !item.name.trim()) {
|
|
614
|
+
return null
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
return {
|
|
618
|
+
barcode,
|
|
619
|
+
barcode_type: format,
|
|
620
|
+
name: item.name.trim(),
|
|
621
|
+
description: null,
|
|
622
|
+
brand: null,
|
|
623
|
+
manufacturer:
|
|
624
|
+
typeof item.issuingCountry === "string" ? item.issuingCountry : null,
|
|
625
|
+
categories: normalizeStringArray([item.categoryName]),
|
|
626
|
+
images: [],
|
|
627
|
+
weight: null,
|
|
628
|
+
weight_unit: null,
|
|
629
|
+
dimensions: null,
|
|
630
|
+
quantity_label: null,
|
|
631
|
+
ingredients: null,
|
|
632
|
+
nutrition: null,
|
|
633
|
+
country_of_origin:
|
|
634
|
+
typeof item.issuingCountry === "string" ? item.issuingCountry : null,
|
|
635
|
+
suggested_price: null,
|
|
636
|
+
currency_code: null,
|
|
637
|
+
isbn: null,
|
|
638
|
+
authors: [],
|
|
639
|
+
publisher: null,
|
|
640
|
+
published_date: null,
|
|
641
|
+
page_count: null,
|
|
642
|
+
provider: this.name,
|
|
643
|
+
raw_data: item,
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
}
|
|
647
|
+
|
|
648
|
+
/**
|
|
649
|
+
* BarcodeLookup.com commercial API provider (requires API key)
|
|
650
|
+
*/
|
|
651
|
+
export class BarcodeLookupProvider extends BaseBarcodeProvider {
|
|
652
|
+
readonly name = "barcodelookup"
|
|
653
|
+
|
|
654
|
+
constructor(config: ProviderConfig = {}) {
|
|
655
|
+
super({ priority: 70, ...config })
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
async lookup(
|
|
659
|
+
barcode: string,
|
|
660
|
+
format: BarcodeSymbology
|
|
661
|
+
): Promise<NormalizedBarcodeProduct | null> {
|
|
662
|
+
if (!this.apiKey) {
|
|
663
|
+
return null
|
|
664
|
+
}
|
|
665
|
+
const host = this.baseUrl || "https://api.barcodelookup.com/v3/products"
|
|
666
|
+
const url = `${host}?barcode=${encodeURIComponent(
|
|
667
|
+
barcode
|
|
668
|
+
)}&formatted=y&key=${encodeURIComponent(this.apiKey)}`
|
|
669
|
+
|
|
670
|
+
const data = await this.fetchJson<{
|
|
671
|
+
products?: Array<Record<string, unknown>>
|
|
672
|
+
}>(url)
|
|
673
|
+
const item = data?.products?.[0]
|
|
674
|
+
if (!item || typeof item.title !== "string" || !item.title.trim()) {
|
|
675
|
+
return null
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
const images = normalizeStringArray(item.images).filter((img) =>
|
|
679
|
+
Boolean(validateExternalImageUrl(img))
|
|
680
|
+
)
|
|
681
|
+
|
|
682
|
+
const weightGrams = parseWeightGrams(item.weight || item.size)
|
|
683
|
+
const parsedDims = parseDimensionMm(item.size || item.dimension)
|
|
684
|
+
|
|
685
|
+
return {
|
|
686
|
+
barcode,
|
|
687
|
+
barcode_type: format,
|
|
688
|
+
name: item.title.trim(),
|
|
689
|
+
description:
|
|
690
|
+
typeof item.description === "string" ? item.description.trim() : null,
|
|
691
|
+
brand: typeof item.brand === "string" ? item.brand.trim() : null,
|
|
692
|
+
manufacturer:
|
|
693
|
+
typeof item.manufacturer === "string" ? item.manufacturer.trim() : null,
|
|
694
|
+
categories:
|
|
695
|
+
typeof item.category === "string"
|
|
696
|
+
? item.category
|
|
697
|
+
.split(">")
|
|
698
|
+
.map((c) => c.trim())
|
|
699
|
+
.filter(Boolean)
|
|
700
|
+
: [],
|
|
701
|
+
images,
|
|
702
|
+
weight: weightGrams,
|
|
703
|
+
weight_unit: weightGrams !== null ? "g" : null,
|
|
704
|
+
length: parsedDims.length,
|
|
705
|
+
width: parsedDims.width,
|
|
706
|
+
height: parsedDims.height,
|
|
707
|
+
dimensions: typeof item.size === "string" ? item.size : null,
|
|
708
|
+
quantity_label: typeof item.size === "string" ? item.size : null,
|
|
709
|
+
ingredients:
|
|
710
|
+
typeof item.ingredients === "string" ? item.ingredients : null,
|
|
711
|
+
nutrition: null,
|
|
712
|
+
country_of_origin: null,
|
|
713
|
+
suggested_price: null,
|
|
714
|
+
currency_code: null,
|
|
715
|
+
isbn: null,
|
|
716
|
+
authors: [],
|
|
717
|
+
publisher: null,
|
|
718
|
+
published_date: null,
|
|
719
|
+
page_count: null,
|
|
720
|
+
provider: this.name,
|
|
721
|
+
raw_data: item,
|
|
722
|
+
}
|
|
723
|
+
}
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
/**
|
|
727
|
+
* Registry of active barcode lookup providers ordered by priority.
|
|
728
|
+
*/
|
|
729
|
+
export class ProviderRegistry {
|
|
730
|
+
private readonly providers = new Map<string, BaseBarcodeProvider>()
|
|
731
|
+
|
|
732
|
+
register(provider: BaseBarcodeProvider): this {
|
|
733
|
+
this.providers.set(provider.name, provider)
|
|
734
|
+
return this
|
|
735
|
+
}
|
|
736
|
+
|
|
737
|
+
unregister(name: string): boolean {
|
|
738
|
+
return this.providers.delete(name)
|
|
739
|
+
}
|
|
740
|
+
|
|
741
|
+
get(name: string): BaseBarcodeProvider | undefined {
|
|
742
|
+
return this.providers.get(name)
|
|
743
|
+
}
|
|
744
|
+
|
|
745
|
+
getAll(): BaseBarcodeProvider[] {
|
|
746
|
+
return Array.from(this.providers.values()).toSorted(
|
|
747
|
+
(a, b) => a.priority - b.priority
|
|
748
|
+
)
|
|
749
|
+
}
|
|
750
|
+
|
|
751
|
+
getProviderNames(): string[] {
|
|
752
|
+
return this.getAll().map((p) => p.name)
|
|
753
|
+
}
|
|
754
|
+
|
|
755
|
+
/**
|
|
756
|
+
* Returns providers ordered for a specific barcode, promoting book/ISBN
|
|
757
|
+
* providers (`googlebooks`, `openlibrary`) to the front when scanning 978/979 ISBNs.
|
|
758
|
+
*/
|
|
759
|
+
getOrderedForBarcode(
|
|
760
|
+
barcode: string,
|
|
761
|
+
format: BarcodeSymbology,
|
|
762
|
+
preferredProviders?: string[]
|
|
763
|
+
): BaseBarcodeProvider[] {
|
|
764
|
+
const all = this.getAll().filter((p) => p.supportsFormat(format))
|
|
765
|
+
|
|
766
|
+
if (preferredProviders && preferredProviders.length > 0) {
|
|
767
|
+
const preferredSet = new Set(preferredProviders)
|
|
768
|
+
return all.filter((p) => preferredSet.has(p.name))
|
|
769
|
+
}
|
|
770
|
+
|
|
771
|
+
const isIsbn =
|
|
772
|
+
format === "isbn13" ||
|
|
773
|
+
barcode.startsWith("978") ||
|
|
774
|
+
barcode.startsWith("979")
|
|
775
|
+
|
|
776
|
+
if (!isIsbn) {
|
|
777
|
+
return all
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
return [...all].toSorted((a, b) => {
|
|
781
|
+
const aIsBook =
|
|
782
|
+
a.name === "googlebooks" || a.name === "openlibrary" ? 0 : 1
|
|
783
|
+
const bIsBook =
|
|
784
|
+
b.name === "googlebooks" || b.name === "openlibrary" ? 0 : 1
|
|
785
|
+
if (aIsBook !== bIsBook) return aIsBook - bIsBook
|
|
786
|
+
return a.priority - b.priority
|
|
787
|
+
})
|
|
788
|
+
}
|
|
789
|
+
}
|
|
790
|
+
|
|
791
|
+
/**
|
|
792
|
+
* Creates a default ProviderRegistry with all 10 built-in providers configured.
|
|
793
|
+
*/
|
|
794
|
+
export function createDefaultProviderRegistry(
|
|
795
|
+
options: BarcodeModuleOptions = {}
|
|
796
|
+
): ProviderRegistry {
|
|
797
|
+
const cfg = options.providers || {}
|
|
798
|
+
const timeout = options.requestTimeoutMs ?? 5000
|
|
799
|
+
const registry = new ProviderRegistry()
|
|
800
|
+
|
|
801
|
+
if (cfg.openFoodFacts?.enabled !== false) {
|
|
802
|
+
registry.register(
|
|
803
|
+
new OpenFoodFactsProvider({ timeout, ...cfg.openFoodFacts })
|
|
804
|
+
)
|
|
805
|
+
}
|
|
806
|
+
if (cfg.googleBooks?.enabled !== false) {
|
|
807
|
+
registry.register(new GoogleBooksProvider({ timeout, ...cfg.googleBooks }))
|
|
808
|
+
}
|
|
809
|
+
if (cfg.openLibrary?.enabled !== false) {
|
|
810
|
+
registry.register(new OpenLibraryProvider({ timeout, ...cfg.openLibrary }))
|
|
811
|
+
}
|
|
812
|
+
if (cfg.openBeautyFacts?.enabled !== false) {
|
|
813
|
+
registry.register(
|
|
814
|
+
new OpenBeautyFactsProvider({ timeout, ...cfg.openBeautyFacts })
|
|
815
|
+
)
|
|
816
|
+
}
|
|
817
|
+
if (cfg.openPetFoodFacts?.enabled !== false) {
|
|
818
|
+
registry.register(
|
|
819
|
+
new OpenPetFoodFactsProvider({ timeout, ...cfg.openPetFoodFacts })
|
|
820
|
+
)
|
|
821
|
+
}
|
|
822
|
+
if (cfg.openProductsFacts?.enabled !== false) {
|
|
823
|
+
registry.register(
|
|
824
|
+
new OpenProductsFactsProvider({ timeout, ...cfg.openProductsFacts })
|
|
825
|
+
)
|
|
826
|
+
}
|
|
827
|
+
if (cfg.brocade?.enabled !== false) {
|
|
828
|
+
registry.register(new BrocadeProvider({ timeout, ...cfg.brocade }))
|
|
829
|
+
}
|
|
830
|
+
if (cfg.upcItemDb?.enabled !== false) {
|
|
831
|
+
registry.register(new UpcItemDbProvider({ timeout, ...cfg.upcItemDb }))
|
|
832
|
+
}
|
|
833
|
+
if (cfg.eanSearch?.enabled !== false && cfg.eanSearch?.apiKey) {
|
|
834
|
+
registry.register(new EanSearchProvider({ timeout, ...cfg.eanSearch }))
|
|
835
|
+
}
|
|
836
|
+
if (cfg.barcodeLookup?.enabled !== false && cfg.barcodeLookup?.apiKey) {
|
|
837
|
+
registry.register(
|
|
838
|
+
new BarcodeLookupProvider({ timeout, ...cfg.barcodeLookup })
|
|
839
|
+
)
|
|
840
|
+
}
|
|
841
|
+
|
|
842
|
+
return registry
|
|
843
|
+
}
|
|
844
|
+
|
|
845
|
+
/**
|
|
846
|
+
* Executes the multi-provider lookup chain using either `first-hit` or `deep-merge` strategy.
|
|
847
|
+
*/
|
|
848
|
+
export async function runProviderLookupChain(
|
|
849
|
+
rawBarcode: string,
|
|
850
|
+
registry: ProviderRegistry,
|
|
851
|
+
options: {
|
|
852
|
+
strategy?: EnrichmentStrategy
|
|
853
|
+
preferredProviders?: string[]
|
|
854
|
+
} = {}
|
|
855
|
+
): Promise<BarcodeLookupChainResult> {
|
|
856
|
+
const parsed = parseBarcode(rawBarcode)
|
|
857
|
+
const strategy = options.strategy || "first-hit"
|
|
858
|
+
const providers = registry.getOrderedForBarcode(
|
|
859
|
+
parsed.normalized,
|
|
860
|
+
parsed.type,
|
|
861
|
+
options.preferredProviders
|
|
862
|
+
)
|
|
863
|
+
|
|
864
|
+
const outcomes: ProviderLookupOutcome[] = []
|
|
865
|
+
const hits: NormalizedBarcodeProduct[] = []
|
|
866
|
+
|
|
867
|
+
for (const provider of providers) {
|
|
868
|
+
const start = Date.now()
|
|
869
|
+
try {
|
|
870
|
+
const product = await provider.lookup(parsed.normalized, parsed.type)
|
|
871
|
+
const durationMs = Date.now() - start
|
|
872
|
+
outcomes.push({
|
|
873
|
+
provider: provider.name,
|
|
874
|
+
found: Boolean(product),
|
|
875
|
+
durationMs,
|
|
876
|
+
product,
|
|
877
|
+
})
|
|
878
|
+
|
|
879
|
+
if (product) {
|
|
880
|
+
hits.push(product)
|
|
881
|
+
if (strategy === "first-hit") {
|
|
882
|
+
break
|
|
883
|
+
}
|
|
884
|
+
}
|
|
885
|
+
} catch (err) {
|
|
886
|
+
outcomes.push({
|
|
887
|
+
provider: provider.name,
|
|
888
|
+
found: false,
|
|
889
|
+
durationMs: Date.now() - start,
|
|
890
|
+
error: err instanceof Error ? err.message : "Provider lookup failed",
|
|
891
|
+
})
|
|
892
|
+
}
|
|
893
|
+
}
|
|
894
|
+
|
|
895
|
+
const mergedProduct =
|
|
896
|
+
strategy === "deep-merge" ? mergeNormalizedProducts(hits) : hits[0] || null
|
|
897
|
+
|
|
898
|
+
return {
|
|
899
|
+
barcode: parsed.normalized,
|
|
900
|
+
parsed,
|
|
901
|
+
found: Boolean(mergedProduct),
|
|
902
|
+
cached: false,
|
|
903
|
+
strategy,
|
|
904
|
+
product: mergedProduct,
|
|
905
|
+
outcomes,
|
|
906
|
+
}
|
|
907
|
+
}
|
|
908
|
+
|
|
909
|
+
/**
|
|
910
|
+
* Safely downloads an external product image buffer with SSRF & size checks (max 8MB).
|
|
911
|
+
*/
|
|
912
|
+
export async function downloadProductImageBuffer(
|
|
913
|
+
imageUrl: string,
|
|
914
|
+
timeoutMs = 5000
|
|
915
|
+
): Promise<{ buffer: Buffer; mimeType: string; filename: string } | null> {
|
|
916
|
+
const safeUrl = validateExternalImageUrl(imageUrl)
|
|
917
|
+
if (!safeUrl) {
|
|
918
|
+
return null
|
|
919
|
+
}
|
|
920
|
+
|
|
921
|
+
const controller = new AbortController()
|
|
922
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs)
|
|
923
|
+
try {
|
|
924
|
+
const response = await fetch(safeUrl, {
|
|
925
|
+
headers: { "User-Agent": DEFAULT_USER_AGENT },
|
|
926
|
+
signal: controller.signal,
|
|
927
|
+
})
|
|
928
|
+
if (!response.ok) {
|
|
929
|
+
return null
|
|
930
|
+
}
|
|
931
|
+
const contentType = response.headers.get("content-type") || "image/jpeg"
|
|
932
|
+
if (!contentType.startsWith("image/")) {
|
|
933
|
+
return null
|
|
934
|
+
}
|
|
935
|
+
const arrayBuffer = await response.arrayBuffer()
|
|
936
|
+
if (
|
|
937
|
+
arrayBuffer.byteLength === 0 ||
|
|
938
|
+
arrayBuffer.byteLength > 8 * 1024 * 1024
|
|
939
|
+
) {
|
|
940
|
+
return null
|
|
941
|
+
}
|
|
942
|
+
const ext = contentType.includes("png")
|
|
943
|
+
? "png"
|
|
944
|
+
: contentType.includes("webp")
|
|
945
|
+
? "webp"
|
|
946
|
+
: "jpg"
|
|
947
|
+
const filename = `barcode-${Date.now()}.${ext}`
|
|
948
|
+
return {
|
|
949
|
+
buffer: Buffer.from(arrayBuffer),
|
|
950
|
+
mimeType: contentType.split(";")[0] || "image/jpeg",
|
|
951
|
+
filename,
|
|
952
|
+
}
|
|
953
|
+
} catch {
|
|
954
|
+
return null
|
|
955
|
+
} finally {
|
|
956
|
+
clearTimeout(timer)
|
|
957
|
+
}
|
|
958
|
+
}
|