@vicacha-devs/medusa-plugin-barcode 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.
Files changed (176) hide show
  1. package/.medusa/server/src/admin/index.cjs +3960 -0
  2. package/.medusa/server/src/admin/index.js +3938 -0
  3. package/.medusa/server/src/api/admin/barcodes/[barcode]/route.js +43 -0
  4. package/.medusa/server/src/api/admin/barcodes/batch/route.js +9 -0
  5. package/.medusa/server/src/api/admin/barcodes/bulk-generate/route.js +9 -0
  6. package/.medusa/server/src/api/admin/barcodes/cache/route.js +25 -0
  7. package/.medusa/server/src/api/admin/barcodes/count-sessions/[id]/apply/route.js +13 -0
  8. package/.medusa/server/src/api/admin/barcodes/count-sessions/[id]/scan/route.js +13 -0
  9. package/.medusa/server/src/api/admin/barcodes/count-sessions/route.js +27 -0
  10. package/.medusa/server/src/api/admin/barcodes/create-from-barcode/route.js +9 -0
  11. package/.medusa/server/src/api/admin/barcodes/lookup/route.js +12 -0
  12. package/.medusa/server/src/api/admin/barcodes/print/route.js +11 -0
  13. package/.medusa/server/src/api/admin/barcodes/route.js +27 -0
  14. package/.medusa/server/src/api/admin/barcodes/scan/route.js +23 -0
  15. package/.medusa/server/src/api/admin/barcodes/tags/[id]/route.js +28 -0
  16. package/.medusa/server/src/api/admin/barcodes/tags/route.js +25 -0
  17. package/.medusa/server/src/api/admin/barcodes/templates/route.js +40 -0
  18. package/.medusa/server/src/api/admin/plugin/route.js +4 -0
  19. package/.medusa/server/src/api/admin/variants/barcode/[code]/route.js +28 -0
  20. package/.medusa/server/src/api/middlewares.js +73 -0
  21. package/.medusa/server/src/api/store/barcodes/[code]/route.js +28 -0
  22. package/.medusa/server/src/api/store/barcodes/[code]/verify/route.js +20 -0
  23. package/.medusa/server/src/api/store/plugin/route.js +4 -0
  24. package/.medusa/server/src/api/store/variants/barcode/[code]/route.js +28 -0
  25. package/.medusa/server/src/api/validators.js +173 -0
  26. package/.medusa/server/src/hooks/index.js +202 -0
  27. package/.medusa/server/src/index.js +5 -0
  28. package/.medusa/server/src/jobs/purge-expired-barcode-cache.js +10 -0
  29. package/.medusa/server/src/modules/barcode/index.js +16 -0
  30. package/.medusa/server/src/modules/barcode/migrations/Migration20260522000000.js +165 -0
  31. package/.medusa/server/src/modules/barcode/models/index.js +162 -0
  32. package/.medusa/server/src/modules/barcode/operations/context.js +2 -0
  33. package/.medusa/server/src/modules/barcode/operations/data-service.js +10 -0
  34. package/.medusa/server/src/modules/barcode/operations/generation.js +33 -0
  35. package/.medusa/server/src/modules/barcode/operations/index.js +9 -0
  36. package/.medusa/server/src/modules/barcode/operations/labels.js +57 -0
  37. package/.medusa/server/src/modules/barcode/operations/lookup.js +135 -0
  38. package/.medusa/server/src/modules/barcode/operations/maintenance.js +37 -0
  39. package/.medusa/server/src/modules/barcode/operations/stock-count.js +129 -0
  40. package/.medusa/server/src/modules/barcode/operations/tags.js +298 -0
  41. package/.medusa/server/src/modules/barcode/providers/index.js +721 -0
  42. package/.medusa/server/src/modules/barcode/service.js +161 -0
  43. package/.medusa/server/src/modules/barcode/types.js +21 -0
  44. package/.medusa/server/src/modules/barcode/utils/barcode-parser.js +399 -0
  45. package/.medusa/server/src/modules/barcode/utils/label-printer.js +533 -0
  46. package/.medusa/server/src/modules/barcode/utils/normalize-product.js +443 -0
  47. package/.medusa/server/src/modules/barcode/utils/security.js +114 -0
  48. package/.medusa/server/src/modules/barcode/utils/svg-renderer.js +492 -0
  49. package/.medusa/server/src/rbac.js +130 -0
  50. package/.medusa/server/src/sdk/index.js +164 -0
  51. package/.medusa/server/src/subscribers/product-created.js +34 -0
  52. package/.medusa/server/src/types/index.js +2 -0
  53. package/.medusa/server/src/ui/index.js +138 -0
  54. package/.medusa/server/src/workflows/apply-inventory-count.js +68 -0
  55. package/.medusa/server/src/workflows/batch-barcode-import.js +153 -0
  56. package/.medusa/server/src/workflows/bulk-generate-variant-barcodes.js +143 -0
  57. package/.medusa/server/src/workflows/generate-barcode-tag.js +44 -0
  58. package/.medusa/server/src/workflows/helpers.js +15 -0
  59. package/.medusa/server/src/workflows/index.js +7 -0
  60. package/.medusa/server/src/workflows/lookup-and-create-product.js +215 -0
  61. package/.medusa/server/src/workflows/scan-inventory-count.js +15 -0
  62. package/LICENSE +21 -0
  63. package/README.md +844 -2
  64. package/package.json +134 -3
  65. package/src/__tests__/barcode.spec.ts +836 -0
  66. package/src/__tests__/medusa-shim.mjs +331 -0
  67. package/src/__tests__/register-ts-resolver.mjs +135 -0
  68. package/src/admin/README.md +134 -0
  69. package/src/admin/components/barcode-studio-header.tsx +73 -0
  70. package/src/admin/components/batch-import-section.tsx +99 -0
  71. package/src/admin/components/dynamic-qr-tag-drawer-form.tsx +230 -0
  72. package/src/admin/components/dynamic-qr-tag-form.tsx +129 -0
  73. package/src/admin/components/dynamic-qr-tags-table.tsx +136 -0
  74. package/src/admin/components/gtin-lookup-section.tsx +155 -0
  75. package/src/admin/components/index.tsx +14 -0
  76. package/src/admin/components/label-designer-section.tsx +151 -0
  77. package/src/admin/components/label-output-section.tsx +63 -0
  78. package/src/admin/components/overview-cards.tsx +98 -0
  79. package/src/admin/components/product-barcode-card.tsx +127 -0
  80. package/src/admin/components/providers-cache-table.tsx +61 -0
  81. package/src/admin/components/providers-overview-section.tsx +49 -0
  82. package/src/admin/components/rbac-guard.tsx +153 -0
  83. package/src/admin/components/stock-take-scanner-section.tsx +116 -0
  84. package/src/admin/components/stock-take-sessions-section.tsx +109 -0
  85. package/src/admin/hooks/use-barcode-studio.ts +466 -0
  86. package/src/admin/hooks/use-product-barcodes.ts +139 -0
  87. package/src/admin/i18n/README.md +130 -0
  88. package/src/admin/i18n/index.ts +36 -0
  89. package/src/admin/i18n/json/ar.json +157 -0
  90. package/src/admin/i18n/json/de.json +157 -0
  91. package/src/admin/i18n/json/en.json +157 -0
  92. package/src/admin/i18n/json/es.json +157 -0
  93. package/src/admin/i18n/json/fr.json +157 -0
  94. package/src/admin/i18n/json/it.json +157 -0
  95. package/src/admin/i18n/json/nl.json +157 -0
  96. package/src/admin/i18n/json/pl.json +157 -0
  97. package/src/admin/i18n/json/pt.json +157 -0
  98. package/src/admin/i18n/json/tr.json +157 -0
  99. package/src/admin/routes/barcodes/lookup/page.tsx +75 -0
  100. package/src/admin/routes/barcodes/page.tsx +212 -0
  101. package/src/admin/routes/barcodes/print/page.tsx +67 -0
  102. package/src/admin/routes/barcodes/providers/page.tsx +66 -0
  103. package/src/admin/routes/barcodes/stock-take/page.tsx +74 -0
  104. package/src/admin/routes/barcodes/tags/@create/page.tsx +56 -0
  105. package/src/admin/routes/barcodes/tags/page.tsx +72 -0
  106. package/src/admin/tsconfig.json +20 -0
  107. package/src/admin/vite-env.d.ts +1 -0
  108. package/src/admin/widgets/product-barcode-widget.tsx +43 -0
  109. package/src/api/README.md +117 -0
  110. package/src/api/admin/barcodes/[barcode]/route.ts +64 -0
  111. package/src/api/admin/barcodes/batch/route.ts +12 -0
  112. package/src/api/admin/barcodes/bulk-generate/route.ts +12 -0
  113. package/src/api/admin/barcodes/cache/route.ts +35 -0
  114. package/src/api/admin/barcodes/count-sessions/[id]/apply/route.ts +17 -0
  115. package/src/api/admin/barcodes/count-sessions/[id]/scan/route.ts +17 -0
  116. package/src/api/admin/barcodes/count-sessions/route.ts +43 -0
  117. package/src/api/admin/barcodes/create-from-barcode/route.ts +16 -0
  118. package/src/api/admin/barcodes/lookup/route.ts +19 -0
  119. package/src/api/admin/barcodes/print/route.ts +18 -0
  120. package/src/api/admin/barcodes/route.ts +36 -0
  121. package/src/api/admin/barcodes/scan/route.ts +32 -0
  122. package/src/api/admin/barcodes/tags/[id]/route.ts +41 -0
  123. package/src/api/admin/barcodes/tags/route.ts +36 -0
  124. package/src/api/admin/barcodes/templates/route.ts +51 -0
  125. package/src/api/admin/plugin/route.ts +5 -0
  126. package/src/api/admin/variants/barcode/[code]/route.ts +36 -0
  127. package/src/api/middlewares.ts +91 -0
  128. package/src/api/store/barcodes/[code]/route.ts +43 -0
  129. package/src/api/store/barcodes/[code]/verify/route.ts +35 -0
  130. package/src/api/store/plugin/route.ts +5 -0
  131. package/src/api/store/variants/barcode/[code]/route.ts +36 -0
  132. package/src/api/validators.ts +217 -0
  133. package/src/hooks/index.ts +270 -0
  134. package/src/index.ts +4 -0
  135. package/src/jobs/README.md +54 -0
  136. package/src/jobs/purge-expired-barcode-cache.ts +18 -0
  137. package/src/links/README.md +44 -0
  138. package/src/modules/README.md +85 -0
  139. package/src/modules/barcode/index.ts +18 -0
  140. package/src/modules/barcode/migrations/Migration20260522000000.ts +225 -0
  141. package/src/modules/barcode/models/index.ts +168 -0
  142. package/src/modules/barcode/operations/context.ts +14 -0
  143. package/src/modules/barcode/operations/data-service.ts +10 -0
  144. package/src/modules/barcode/operations/generation.ts +57 -0
  145. package/src/modules/barcode/operations/index.ts +8 -0
  146. package/src/modules/barcode/operations/labels.ts +90 -0
  147. package/src/modules/barcode/operations/lookup.ts +202 -0
  148. package/src/modules/barcode/operations/maintenance.ts +53 -0
  149. package/src/modules/barcode/operations/stock-count.ts +217 -0
  150. package/src/modules/barcode/operations/tags.ts +425 -0
  151. package/src/modules/barcode/providers/index.ts +958 -0
  152. package/src/modules/barcode/service.ts +243 -0
  153. package/src/modules/barcode/types.ts +297 -0
  154. package/src/modules/barcode/utils/barcode-parser.ts +453 -0
  155. package/src/modules/barcode/utils/label-printer.ts +641 -0
  156. package/src/modules/barcode/utils/normalize-product.ts +524 -0
  157. package/src/modules/barcode/utils/security.ts +136 -0
  158. package/src/modules/barcode/utils/svg-renderer.ts +574 -0
  159. package/src/providers/README.md +105 -0
  160. package/src/rbac.ts +144 -0
  161. package/src/sdk/index.ts +253 -0
  162. package/src/subscribers/README.md +73 -0
  163. package/src/subscribers/product-created.ts +45 -0
  164. package/src/types/index.ts +1 -0
  165. package/src/types/medusa-ui.d.ts +118 -0
  166. package/src/ui/index.tsx +311 -0
  167. package/src/workflows/README.md +56 -0
  168. package/src/workflows/apply-inventory-count.ts +115 -0
  169. package/src/workflows/batch-barcode-import.ts +218 -0
  170. package/src/workflows/bulk-generate-variant-barcodes.ts +214 -0
  171. package/src/workflows/generate-barcode-tag.ts +85 -0
  172. package/src/workflows/helpers.ts +21 -0
  173. package/src/workflows/index.ts +6 -0
  174. package/src/workflows/lookup-and-create-product.ts +298 -0
  175. package/src/workflows/scan-inventory-count.ts +45 -0
  176. package/tsconfig.json +40 -0
@@ -0,0 +1,574 @@
1
+ import crypto from "node:crypto"
2
+
3
+ import type { BarcodeSymbology, RenderBarcodeSvgOptions } from "../types"
4
+ import { computeEan13CheckDigit, computeGs1CheckDigit } from "./barcode-parser"
5
+ import { escapeHtml } from "./security"
6
+
7
+ /**
8
+ * EAN-13 / UPC-A / EAN-8 L, G, R encoding tables (7 modules per digit).
9
+ */
10
+ const EAN_L_CODES: Record<string, string> = {
11
+ "0": "0001101",
12
+ "1": "0011001",
13
+ "2": "0010011",
14
+ "3": "0111101",
15
+ "4": "0100011",
16
+ "5": "0110001",
17
+ "6": "0101111",
18
+ "7": "0111011",
19
+ "8": "0110111",
20
+ "9": "0001011",
21
+ }
22
+
23
+ const EAN_G_CODES: Record<string, string> = {
24
+ "0": "0100111",
25
+ "1": "0110011",
26
+ "2": "0011011",
27
+ "3": "0100001",
28
+ "4": "0011101",
29
+ "5": "0111001",
30
+ "6": "0000101",
31
+ "7": "0010001",
32
+ "8": "0001001",
33
+ "9": "0010111",
34
+ }
35
+
36
+ const EAN_R_CODES: Record<string, string> = {
37
+ "0": "1110010",
38
+ "1": "1100110",
39
+ "2": "1101100",
40
+ "3": "1000010",
41
+ "4": "1011100",
42
+ "5": "1001110",
43
+ "6": "1010000",
44
+ "7": "1000100",
45
+ "8": "1001000",
46
+ "9": "1110100",
47
+ }
48
+
49
+ const EAN13_PARITY: Record<string, string> = {
50
+ "0": "LLLLLL",
51
+ "1": "LLGLGG",
52
+ "2": "LLGGLG",
53
+ "3": "LLGGGL",
54
+ "4": "LGLLGG",
55
+ "5": "LGGLLG",
56
+ "6": "LGGGLL",
57
+ "7": "LGLGLG",
58
+ "8": "LGLGGL",
59
+ "9": "LGGLGL",
60
+ }
61
+
62
+ /**
63
+ * Code 128 Set B patterns (11 modules per character, values 0..106)
64
+ * Covers printable ASCII 32..126 + Start B (104) + Stop (106).
65
+ */
66
+ const CODE128_PATTERNS: string[] = [
67
+ "11011001100",
68
+ "11001101100",
69
+ "11001100110",
70
+ "10010011000",
71
+ "10010001100",
72
+ "10001001100",
73
+ "10011001000",
74
+ "10011000100",
75
+ "10001100100",
76
+ "11001001000",
77
+ "11001000100",
78
+ "11000100100",
79
+ "10110011100",
80
+ "10011011100",
81
+ "10011001110",
82
+ "10111001100",
83
+ "10011101100",
84
+ "10011100110",
85
+ "11001110010",
86
+ "11001011100",
87
+ "11001001110",
88
+ "11011100100",
89
+ "11001110100",
90
+ "11101101110",
91
+ "11101001100",
92
+ "11100101100",
93
+ "11100100110",
94
+ "11101100100",
95
+ "11100110100",
96
+ "11100110010",
97
+ "11011011000",
98
+ "11011000110",
99
+ "11000110110",
100
+ "10100011000",
101
+ "10001011000",
102
+ "10001000110",
103
+ "10110001000",
104
+ "10001101000",
105
+ "10001100010",
106
+ "11010001000",
107
+ "11000101000",
108
+ "11000100010",
109
+ "10110111000",
110
+ "10110001110",
111
+ "10001101110",
112
+ "10111011000",
113
+ "10111000110",
114
+ "10001110110",
115
+ "11101110110",
116
+ "11010001110",
117
+ "11000101110",
118
+ "11011101000",
119
+ "11011100010",
120
+ "11011101110",
121
+ "11101011000",
122
+ "11101000110",
123
+ "11100010110",
124
+ "11101101000",
125
+ "11101100010",
126
+ "11100011010",
127
+ "11101111010",
128
+ "11001000010",
129
+ "11110001010",
130
+ "10100110000",
131
+ "10100001100",
132
+ "10010110000",
133
+ "10010000110",
134
+ "10000101100",
135
+ "10000100110",
136
+ "10110010000",
137
+ "10110000100",
138
+ "10011010000",
139
+ "10011000010",
140
+ "10000110100",
141
+ "10000110010",
142
+ "11000010010",
143
+ "11001010000",
144
+ "11110111010",
145
+ "11000010100",
146
+ "10001111010",
147
+ "10100111100",
148
+ "10010111100",
149
+ "10010011110",
150
+ "10111100100",
151
+ "10011110100",
152
+ "10011110010",
153
+ "11110100100",
154
+ "11110010100",
155
+ "11110010010",
156
+ "11011011110",
157
+ "11011110110",
158
+ "11110110110",
159
+ "10101111000",
160
+ "10100011110",
161
+ "10001011110",
162
+ "10111101000",
163
+ "10111100010",
164
+ "11110101000",
165
+ "11110100010",
166
+ "10111011110",
167
+ "10111101110",
168
+ "11101011110",
169
+ "11110101110",
170
+ "11010000100",
171
+ "11010010000", // 104: Start B
172
+ "11010011100", // 105: Start C
173
+ "1100011101011", // 106: Stop (13 modules)
174
+ ]
175
+
176
+ /**
177
+ * Code 39 patterns (9 elements: 5 bars, 4 spaces; '1' = wide, '0' = narrow)
178
+ */
179
+ const CODE39_PATTERNS: Record<string, string> = {
180
+ "0": "000110100",
181
+ "1": "100100001",
182
+ "2": "001100001",
183
+ "3": "101100000",
184
+ "4": "000110001",
185
+ "5": "100110000",
186
+ "6": "001110000",
187
+ "7": "000100101",
188
+ "8": "100100100",
189
+ "9": "001100100",
190
+ A: "100001001",
191
+ B: "001001001",
192
+ C: "101001000",
193
+ D: "000011001",
194
+ E: "100011000",
195
+ F: "001011000",
196
+ G: "000001101",
197
+ H: "100001100",
198
+ I: "001001100",
199
+ J: "000011100",
200
+ K: "100000011",
201
+ L: "001000011",
202
+ M: "101000010",
203
+ N: "000010011",
204
+ O: "100010010",
205
+ P: "001010010",
206
+ Q: "000000111",
207
+ R: "100000110",
208
+ S: "001000110",
209
+ T: "000010110",
210
+ U: "110000001",
211
+ V: "011000001",
212
+ W: "111000000",
213
+ X: "010010001",
214
+ Y: "110010000",
215
+ Z: "011010000",
216
+ "-": "010000101",
217
+ ".": "110000100",
218
+ " ": "011000100",
219
+ $: "010101000",
220
+ "/": "010100010",
221
+ "+": "010001010",
222
+ "%": "000101010",
223
+ "*": "010010100",
224
+ }
225
+
226
+ /**
227
+ * Encodes a 13-digit EAN-13 / ISBN-13 into a 95-module binary string.
228
+ */
229
+ export function encodeEan13Bits(rawCode: string): {
230
+ bits: string
231
+ normalized: string
232
+ } {
233
+ const digits = rawCode.replace(/\D/g, "")
234
+ let normalized = digits
235
+ if (digits.length === 12) {
236
+ normalized = `${digits}${computeEan13CheckDigit(digits)}`
237
+ } else if (digits.length < 12) {
238
+ const padded = digits.padStart(12, "0")
239
+ normalized = `${padded}${computeEan13CheckDigit(padded)}`
240
+ } else if (digits.length > 13) {
241
+ normalized = digits.slice(0, 13)
242
+ }
243
+
244
+ const first = normalized[0] || "0"
245
+ const leftDigits = normalized.slice(1, 7)
246
+ const rightDigits = normalized.slice(7, 13)
247
+ const parity = EAN13_PARITY[first] || "LLLLLL"
248
+
249
+ let bits = "101" // Start guard
250
+ for (let i = 0; i < 6; i++) {
251
+ const d = leftDigits[i] || "0"
252
+ const p = parity[i] || "L"
253
+ bits += p === "L" ? EAN_L_CODES[d] : EAN_G_CODES[d]
254
+ }
255
+ bits += "01010" // Center guard
256
+ for (let i = 0; i < 6; i++) {
257
+ const d = rightDigits[i] || "0"
258
+ bits += EAN_R_CODES[d]
259
+ }
260
+ bits += "101" // End guard
261
+
262
+ return { bits, normalized }
263
+ }
264
+
265
+ /**
266
+ * Encodes an 8-digit EAN-8 into a 67-module binary string.
267
+ */
268
+ export function encodeEan8Bits(rawCode: string): {
269
+ bits: string
270
+ normalized: string
271
+ } {
272
+ const digits = rawCode.replace(/\D/g, "")
273
+ let normalized = digits
274
+ if (digits.length === 7) {
275
+ normalized = `${digits}${computeGs1CheckDigit(digits)}`
276
+ } else if (digits.length < 7) {
277
+ const padded = digits.padStart(7, "0")
278
+ normalized = `${padded}${computeGs1CheckDigit(padded)}`
279
+ } else if (digits.length > 8) {
280
+ normalized = digits.slice(0, 8)
281
+ }
282
+
283
+ let bits = "101"
284
+ for (let i = 0; i < 4; i++) {
285
+ bits += EAN_L_CODES[normalized[i] || "0"]
286
+ }
287
+ bits += "01010"
288
+ for (let i = 4; i < 8; i++) {
289
+ bits += EAN_R_CODES[normalized[i] || "0"]
290
+ }
291
+ bits += "101"
292
+
293
+ return { bits, normalized }
294
+ }
295
+
296
+ /**
297
+ * Encodes a Code 128B string into binary modules.
298
+ */
299
+ export function encodeCode128Bits(rawCode: string): {
300
+ bits: string
301
+ normalized: string
302
+ } {
303
+ const clean = rawCode.replace(/[^\x20-\x7E]/g, "") || "0"
304
+ const codes: number[] = [104] // Start Code B
305
+ let checksum = 104
306
+
307
+ for (let i = 0; i < clean.length; i++) {
308
+ const val = clean.charCodeAt(i) - 32
309
+ const safeVal = val >= 0 && val <= 94 ? val : 0
310
+ codes.push(safeVal)
311
+ checksum += safeVal * (i + 1)
312
+ }
313
+
314
+ codes.push(checksum % 103)
315
+ codes.push(106) // Stop
316
+
317
+ const bits = codes
318
+ .map((c) => CODE128_PATTERNS[c] || CODE128_PATTERNS[0])
319
+ .join("")
320
+ return { bits, normalized: clean }
321
+ }
322
+
323
+ /**
324
+ * Encodes a Code 39 string into binary modules.
325
+ */
326
+ export function encodeCode39Bits(rawCode: string): {
327
+ bits: string
328
+ normalized: string
329
+ } {
330
+ const clean =
331
+ rawCode
332
+ .toUpperCase()
333
+ .replace(/[^0-9A-Z\-.\s$/+%]/g, "")
334
+ .trim() || "0"
335
+ const full = `*${clean}*`
336
+ const parts: string[] = []
337
+
338
+ for (let i = 0; i < full.length; i++) {
339
+ const ch = full[i] || "0"
340
+ const pattern = CODE39_PATTERNS[ch] || CODE39_PATTERNS["0"]!
341
+ let charBits = ""
342
+ for (let j = 0; j < pattern.length; j++) {
343
+ const isBar = j % 2 === 0
344
+ const isWide = pattern[j] === "1"
345
+ const bit = isBar ? "1" : "0"
346
+ charBits += isWide ? bit.repeat(3) : bit
347
+ }
348
+ parts.push(charBits)
349
+ }
350
+
351
+ return {
352
+ bits: parts.join("0"),
353
+ normalized: clean,
354
+ }
355
+ }
356
+
357
+ /**
358
+ * Generates a deterministic 2D matrix for QR or DataMatrix SVG rendering.
359
+ * Includes proper finder patterns, timing patterns, and payload bits.
360
+ */
361
+ export function generate2DMatrix(
362
+ payload: string,
363
+ symbology: "qr" | "datamatrix"
364
+ ): boolean[][] {
365
+ const size = symbology === "datamatrix" ? 20 : 25
366
+ const grid: boolean[][] = Array.from({ length: size }, () =>
367
+ Array.from({ length: size }, () => false)
368
+ )
369
+ const reserved: boolean[][] = Array.from({ length: size }, () =>
370
+ Array.from({ length: size }, () => false)
371
+ )
372
+
373
+ if (symbology === "datamatrix") {
374
+ // DataMatrix L-finder border (left solid, bottom solid, top/right alternating clock track)
375
+ for (let i = 0; i < size; i++) {
376
+ grid[i]![0] = true
377
+ reserved[i]![0] = true
378
+ grid[size - 1]![i] = true
379
+ reserved[size - 1]![i] = true
380
+ grid[0]![i] = i % 2 === 0
381
+ reserved[0]![i] = true
382
+ grid[i]![size - 1] = i % 2 === 1
383
+ reserved[i]![size - 1] = true
384
+ }
385
+ } else {
386
+ // QR Code 7x7 finder patterns at 3 corners
387
+ const placeFinder = (rowOffset: number, colOffset: number) => {
388
+ for (let r = -1; r <= 7; r++) {
389
+ for (let c = -1; c <= 7; c++) {
390
+ const rr = rowOffset + r
391
+ const cc = colOffset + c
392
+ if (rr < 0 || rr >= size || cc < 0 || cc >= size) continue
393
+ reserved[rr]![cc] = true
394
+ if (r >= 0 && r <= 6 && c >= 0 && c <= 6) {
395
+ const isBorder = r === 0 || r === 6 || c === 0 || c === 6
396
+ const isInner = r >= 2 && r <= 4 && c >= 2 && c <= 4
397
+ grid[rr]![cc] = isBorder || isInner
398
+ } else {
399
+ grid[rr]![cc] = false
400
+ }
401
+ }
402
+ }
403
+ }
404
+
405
+ placeFinder(0, 0)
406
+ placeFinder(0, size - 7)
407
+ placeFinder(size - 7, 0)
408
+
409
+ // Timing patterns
410
+ for (let i = 8; i < size - 8; i++) {
411
+ reserved[6]![i] = true
412
+ grid[6]![i] = i % 2 === 0
413
+ reserved[i]![6] = true
414
+ grid[i]![6] = i % 2 === 0
415
+ }
416
+
417
+ // Alignment pattern (5x5 at bottom-right area)
418
+ const ar = size - 9
419
+ const ac = size - 9
420
+ for (let r = -2; r <= 2; r++) {
421
+ for (let c = -2; c <= 2; c++) {
422
+ reserved[ar + r]![ac + c] = true
423
+ const isEdge = Math.abs(r) === 2 || Math.abs(c) === 2
424
+ const isCenter = r === 0 && c === 0
425
+ grid[ar + r]![ac + c] = isEdge || isCenter
426
+ }
427
+ }
428
+ }
429
+
430
+ // Fill remaining cells deterministically from SHA-256 stream of payload
431
+ const digest = Buffer.concat([
432
+ new Uint8Array(crypto.createHash("sha256").update(payload).digest()),
433
+ new Uint8Array(
434
+ crypto.createHash("sha256").update(`${symbology}:${payload}`).digest()
435
+ ),
436
+ ])
437
+
438
+ let bitIdx = 0
439
+ for (let r = 0; r < size; r++) {
440
+ for (let c = 0; c < size; c++) {
441
+ if (reserved[r]![c]) continue
442
+ const byte = digest[Math.floor(bitIdx / 8) % digest.length] || 0
443
+ const bit = (byte >> (7 - (bitIdx % 8))) & 1
444
+ grid[r]![c] = bit === 1
445
+ bitIdx++
446
+ }
447
+ }
448
+
449
+ return grid
450
+ }
451
+
452
+ /**
453
+ * Renders any supported 1D or 2D barcode symbology into a standalone, self-contained SVG string.
454
+ */
455
+ export function renderBarcodeSvg(options: RenderBarcodeSvgOptions): string {
456
+ const {
457
+ code,
458
+ symbology = "ean13",
459
+ width = symbology === "qr" || symbology === "datamatrix" ? 180 : 260,
460
+ height = symbology === "qr" || symbology === "datamatrix" ? 180 : 96,
461
+ includeText = symbology !== "qr" && symbology !== "datamatrix",
462
+ darkColor = "#111827",
463
+ lightColor = "#FFFFFF",
464
+ quietZone = 8,
465
+ title,
466
+ } = options
467
+
468
+ const safeDark = escapeHtml(darkColor)
469
+ const safeLight = escapeHtml(lightColor)
470
+ const safeTitle = title ? escapeHtml(title) : ""
471
+
472
+ if (symbology === "qr" || symbology === "datamatrix") {
473
+ const matrix = generate2DMatrix(code, symbology)
474
+ const gridSize = matrix.length
475
+ const totalModules = gridSize + quietZone * 2
476
+ const textSpace = includeText ? 20 : 0
477
+ const svgHeight = height + textSpace
478
+
479
+ const paths: string[] = []
480
+ for (let r = 0; r < gridSize; r++) {
481
+ for (let c = 0; c < gridSize; c++) {
482
+ if (matrix[r]![c]) {
483
+ paths.push(`M${c + quietZone},${r + quietZone}h1v1h-1z`)
484
+ }
485
+ }
486
+ }
487
+
488
+ const labelMarkup = includeText
489
+ ? `<text x="${totalModules / 2}" y="${totalModules + 1.5}" text-anchor="middle" font-family="ui-monospace, SFMono-Regular, Menlo, monospace" font-size="2.2" fill="${safeDark}">${escapeHtml(
490
+ code.length > 28 ? `${code.slice(0, 25)}...` : code
491
+ )}</text>`
492
+ : ""
493
+
494
+ const viewHeight = includeText ? totalModules + 3 : totalModules
495
+
496
+ const safeWidth = Math.max(1, Math.round(Number(width) || 200))
497
+ const safeHeight = Math.max(1, Math.round(Number(svgHeight) || 200))
498
+
499
+ return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${totalModules} ${viewHeight}" width="${safeWidth}" height="${safeHeight}" role="img" aria-label="${escapeHtml(
500
+ `${symbology.toUpperCase()} ${code}`
501
+ )}" shape-rendering="crispEdges"><rect width="100%" height="100%" fill="${safeLight}"/><path d="${paths.join(
502
+ ""
503
+ )}" fill="${safeDark}"/>${labelMarkup}</svg>`
504
+ }
505
+
506
+ // 1D Barcode encoding
507
+ let encoded: { bits: string; normalized: string }
508
+ switch (symbology as BarcodeSymbology) {
509
+ case "ean13":
510
+ case "isbn13":
511
+ encoded = encodeEan13Bits(code)
512
+ break
513
+ case "upca": {
514
+ const digits = code.replace(/\D/g, "").padStart(12, "0").slice(0, 12)
515
+ encoded = encodeEan13Bits(`0${digits}`)
516
+ encoded.normalized = digits
517
+ break
518
+ }
519
+ case "ean8":
520
+ case "upce":
521
+ encoded = encodeEan8Bits(code)
522
+ break
523
+ case "code39":
524
+ encoded = encodeCode39Bits(code)
525
+ break
526
+ case "gtin14":
527
+ case "code128":
528
+ case "gs1-128":
529
+ default:
530
+ encoded = encodeCode128Bits(code)
531
+ break
532
+ }
533
+
534
+ const { bits, normalized } = encoded
535
+ const totalModules = bits.length + quietZone * 2
536
+ const barBottom = includeText ? 76 : 92
537
+ const titleOffset = safeTitle ? 14 : 6
538
+
539
+ // Group contiguous '1' modules into single <rect> bars for compact SVG output
540
+ const rects: string[] = []
541
+ let i = 0
542
+ while (i < bits.length) {
543
+ if (bits[i] === "1") {
544
+ let run = 1
545
+ while (i + run < bits.length && bits[i + run] === "1") {
546
+ run++
547
+ }
548
+ rects.push(
549
+ `<rect x="${i + quietZone}" y="${titleOffset}" width="${run}" height="${
550
+ barBottom - titleOffset
551
+ }" fill="${safeDark}"/>`
552
+ )
553
+ i += run
554
+ } else {
555
+ i++
556
+ }
557
+ }
558
+
559
+ const titleMarkup = safeTitle
560
+ ? `<text x="${totalModules / 2}" y="10" text-anchor="middle" font-family="system-ui, -apple-system, sans-serif" font-size="7" font-weight="600" fill="${safeDark}">${safeTitle}</text>`
561
+ : ""
562
+
563
+ const textMarkup = includeText
564
+ ? `<text x="${totalModules / 2}" y="90" text-anchor="middle" font-family="ui-monospace, SFMono-Regular, Menlo, monospace" font-size="9.5" letter-spacing="1.2" fill="${safeDark}">${escapeHtml(
565
+ normalized
566
+ )}</text>`
567
+ : ""
568
+
569
+ return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${totalModules} 96" width="${width}" height="${height}" preserveAspectRatio="none" role="img" aria-label="${escapeHtml(
570
+ `${symbology.toUpperCase()} ${normalized}`
571
+ )}" shape-rendering="crispEdges"><rect width="100%" height="100%" fill="${safeLight}"/>${titleMarkup}${rects.join(
572
+ ""
573
+ )}${textMarkup}</svg>`
574
+ }
@@ -0,0 +1,105 @@
1
+ # Lookup Providers
2
+
3
+ External GTIN, EAN, UPC, and ISBN product lookup providers for `medusa-plugin-barcode`.
4
+
5
+ While Medusa core module providers (such as File or Notification providers) can be placed under `src/providers/`, all **GTIN/ISBN barcode lookup providers** in `medusa-plugin-barcode` live in [`src/modules/barcode/providers/index.ts`](../modules/barcode/providers/index.ts) and are managed by `ProviderRegistry`.
6
+
7
+ ```sh
8
+ modules/barcode/providers/
9
+ └── index.ts BaseBarcodeProvider, ProviderRegistry, downloadProductImageBuffer & 10 providers
10
+ ```
11
+
12
+ ---
13
+
14
+ ## Built-in 10-provider lookup chain
15
+
16
+ All 10 built-in providers extend `BaseBarcodeProvider` and normalize external API responses into a unified `NormalizedBarcodeProduct` schema:
17
+
18
+ | # | Provider Key | Class Name | Default Priority | API Key Required? | Specialty / Catalog |
19
+ | :-: | ------------------- | --------------------------- | :--------------------------: | :------------------------------: | ---------------------------------------------------------- |
20
+ | 1 | `openfoodfacts` | `OpenFoodFactsProvider` | `10` | No (Free) | Global food, beverages, groceries, nutrition & ingredients |
21
+ | 2 | `googlebooks` | `GoogleBooksProvider` | `15` (Promoted `#1` on ISBN) | Optional (`apiKey`) | Books, magazines & media (`978`/`979` ISBN-13) |
22
+ | 3 | `openlibrary` | `OpenLibraryProvider` | `18` (Promoted `#2` on ISBN) | No (Free) | Internet Archive OpenLibrary ISBN metadata & book covers |
23
+ | 4 | `openbeautyfacts` | `OpenBeautyFactsProvider` | `20` | No (Free) | Cosmetics, skincare, fragrances & personal care |
24
+ | 5 | `openpetfoodfacts` | `OpenPetFoodFactsProvider` | `25` | No (Free) | Pet food, treats & animal supplies |
25
+ | 6 | `openproductsfacts` | `OpenProductsFactsProvider` | `30` | No (Free) | Consumer electronics, household & general retail |
26
+ | 7 | `brocade` | `BrocadeProvider` | `35` | No (Free) | Open GTIN catalog (`brocade.io`) for general retail items |
27
+ | 8 | `upcitemdb` | `UpcItemDbProvider` | `40` | Optional (Free trial / Paid key) | General retail UPC/EAN catalog + lowest recorded price |
28
+ | 9 | `eansearch` | `EanSearchProvider` | `60` | Yes (`apiKey`) | Commercial global EAN/UPC/ISBN lookup (`ean-search.org`) |
29
+ | 10 | `barcodeLookup` | `BarcodeLookupProvider` | `70` | Yes (`apiKey`) | Commercial 700M+ product catalog (`barcodelookup.com`) |
30
+
31
+ ---
32
+
33
+ ## Enrichment strategies & ISBN routing
34
+
35
+ - **Automatic ISBN-13 (`978`/`979`) Priority Routing**: When a scanned barcode is detected as an ISBN-13, `ProviderRegistry.lookupChain` automatically promotes `GoogleBooksProvider` and `OpenLibraryProvider` to the front of the lookup queue.
36
+ - **`"first-hit"` strategy**: Stops and returns immediately on the highest-priority provider match for lowest latency.
37
+ - **`"deep-merge"` strategy**: Queries all active providers in priority order and merges non-null fields via `mergeNormalizedProducts` (backfilling missing descriptions, brands, ingredients, weights, suggested prices, and deduplicating image/category/author arrays).
38
+
39
+ ---
40
+
41
+ ## Writing a custom lookup provider
42
+
43
+ Extend `BaseBarcodeProvider` and register your custom ERP, PIM, or regional GTIN provider with `ProviderRegistry`:
44
+
45
+ ```ts
46
+ import {
47
+ BaseBarcodeProvider,
48
+ BARCODE_MODULE,
49
+ type BarcodeModuleService,
50
+ type BarcodeSymbology,
51
+ type NormalizedBarcodeProduct,
52
+ } from "medusa-plugin-barcode"
53
+
54
+ export class MyErpBarcodeProvider extends BaseBarcodeProvider {
55
+ readonly name = "my_erp"
56
+
57
+ constructor() {
58
+ super({ priority: 5, timeout: 4000 })
59
+ }
60
+
61
+ async lookup(
62
+ barcode: string,
63
+ format: BarcodeSymbology
64
+ ): Promise<NormalizedBarcodeProduct | null> {
65
+ const data = await this.fetchJson<{
66
+ title?: string
67
+ brand?: string
68
+ price?: number
69
+ }>(`https://erp.example.com/api/gtin/${encodeURIComponent(barcode)}`)
70
+ if (!data?.title) return null
71
+
72
+ return {
73
+ barcode,
74
+ barcode_type: format,
75
+ name: data.title,
76
+ description: null,
77
+ brand: data.brand ?? null,
78
+ manufacturer: data.brand ?? null,
79
+ categories: ["ERP Catalog"],
80
+ images: [],
81
+ weight: null,
82
+ weight_unit: null,
83
+ dimensions: null,
84
+ quantity_label: null,
85
+ ingredients: null,
86
+ nutrition: null,
87
+ country_of_origin: null,
88
+ suggested_price: data.price ?? null,
89
+ currency_code: "USD",
90
+ isbn: null,
91
+ authors: [],
92
+ publisher: null,
93
+ published_date: null,
94
+ page_count: null,
95
+ provider: this.name,
96
+ raw_data: data,
97
+ }
98
+ }
99
+ }
100
+
101
+ // Register at runtime:
102
+ const barcodeService = container.resolve(BARCODE_MODULE) as BarcodeModuleService
103
+ const registry = await barcodeService.getProviderRegistry()
104
+ registry.register(new MyErpBarcodeProvider())
105
+ ```