qrcodesolid 0.0.0 → 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 (52) hide show
  1. package/README.md +493 -2
  2. package/dist/color-parse-empty.d.ts +6 -0
  3. package/dist/color-parse-empty.js +7 -0
  4. package/dist/color-parse.d.ts +8 -0
  5. package/dist/color-parse.js +49 -0
  6. package/dist/index.d.ts +372 -0
  7. package/dist/index.js +2640 -0
  8. package/dist/paint-ChCPh-rm.d.ts +29 -0
  9. package/dist/payload.d.ts +53 -0
  10. package/dist/payload.js +93 -0
  11. package/dist/server.d.ts +399 -0
  12. package/dist/server.js +2833 -0
  13. package/dist/source/components/GradientDef.jsx +19 -0
  14. package/dist/source/components/QRCode.jsx +10 -0
  15. package/dist/source/components/QRCodeCanvas.jsx +72 -0
  16. package/dist/source/components/QRCodeSVG.jsx +57 -0
  17. package/dist/source/core/caption.js +77 -0
  18. package/dist/source/core/color-names.js +34 -0
  19. package/dist/source/core/color-parse-empty.js +5 -0
  20. package/dist/source/core/color-parse.js +41 -0
  21. package/dist/source/core/encode.js +120 -0
  22. package/dist/source/core/logo.js +90 -0
  23. package/dist/source/core/options.js +56 -0
  24. package/dist/source/core/output.js +23 -0
  25. package/dist/source/core/paint.js +30 -0
  26. package/dist/source/core/path.js +46 -0
  27. package/dist/source/core/qrcodegen.js +875 -0
  28. package/dist/source/core/scene.js +141 -0
  29. package/dist/source/core/stages.js +24 -0
  30. package/dist/source/core/warnings.js +38 -0
  31. package/dist/source/export/index.js +105 -0
  32. package/dist/source/index.js +16 -0
  33. package/dist/source/payload/contact.js +42 -0
  34. package/dist/source/payload/escape.js +3 -0
  35. package/dist/source/payload/index.js +3 -0
  36. package/dist/source/payload/message.js +19 -0
  37. package/dist/source/payload/place.js +40 -0
  38. package/dist/source/primitives/createColorScheme.js +18 -0
  39. package/dist/source/primitives/createPixelRatio.js +25 -0
  40. package/dist/source/primitives/createQRCode.js +47 -0
  41. package/dist/source/render/canvas.js +46 -0
  42. package/dist/source/render/color.js +63 -0
  43. package/dist/source/render/image.js +123 -0
  44. package/dist/source/render/svg-string.js +55 -0
  45. package/dist/source/shapes/bars.js +50 -0
  46. package/dist/source/shapes/finders.js +30 -0
  47. package/dist/source/shapes/frames.js +62 -0
  48. package/dist/source/shapes/modules.js +39 -0
  49. package/dist/source/shapes/types.js +8 -0
  50. package/llms.txt +117 -0
  51. package/package.json +95 -6
  52. package/skills/qrcodesolid/SKILL.md +101 -0
package/dist/server.js ADDED
@@ -0,0 +1,2833 @@
1
+ import { escape as escape$1, isDev, isServer, memo, scope, ssr, ssrAttribute, ssrElement, ssrElementAttribute, ssrGroup, ssrHydrationKey } from "@solidjs/web";
2
+ import { For, Match, Show, Switch, createEffect, createMemo, createSignal, createUniqueId, omit, onSettled } from "solid-js";
3
+ import { parseColor } from "#color-parse";
4
+ // src/core/caption.ts
5
+ function toCaptionShape(caption) {
6
+ if (!caption) return void 0;
7
+ const { color: _color, ...shape } = caption;
8
+ return shape;
9
+ }
10
+ const sameCaptionShape = (a, b) => a === b || !!a && !!b && a.text === b.text && a.position === b.position && a.fontSize === b.fontSize && a.fontFamily === b.fontFamily && a.fontWeight === b.fontWeight;
11
+ const minFontSize = 1;
12
+ /** East Asian wide ranges and the main emoji blocks, by code point. */
13
+ const isWide = (c) => c >= 4352 && c <= 4447 || c >= 11904 && c <= 42191 || c >= 44032 && c <= 55203 || c >= 63744 && c <= 64255 || c >= 65072 && c <= 65103 || c >= 65280 && c <= 65376 || c >= 65504 && c <= 65510 || c >= 127744 && c <= 129791 || c >= 131072 && c <= 262141;
14
+ function estimateTextWidth(text, fontSize) {
15
+ let [chars, wide] = [0, 0];
16
+ for (const char of text) {
17
+ chars++;
18
+ if (isWide(char.codePointAt(0))) wide++;
19
+ }
20
+ return ((chars - wide) * .6 + wide) * fontSize;
21
+ }
22
+ /**
23
+ * Lowers `fontSize` until the text fits `width`, but not below 1 module.
24
+ * `overflows` is true when the text is still too wide at that size.
25
+ */
26
+ function fitFontSize(text, fontSize, width) {
27
+ const fit = width / estimateTextWidth(text, 1);
28
+ if (fontSize <= fit) return {
29
+ fontSize,
30
+ overflows: false
31
+ };
32
+ const fitted = Math.max(fit, Math.min(fontSize, minFontSize));
33
+ return {
34
+ fontSize: fitted,
35
+ overflows: fitted > fit
36
+ };
37
+ }
38
+ /** The dev warning for `subject` when its fitted text still overflows `width`, else undefined. */
39
+ function overflowWarning(subject, text, fitted, width, space) {
40
+ if (!fitted.overflows) return void 0;
41
+ const wide = Math.round(estimateTextWidth(text, fitted.fontSize));
42
+ return `The ${subject} was shrunk to fontSize ${fitted.fontSize}, the minimum, and is still about ${wide} modules wide, wider than ${space} (${width} modules); shorten it.`;
43
+ }
44
+ /** Adds a text band above or below the layout. Long text shrinks to fit the layout width. */
45
+ function layoutCaption({ width, height, qr }, caption) {
46
+ const fitted = fitFontSize(caption.text, caption.fontSize ?? 2, width);
47
+ const { fontSize } = fitted;
48
+ const warning = overflowWarning("caption", caption.text, fitted, width, "the code with its margin");
49
+ const band = fontSize * 1.75;
50
+ const top = caption.position === "top";
51
+ return {
52
+ layout: {
53
+ width,
54
+ height: height + band,
55
+ qr: top ? {
56
+ ...qr,
57
+ y: qr.y + band
58
+ } : qr
59
+ },
60
+ texts: [{
61
+ text: caption.text,
62
+ x: width / 2,
63
+ y: (top ? 0 : height) + band / 2,
64
+ fontSize,
65
+ fontFamily: caption.fontFamily ?? "system-ui, sans-serif",
66
+ fontWeight: caption.fontWeight ?? "normal",
67
+ paint: "caption"
68
+ }],
69
+ warnings: warning ? [warning] : []
70
+ };
71
+ }
72
+ // src/core/qrcodegen.ts
73
+ /**
74
+ * @license QR Code generator library (TypeScript)
75
+ * Copyright (c) Project Nayuki.
76
+ * SPDX-License-Identifier: MIT
77
+ *
78
+ * Local change: the mask penalty scoring was optimised with typed arrays and fewer passes.
79
+ * Its scores match the original bit for bit; test/penalty.test.ts checks this.
80
+ */
81
+ let qrcodegen;
82
+ (function(_qrcodegen) {
83
+ class QrCode {
84
+ version;
85
+ errorCorrectionLevel;
86
+ static encodeText(text, ecl) {
87
+ const segs = qrcodegen.QrSegment.makeSegments(text);
88
+ return QrCode.encodeSegments(segs, ecl);
89
+ }
90
+ static encodeBinary(data, ecl) {
91
+ const seg = qrcodegen.QrSegment.makeBytes(data);
92
+ return QrCode.encodeSegments([seg], ecl);
93
+ }
94
+ static encodeSegments(segs, ecl, minVersion = 1, maxVersion = 40, mask = -1, boostEcl = true) {
95
+ if (!(QrCode.MIN_VERSION <= minVersion && minVersion <= maxVersion && maxVersion <= QrCode.MAX_VERSION) || mask < -1 || mask > 7) throw new RangeError("Invalid value");
96
+ let version;
97
+ let dataUsedBits;
98
+ for (version = minVersion;; version++) {
99
+ const dataCapacityBits = QrCode.getNumDataCodewords(version, ecl) * 8;
100
+ const usedBits = QrSegment.getTotalBits(segs, version);
101
+ if (usedBits <= dataCapacityBits) {
102
+ dataUsedBits = usedBits;
103
+ break;
104
+ }
105
+ if (version >= maxVersion) throw new RangeError("Data too long");
106
+ }
107
+ for (const newEcl of [
108
+ QrCode.Ecc.MEDIUM,
109
+ QrCode.Ecc.QUARTILE,
110
+ QrCode.Ecc.HIGH
111
+ ]) if (boostEcl && dataUsedBits <= QrCode.getNumDataCodewords(version, newEcl) * 8) ecl = newEcl;
112
+ let bb = [];
113
+ for (const seg of segs) {
114
+ appendBits(seg.mode.modeBits, 4, bb);
115
+ appendBits(seg.numChars, seg.mode.numCharCountBits(version), bb);
116
+ for (const b of seg.getData()) bb.push(b);
117
+ }
118
+ assert(bb.length == dataUsedBits);
119
+ const dataCapacityBits = QrCode.getNumDataCodewords(version, ecl) * 8;
120
+ assert(bb.length <= dataCapacityBits);
121
+ appendBits(0, Math.min(4, dataCapacityBits - bb.length), bb);
122
+ appendBits(0, (8 - bb.length % 8) % 8, bb);
123
+ assert(bb.length % 8 == 0);
124
+ for (let padByte = 236; bb.length < dataCapacityBits; padByte ^= 253) appendBits(padByte, 8, bb);
125
+ let dataCodewords = [];
126
+ while (dataCodewords.length * 8 < bb.length) dataCodewords.push(0);
127
+ bb.forEach((b, i) => dataCodewords[i >>> 3] |= b << 7 - (i & 7));
128
+ return new QrCode(version, ecl, dataCodewords, mask);
129
+ }
130
+ size;
131
+ mask;
132
+ modules = [];
133
+ isFunction = [];
134
+ constructor(version, errorCorrectionLevel, dataCodewords, msk) {
135
+ this.version = version;
136
+ this.errorCorrectionLevel = errorCorrectionLevel;
137
+ if (version < QrCode.MIN_VERSION || version > QrCode.MAX_VERSION) throw new RangeError("Version value out of range");
138
+ if (msk < -1 || msk > 7) throw new RangeError("Mask value out of range");
139
+ this.size = version * 4 + 17;
140
+ let row = [];
141
+ for (let i = 0; i < this.size; i++) row.push(false);
142
+ for (let i = 0; i < this.size; i++) {
143
+ this.modules.push(row.slice());
144
+ this.isFunction.push(row.slice());
145
+ }
146
+ this.drawFunctionPatterns();
147
+ const allCodewords = this.addEccAndInterleave(dataCodewords);
148
+ this.drawCodewords(allCodewords);
149
+ if (msk == -1) {
150
+ const cells = this.size * this.size;
151
+ const base = new Uint8Array(cells);
152
+ const free = new Uint8Array(cells);
153
+ for (let y = 0; y < this.size; y++) for (let x = 0; x < this.size; x++) {
154
+ base[y * this.size + x] = this.modules[y][x] ? 1 : 0;
155
+ free[y * this.size + x] = this.isFunction[y][x] ? 0 : 1;
156
+ }
157
+ const grid = new Uint8Array(cells);
158
+ let minPenalty = 1e9;
159
+ for (let i = 0; i < 8; i++) {
160
+ this.drawFormatBits(i);
161
+ this.fillMaskedGrid(i, base, free, grid);
162
+ const penalty = getPenaltyScore(grid, this.size);
163
+ if (penalty < minPenalty) {
164
+ msk = i;
165
+ minPenalty = penalty;
166
+ }
167
+ }
168
+ }
169
+ assert(0 <= msk && msk <= 7);
170
+ this.mask = msk;
171
+ this.applyMask(msk);
172
+ this.drawFormatBits(msk);
173
+ this.isFunction = [];
174
+ }
175
+ getModule(x, y) {
176
+ return 0 <= x && x < this.size && 0 <= y && y < this.size && this.modules[y][x];
177
+ }
178
+ getModules() {
179
+ return this.modules;
180
+ }
181
+ drawFunctionPatterns() {
182
+ for (let i = 0; i < this.size; i++) {
183
+ this.setFunctionModule(6, i, i % 2 == 0);
184
+ this.setFunctionModule(i, 6, i % 2 == 0);
185
+ }
186
+ this.drawFinderPattern(3, 3);
187
+ this.drawFinderPattern(this.size - 4, 3);
188
+ this.drawFinderPattern(3, this.size - 4);
189
+ const alignPatPos = this.getAlignmentPatternPositions();
190
+ const numAlign = alignPatPos.length;
191
+ for (let i = 0; i < numAlign; i++) for (let j = 0; j < numAlign; j++) if (!(i == 0 && j == 0 || i == 0 && j == numAlign - 1 || i == numAlign - 1 && j == 0)) this.drawAlignmentPattern(alignPatPos[i], alignPatPos[j]);
192
+ this.drawFormatBits(0);
193
+ this.drawVersion();
194
+ }
195
+ drawFormatBits(mask) {
196
+ const data = this.errorCorrectionLevel.formatBits << 3 | mask;
197
+ let rem = data;
198
+ for (let i = 0; i < 10; i++) rem = rem << 1 ^ (rem >>> 9) * 1335;
199
+ const bits = (data << 10 | rem) ^ 21522;
200
+ assert(bits >>> 15 == 0);
201
+ for (let i = 0; i <= 5; i++) this.setFunctionModule(8, i, getBit(bits, i));
202
+ this.setFunctionModule(8, 7, getBit(bits, 6));
203
+ this.setFunctionModule(8, 8, getBit(bits, 7));
204
+ this.setFunctionModule(7, 8, getBit(bits, 8));
205
+ for (let i = 9; i < 15; i++) this.setFunctionModule(14 - i, 8, getBit(bits, i));
206
+ for (let i = 0; i < 8; i++) this.setFunctionModule(this.size - 1 - i, 8, getBit(bits, i));
207
+ for (let i = 8; i < 15; i++) this.setFunctionModule(8, this.size - 15 + i, getBit(bits, i));
208
+ this.setFunctionModule(8, this.size - 8, true);
209
+ }
210
+ drawVersion() {
211
+ if (this.version < 7) return;
212
+ let rem = this.version;
213
+ for (let i = 0; i < 12; i++) rem = rem << 1 ^ (rem >>> 11) * 7973;
214
+ const bits = this.version << 12 | rem;
215
+ assert(bits >>> 18 == 0);
216
+ for (let i = 0; i < 18; i++) {
217
+ const color = getBit(bits, i);
218
+ const a = this.size - 11 + i % 3;
219
+ const b = Math.floor(i / 3);
220
+ this.setFunctionModule(a, b, color);
221
+ this.setFunctionModule(b, a, color);
222
+ }
223
+ }
224
+ drawFinderPattern(x, y) {
225
+ for (let dy = -4; dy <= 4; dy++) for (let dx = -4; dx <= 4; dx++) {
226
+ const dist = Math.max(Math.abs(dx), Math.abs(dy));
227
+ const xx = x + dx;
228
+ const yy = y + dy;
229
+ if (0 <= xx && xx < this.size && 0 <= yy && yy < this.size) this.setFunctionModule(xx, yy, dist != 2 && dist != 4);
230
+ }
231
+ }
232
+ drawAlignmentPattern(x, y) {
233
+ for (let dy = -2; dy <= 2; dy++) for (let dx = -2; dx <= 2; dx++) this.setFunctionModule(x + dx, y + dy, Math.max(Math.abs(dx), Math.abs(dy)) != 1);
234
+ }
235
+ setFunctionModule(x, y, isDark) {
236
+ this.modules[y][x] = isDark;
237
+ this.isFunction[y][x] = true;
238
+ }
239
+ addEccAndInterleave(data) {
240
+ const ver = this.version;
241
+ const ecl = this.errorCorrectionLevel;
242
+ if (data.length != QrCode.getNumDataCodewords(ver, ecl)) throw new RangeError("Invalid argument");
243
+ const numBlocks = QrCode.NUM_ERROR_CORRECTION_BLOCKS[ecl.ordinal][ver];
244
+ const blockEccLen = QrCode.ECC_CODEWORDS_PER_BLOCK[ecl.ordinal][ver];
245
+ const rawCodewords = Math.floor(QrCode.getNumRawDataModules(ver) / 8);
246
+ const numShortBlocks = numBlocks - rawCodewords % numBlocks;
247
+ const shortBlockLen = Math.floor(rawCodewords / numBlocks);
248
+ let blocks = [];
249
+ const rsDiv = QrCode.reedSolomonComputeDivisor(blockEccLen);
250
+ for (let i = 0, k = 0; i < numBlocks; i++) {
251
+ let dat = data.slice(k, k + shortBlockLen - blockEccLen + (i < numShortBlocks ? 0 : 1));
252
+ k += dat.length;
253
+ const ecc = QrCode.reedSolomonComputeRemainder(dat, rsDiv);
254
+ if (i < numShortBlocks) dat.push(0);
255
+ blocks.push(dat.concat(ecc));
256
+ }
257
+ let result = [];
258
+ for (let i = 0; i < blocks[0].length; i++) blocks.forEach((block, j) => {
259
+ if (i != shortBlockLen - blockEccLen || j >= numShortBlocks) result.push(block[i]);
260
+ });
261
+ assert(result.length == rawCodewords);
262
+ return result;
263
+ }
264
+ drawCodewords(data) {
265
+ if (data.length != Math.floor(QrCode.getNumRawDataModules(this.version) / 8)) throw new RangeError("Invalid argument");
266
+ let i = 0;
267
+ for (let right = this.size - 1; right >= 1; right -= 2) {
268
+ if (right == 6) right = 5;
269
+ for (let vert = 0; vert < this.size; vert++) for (let j = 0; j < 2; j++) {
270
+ const x = right - j;
271
+ const y = (right + 1 & 2) == 0 ? this.size - 1 - vert : vert;
272
+ if (!this.isFunction[y][x] && i < data.length * 8) {
273
+ this.modules[y][x] = getBit(data[i >>> 3], 7 - (i & 7));
274
+ i++;
275
+ }
276
+ }
277
+ }
278
+ assert(i == data.length * 8);
279
+ }
280
+ applyMask(mask) {
281
+ if (mask < 0 || mask > 7) throw new RangeError("Mask value out of range");
282
+ for (let y = 0; y < this.size; y++) for (let x = 0; x < this.size; x++) if (!this.isFunction[y][x] && maskBit(mask, x, y)) this.modules[y][x] = !this.modules[y][x];
283
+ }
284
+ fillMaskedGrid(mask, base, free, grid) {
285
+ const size = this.size;
286
+ const pattern = getMaskPattern(mask);
287
+ for (let y = 0, p = 0; y < size; y++) {
288
+ const row = y % MASK_PERIOD * MASK_PERIOD;
289
+ for (let x = 0, column = 0; x < size; x++, p++) {
290
+ grid[p] = base[p] ^ pattern[row + column] & free[p];
291
+ if (++column == MASK_PERIOD) column = 0;
292
+ }
293
+ }
294
+ for (let i = 0; i < size; i++) {
295
+ if (this.isFunction[8][i]) grid[8 * size + i] = this.modules[8][i] ? 1 : 0;
296
+ if (this.isFunction[i][8]) grid[i * size + 8] = this.modules[i][8] ? 1 : 0;
297
+ }
298
+ }
299
+ getAlignmentPatternPositions() {
300
+ if (this.version == 1) return [];
301
+ else {
302
+ const numAlign = Math.floor(this.version / 7) + 2;
303
+ const step = this.version == 32 ? 26 : Math.ceil((this.version * 4 + 4) / (numAlign * 2 - 2)) * 2;
304
+ let result = [6];
305
+ for (let pos = this.size - 7; result.length < numAlign; pos -= step) result.splice(1, 0, pos);
306
+ return result;
307
+ }
308
+ }
309
+ static getNumRawDataModules(ver) {
310
+ if (ver < QrCode.MIN_VERSION || ver > QrCode.MAX_VERSION) throw new RangeError("Version number out of range");
311
+ let result = (16 * ver + 128) * ver + 64;
312
+ if (ver >= 2) {
313
+ const numAlign = Math.floor(ver / 7) + 2;
314
+ result -= (25 * numAlign - 10) * numAlign - 55;
315
+ if (ver >= 7) result -= 36;
316
+ }
317
+ assert(208 <= result && result <= 29648);
318
+ return result;
319
+ }
320
+ static getNumDataCodewords(ver, ecl) {
321
+ return Math.floor(QrCode.getNumRawDataModules(ver) / 8) - QrCode.ECC_CODEWORDS_PER_BLOCK[ecl.ordinal][ver] * QrCode.NUM_ERROR_CORRECTION_BLOCKS[ecl.ordinal][ver];
322
+ }
323
+ static reedSolomonComputeDivisor(degree) {
324
+ if (degree < 1 || degree > 255) throw new RangeError("Degree out of range");
325
+ let result = [];
326
+ for (let i = 0; i < degree - 1; i++) result.push(0);
327
+ result.push(1);
328
+ let root = 1;
329
+ for (let i = 0; i < degree; i++) {
330
+ for (let j = 0; j < result.length; j++) {
331
+ result[j] = QrCode.reedSolomonMultiply(result[j], root);
332
+ if (j + 1 < result.length) result[j] ^= result[j + 1];
333
+ }
334
+ root = QrCode.reedSolomonMultiply(root, 2);
335
+ }
336
+ return result;
337
+ }
338
+ static reedSolomonComputeRemainder(data, divisor) {
339
+ let result = divisor.map((_) => 0);
340
+ for (const b of data) {
341
+ const factor = b ^ result.shift();
342
+ result.push(0);
343
+ divisor.forEach((coef, i) => result[i] ^= QrCode.reedSolomonMultiply(coef, factor));
344
+ }
345
+ return result;
346
+ }
347
+ static reedSolomonMultiply(x, y) {
348
+ if (x >>> 8 != 0 || y >>> 8 != 0) throw new RangeError("Byte out of range");
349
+ let z = 0;
350
+ for (let i = 7; i >= 0; i--) {
351
+ z = z << 1 ^ (z >>> 7) * 285;
352
+ z ^= (y >>> i & 1) * x;
353
+ }
354
+ assert(z >>> 8 == 0);
355
+ return z;
356
+ }
357
+ static MIN_VERSION = 1;
358
+ static MAX_VERSION = 40;
359
+ static ECC_CODEWORDS_PER_BLOCK = [
360
+ [
361
+ -1,
362
+ 7,
363
+ 10,
364
+ 15,
365
+ 20,
366
+ 26,
367
+ 18,
368
+ 20,
369
+ 24,
370
+ 30,
371
+ 18,
372
+ 20,
373
+ 24,
374
+ 26,
375
+ 30,
376
+ 22,
377
+ 24,
378
+ 28,
379
+ 30,
380
+ 28,
381
+ 28,
382
+ 28,
383
+ 28,
384
+ 30,
385
+ 30,
386
+ 26,
387
+ 28,
388
+ 30,
389
+ 30,
390
+ 30,
391
+ 30,
392
+ 30,
393
+ 30,
394
+ 30,
395
+ 30,
396
+ 30,
397
+ 30,
398
+ 30,
399
+ 30,
400
+ 30,
401
+ 30
402
+ ],
403
+ [
404
+ -1,
405
+ 10,
406
+ 16,
407
+ 26,
408
+ 18,
409
+ 24,
410
+ 16,
411
+ 18,
412
+ 22,
413
+ 22,
414
+ 26,
415
+ 30,
416
+ 22,
417
+ 22,
418
+ 24,
419
+ 24,
420
+ 28,
421
+ 28,
422
+ 26,
423
+ 26,
424
+ 26,
425
+ 26,
426
+ 28,
427
+ 28,
428
+ 28,
429
+ 28,
430
+ 28,
431
+ 28,
432
+ 28,
433
+ 28,
434
+ 28,
435
+ 28,
436
+ 28,
437
+ 28,
438
+ 28,
439
+ 28,
440
+ 28,
441
+ 28,
442
+ 28,
443
+ 28,
444
+ 28
445
+ ],
446
+ [
447
+ -1,
448
+ 13,
449
+ 22,
450
+ 18,
451
+ 26,
452
+ 18,
453
+ 24,
454
+ 18,
455
+ 22,
456
+ 20,
457
+ 24,
458
+ 28,
459
+ 26,
460
+ 24,
461
+ 20,
462
+ 30,
463
+ 24,
464
+ 28,
465
+ 28,
466
+ 26,
467
+ 30,
468
+ 28,
469
+ 30,
470
+ 30,
471
+ 30,
472
+ 30,
473
+ 28,
474
+ 30,
475
+ 30,
476
+ 30,
477
+ 30,
478
+ 30,
479
+ 30,
480
+ 30,
481
+ 30,
482
+ 30,
483
+ 30,
484
+ 30,
485
+ 30,
486
+ 30,
487
+ 30
488
+ ],
489
+ [
490
+ -1,
491
+ 17,
492
+ 28,
493
+ 22,
494
+ 16,
495
+ 22,
496
+ 28,
497
+ 26,
498
+ 26,
499
+ 24,
500
+ 28,
501
+ 24,
502
+ 28,
503
+ 22,
504
+ 24,
505
+ 24,
506
+ 30,
507
+ 28,
508
+ 28,
509
+ 26,
510
+ 28,
511
+ 30,
512
+ 24,
513
+ 30,
514
+ 30,
515
+ 30,
516
+ 30,
517
+ 30,
518
+ 30,
519
+ 30,
520
+ 30,
521
+ 30,
522
+ 30,
523
+ 30,
524
+ 30,
525
+ 30,
526
+ 30,
527
+ 30,
528
+ 30,
529
+ 30,
530
+ 30
531
+ ]
532
+ ];
533
+ static NUM_ERROR_CORRECTION_BLOCKS = [
534
+ [
535
+ -1,
536
+ 1,
537
+ 1,
538
+ 1,
539
+ 1,
540
+ 1,
541
+ 2,
542
+ 2,
543
+ 2,
544
+ 2,
545
+ 4,
546
+ 4,
547
+ 4,
548
+ 4,
549
+ 4,
550
+ 6,
551
+ 6,
552
+ 6,
553
+ 6,
554
+ 7,
555
+ 8,
556
+ 8,
557
+ 9,
558
+ 9,
559
+ 10,
560
+ 12,
561
+ 12,
562
+ 12,
563
+ 13,
564
+ 14,
565
+ 15,
566
+ 16,
567
+ 17,
568
+ 18,
569
+ 19,
570
+ 19,
571
+ 20,
572
+ 21,
573
+ 22,
574
+ 24,
575
+ 25
576
+ ],
577
+ [
578
+ -1,
579
+ 1,
580
+ 1,
581
+ 1,
582
+ 2,
583
+ 2,
584
+ 4,
585
+ 4,
586
+ 4,
587
+ 5,
588
+ 5,
589
+ 5,
590
+ 8,
591
+ 9,
592
+ 9,
593
+ 10,
594
+ 10,
595
+ 11,
596
+ 13,
597
+ 14,
598
+ 16,
599
+ 17,
600
+ 17,
601
+ 18,
602
+ 20,
603
+ 21,
604
+ 23,
605
+ 25,
606
+ 26,
607
+ 28,
608
+ 29,
609
+ 31,
610
+ 33,
611
+ 35,
612
+ 37,
613
+ 38,
614
+ 40,
615
+ 43,
616
+ 45,
617
+ 47,
618
+ 49
619
+ ],
620
+ [
621
+ -1,
622
+ 1,
623
+ 1,
624
+ 2,
625
+ 2,
626
+ 4,
627
+ 4,
628
+ 6,
629
+ 6,
630
+ 8,
631
+ 8,
632
+ 8,
633
+ 10,
634
+ 12,
635
+ 16,
636
+ 12,
637
+ 17,
638
+ 16,
639
+ 18,
640
+ 21,
641
+ 20,
642
+ 23,
643
+ 23,
644
+ 25,
645
+ 27,
646
+ 29,
647
+ 34,
648
+ 34,
649
+ 35,
650
+ 38,
651
+ 40,
652
+ 43,
653
+ 45,
654
+ 48,
655
+ 51,
656
+ 53,
657
+ 56,
658
+ 59,
659
+ 62,
660
+ 65,
661
+ 68
662
+ ],
663
+ [
664
+ -1,
665
+ 1,
666
+ 1,
667
+ 2,
668
+ 4,
669
+ 4,
670
+ 4,
671
+ 5,
672
+ 6,
673
+ 8,
674
+ 8,
675
+ 11,
676
+ 11,
677
+ 16,
678
+ 16,
679
+ 18,
680
+ 16,
681
+ 19,
682
+ 21,
683
+ 25,
684
+ 25,
685
+ 25,
686
+ 34,
687
+ 30,
688
+ 32,
689
+ 35,
690
+ 37,
691
+ 40,
692
+ 42,
693
+ 45,
694
+ 48,
695
+ 51,
696
+ 54,
697
+ 57,
698
+ 60,
699
+ 63,
700
+ 66,
701
+ 70,
702
+ 74,
703
+ 77,
704
+ 81
705
+ ]
706
+ ];
707
+ }
708
+ _qrcodegen.QrCode = QrCode;
709
+ function appendBits(val, len, bb) {
710
+ if (len < 0 || len > 31 || val >>> len != 0) throw new RangeError("Value out of range");
711
+ for (let i = len - 1; i >= 0; i--) bb.push(val >>> i & 1);
712
+ }
713
+ function getBit(x, i) {
714
+ return (x >>> i & 1) != 0;
715
+ }
716
+ function maskBit(mask, x, y) {
717
+ switch (mask) {
718
+ case 0: return (x + y) % 2 == 0;
719
+ case 1: return y % 2 == 0;
720
+ case 2: return x % 3 == 0;
721
+ case 3: return (x + y) % 3 == 0;
722
+ case 4: return (Math.floor(x / 3) + Math.floor(y / 2)) % 2 == 0;
723
+ case 5: return x * y % 2 + x * y % 3 == 0;
724
+ case 6: return (x * y % 2 + x * y % 3) % 2 == 0;
725
+ case 7: return ((x + y) % 2 + x * y % 3) % 2 == 0;
726
+ default: throw new Error("Unreachable");
727
+ }
728
+ }
729
+ const MASK_PERIOD = 12;
730
+ const maskPatterns = [];
731
+ function getMaskPattern(mask) {
732
+ if (!maskPatterns[mask]) {
733
+ const tile = /* @__PURE__ */ new Uint8Array(144);
734
+ for (let y = 0; y < MASK_PERIOD; y++) for (let x = 0; x < MASK_PERIOD; x++) tile[y * MASK_PERIOD + x] = maskBit(mask, x, y) ? 1 : 0;
735
+ maskPatterns[mask] = tile;
736
+ }
737
+ return maskPatterns[mask];
738
+ }
739
+ const PENALTY_N1 = 3;
740
+ const PENALTY_N2 = 3;
741
+ const PENALTY_N3 = 40;
742
+ const PENALTY_N4 = 10;
743
+ const BLOCK_PENALTY = new Uint8Array([
744
+ PENALTY_N2,
745
+ 0,
746
+ 0,
747
+ 0,
748
+ PENALTY_N2
749
+ ]);
750
+ function getPenaltyScore(grid, size) {
751
+ let result = 0;
752
+ const runStarts = new Int32Array(size + 1);
753
+ for (let i = 0; i < size; i++) {
754
+ result += getLinePenalty(grid, i * size, 1, size, runStarts);
755
+ result += getLinePenalty(grid, i, size, size, runStarts);
756
+ }
757
+ let dark = 0;
758
+ for (let y = 0; y < size - 1; y++) {
759
+ let p = y * size;
760
+ let left = grid[p] + grid[p + size];
761
+ dark += grid[p];
762
+ for (let x = 1; x < size; x++) {
763
+ p++;
764
+ const right = grid[p] + grid[p + size];
765
+ result += BLOCK_PENALTY[left + right];
766
+ dark += grid[p];
767
+ left = right;
768
+ }
769
+ }
770
+ for (let p = (size - 1) * size; p < size * size; p++) dark += grid[p];
771
+ const total = size * size;
772
+ const k = Math.ceil(Math.abs(dark * 20 - total * 10) / total) - 1;
773
+ assert(0 <= k && k <= 9);
774
+ result += k * PENALTY_N4;
775
+ assert(0 <= result && result <= 2568888);
776
+ return result;
777
+ }
778
+ _qrcodegen.getPenaltyScore = getPenaltyScore;
779
+ function getLinePenalty(grid, start, step, size, runStarts) {
780
+ const firstColor = grid[start];
781
+ let runs = 1;
782
+ let previous = firstColor;
783
+ runStarts[0] = 0;
784
+ for (let i = 1, p = start + step; i < size; i++, p += step) {
785
+ const color = grid[p];
786
+ runStarts[runs] = i;
787
+ runs += color ^ previous;
788
+ previous = color;
789
+ }
790
+ runStarts[runs] = size;
791
+ let result = 0;
792
+ let h0 = 0, h1 = 0, h2 = 0, h3 = 0, h4 = 0, h5 = 0, h6 = 0;
793
+ let color = firstColor;
794
+ if (color == 1) {
795
+ h0 = size;
796
+ result += countFinderPatterns(h0, h1, h2, h3, h4, h5, h6) * PENALTY_N3;
797
+ }
798
+ for (let r = 0; r < runs; r++, color ^= 1) {
799
+ let length = runStarts[r + 1] - runStarts[r];
800
+ if (length >= 5) result += PENALTY_N1 + length - 5;
801
+ if (r == runs - 1 && color == 0) length += size;
802
+ h6 = h5;
803
+ h5 = h4;
804
+ h4 = h3;
805
+ h3 = h2;
806
+ h2 = h1;
807
+ h1 = h0;
808
+ h0 = h1 == 0 ? length + size : length;
809
+ if (color == 0) result += countFinderPatterns(h0, h1, h2, h3, h4, h5, h6) * PENALTY_N3;
810
+ }
811
+ if (color == 0) {
812
+ h6 = h5;
813
+ h5 = h4;
814
+ h4 = h3;
815
+ h3 = h2;
816
+ h2 = h1;
817
+ h1 = h0;
818
+ h0 = size;
819
+ result += countFinderPatterns(h0, h1, h2, h3, h4, h5, h6) * PENALTY_N3;
820
+ }
821
+ return result;
822
+ }
823
+ function countFinderPatterns(h0, h1, h2, h3, h4, h5, h6) {
824
+ const n = h1;
825
+ const core = n > 0 && h2 == n && h3 == n * 3 && h4 == n && h5 == n;
826
+ return (core && h0 >= n * 4 && h6 >= n ? 1 : 0) + (core && h6 >= n * 4 && h0 >= n ? 1 : 0);
827
+ }
828
+ function assert(cond) {
829
+ if (!cond) throw new Error("Assertion error");
830
+ }
831
+ class QrSegment {
832
+ mode;
833
+ numChars;
834
+ bitData;
835
+ static makeBytes(data) {
836
+ let bb = [];
837
+ for (const b of data) appendBits(b, 8, bb);
838
+ return new QrSegment(QrSegment.Mode.BYTE, data.length, bb);
839
+ }
840
+ static makeNumeric(digits) {
841
+ if (!QrSegment.isNumeric(digits)) throw new RangeError("String contains non-numeric characters");
842
+ let bb = [];
843
+ for (let i = 0; i < digits.length;) {
844
+ const n = Math.min(digits.length - i, 3);
845
+ appendBits(parseInt(digits.substring(i, i + n), 10), n * 3 + 1, bb);
846
+ i += n;
847
+ }
848
+ return new QrSegment(QrSegment.Mode.NUMERIC, digits.length, bb);
849
+ }
850
+ static makeAlphanumeric(text) {
851
+ if (!QrSegment.isAlphanumeric(text)) throw new RangeError("String contains unencodable characters in alphanumeric mode");
852
+ let bb = [];
853
+ let i = 0;
854
+ for (; i + 2 <= text.length; i += 2) {
855
+ let temp = QrSegment.ALPHANUMERIC_CHARSET.indexOf(text.charAt(i)) * 45;
856
+ temp += QrSegment.ALPHANUMERIC_CHARSET.indexOf(text.charAt(i + 1));
857
+ appendBits(temp, 11, bb);
858
+ }
859
+ if (i < text.length) appendBits(QrSegment.ALPHANUMERIC_CHARSET.indexOf(text.charAt(i)), 6, bb);
860
+ return new QrSegment(QrSegment.Mode.ALPHANUMERIC, text.length, bb);
861
+ }
862
+ static makeSegments(text) {
863
+ if (text == "") return [];
864
+ else if (QrSegment.isNumeric(text)) return [QrSegment.makeNumeric(text)];
865
+ else if (QrSegment.isAlphanumeric(text)) return [QrSegment.makeAlphanumeric(text)];
866
+ else return [QrSegment.makeBytes(QrSegment.toUtf8ByteArray(text))];
867
+ }
868
+ static makeEci(assignVal) {
869
+ let bb = [];
870
+ if (assignVal < 0) throw new RangeError("ECI assignment value out of range");
871
+ else if (assignVal < 128) appendBits(assignVal, 8, bb);
872
+ else if (assignVal < 16384) {
873
+ appendBits(2, 2, bb);
874
+ appendBits(assignVal, 14, bb);
875
+ } else if (assignVal < 1e6) {
876
+ appendBits(6, 3, bb);
877
+ appendBits(assignVal, 21, bb);
878
+ } else throw new RangeError("ECI assignment value out of range");
879
+ return new QrSegment(QrSegment.Mode.ECI, 0, bb);
880
+ }
881
+ static isNumeric(text) {
882
+ return QrSegment.NUMERIC_REGEX.test(text);
883
+ }
884
+ static isAlphanumeric(text) {
885
+ return QrSegment.ALPHANUMERIC_REGEX.test(text);
886
+ }
887
+ constructor(mode, numChars, bitData) {
888
+ this.mode = mode;
889
+ this.numChars = numChars;
890
+ this.bitData = bitData;
891
+ if (numChars < 0) throw new RangeError("Invalid argument");
892
+ this.bitData = bitData.slice();
893
+ }
894
+ getData() {
895
+ return this.bitData.slice();
896
+ }
897
+ static getTotalBits(segs, version) {
898
+ let result = 0;
899
+ for (const seg of segs) {
900
+ const ccbits = seg.mode.numCharCountBits(version);
901
+ if (seg.numChars >= 1 << ccbits) return 1e400;
902
+ result += 4 + ccbits + seg.bitData.length;
903
+ }
904
+ return result;
905
+ }
906
+ static toUtf8ByteArray(str) {
907
+ str = encodeURI(str);
908
+ let result = [];
909
+ for (let i = 0; i < str.length; i++) if (str.charAt(i) != "%") result.push(str.charCodeAt(i));
910
+ else {
911
+ result.push(parseInt(str.substring(i + 1, i + 3), 16));
912
+ i += 2;
913
+ }
914
+ return result;
915
+ }
916
+ static NUMERIC_REGEX = /^[0-9]*$/;
917
+ static ALPHANUMERIC_REGEX = /^[A-Z0-9 $%*+.\/:-]*$/;
918
+ static ALPHANUMERIC_CHARSET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:";
919
+ }
920
+ _qrcodegen.QrSegment = QrSegment;
921
+ })(qrcodegen || (qrcodegen = {}));
922
+ (function(_qrcodegen2) {
923
+ let QrCode;
924
+ (function(_QrCode) {
925
+ class Ecc {
926
+ ordinal;
927
+ formatBits;
928
+ static LOW = new Ecc(0, 1);
929
+ static MEDIUM = new Ecc(1, 0);
930
+ static QUARTILE = new Ecc(2, 3);
931
+ static HIGH = new Ecc(3, 2);
932
+ constructor(ordinal, formatBits) {
933
+ this.ordinal = ordinal;
934
+ this.formatBits = formatBits;
935
+ }
936
+ }
937
+ _QrCode.Ecc = Ecc;
938
+ })(QrCode || (QrCode = _qrcodegen2.QrCode || (_qrcodegen2.QrCode = {})));
939
+ })(qrcodegen || (qrcodegen = {}));
940
+ (function(_qrcodegen3) {
941
+ let QrSegment;
942
+ (function(_QrSegment) {
943
+ class Mode {
944
+ modeBits;
945
+ numBitsCharCount;
946
+ static NUMERIC = new Mode(1, [
947
+ 10,
948
+ 12,
949
+ 14
950
+ ]);
951
+ static ALPHANUMERIC = new Mode(2, [
952
+ 9,
953
+ 11,
954
+ 13
955
+ ]);
956
+ static BYTE = new Mode(4, [
957
+ 8,
958
+ 16,
959
+ 16
960
+ ]);
961
+ static KANJI = new Mode(8, [
962
+ 8,
963
+ 10,
964
+ 12
965
+ ]);
966
+ static ECI = new Mode(7, [
967
+ 0,
968
+ 0,
969
+ 0
970
+ ]);
971
+ constructor(modeBits, numBitsCharCount) {
972
+ this.modeBits = modeBits;
973
+ this.numBitsCharCount = numBitsCharCount;
974
+ }
975
+ numCharCountBits(ver) {
976
+ return this.numBitsCharCount[Math.floor((ver + 7) / 17)];
977
+ }
978
+ }
979
+ _QrSegment.Mode = Mode;
980
+ })(QrSegment || (QrSegment = _qrcodegen3.QrSegment || (_qrcodegen3.QrSegment = {})));
981
+ })(qrcodegen || (qrcodegen = {}));
982
+ // src/core/encode.ts
983
+ const { QrCode, QrSegment } = qrcodegen;
984
+ const Region = {
985
+ Data: 0,
986
+ Finder: 1,
987
+ Alignment: 2,
988
+ Timing: 3,
989
+ Format: 4
990
+ };
991
+ var QRCapacityError = class extends Error {
992
+ version;
993
+ level;
994
+ dataLength;
995
+ constructor(version, level, dataLength) {
996
+ super(`Data too long for QR version ${version} at level ${level}`);
997
+ this.version = version;
998
+ this.level = level;
999
+ this.dataLength = dataLength;
1000
+ this.name = "QRCapacityError";
1001
+ }
1002
+ };
1003
+ const eccByLevel = {
1004
+ L: QrCode.Ecc.LOW,
1005
+ M: QrCode.Ecc.MEDIUM,
1006
+ Q: QrCode.Ecc.QUARTILE,
1007
+ H: QrCode.Ecc.HIGH
1008
+ };
1009
+ const levelByOrdinal = [
1010
+ "L",
1011
+ "M",
1012
+ "Q",
1013
+ "H"
1014
+ ];
1015
+ function isDark(m, x, y) {
1016
+ return x >= 0 && y >= 0 && x < m.size && y < m.size && m.dark[y * m.size + x] === 1;
1017
+ }
1018
+ function makeSegments(value) {
1019
+ if (typeof value === "string") return QrSegment.makeSegments(value);
1020
+ return value.flatMap((v) => QrSegment.makeSegments(v));
1021
+ }
1022
+ function markRegions(qr) {
1023
+ const { size, version } = qr;
1024
+ const region = new Uint8Array(size * size);
1025
+ const inFinder = (x, y) => x < 8 && y < 8 || x >= size - 8 && y < 8 || x < 8 && y >= size - 8;
1026
+ for (let y = 0; y < size; y++) for (let x = 0; x < size; x++) {
1027
+ let r = Region.Data;
1028
+ if (inFinder(x, y)) r = Region.Finder;
1029
+ else if (y === 8 && x !== 6 && (x <= 8 || x >= size - 8) || x === 8 && y !== 6 && (y <= 8 || y >= size - 8)) r = Region.Format;
1030
+ else if (version >= 7 && (x < 6 && y >= size - 11 && y < size - 8 || y < 6 && x >= size - 11 && x < size - 8)) r = Region.Format;
1031
+ else if (x === 6 || y === 6) r = Region.Timing;
1032
+ region[y * size + x] = r;
1033
+ }
1034
+ const pos = qr.getAlignmentPatternPositions();
1035
+ const last = pos.length - 1;
1036
+ pos.forEach((cy, i) => pos.forEach((cx, j) => {
1037
+ if (i === 0 && (j === 0 || j === last) || i === last && j === 0) return;
1038
+ for (let dy = -2; dy <= 2; dy++) for (let dx = -2; dx <= 2; dx++) region[(cy + dy) * size + cx + dx] = Region.Alignment;
1039
+ }));
1040
+ return region;
1041
+ }
1042
+ const cacheSize = 16;
1043
+ /** Recent matrices by input, oldest first: a Map keeps insertion order. */
1044
+ const cache = /* @__PURE__ */ new Map();
1045
+ /**
1046
+ * Encodes `value` into a module matrix, without Solid.
1047
+ * Repeat calls with the same input return the cached object; see `QRMatrix`.
1048
+ * `level` defaults to `'L'` here. The components default to `'M'`, or `'Q'` with a logo.
1049
+ * @throws {QRCapacityError} when the data does not fit `maxVersion`.
1050
+ * @throws {RangeError} when `minVersion` exceeds `maxVersion`, or a version or mask is out of range.
1051
+ */
1052
+ function encode(value, options = {}) {
1053
+ const { level = "L", minVersion = 1, maxVersion = 40, mask = -1, boostLevel = true } = options;
1054
+ const key = JSON.stringify([
1055
+ value,
1056
+ level,
1057
+ minVersion,
1058
+ maxVersion,
1059
+ mask,
1060
+ boostLevel
1061
+ ]);
1062
+ const hit = cache.get(key);
1063
+ if (hit) {
1064
+ cache.delete(key);
1065
+ cache.set(key, hit);
1066
+ return hit;
1067
+ }
1068
+ const matrix = encodeUncached(value, level, minVersion, maxVersion, mask, boostLevel);
1069
+ cache.set(key, matrix);
1070
+ if (cache.size > cacheSize) cache.delete(cache.keys().next().value);
1071
+ return matrix;
1072
+ }
1073
+ function encodeUncached(value, level, minVersion, maxVersion, mask, boostLevel) {
1074
+ if (minVersion > maxVersion) throw new RangeError(`minVersion (${minVersion}) must not exceed maxVersion (${maxVersion})`);
1075
+ const segments = makeSegments(value);
1076
+ let qr;
1077
+ try {
1078
+ qr = QrCode.encodeSegments(segments, eccByLevel[level], minVersion, maxVersion, mask, boostLevel);
1079
+ } catch (e) {
1080
+ if (e instanceof RangeError && e.message === "Data too long") throw new QRCapacityError(maxVersion, level, segments.reduce((n, s) => n + s.numChars, 0));
1081
+ throw e;
1082
+ }
1083
+ const { size } = qr;
1084
+ const dark = new Uint8Array(size * size);
1085
+ qr.getModules().forEach((row, y) => row.forEach((on, x) => dark[y * size + x] = on ? 1 : 0));
1086
+ return Object.freeze({
1087
+ size,
1088
+ version: qr.version,
1089
+ level: levelByOrdinal[qr.errorCorrectionLevel.ordinal],
1090
+ mask: qr.mask,
1091
+ dark,
1092
+ region: markRegions(qr),
1093
+ finders: Object.freeze([
1094
+ Object.freeze([0, 0]),
1095
+ Object.freeze([size - 7, 0]),
1096
+ Object.freeze([0, size - 7])
1097
+ ])
1098
+ });
1099
+ }
1100
+ // src/shapes/types.ts
1101
+ function defineModuleShape(draw) {
1102
+ return {
1103
+ kind: "module",
1104
+ draw
1105
+ };
1106
+ }
1107
+ function defineLayerShape(draw) {
1108
+ return {
1109
+ kind: "layer",
1110
+ draw
1111
+ };
1112
+ }
1113
+ /** Formats a path coordinate without float noise: 3 decimals, trailing zeros trimmed. */
1114
+ const coord = (v) => String(Math.round(v * 1e3) / 1e3 + 0);
1115
+ // src/shapes/modules.ts
1116
+ /** Square modules, merged into one subpath per horizontal run. */
1117
+ const square = defineLayerShape(({ matrix: m, include, offset }) => {
1118
+ let d = "";
1119
+ for (let y = 0; y < m.size; y++) {
1120
+ let x = 0;
1121
+ while (x < m.size) {
1122
+ if (!(include(x, y) && isDark(m, x, y))) {
1123
+ x++;
1124
+ continue;
1125
+ }
1126
+ const start = x;
1127
+ while (x < m.size && include(x, y) && isDark(m, x, y)) x++;
1128
+ const len = x - start;
1129
+ d += `M${coord(start + offset.x)} ${coord(y + offset.y)}h${len}v1h-${len}z`;
1130
+ }
1131
+ }
1132
+ return d;
1133
+ });
1134
+ const cell = (x, y) => `M${coord(x)} ${coord(y)}h1v1h-1z`;
1135
+ const dots = defineModuleShape(({ x, y, alignment }) => {
1136
+ if (alignment) return cell(x, y);
1137
+ const r = .4;
1138
+ return `M${coord(x + .5 - r)} ${coord(y + .5)}a${r} ${r} 0 1 0 ${coord(2 * r)} 0a${r} ${r} 0 1 0 -${coord(2 * r)} 0z`;
1139
+ });
1140
+ const diamond = defineModuleShape(({ x, y, alignment }) => alignment ? cell(x, y) : `M${coord(x + .5)} ${coord(y)}L${coord(x + 1)} ${coord(y + .5)}L${coord(x + .5)} ${coord(y + 1)}L${coord(x)} ${coord(y + .5)}z`);
1141
+ /** A corner is round only when both orthogonal neighbours on that side are not drawn. */
1142
+ const rounded = defineModuleShape(({ x, y, neighbors: { n, e, s, w } }) => {
1143
+ const [tl, tr, br, bl] = [
1144
+ !n && !w,
1145
+ !n && !e,
1146
+ !s && !e,
1147
+ !s && !w
1148
+ ].map((round) => round ? .5 : 0);
1149
+ const arc = (to, r) => r ? `A.5 .5 0 0 1 ${coord(to[0])} ${coord(to[1])}` : "";
1150
+ return `M${coord(x + tl)} ${coord(y)}H${coord(x + 1 - tr)}${arc([x + 1, y + tr], tr)}V${coord(y + 1 - br)}${arc([x + 1 - br, y + 1], br)}H${coord(x + bl)}${arc([x, y + 1 - bl], bl)}V${coord(y + tl)}${arc([x + tl, y], tl)}z`;
1151
+ });
1152
+ /** The option props, which the components keep off the DOM element. */
1153
+ const optionKeys = Object.keys({
1154
+ value: true,
1155
+ size: true,
1156
+ level: true,
1157
+ margin: true,
1158
+ fg: true,
1159
+ bg: true,
1160
+ modules: true,
1161
+ finder: true,
1162
+ image: true,
1163
+ caption: true,
1164
+ frame: true,
1165
+ title: true,
1166
+ id: true,
1167
+ encoding: true
1168
+ });
1169
+ const defaults = {
1170
+ size: 128,
1171
+ margin: 4,
1172
+ fg: "var(--qr-fg, #000)",
1173
+ bg: "var(--qr-bg, #fff)"
1174
+ };
1175
+ /** The finder shape without its colours. */
1176
+ const toFinderShape = (finder = {}) => ({
1177
+ outer: finder.outer,
1178
+ inner: finder.inner
1179
+ });
1180
+ /**
1181
+ * The paint-free part of the design, with defaults applied. Reads no colour field.
1182
+ * Pass `finder` and `caption` to keep it from reading the options that also hold colours.
1183
+ */
1184
+ function toGeometryDesign(options, finder = toFinderShape(options.finder), caption = toCaptionShape(options.caption)) {
1185
+ return {
1186
+ margin: options.margin ?? defaults.margin,
1187
+ modules: options.modules ?? square,
1188
+ finder,
1189
+ image: options.image,
1190
+ caption,
1191
+ frame: options.frame
1192
+ };
1193
+ }
1194
+ /** The paints, with defaults applied. */
1195
+ function toPaints(options) {
1196
+ return {
1197
+ fg: options.fg ?? defaults.fg,
1198
+ bg: options.bg ?? defaults.bg,
1199
+ finder: options.finder?.color,
1200
+ finderInner: options.finder?.innerColor,
1201
+ caption: options.caption?.color
1202
+ };
1203
+ }
1204
+ // src/core/output.ts
1205
+ /** The size of a drawing in CSS pixels. `size` is the width; the height keeps the scene ratio. */
1206
+ const outputSize = (scene, size = defaults.size) => ({
1207
+ width: size,
1208
+ height: size * scene.height / scene.width
1209
+ });
1210
+ /** A JSX attribute may hold `false` to remove it, so only a non-empty string counts. */
1211
+ const text = (value) => typeof value === "string" && value ? value : void 0;
1212
+ /**
1213
+ * The `aria-label` for a drawing, or undefined when another attribute names it.
1214
+ * An SVG names itself through its `<title>`; a canvas has no such element,
1215
+ * so with `titleIsLabel` the title becomes its label.
1216
+ */
1217
+ function ariaLabel(props, titleIsLabel) {
1218
+ const [title, label, labelledby] = [
1219
+ text(props.title),
1220
+ text(props["aria-label"]),
1221
+ text(props["aria-labelledby"])
1222
+ ];
1223
+ if (titleIsLabel) return title ?? label ?? (labelledby ? void 0 : "QR code");
1224
+ return title || label || labelledby ? void 0 : "QR code";
1225
+ }
1226
+ // src/primitives/createColorScheme.ts
1227
+ /** Tracks `prefers-color-scheme`. 'light' on the server and where `matchMedia` is missing. */
1228
+ function createColorScheme() {
1229
+ if (isServer) return () => "light";
1230
+ const [scheme, setScheme] = createSignal("light");
1231
+ onSettled(() => {
1232
+ if (typeof matchMedia !== "function") return;
1233
+ const query = matchMedia("(prefers-color-scheme: dark)");
1234
+ const onChange = () => setScheme(query.matches ? "dark" : "light");
1235
+ onChange();
1236
+ query.addEventListener("change", onChange);
1237
+ return () => query.removeEventListener("change", onChange);
1238
+ });
1239
+ return scheme;
1240
+ }
1241
+ // src/primitives/createPixelRatio.ts
1242
+ /** Tracks `devicePixelRatio`, which changes on zoom or a move to another screen. 1 on the server. */
1243
+ function createPixelRatio() {
1244
+ if (isServer) return () => 1;
1245
+ const [ratio, setRatio] = createSignal(window.devicePixelRatio || 1);
1246
+ onSettled(() => {
1247
+ if (typeof matchMedia !== "function") return;
1248
+ let query;
1249
+ const arm = () => {
1250
+ query = matchMedia(`(resolution: ${window.devicePixelRatio}dppx)`);
1251
+ query.addEventListener("change", onChange, { once: true });
1252
+ };
1253
+ const onChange = () => {
1254
+ setRatio(window.devicePixelRatio || 1);
1255
+ arm();
1256
+ };
1257
+ arm();
1258
+ return () => query.removeEventListener("change", onChange);
1259
+ });
1260
+ return ratio;
1261
+ }
1262
+ // src/core/logo.ts
1263
+ /**
1264
+ * The largest share of all modules (size squared) that the excavated box may cover, per level,
1265
+ * as `[versions 1-6, versions 7+]`. The box is the image plus padding, rounded outward.
1266
+ * About 75% of the smallest box share that jsQR and ZXing both decoded on versions 2-15,
1267
+ * with two values and the square and dots shapes. L is not recommended with a logo: its budget
1268
+ * fits a tiny logo at best, so most L logos are reduced or dropped.
1269
+ */
1270
+ const maxLogoArea = {
1271
+ L: [.022, .022],
1272
+ M: [.03, .07],
1273
+ Q: [.072, .088],
1274
+ H: [.116, .07]
1275
+ };
1276
+ /** A logo narrower than this many modules is dropped, not drawn over modules. */
1277
+ const minLogoWidth = 2;
1278
+ function place(n, image, size) {
1279
+ const aspect = image.aspect ?? 1;
1280
+ const padding = image.excavate === false ? 0 : image.padding ?? 1;
1281
+ const width = size * n;
1282
+ const height = width / aspect;
1283
+ const [x, y] = [(n - width) / 2, (n - height) / 2];
1284
+ return {
1285
+ x,
1286
+ y,
1287
+ width,
1288
+ height,
1289
+ cells: {
1290
+ x0: Math.floor(x - padding),
1291
+ y0: Math.floor(y - padding),
1292
+ x1: Math.ceil(x + width + padding),
1293
+ y1: Math.ceil(y + height + padding)
1294
+ }
1295
+ };
1296
+ }
1297
+ /**
1298
+ * True when the box stays in budget and covers only data cells. From version 7 an alignment
1299
+ * pattern sits at the centre, so there the box may also cover alignment cells.
1300
+ */
1301
+ function fits(m, c, budget) {
1302
+ if (c.x0 < 0 || c.y0 < 0 || c.x1 > m.size || c.y1 > m.size) return false;
1303
+ if ((c.x1 - c.x0) * (c.y1 - c.y0) > budget * m.size * m.size) return false;
1304
+ const allowed = (r) => r === Region.Data || m.version >= 7 && r === Region.Alignment;
1305
+ for (let y = c.y0; y < c.y1; y++) for (let x = c.x0; x < c.x1; x++) if (!allowed(m.region[y * m.size + x])) return false;
1306
+ return true;
1307
+ }
1308
+ /**
1309
+ * The largest logo width fraction, up to `image.size`, whose box fits the level budget and
1310
+ * covers only data cells. Returns 0 when no logo fits.
1311
+ */
1312
+ function clampImageSize(matrix, image) {
1313
+ const budget = maxLogoArea[matrix.level][matrix.version >= 7 ? 1 : 0];
1314
+ const ok = (size) => fits(matrix, place(matrix.size, image, size).cells, budget);
1315
+ const size = image.size ?? .2;
1316
+ if (ok(size)) return size;
1317
+ let [lo, hi] = [0, size];
1318
+ for (let i = 0; i < 24; i++) {
1319
+ const mid = (lo + hi) / 2;
1320
+ if (ok(mid)) lo = mid;
1321
+ else hi = mid;
1322
+ }
1323
+ return lo * matrix.size < minLogoWidth ? 0 : lo;
1324
+ }
1325
+ /**
1326
+ * Centres the logo on the code, in scene units with the code box at the origin, or returns
1327
+ * undefined when it cannot fit. `cells` is empty when `excavate` is false.
1328
+ */
1329
+ function logoBox(matrix, margin, image) {
1330
+ const size = clampImageSize(matrix, image);
1331
+ if (!size) return void 0;
1332
+ const { x, y, width, height, cells } = place(matrix.size, image, size);
1333
+ const box = {
1334
+ href: image.src,
1335
+ x: x + margin,
1336
+ y: y + margin,
1337
+ width,
1338
+ height,
1339
+ radius: Math.min(.5, image.radius ?? 0) * Math.min(width, height),
1340
+ opacity: image.opacity ?? 1,
1341
+ cells: image.excavate === false ? {
1342
+ x0: 0,
1343
+ y0: 0,
1344
+ x1: 0,
1345
+ y1: 0
1346
+ } : cells
1347
+ };
1348
+ if (image.crossOrigin !== void 0) box.crossOrigin = image.crossOrigin;
1349
+ return box;
1350
+ }
1351
+ // src/core/path.ts
1352
+ /** The axis each argument of an absolute command moves along: x, y, or none (-). */
1353
+ const axes = {
1354
+ M: "xy",
1355
+ L: "xy",
1356
+ T: "xy",
1357
+ H: "x",
1358
+ V: "y",
1359
+ C: "xyxyxy",
1360
+ S: "xyxy",
1361
+ Q: "xyxy",
1362
+ A: "-----xy",
1363
+ Z: ""
1364
+ };
1365
+ const numberPattern = /^[\s,]*([-+]?(?:\d+\.?\d*|\.\d+)(?:e[-+]?\d+)?)/i;
1366
+ const flagPattern = /^[\s,]*([01])/;
1367
+ /**
1368
+ * Moves SVG path data by (dx, dy). Relative commands keep their values; absolute commands and
1369
+ * the first pair of a leading `m` move.
1370
+ */
1371
+ function translatePath(d, dx, dy) {
1372
+ if (!dx && !dy) return d;
1373
+ let first = true;
1374
+ return d.replace(/([a-df-z])([^a-df-z]*)/gi, (_, command, args) => {
1375
+ const leadingMove = first && command === "m";
1376
+ first = false;
1377
+ const upper = command.toUpperCase();
1378
+ if (command !== upper && !leadingMove) return command + args;
1379
+ const pattern = leadingMove ? "xy" : axes[upper];
1380
+ const values = [];
1381
+ for (let i = 0;; i++) {
1382
+ const axis = pattern[i % pattern.length];
1383
+ const match = (upper === "A" && (i % 7 === 3 || i % 7 === 4) ? flagPattern : numberPattern).exec(args);
1384
+ if (!match || !axis || leadingMove && i >= 2) break;
1385
+ args = args.slice(match[0].length);
1386
+ const value = Number(match[1]);
1387
+ values.push(axis === "x" ? coord(value + dx) : axis === "y" ? coord(value + dy) : match[1]);
1388
+ }
1389
+ return command + values.join(" ") + args;
1390
+ });
1391
+ }
1392
+ // src/core/paint.ts
1393
+ /** Rounds to 4 decimals; `+ 0` turns -0 into 0. */
1394
+ const round = (v) => Math.round(v * 1e4) / 1e4 + 0;
1395
+ const clamp = (v) => Math.min(1, Math.max(0, v));
1396
+ function placeStops(stops) {
1397
+ if (stops.length < 2) throw new RangeError(`A gradient needs at least 2 stops, got ${stops.length}.`);
1398
+ const last = stops.length - 1;
1399
+ return stops.map((s, i) => typeof s === "string" ? [round(i / last), s] : [clamp(s[0]), s[1]]);
1400
+ }
1401
+ /** Maps a paint to user-space gradient coordinates over `box`. */
1402
+ function placePaint(paint, box) {
1403
+ if (typeof paint === "string") return paint;
1404
+ const half = box.size / 2;
1405
+ const [cx, cy] = [box.x + half, box.y + half];
1406
+ const stops = placeStops(paint.stops);
1407
+ if (paint.type === "radial") return {
1408
+ type: "radial",
1409
+ cx,
1410
+ cy,
1411
+ r: half,
1412
+ stops
1413
+ };
1414
+ const angle = (paint.rotate ?? 0) * Math.PI / 180;
1415
+ const [dx, dy] = [Math.cos(angle) * half, Math.sin(angle) * half];
1416
+ return {
1417
+ type: "linear",
1418
+ x1: round(cx - dx),
1419
+ y1: round(cy - dy),
1420
+ x2: round(cx + dx),
1421
+ y2: round(cy + dy),
1422
+ stops
1423
+ };
1424
+ }
1425
+ // src/shapes/finders.ts
1426
+ const rect = (x, y, w, h, radius) => {
1427
+ const r = Math.max(0, Math.min(radius, w / 2, h / 2));
1428
+ if (r === 0) return `M${coord(x)} ${coord(y)}h${coord(w)}v${coord(h)}h-${coord(w)}z`;
1429
+ const [rc, sw, sh] = [
1430
+ coord(r),
1431
+ coord(w - 2 * r),
1432
+ coord(h - 2 * r)
1433
+ ];
1434
+ const arc = (dx, dy) => `a${rc} ${rc} 0 0 1 ${dx} ${dy}`;
1435
+ return `M${coord(x + r)} ${coord(y)}h${sw}${arc(rc, rc)}v${sh}${arc(`-${rc}`, rc)}h-${sw}${arc(`-${rc}`, `-${rc}`)}v-${sh}${arc(rc, `-${rc}`)}z`;
1436
+ };
1437
+ const circle = (cx, cy, r) => `M${coord(cx - r)} ${coord(cy)}a${r} ${r} 0 1 0 ${coord(2 * r)} 0a${r} ${r} 0 1 0 -${coord(2 * r)} 0z`;
1438
+ /** Outer presets are two subpaths (contour + hole); the layer fills with `evenodd`. */
1439
+ const finderOuter = {
1440
+ square: (x, y) => rect(x, y, 7, 7, 0) + rect(x + 1, y + 1, 5, 5, 0),
1441
+ rounded: (x, y) => rect(x, y, 7, 7, 2) + rect(x + 1, y + 1, 5, 5, 1),
1442
+ circle: (x, y) => circle(x + 3.5, y + 3.5, 3.5) + circle(x + 3.5, y + 3.5, 2.5)
1443
+ };
1444
+ const finderInner = {
1445
+ square: (x, y) => rect(x + 2, y + 2, 3, 3, 0),
1446
+ rounded: (x, y) => rect(x + 2, y + 2, 3, 3, .8),
1447
+ dot: (x, y) => circle(x + 3.5, y + 3.5, 1.6),
1448
+ diamond: (x, y) => `M${coord(x + 3.5)} ${coord(y + 1.5)}L${coord(x + 5.5)} ${coord(y + 3.5)}L${coord(x + 3.5)} ${coord(y + 5.5)}L${coord(x + 1.5)} ${coord(y + 3.5)}z`
1449
+ };
1450
+ function getFinder(style) {
1451
+ const { outer = "square", inner = "square" } = style;
1452
+ return {
1453
+ outer: typeof outer === "function" ? outer : finderOuter[outer],
1454
+ inner: typeof inner === "function" ? inner : finderInner[inner]
1455
+ };
1456
+ }
1457
+ // src/core/scene.ts
1458
+ const toShape = (input) => typeof input === "function" ? {
1459
+ kind: "module",
1460
+ draw: input
1461
+ } : input;
1462
+ function drawModules(m, shape, offset, cut) {
1463
+ const excavated = (x, y) => !!cut && x >= cut.x0 && x < cut.x1 && y >= cut.y0 && y < cut.y1;
1464
+ const include = (x, y) => x >= 0 && y >= 0 && x < m.size && y < m.size && m.region[y * m.size + x] !== Region.Finder && !excavated(x, y);
1465
+ if (shape.kind === "layer") return shape.draw({
1466
+ matrix: m,
1467
+ include,
1468
+ offset
1469
+ });
1470
+ const on = (x, y) => include(x, y) && isDark(m, x, y);
1471
+ let d = "";
1472
+ for (let y = 0; y < m.size; y++) for (let x = 0; x < m.size; x++) {
1473
+ if (!on(x, y)) continue;
1474
+ const neighbors = {
1475
+ n: on(x, y - 1),
1476
+ e: on(x + 1, y),
1477
+ s: on(x, y + 1),
1478
+ w: on(x - 1, y)
1479
+ };
1480
+ const alignment = m.region[y * m.size + x] === Region.Alignment;
1481
+ const context = {
1482
+ x: x + offset.x,
1483
+ y: y + offset.y,
1484
+ neighbors,
1485
+ alignment
1486
+ };
1487
+ d += shape.draw(context);
1488
+ }
1489
+ return d;
1490
+ }
1491
+ /**
1492
+ * Applies the frames from the inside out. Each frame's paths and texts move with the code
1493
+ * when an outer frame moves it. Outer frames draw first, so inner ones paint over them.
1494
+ */
1495
+ function applyFrames(content, frame) {
1496
+ const results = (typeof frame === "function" ? [frame] : frame ?? []).reduce((done, plugin) => [...done, plugin(done.at(-1)?.layout ?? content)], []);
1497
+ const layout = results.at(-1)?.layout ?? content;
1498
+ const ids = /* @__PURE__ */ new Set();
1499
+ const paths = [];
1500
+ const texts = [];
1501
+ const warnings = results.flatMap((result) => result.warnings ?? []);
1502
+ for (const result of [...results].reverse()) {
1503
+ const [dx, dy] = [layout.qr.x - result.layout.qr.x, layout.qr.y - result.layout.qr.y];
1504
+ for (const path of result.paths) {
1505
+ let id = path.id;
1506
+ for (let n = 2; ids.has(id); n++) id = `${path.id}-${n}`;
1507
+ ids.add(id);
1508
+ paths.push({
1509
+ ...path,
1510
+ id,
1511
+ d: translatePath(path.d, dx, dy)
1512
+ });
1513
+ }
1514
+ texts.unshift(...result.texts.map((t) => ({
1515
+ ...t,
1516
+ x: t.x + dx,
1517
+ y: t.y + dy
1518
+ })));
1519
+ }
1520
+ return {
1521
+ layout,
1522
+ paths,
1523
+ texts,
1524
+ warnings
1525
+ };
1526
+ }
1527
+ /**
1528
+ * Builds paint-free path data. Colour changes only need `paintScene`.
1529
+ * The layout composes code, then caption, then frames: the frames wrap the caption.
1530
+ * Layer order: frame layers, then `bg` over the code and caption, then modules and finders.
1531
+ * Texts follow every layer: the caption, then frame texts.
1532
+ */
1533
+ function buildGeometry(matrix, design) {
1534
+ const size = matrix.size + 2 * design.margin;
1535
+ const base = {
1536
+ width: size,
1537
+ height: size,
1538
+ qr: {
1539
+ x: 0,
1540
+ y: 0,
1541
+ size
1542
+ }
1543
+ };
1544
+ const captioned = design.caption ? layoutCaption(base, design.caption) : {
1545
+ layout: base,
1546
+ texts: [],
1547
+ warnings: []
1548
+ };
1549
+ const content = captioned.layout;
1550
+ const framed = applyFrames(content, design.frame);
1551
+ const layout = framed.layout;
1552
+ const [dx, dy] = [layout.qr.x - content.qr.x, layout.qr.y - content.qr.y];
1553
+ const offset = {
1554
+ x: layout.qr.x + design.margin,
1555
+ y: layout.qr.y + design.margin
1556
+ };
1557
+ const finder = getFinder(design.finder);
1558
+ const corners = matrix.finders.map(([x, y]) => [x + offset.x, y + offset.y]);
1559
+ const logo = design.image && logoBox(matrix, design.margin, design.image);
1560
+ const [w, h] = [coord(content.width), coord(content.height)];
1561
+ const geometry = {
1562
+ ...layout,
1563
+ paths: [
1564
+ ...framed.paths,
1565
+ {
1566
+ id: "bg",
1567
+ d: `M${coord(dx)} ${coord(dy)}h${w}v${h}h-${w}z`,
1568
+ paint: "bg"
1569
+ },
1570
+ {
1571
+ id: "modules",
1572
+ d: drawModules(matrix, toShape(design.modules), offset, logo?.cells),
1573
+ paint: "fg"
1574
+ },
1575
+ {
1576
+ id: "finder-outer",
1577
+ d: corners.map(([x, y]) => finder.outer(x, y)).join(""),
1578
+ fillRule: "evenodd",
1579
+ paint: "finder"
1580
+ },
1581
+ {
1582
+ id: "finder-inner",
1583
+ d: corners.map(([x, y]) => finder.inner(x, y)).join(""),
1584
+ paint: "finderInner"
1585
+ }
1586
+ ],
1587
+ texts: [...captioned.texts.map((t) => ({
1588
+ ...t,
1589
+ x: t.x + dx,
1590
+ y: t.y + dy
1591
+ })), ...framed.texts]
1592
+ };
1593
+ const warnings = [...captioned.warnings, ...framed.warnings ?? []];
1594
+ if (warnings.length) geometry.warnings = warnings;
1595
+ if (logo) {
1596
+ const { cells: _cells, x, y, ...rest } = logo;
1597
+ geometry.image = {
1598
+ ...rest,
1599
+ x: x + layout.qr.x,
1600
+ y: y + layout.qr.y
1601
+ };
1602
+ }
1603
+ return geometry;
1604
+ }
1605
+ function pickPaint(key, paints) {
1606
+ switch (key) {
1607
+ case "fg":
1608
+ case "bg": return paints[key];
1609
+ case "finder": return paints.finder ?? paints.fg;
1610
+ case "finderInner": return paints.finderInner ?? paints.finder ?? paints.fg;
1611
+ case "caption": return paints.caption ?? paints.fg;
1612
+ default: return key;
1613
+ }
1614
+ }
1615
+ /** Places every paint over the qr box. Path strings are reused, not copied. */
1616
+ function paintScene(geometry, paints) {
1617
+ const place = (key) => placePaint(pickPaint(key, paints), geometry.qr);
1618
+ const layers = [];
1619
+ for (const { id, d, fillRule, paint } of geometry.paths) {
1620
+ const fill = place(paint);
1621
+ if (fill === "transparent" || !d) continue;
1622
+ layers.push(fillRule ? {
1623
+ id,
1624
+ d,
1625
+ fill,
1626
+ fillRule
1627
+ } : {
1628
+ id,
1629
+ d,
1630
+ fill
1631
+ });
1632
+ }
1633
+ const texts = geometry.texts.map(({ paint, ...text }) => ({
1634
+ ...text,
1635
+ fill: place(paint)
1636
+ }));
1637
+ const { width, height, image } = geometry;
1638
+ return image ? {
1639
+ width,
1640
+ height,
1641
+ layers,
1642
+ image,
1643
+ texts
1644
+ } : {
1645
+ width,
1646
+ height,
1647
+ layers,
1648
+ texts
1649
+ };
1650
+ }
1651
+ // src/core/stages.ts
1652
+ /** An image covers modules, so it defaults to the stronger 'Q' level. */
1653
+ function applyLevelDefault(level, hasImage) {
1654
+ return level ?? (hasImage ? "Q" : "M");
1655
+ }
1656
+ /**
1657
+ * The encode options for a code, with scan-safety defaults applied.
1658
+ * With an image, `level` defaults to Q and `minVersion` to 2, capped by `maxVersion`.
1659
+ */
1660
+ function applyEncodingDefaults(options, hasImage) {
1661
+ const lift = Math.min(2, options.encoding?.maxVersion ?? 40);
1662
+ const minVersion = options.encoding?.minVersion ?? (hasImage ? lift : void 0);
1663
+ return {
1664
+ ...options.encoding,
1665
+ minVersion,
1666
+ level: applyLevelDefault(options.level, hasImage)
1667
+ };
1668
+ }
1669
+ /** The matrix stage. `hasImage` is a parameter so a new image src does not re-encode. */
1670
+ const toMatrix = (options, hasImage = !!options.image) => encode(options.value, applyEncodingDefaults(options, hasImage));
1671
+ /**
1672
+ * The geometry stage. Pass `finder` and `caption` to keep it from reading the options
1673
+ * that also hold colours.
1674
+ */
1675
+ const toGeometry = (matrix, options, finder, caption) => buildGeometry(matrix, toGeometryDesign(options, finder, caption));
1676
+ // src/core/warnings.ts
1677
+ /** WCAG 2 relative luminance. */
1678
+ function luminance(rgb) {
1679
+ const [r, g, b] = rgb.map((v) => {
1680
+ const c = v / 255;
1681
+ return c <= .03928 ? c / 12.92 : ((c + .055) / 1.055) ** 2.4;
1682
+ });
1683
+ return .2126 * r + .7152 * g + .0722 * b;
1684
+ }
1685
+ /** WCAG non-text contrast; a rough scan-safety floor. */
1686
+ const minContrast = 3;
1687
+ /** Lists scan risks in the options. The caller logs them in dev builds. */
1688
+ function devWarnings(o) {
1689
+ const warnings = [];
1690
+ const [fg, bg] = [parseColor(o.fg), parseColor(o.bg)];
1691
+ if (fg && bg) {
1692
+ const [fgLight, bgLight] = [luminance(fg), luminance(bg)];
1693
+ const [hi, lo] = [Math.max(fgLight, bgLight), Math.min(fgLight, bgLight)];
1694
+ const ratio = (hi + .05) / (lo + .05);
1695
+ if (ratio < minContrast) warnings.push(`Low contrast ${ratio.toFixed(2)}:1 between fg and bg; aim for ${minContrast}:1.`);
1696
+ else if (fgLight > bgLight) warnings.push("fg is lighter than bg: light-on-dark codes are not read by every scanner.");
1697
+ }
1698
+ if (o.margin < 2) warnings.push(`A margin of ${o.margin} leaves too small a quiet zone; use at least 2.`);
1699
+ if (o.image) {
1700
+ const size = o.image.size ?? .2;
1701
+ const clamped = clampImageSize(o.matrix, o.image);
1702
+ const at = `at level ${o.matrix.level}, version ${o.matrix.version}`;
1703
+ if (!clamped) warnings.push(`The logo does not fit ${at}; it was dropped to keep the code scannable.`);
1704
+ else if (clamped < size) warnings.push(`The logo was reduced to ${clamped.toFixed(3)} to keep the code scannable ${at}.`);
1705
+ }
1706
+ return warnings;
1707
+ }
1708
+ // src/primitives/createQRCode.ts
1709
+ /**
1710
+ * Derives the matrix, geometry and scene from options, which may be a reactive props object.
1711
+ * A colour change repaints the scene only; it does not encode or rebuild paths.
1712
+ */
1713
+ function createQRCode(options) {
1714
+ const hasImage = createMemo(() => !!options.image);
1715
+ const matrix = createMemo(() => toMatrix(options, hasImage()), { name: "qr.matrix" });
1716
+ const finderShape = createMemo(() => toFinderShape(options.finder), {
1717
+ name: "qr.finderShape",
1718
+ equals: (a, b) => a.outer === b.outer && a.inner === b.inner
1719
+ });
1720
+ const captionShape = createMemo(() => toCaptionShape(options.caption), {
1721
+ name: "qr.captionShape",
1722
+ equals: sameCaptionShape
1723
+ });
1724
+ const geometry = createMemo(() => toGeometry(matrix(), options, finderShape(), captionShape()), { name: "qr.geometry" });
1725
+ const scene = createMemo(() => paintScene(geometry(), toPaints(options)), { name: "qr.scene" });
1726
+ if (isDev) createEffect(() => devWarnings({
1727
+ fg: options.fg ?? defaults.fg,
1728
+ bg: options.bg ?? defaults.bg,
1729
+ margin: options.margin ?? defaults.margin,
1730
+ image: options.image,
1731
+ matrix: matrix()
1732
+ }).concat(geometry().warnings ?? []).map((w) => `[qrcodesolid] ${w}`).join("\n"), (text) => {
1733
+ if (text) console.warn(text);
1734
+ });
1735
+ return {
1736
+ matrix,
1737
+ geometry,
1738
+ scene
1739
+ };
1740
+ }
1741
+ // src/render/canvas.ts
1742
+ function fillStyle(ctx, paint, resolve) {
1743
+ if (typeof paint === "string") return resolve(paint);
1744
+ const gradient = paint.type === "linear" ? ctx.createLinearGradient(paint.x1, paint.y1, paint.x2, paint.y2) : ctx.createRadialGradient(paint.cx, paint.cy, 0, paint.cx, paint.cy, paint.r);
1745
+ for (const [offset, color] of paint.stops) gradient.addColorStop(offset, resolve(color));
1746
+ return gradient;
1747
+ }
1748
+ function sourceSize(source) {
1749
+ const s = source;
1750
+ const width = s.naturalWidth || s.videoWidth || s.displayWidth || s.width;
1751
+ const height = s.naturalHeight || s.videoHeight || s.displayHeight || s.height;
1752
+ return typeof width === "number" && typeof height === "number" ? [width, height] : [0, 0];
1753
+ }
1754
+ /** Draws the image centred in its box at its own aspect ratio, like `xMidYMid meet`. */
1755
+ function drawImage(ctx, source, box) {
1756
+ const [w, h] = sourceSize(source);
1757
+ const k = w && h ? Math.min(box.width / w, box.height / h) : 0;
1758
+ const [dw, dh] = k ? [w * k, h * k] : [box.width, box.height];
1759
+ ctx.save();
1760
+ ctx.beginPath();
1761
+ ctx.roundRect(box.x, box.y, box.width, box.height, box.radius);
1762
+ ctx.clip();
1763
+ ctx.globalAlpha = box.opacity;
1764
+ ctx.drawImage(source, box.x + (box.width - dw) / 2, box.y + (box.height - dh) / 2, dw, dh);
1765
+ ctx.restore();
1766
+ }
1767
+ /** Paints a scene onto a 2D context. The caller sizes and clears the canvas. */
1768
+ function drawScene(ctx, scene, options) {
1769
+ ctx.setTransform(options.scale, 0, 0, options.scale, 0, 0);
1770
+ for (const layer of scene.layers) {
1771
+ ctx.fillStyle = fillStyle(ctx, layer.fill, options.resolveColor);
1772
+ ctx.fill(new Path2D(layer.d), layer.fillRule ?? "nonzero");
1773
+ }
1774
+ if (scene.image && options.image) drawImage(ctx, options.image, scene.image);
1775
+ ctx.textAlign = "center";
1776
+ ctx.textBaseline = "middle";
1777
+ for (const text of scene.texts) {
1778
+ ctx.font = `${text.fontWeight} ${text.fontSize}px ${text.fontFamily}`;
1779
+ ctx.fillStyle = fillStyle(ctx, text.fill, options.resolveColor);
1780
+ ctx.fillText(text.text, text.x, text.y);
1781
+ }
1782
+ }
1783
+ // src/render/color.ts
1784
+ /**
1785
+ * Follows nested `var(--x, fallback)` to the innermost fallback.
1786
+ * A var with no fallback becomes black: canvas rejects a bare var() without a word.
1787
+ */
1788
+ function parseVarFallback(value) {
1789
+ let v = value.trim();
1790
+ while (v.startsWith("var(")) {
1791
+ const comma = v.indexOf(",");
1792
+ if (comma < 0) return "#000";
1793
+ v = v.slice(comma + 1, v.lastIndexOf(")")).trim();
1794
+ }
1795
+ return v;
1796
+ }
1797
+ /**
1798
+ * Turns a CSS colour into one canvas accepts. With `el`, custom properties and
1799
+ * `currentColor` resolve against `el` through a hidden probe child.
1800
+ */
1801
+ function resolveColor(value, el) {
1802
+ if (el?.isConnected) {
1803
+ const probe = document.createElement("span");
1804
+ probe.style.color = value;
1805
+ if (probe.style.color) {
1806
+ probe.style.display = "none";
1807
+ el.appendChild(probe);
1808
+ const color = getComputedStyle(probe).color;
1809
+ probe.remove();
1810
+ if (color) return color;
1811
+ }
1812
+ }
1813
+ const color = parseVarFallback(value);
1814
+ return color === "currentColor" ? "#000" : color;
1815
+ }
1816
+ /**
1817
+ * A `resolveColor` for one element that remembers each answer.
1818
+ * Layers share colours, and each probe lookup adds an element to the page.
1819
+ */
1820
+ function colorResolver(el) {
1821
+ const answers = /* @__PURE__ */ new Map();
1822
+ return (value) => {
1823
+ if (!answers.has(value)) answers.set(value, resolveColor(value, el));
1824
+ return answers.get(value);
1825
+ };
1826
+ }
1827
+ function resolvePaintColors(paint, resolve) {
1828
+ if (typeof paint === "string") return resolve(paint);
1829
+ return {
1830
+ ...paint,
1831
+ stops: paint.stops.map(([offset, c]) => [offset, resolve(c)])
1832
+ };
1833
+ }
1834
+ /**
1835
+ * Replaces var() and currentColor in every paint, for output that has no page CSS.
1836
+ * With `el`, they resolve against it, as on a canvas drawn there. A detached `el` is ignored.
1837
+ */
1838
+ function resolveSceneColors(scene, el) {
1839
+ const resolve = colorResolver(el);
1840
+ return {
1841
+ ...scene,
1842
+ layers: scene.layers.map((l) => ({
1843
+ ...l,
1844
+ fill: resolvePaintColors(l.fill, resolve)
1845
+ })),
1846
+ texts: scene.texts.map((t) => ({
1847
+ ...t,
1848
+ fill: resolvePaintColors(t.fill, resolve)
1849
+ }))
1850
+ };
1851
+ }
1852
+ // src/render/image.ts
1853
+ const browserIO = {
1854
+ fetch: (input, init) => fetch(input, init),
1855
+ makeImage: () => typeof Image === "undefined" ? void 0 : new Image(),
1856
+ decodeBlob: (blob) => createImageBitmap(blob)
1857
+ };
1858
+ const timeoutDefault = 1e4;
1859
+ const maxBytesDefault = 2097152;
1860
+ /**
1861
+ * Fetches the image with the CORS mode an `<img crossorigin>` would use.
1862
+ * Rejects on a timeout, a cancel, an HTTP error, a body over `maxBytes`, or a non-image body.
1863
+ */
1864
+ async function fetchImage(image, limits = {}, io = browserIO) {
1865
+ const { timeout = timeoutDefault, maxBytes = maxBytesDefault, signal } = limits;
1866
+ const credentials = image.crossOrigin === "use-credentials" ? "include" : "same-origin";
1867
+ const controller = new AbortController();
1868
+ const timer = setTimeout(() => controller.abort(/* @__PURE__ */ new Error(`Timed out after ${timeout} ms`)), timeout);
1869
+ const cancel = () => controller.abort(signal?.reason);
1870
+ signal?.addEventListener("abort", cancel, { once: true });
1871
+ const tooLarge = (bytes) => /* @__PURE__ */ new Error(`Image is ${bytes} bytes, over the ${maxBytes} byte limit`);
1872
+ try {
1873
+ signal?.throwIfAborted();
1874
+ const response = await io.fetch(image.src, {
1875
+ mode: "cors",
1876
+ credentials,
1877
+ signal: controller.signal
1878
+ });
1879
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
1880
+ const length = Number(response.headers.get("content-length"));
1881
+ if (length > maxBytes) {
1882
+ controller.abort();
1883
+ throw tooLarge(length);
1884
+ }
1885
+ const blob = await readBody(response, maxBytes, (bytes) => {
1886
+ controller.abort();
1887
+ return tooLarge(bytes);
1888
+ });
1889
+ if (!blob.type.startsWith("image/")) throw new Error(`Not an image: ${blob.type || "no type"}`);
1890
+ return blob;
1891
+ } finally {
1892
+ clearTimeout(timer);
1893
+ signal?.removeEventListener("abort", cancel);
1894
+ }
1895
+ }
1896
+ /** Reads the body, and stops once it passes `maxBytes`, so a huge logo is never held whole. */
1897
+ async function readBody(response, maxBytes, tooLarge) {
1898
+ if (!response.body) {
1899
+ const blob = await response.blob();
1900
+ if (blob.size > maxBytes) throw tooLarge(blob.size);
1901
+ return blob;
1902
+ }
1903
+ const reader = response.body.getReader();
1904
+ const chunks = [];
1905
+ let bytes = 0;
1906
+ for (let chunk = await reader.read(); !chunk.done; chunk = await reader.read()) {
1907
+ bytes += chunk.value.byteLength;
1908
+ if (bytes > maxBytes) {
1909
+ reader.cancel().catch(() => {});
1910
+ throw tooLarge(bytes);
1911
+ }
1912
+ chunks.push(chunk.value);
1913
+ }
1914
+ return new Blob(chunks, { type: response.headers.get("content-type") ?? "" });
1915
+ }
1916
+ /** Loads the image, or returns undefined when it fails: the code draws without it. */
1917
+ async function loadImage(image, limits = {}, io = browserIO) {
1918
+ const { timeout = timeoutDefault, signal, warn = true } = limits;
1919
+ try {
1920
+ signal?.throwIfAborted();
1921
+ const img = io.makeImage();
1922
+ if (!img) return await io.decodeBlob(await fetchImage(image, limits, io));
1923
+ if (image.crossOrigin !== void 0) img.crossOrigin = image.crossOrigin;
1924
+ img.src = image.src;
1925
+ let timer;
1926
+ let stop = () => {};
1927
+ const cancelled = new Promise((_resolve, reject) => {
1928
+ timer = setTimeout(() => reject(/* @__PURE__ */ new Error(`Timed out after ${timeout} ms`)), timeout);
1929
+ const onAbort = () => reject(signal?.reason);
1930
+ signal?.addEventListener("abort", onAbort, { once: true });
1931
+ stop = () => signal?.removeEventListener("abort", onAbort);
1932
+ });
1933
+ cancelled.catch(() => {});
1934
+ try {
1935
+ await Promise.race([img.decode(), cancelled]);
1936
+ } catch (err) {
1937
+ img.src = "";
1938
+ throw err;
1939
+ } finally {
1940
+ clearTimeout(timer);
1941
+ stop();
1942
+ }
1943
+ return img;
1944
+ } catch (err) {
1945
+ if (warn && !signal?.aborted) console.warn(`[qrcodesolid] Failed to load image: ${image.src}`, err);
1946
+ return;
1947
+ }
1948
+ }
1949
+ async function blobToDataURL(blob) {
1950
+ if (typeof FileReader !== "undefined") return new Promise((resolve, reject) => {
1951
+ const reader = new FileReader();
1952
+ reader.onload = () => resolve(reader.result);
1953
+ reader.onerror = () => reject(reader.error);
1954
+ reader.readAsDataURL(blob);
1955
+ });
1956
+ const bytes = new Uint8Array(await blob.arrayBuffer());
1957
+ let binary = "";
1958
+ for (let i = 0; i < bytes.length; i += 32768) binary += String.fromCharCode(...bytes.subarray(i, i + 32768));
1959
+ return `data:${blob.type || "application/octet-stream"};base64,${btoa(binary)}`;
1960
+ }
1961
+ // src/components/QRCodeCanvas.tsx
1962
+ var _sk$ = (k) => k === "aria-label";
1963
+ var _m$$2 = Symbol();
1964
+ var _d$$2 = {
1965
+ get() {
1966
+ return this[_m$$2].id;
1967
+ },
1968
+ enumerable: true,
1969
+ configurable: true
1970
+ };
1971
+ function _P$$2(_p, _p2) {
1972
+ this[_m$$2] = _p;
1973
+ this.role = _p2;
1974
+ Object.defineProperty(this, "id", _d$$2);
1975
+ }
1976
+ _P$$2.prototype = Object.prototype;
1977
+ /**
1978
+ * Renders a QR code to a canvas sized for the device pixel ratio.
1979
+ * It redraws when `prefers-color-scheme` changes, since CSS colours may depend on it.
1980
+ */
1981
+ function QRCodeCanvas(props) {
1982
+ const rest = omit(props, ...optionKeys, "onReady", "repaint", "imageTimeout");
1983
+ const { scene } = createQRCode(props);
1984
+ const ratio = createPixelRatio();
1985
+ const scheme = createColorScheme();
1986
+ const src = createMemo(() => props.image?.src, { name: "qr.imageSrc" });
1987
+ const crossOrigin = createMemo(() => props.image?.crossOrigin, { name: "qr.crossOrigin" });
1988
+ const imageTimeout = createMemo(() => props.imageTimeout, { name: "qr.imageTimeout" });
1989
+ const [loaded, setLoaded] = createSignal();
1990
+ let canvas;
1991
+ createEffect(() => [
1992
+ src(),
1993
+ crossOrigin(),
1994
+ imageTimeout()
1995
+ ], ([src, crossOrigin, timeout]) => {
1996
+ if (!src) return;
1997
+ const controller = new AbortController();
1998
+ loadImage({
1999
+ src,
2000
+ crossOrigin
2001
+ }, {
2002
+ timeout,
2003
+ signal: controller.signal,
2004
+ warn: isDev
2005
+ }).then((image) => {
2006
+ if (!controller.signal.aborted) setLoaded({
2007
+ src,
2008
+ image: image ?? "error"
2009
+ });
2010
+ });
2011
+ return () => controller.abort();
2012
+ });
2013
+ createEffect(() => {
2014
+ const result = loaded();
2015
+ return {
2016
+ scene: scene(),
2017
+ ratio: ratio(),
2018
+ scheme: scheme(),
2019
+ repaint: props.repaint,
2020
+ size: props.size,
2021
+ image: result && result.src === src() ? result.image : void 0,
2022
+ settled: !src() || result?.src === src(),
2023
+ onReady: props.onReady
2024
+ };
2025
+ }, {
2026
+ error: (err) => {
2027
+ throw err;
2028
+ },
2029
+ effect: ({ scene, ratio, size, image, settled, onReady }) => {
2030
+ const output = outputSize(scene, size);
2031
+ canvas.width = Math.round(output.width * ratio);
2032
+ canvas.height = Math.round(output.height * ratio);
2033
+ canvas.style.width = `${output.width}px`;
2034
+ canvas.style.height = `${output.height}px`;
2035
+ const ctx = canvas.getContext("2d");
2036
+ if (!ctx) throw new Error("[qrcodesolid] No 2D canvas context.");
2037
+ drawScene(ctx, scene, {
2038
+ scale: canvas.width / scene.width,
2039
+ image: image === "error" ? void 0 : image,
2040
+ resolveColor: colorResolver(canvas)
2041
+ });
2042
+ if (settled) onReady?.(canvas);
2043
+ }
2044
+ });
2045
+ return ssrElement("canvas", [new _P$$2(props, "img"), rest], void 0, true, _sk$, () => ssrElementAttribute("aria-label", ariaLabel(props, true)));
2046
+ }
2047
+ // src/render/svg-string.ts
2048
+ const entities = {
2049
+ "&": "&amp;",
2050
+ "<": "&lt;",
2051
+ ">": "&gt;",
2052
+ "\"": "&quot;",
2053
+ "'": "&apos;"
2054
+ };
2055
+ const escape = (s) => s.replace(/[&<>"']/g, (c) => entities[c]);
2056
+ /** Square-only scenes contain no curves or diagonals, so crisp edges cannot hurt them. */
2057
+ const isRectilinear = (d) => /^[MHVhvZz\d .-]*$/.test(d);
2058
+ function gradient(id, paint) {
2059
+ const stops = paint.stops.map(([offset, color]) => `<stop offset="${offset}" stop-color="${escape(color)}"/>`).join("");
2060
+ const attrs = paint.type === "linear" ? `x1="${paint.x1}" y1="${paint.y1}" x2="${paint.x2}" y2="${paint.y2}"` : `cx="${paint.cx}" cy="${paint.cy}" r="${paint.r}"`;
2061
+ const tag = paint.type === "linear" ? "linearGradient" : "radialGradient";
2062
+ return `<${tag} id="${escape(id)}" gradientUnits="userSpaceOnUse" ${attrs}>${stops}</${tag}>`;
2063
+ }
2064
+ /** Serialises a scene to a standalone SVG document string. */
2065
+ function sceneToSVGString(scene, options) {
2066
+ const { width, height, image } = scene;
2067
+ const defs = [];
2068
+ const fill = (id, paint) => {
2069
+ if (typeof paint === "string") return escape(paint);
2070
+ const ref = `${options.idPrefix}-${id}`;
2071
+ defs.push(gradient(ref, paint));
2072
+ return `url(#${escape(ref)})`;
2073
+ };
2074
+ const body = scene.layers.map((layer) => {
2075
+ const rule = layer.fillRule ? ` fill-rule="${layer.fillRule}"` : "";
2076
+ return `<path d="${escape(layer.d)}" fill="${fill(layer.id, layer.fill)}"${rule}/>`;
2077
+ });
2078
+ if (image) {
2079
+ const clip = `${options.idPrefix}-image-clip`;
2080
+ const box = `x="${coord(image.x)}" y="${coord(image.y)}" width="${coord(image.width)}" height="${coord(image.height)}"`;
2081
+ const r = coord(image.radius);
2082
+ defs.push(`<clipPath id="${escape(clip)}"><rect ${box} rx="${r}" ry="${r}"/></clipPath>`);
2083
+ const crossOrigin = image.crossOrigin === void 0 ? "" : ` crossorigin="${image.crossOrigin}"`;
2084
+ body.push(`<image href="${escape(image.href)}" ${box} opacity="${image.opacity}" preserveAspectRatio="xMidYMid meet" clip-path="url(#${escape(clip)})"${crossOrigin}/>`);
2085
+ }
2086
+ scene.texts.forEach((t, i) => {
2087
+ const font = `font-size="${coord(t.fontSize)}" font-family="${escape(t.fontFamily)}" font-weight="${escape(String(t.fontWeight))}"`;
2088
+ body.push(`<text x="${coord(t.x)}" y="${coord(t.y)}" ${font} fill="${fill(`text-${i}`, t.fill)}" text-anchor="middle" dominant-baseline="central">${escape(t.text)}</text>`);
2089
+ });
2090
+ const crisp = scene.layers.every((l) => isRectilinear(l.d)) ? " shape-rendering=\"crispEdges\"" : "";
2091
+ const title = options.title ? `<title>${escape(options.title)}</title>` : "";
2092
+ return `${`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${coord(width)} ${coord(height)}" width="${coord(options.size)}" height="${coord(options.size * height / width)}"${crisp}>`}${title}${defs.length ? `<defs>${defs.join("")}</defs>` : ""}${body.join("")}</svg>`;
2093
+ }
2094
+ // src/components/GradientDef.tsx
2095
+ var _tmpl$$1 = [
2096
+ "<stop",
2097
+ "",
2098
+ "",
2099
+ "></stop>"
2100
+ ];
2101
+ var _tmpl$2$1 = [
2102
+ "<linearGradient",
2103
+ "",
2104
+ " gradientUnits=\"userSpaceOnUse\"",
2105
+ "",
2106
+ "",
2107
+ "",
2108
+ ">",
2109
+ "</linearGradient>"
2110
+ ];
2111
+ var _tmpl$3$1 = [
2112
+ "<radialGradient",
2113
+ "",
2114
+ " gradientUnits=\"userSpaceOnUse\"",
2115
+ "",
2116
+ "",
2117
+ ">",
2118
+ "</radialGradient>"
2119
+ ];
2120
+ var _m$$1 = Symbol();
2121
+ var _m$2$1 = Symbol();
2122
+ var _d$$1 = {
2123
+ get() {
2124
+ return this[_m$$1].paint.stops;
2125
+ },
2126
+ enumerable: true,
2127
+ configurable: true
2128
+ };
2129
+ function _P$$1(_p, _p2, _p3) {
2130
+ this[_m$$1] = _p;
2131
+ Object.defineProperty(this, "each", _d$$1);
2132
+ this.keyed = _p2;
2133
+ this.children = _p3;
2134
+ }
2135
+ _P$$1.prototype = Object.prototype;
2136
+ var _d$2$1 = {
2137
+ get() {
2138
+ const props = this[_m$$1];
2139
+ return memo(() => {
2140
+ return props.paint.type === "linear";
2141
+ })() && props.paint;
2142
+ },
2143
+ enumerable: true,
2144
+ configurable: true
2145
+ };
2146
+ function _P$2$1(_p4, _p5) {
2147
+ this[_m$$1] = _p4;
2148
+ Object.defineProperty(this, "when", _d$2$1);
2149
+ this.children = _p5;
2150
+ }
2151
+ _P$2$1.prototype = Object.prototype;
2152
+ var _d$3$1 = {
2153
+ get() {
2154
+ const props = this[_m$$1];
2155
+ return memo(() => {
2156
+ return props.paint.type === "radial";
2157
+ })() && props.paint;
2158
+ },
2159
+ enumerable: true,
2160
+ configurable: true
2161
+ };
2162
+ function _P$3$1(_p6, _p7) {
2163
+ this[_m$$1] = _p6;
2164
+ Object.defineProperty(this, "when", _d$3$1);
2165
+ this.children = _p7;
2166
+ }
2167
+ _P$3$1.prototype = Object.prototype;
2168
+ var _d$4$1 = {
2169
+ get() {
2170
+ const props = this[_m$$1];
2171
+ const stops = this[_m$2$1];
2172
+ return [Match(new _P$2$1(props, (p) => {
2173
+ var _v$4 = ssrHydrationKey(), _g$2 = ssrGroup(() => {
2174
+ return [
2175
+ ssrAttribute("id", escape$1(props.id, true)),
2176
+ ssrAttribute("x1", escape$1(p().x1, true)),
2177
+ ssrAttribute("y1", escape$1(p().y1, true)),
2178
+ ssrAttribute("x2", escape$1(p().x2, true)),
2179
+ ssrAttribute("y2", escape$1(p().y2, true))
2180
+ ];
2181
+ }, 5), _v$10 = scope(() => {
2182
+ return escape$1(stops());
2183
+ });
2184
+ return ssr(_tmpl$2$1, _v$4, _g$2, _g$2, _g$2, _g$2, _g$2, _v$10);
2185
+ })), Match(new _P$3$1(props, (p) => {
2186
+ var _v$11 = ssrHydrationKey(), _g$3 = ssrGroup(() => {
2187
+ return [
2188
+ ssrAttribute("id", escape$1(props.id, true)),
2189
+ ssrAttribute("cx", escape$1(p().cx, true)),
2190
+ ssrAttribute("cy", escape$1(p().cy, true)),
2191
+ ssrAttribute("r", escape$1(p().r, true))
2192
+ ];
2193
+ }, 4), _v$16 = scope(() => {
2194
+ return escape$1(stops());
2195
+ });
2196
+ return ssr(_tmpl$3$1, _v$11, _g$3, _g$3, _g$3, _g$3, _v$16);
2197
+ }))];
2198
+ },
2199
+ enumerable: true,
2200
+ configurable: true
2201
+ };
2202
+ function _P$4$1(_p8, _p9) {
2203
+ this[_m$$1] = _p8;
2204
+ this[_m$2$1] = _p9;
2205
+ Object.defineProperty(this, "children", _d$4$1);
2206
+ }
2207
+ _P$4$1.prototype = Object.prototype;
2208
+ /** One `<defs>` gradient in user-space units, as `sceneToSVGString` writes it. */
2209
+ function GradientDef(props) {
2210
+ const stops = () => For(new _P$$1(props, false, (stop) => {
2211
+ var _v$ = ssrHydrationKey(), _g$ = ssrGroup(() => {
2212
+ return [ssrAttribute("offset", escape$1(stop()[0], true)), ssrAttribute("stop-color", escape$1(stop()[1], true))];
2213
+ }, 2);
2214
+ return ssr(_tmpl$$1, _v$, _g$, _g$);
2215
+ }));
2216
+ return Switch(new _P$4$1(props, stops));
2217
+ }
2218
+ // src/components/QRCodeSVG.tsx
2219
+ var _tmpl$ = [
2220
+ "<title",
2221
+ " id=\"",
2222
+ "\">",
2223
+ "</title>"
2224
+ ];
2225
+ var _tmpl$2 = [
2226
+ "<defs",
2227
+ "><!--$-->",
2228
+ "<!--/--><!--$-->",
2229
+ "<!--/--><!--$-->",
2230
+ "<!--/--></defs>"
2231
+ ];
2232
+ var _tmpl$3 = [
2233
+ "<clipPath",
2234
+ "",
2235
+ "><rect",
2236
+ "",
2237
+ "",
2238
+ "",
2239
+ "",
2240
+ "",
2241
+ "></rect></clipPath>"
2242
+ ];
2243
+ var _tmpl$4 = [
2244
+ "<path",
2245
+ "",
2246
+ "",
2247
+ "",
2248
+ "></path>"
2249
+ ];
2250
+ var _tmpl$5 = [
2251
+ "<text",
2252
+ "",
2253
+ "",
2254
+ "",
2255
+ "",
2256
+ "",
2257
+ "",
2258
+ " text-anchor=\"middle\" dominant-baseline=\"central\">",
2259
+ "</text>"
2260
+ ];
2261
+ var _m$ = Symbol();
2262
+ var _m$2 = Symbol();
2263
+ var _m$3 = Symbol();
2264
+ var _m$4 = Symbol();
2265
+ var _d$ = {
2266
+ get() {
2267
+ const prefix = this[_m$];
2268
+ const g = this[_m$2];
2269
+ return `${prefix()}-${g()[0]}`;
2270
+ },
2271
+ enumerable: true,
2272
+ configurable: true
2273
+ };
2274
+ var _d$2 = {
2275
+ get() {
2276
+ return (0, this[_m$2])()[1];
2277
+ },
2278
+ enumerable: true,
2279
+ configurable: true
2280
+ };
2281
+ function _P$(_p, _p2) {
2282
+ this[_m$] = _p;
2283
+ this[_m$2] = _p2;
2284
+ Object.defineProperty(this, "id", _d$);
2285
+ Object.defineProperty(this, "paint", _d$2);
2286
+ }
2287
+ _P$.prototype = Object.prototype;
2288
+ var _d$3 = {
2289
+ get() {
2290
+ return this[_m$].id;
2291
+ },
2292
+ enumerable: true,
2293
+ configurable: true
2294
+ };
2295
+ var _d$4 = {
2296
+ get() {
2297
+ const props = this[_m$];
2298
+ const prefix = this[_m$2];
2299
+ return props.title ? `${prefix()}-title` : void 0;
2300
+ },
2301
+ enumerable: true,
2302
+ configurable: true
2303
+ };
2304
+ var _d$5 = {
2305
+ get() {
2306
+ return ariaLabel(this[_m$], false);
2307
+ },
2308
+ enumerable: true,
2309
+ configurable: true
2310
+ };
2311
+ var _d$6 = {
2312
+ get() {
2313
+ const scene = this[_m$3];
2314
+ return `0 0 ${coord(scene().width)} ${coord(scene().height)}`;
2315
+ },
2316
+ enumerable: true,
2317
+ configurable: true
2318
+ };
2319
+ var _d$7 = {
2320
+ get() {
2321
+ const output = this[_m$4];
2322
+ return coord(output().width);
2323
+ },
2324
+ enumerable: true,
2325
+ configurable: true
2326
+ };
2327
+ var _d$8 = {
2328
+ get() {
2329
+ const output = this[_m$4];
2330
+ return coord(output().height);
2331
+ },
2332
+ enumerable: true,
2333
+ configurable: true
2334
+ };
2335
+ var _d$9 = {
2336
+ get() {
2337
+ return (0, this[_m$3])().layers.every((l) => isRectilinear(l.d)) ? "crispEdges" : void 0;
2338
+ },
2339
+ enumerable: true,
2340
+ configurable: true
2341
+ };
2342
+ function _P$2(_p3, _p4, _p5, _p6, _p7, _p8) {
2343
+ this[_m$] = _p3;
2344
+ this[_m$2] = _p4;
2345
+ this[_m$3] = _p5;
2346
+ this[_m$4] = _p6;
2347
+ this.xmlns = _p7;
2348
+ Object.defineProperty(this, "id", _d$3);
2349
+ this.role = _p8;
2350
+ Object.defineProperty(this, "aria-labelledby", _d$4);
2351
+ Object.defineProperty(this, "aria-label", _d$5);
2352
+ Object.defineProperty(this, "viewBox", _d$6);
2353
+ Object.defineProperty(this, "width", _d$7);
2354
+ Object.defineProperty(this, "height", _d$8);
2355
+ Object.defineProperty(this, "shape-rendering", _d$9);
2356
+ }
2357
+ _P$2.prototype = Object.prototype;
2358
+ var _d$10 = {
2359
+ get() {
2360
+ return this[_m$].title;
2361
+ },
2362
+ enumerable: true,
2363
+ configurable: true
2364
+ };
2365
+ function _P$3(_p9, _p0) {
2366
+ this[_m$] = _p9;
2367
+ Object.defineProperty(this, "when", _d$10);
2368
+ this.children = _p0;
2369
+ }
2370
+ _P$3.prototype = Object.prototype;
2371
+ var _d$11 = {
2372
+ get() {
2373
+ return (0, this[_m$])();
2374
+ },
2375
+ enumerable: true,
2376
+ configurable: true
2377
+ };
2378
+ function _P$4(_p1, _p10) {
2379
+ this[_m$] = _p1;
2380
+ Object.defineProperty(this, "when", _d$11);
2381
+ this.children = _p10;
2382
+ }
2383
+ _P$4.prototype = Object.prototype;
2384
+ var _d$12 = {
2385
+ get() {
2386
+ return (0, this[_m$])().layers;
2387
+ },
2388
+ enumerable: true,
2389
+ configurable: true
2390
+ };
2391
+ function _P$5(_p11, _p12, _p13) {
2392
+ this[_m$] = _p11;
2393
+ Object.defineProperty(this, "each", _d$12);
2394
+ this.keyed = _p12;
2395
+ this.children = _p13;
2396
+ }
2397
+ _P$5.prototype = Object.prototype;
2398
+ var _d$13 = {
2399
+ get() {
2400
+ return (0, this[_m$])().href;
2401
+ },
2402
+ enumerable: true,
2403
+ configurable: true
2404
+ };
2405
+ var _d$14 = {
2406
+ get() {
2407
+ const img = this[_m$];
2408
+ return coord(img().x);
2409
+ },
2410
+ enumerable: true,
2411
+ configurable: true
2412
+ };
2413
+ var _d$15 = {
2414
+ get() {
2415
+ const img = this[_m$];
2416
+ return coord(img().y);
2417
+ },
2418
+ enumerable: true,
2419
+ configurable: true
2420
+ };
2421
+ var _d$16 = {
2422
+ get() {
2423
+ const img = this[_m$];
2424
+ return coord(img().width);
2425
+ },
2426
+ enumerable: true,
2427
+ configurable: true
2428
+ };
2429
+ var _d$17 = {
2430
+ get() {
2431
+ const img = this[_m$];
2432
+ return coord(img().height);
2433
+ },
2434
+ enumerable: true,
2435
+ configurable: true
2436
+ };
2437
+ var _d$18 = {
2438
+ get() {
2439
+ return (0, this[_m$])().opacity;
2440
+ },
2441
+ enumerable: true,
2442
+ configurable: true
2443
+ };
2444
+ var _d$19 = {
2445
+ get() {
2446
+ return `url(#${(0, this[_m$2])()})`;
2447
+ },
2448
+ enumerable: true,
2449
+ configurable: true
2450
+ };
2451
+ function _P$6(_p14, _p15, _p16) {
2452
+ this[_m$] = _p14;
2453
+ this[_m$2] = _p15;
2454
+ Object.defineProperty(this, "href", _d$13);
2455
+ Object.defineProperty(this, "x", _d$14);
2456
+ Object.defineProperty(this, "y", _d$15);
2457
+ Object.defineProperty(this, "width", _d$16);
2458
+ Object.defineProperty(this, "height", _d$17);
2459
+ Object.defineProperty(this, "opacity", _d$18);
2460
+ this.preserveAspectRatio = _p16;
2461
+ Object.defineProperty(this, "clip-path", _d$19);
2462
+ }
2463
+ _P$6.prototype = Object.prototype;
2464
+ var _d$20 = {
2465
+ get() {
2466
+ return (0, this[_m$])();
2467
+ },
2468
+ enumerable: true,
2469
+ configurable: true
2470
+ };
2471
+ function _P$7(_p17, _p18) {
2472
+ this[_m$] = _p17;
2473
+ Object.defineProperty(this, "when", _d$20);
2474
+ this.children = _p18;
2475
+ }
2476
+ _P$7.prototype = Object.prototype;
2477
+ var _d$21 = {
2478
+ get() {
2479
+ return (0, this[_m$])().texts;
2480
+ },
2481
+ enumerable: true,
2482
+ configurable: true
2483
+ };
2484
+ function _P$8(_p19, _p20, _p21) {
2485
+ this[_m$] = _p19;
2486
+ Object.defineProperty(this, "each", _d$21);
2487
+ this.keyed = _p20;
2488
+ this.children = _p21;
2489
+ }
2490
+ _P$8.prototype = Object.prototype;
2491
+ /** Renders a QR code as inline SVG. The markup matches `sceneToSVGString`. */
2492
+ function QRCodeSVG(props) {
2493
+ const rest = omit(props, ...optionKeys);
2494
+ const { scene } = createQRCode(props);
2495
+ const uniqueId = createUniqueId();
2496
+ const prefix = () => props.id ?? `qr-${uniqueId}`;
2497
+ const output = () => outputSize(scene(), props.size);
2498
+ const fill = (id, paint) => typeof paint === "string" ? paint : `url(#${prefix()}-${id})`;
2499
+ const gradientsOf = (painted) => painted.filter((p) => typeof p[1] !== "string");
2500
+ const layerGradients = createMemo(() => gradientsOf(scene().layers.map((l) => [l.id, l.fill])));
2501
+ const textGradients = createMemo(() => gradientsOf(scene().texts.map((t, i) => [`text-${i}`, t.fill])));
2502
+ const gradientDefs = (gradients) => For({
2503
+ each: gradients,
2504
+ keyed: false,
2505
+ children: (g) => GradientDef(new _P$(prefix, g))
2506
+ });
2507
+ const image = () => scene().image;
2508
+ const clipId = () => `${prefix()}-image-clip`;
2509
+ return ssrElement("svg", [new _P$2(props, prefix, scene, output, "http://www.w3.org/2000/svg", "img"), rest], () => {
2510
+ return [
2511
+ "<!--$-->",
2512
+ escape$1(Show(new _P$3(props, (title) => {
2513
+ var _v$ = ssrHydrationKey(), _v$2 = () => {
2514
+ return `${escape$1(prefix(), true)}-title`;
2515
+ }, _v$3 = scope(() => {
2516
+ return escape$1(title());
2517
+ });
2518
+ return ssr(_tmpl$, _v$, _v$2, _v$3);
2519
+ }))),
2520
+ "<!--/-->",
2521
+ "<!--$-->",
2522
+ scope((() => {
2523
+ var _c$ = memo(() => {
2524
+ return !!(layerGradients().length > 0 || textGradients().length > 0 || image());
2525
+ });
2526
+ return () => {
2527
+ var _v$4, _v$5, _v$6, _v$7;
2528
+ return _c$() ? (_v$4 = ssrHydrationKey(), _v$5 = scope(() => {
2529
+ return escape$1(gradientDefs(layerGradients()));
2530
+ }), _v$6 = escape$1(Show(new _P$4(image, (img) => {
2531
+ var _v$8 = ssrHydrationKey(), _g$ = ssrGroup(() => {
2532
+ return [
2533
+ ssrAttribute("id", escape$1(clipId(), true)),
2534
+ ssrAttribute("x", escape$1(coord(img().x), true)),
2535
+ ssrAttribute("y", escape$1(coord(img().y), true)),
2536
+ ssrAttribute("width", escape$1(coord(img().width), true)),
2537
+ ssrAttribute("height", escape$1(coord(img().height), true)),
2538
+ ssrAttribute("rx", escape$1(coord(img().radius), true)),
2539
+ ssrAttribute("ry", escape$1(coord(img().radius), true))
2540
+ ];
2541
+ }, 7);
2542
+ return ssr(_tmpl$3, _v$8, _g$, _g$, _g$, _g$, _g$, _g$, _g$);
2543
+ }))), _v$7 = scope(() => {
2544
+ return escape$1(gradientDefs(textGradients()));
2545
+ }), ssr(_tmpl$2, _v$4, _v$5, _v$6, _v$7)) : void 0;
2546
+ };
2547
+ })()),
2548
+ "<!--/-->",
2549
+ "<!--$-->",
2550
+ escape$1(For(new _P$5(scene, false, (layer) => {
2551
+ var _v$16 = ssrHydrationKey(), _g$2 = ssrGroup(() => {
2552
+ return [
2553
+ ssrAttribute("d", escape$1(layer().d, true)),
2554
+ ssrAttribute("fill", escape$1(fill(layer().id, layer().fill), true)),
2555
+ ssrAttribute("fill-rule", escape$1(layer().fillRule, true))
2556
+ ];
2557
+ }, 3);
2558
+ return ssr(_tmpl$4, _v$16, _g$2, _g$2, _g$2);
2559
+ }))),
2560
+ "<!--/-->",
2561
+ "<!--$-->",
2562
+ escape$1(Show(new _P$7(image, (img) => ssrElement("image", [new _P$6(img, clipId, "xMidYMid meet"), () => {
2563
+ return { crossorigin: img().crossOrigin };
2564
+ }], void 0, true)))),
2565
+ "<!--/-->",
2566
+ "<!--$-->",
2567
+ escape$1(For(new _P$8(scene, false, (text, i) => {
2568
+ var _v$20 = ssrHydrationKey(), _g$3 = ssrGroup(() => {
2569
+ return [
2570
+ ssrAttribute("x", escape$1(coord(text().x), true)),
2571
+ ssrAttribute("y", escape$1(coord(text().y), true)),
2572
+ ssrAttribute("font-size", escape$1(coord(text().fontSize), true)),
2573
+ ssrAttribute("font-family", escape$1(text().fontFamily, true)),
2574
+ ssrAttribute("font-weight", escape$1(text().fontWeight, true)),
2575
+ ssrAttribute("fill", escape$1(fill(`text-${i}`, text().fill), true))
2576
+ ];
2577
+ }, 6), _v$27 = scope(() => {
2578
+ return escape$1(text().text);
2579
+ });
2580
+ return ssr(_tmpl$5, _v$20, _g$3, _g$3, _g$3, _g$3, _g$3, _g$3, _v$27);
2581
+ }))),
2582
+ "<!--/-->"
2583
+ ];
2584
+ }, true);
2585
+ }
2586
+ // src/components/QRCode.tsx
2587
+ /** Renders a QR code with the renderer that `renderAs` names. Default 'svg'. */
2588
+ function QRCode(props) {
2589
+ const rest = omit(props, "renderAs");
2590
+ return memo(() => {
2591
+ return memo(() => {
2592
+ return props.renderAs === "canvas";
2593
+ })() ? QRCodeCanvas(rest) : QRCodeSVG(rest);
2594
+ });
2595
+ }
2596
+ // src/export/index.ts
2597
+ const limitsOf = (o) => ({
2598
+ timeout: o.imageTimeout,
2599
+ maxBytes: o.imageMaxBytes
2600
+ });
2601
+ /** The scene `createQRCode` derives, computed once without Solid. */
2602
+ function toScene(options) {
2603
+ return paintScene(toGeometry(toMatrix(options), options), toPaints(options));
2604
+ }
2605
+ /**
2606
+ * A standalone SVG document. Ids start with `options.id`, else `qr`.
2607
+ * `resolveColors` replaces var() and currentColor, for files that have no page CSS.
2608
+ * `element` then resolves them against a mounted element; a detached one is ignored.
2609
+ */
2610
+ function toSVGString(options) {
2611
+ const scene = toScene(options);
2612
+ return serialise(options.resolveColors ? resolveSceneColors(scene, options.element) : scene, options);
2613
+ }
2614
+ const serialise = (scene, options) => sceneToSVGString(scene, {
2615
+ size: options.size ?? defaults.size,
2616
+ idPrefix: options.id ?? "qr",
2617
+ title: options.title
2618
+ });
2619
+ /** Inlines the logo as a data URL: a standalone SVG cannot load blob, relative or nested URLs. */
2620
+ async function embedImage(scene, options) {
2621
+ const { image } = options;
2622
+ if (!scene.image || !image || image.src.startsWith("data:")) return scene;
2623
+ try {
2624
+ const href = await blobToDataURL(await fetchImage(image, limitsOf(options)));
2625
+ return {
2626
+ ...scene,
2627
+ image: {
2628
+ ...scene.image,
2629
+ href
2630
+ }
2631
+ };
2632
+ } catch (err) {
2633
+ console.warn(`[qrcodesolid] Failed to embed image: ${image.src}. The SVG keeps the external URL.`, err);
2634
+ return scene;
2635
+ }
2636
+ }
2637
+ function makeCanvas(width, height) {
2638
+ if (typeof OffscreenCanvas !== "undefined") return new OffscreenCanvas(width, height);
2639
+ return Object.assign(document.createElement("canvas"), {
2640
+ width,
2641
+ height
2642
+ });
2643
+ }
2644
+ /** Draws the code onto `canvas`, or onto a new canvas, preferring OffscreenCanvas. */
2645
+ async function toCanvas(options, canvas) {
2646
+ const scene = toScene(options);
2647
+ const image = scene.image && options.image ? await loadImage(options.image, limitsOf(options)) : void 0;
2648
+ const width = Math.round((options.size ?? defaults.size) * (options.scale ?? 1));
2649
+ const height = Math.round(outputSize(scene, width).height);
2650
+ const target = canvas ?? makeCanvas(width, height);
2651
+ Object.assign(target, {
2652
+ width,
2653
+ height
2654
+ });
2655
+ const ctx = target.getContext("2d");
2656
+ if (!ctx) throw new Error("[qrcodesolid] No 2D canvas context.");
2657
+ drawScene(ctx, scene, {
2658
+ scale: width / scene.width,
2659
+ image,
2660
+ resolveColor: colorResolver(options.element)
2661
+ });
2662
+ return target;
2663
+ }
2664
+ /** A PNG of the code. Rejects with a SecurityError when a cross-origin image taints it. */
2665
+ async function toPNGBlob(options) {
2666
+ const canvas = await toCanvas(options);
2667
+ if (!("toBlob" in canvas)) return canvas.convertToBlob({ type: "image/png" });
2668
+ return new Promise((resolve, reject) => canvas.toBlob((blob) => blob ? resolve(blob) : reject(/* @__PURE__ */ new Error("[qrcodesolid] PNG encoding failed.")), "image/png"));
2669
+ }
2670
+ /** A standalone SVG file: colours resolved and the logo embedded. */
2671
+ async function toSVGFile(options) {
2672
+ return serialise(resolveSceneColors(await embedImage(toScene(options), options), options.element), options);
2673
+ }
2674
+ /**
2675
+ * A data URL of the code as PNG or SVG. SVG colours are resolved: a data URL has no page CSS.
2676
+ * The SVG embeds the logo as a data URL, or keeps its URL when the fetch fails.
2677
+ */
2678
+ async function toDataURL(options, type = "image/png") {
2679
+ if (type === "image/svg+xml") return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(await toSVGFile(options))}`;
2680
+ return blobToDataURL(await toPNGBlob(options));
2681
+ }
2682
+ /** Saves the code as a file. A `.svg` filename saves SVG with the logo embedded, any other saves PNG. */
2683
+ async function download(options, filename = "qrcode.png") {
2684
+ const blob = filename.toLowerCase().endsWith(".svg") ? new Blob([await toSVGFile(options)], { type: "image/svg+xml" }) : await toPNGBlob(options);
2685
+ const url = URL.createObjectURL(blob);
2686
+ const a = Object.assign(document.createElement("a"), {
2687
+ href: url,
2688
+ download: filename
2689
+ });
2690
+ a.style.display = "none";
2691
+ document.body.append(a);
2692
+ a.click();
2693
+ a.remove();
2694
+ setTimeout(() => URL.revokeObjectURL(url), 0);
2695
+ }
2696
+ async function copyToClipboard(options) {
2697
+ await navigator.clipboard.write([new ClipboardItem({ "image/png": toPNGBlob(options) })]);
2698
+ }
2699
+ // src/shapes/bars.ts
2700
+ const inset = .1;
2701
+ const radius = .4;
2702
+ /** Pill for one run of `length` cells. `cross` is the cell column (or row), `start` the run origin. */
2703
+ const pill = (vertical, cross, start, length) => {
2704
+ const c0 = cross + inset;
2705
+ const c1 = cross + 1 - inset;
2706
+ const s0 = start + radius;
2707
+ const s1 = start + length - radius;
2708
+ const p = (c, s) => vertical ? `${coord(c)} ${coord(s)}` : `${coord(s)} ${coord(c)}`;
2709
+ const arc = `A${radius} ${radius} 0 0 ${vertical ? 1 : 0}`;
2710
+ return `M${p(c0, s0)}${arc} ${p(c1, s0)}L${p(c1, s1)}${arc} ${p(c0, s1)}z`;
2711
+ };
2712
+ function bars(vertical) {
2713
+ return defineLayerShape(({ matrix: m, include, offset }) => {
2714
+ const on = (a, b) => {
2715
+ const [x, y] = vertical ? [a, b] : [b, a];
2716
+ return include(x, y) && isDark(m, x, y);
2717
+ };
2718
+ const solid = (a, b) => {
2719
+ const [x, y] = vertical ? [a, b] : [b, a];
2720
+ return m.region[y * m.size + x] === Region.Alignment;
2721
+ };
2722
+ let d = "";
2723
+ for (let a = 0; a < m.size; a++) {
2724
+ let b = 0;
2725
+ while (b < m.size) {
2726
+ if (!on(a, b)) {
2727
+ b++;
2728
+ continue;
2729
+ }
2730
+ const start = b;
2731
+ if (solid(a, b)) {
2732
+ b++;
2733
+ const [x, y] = vertical ? [a, start] : [start, a];
2734
+ d += `M${coord(x + offset.x)} ${coord(y + offset.y)}h1v1h-1z`;
2735
+ continue;
2736
+ }
2737
+ while (b < m.size && on(a, b) && !solid(a, b)) b++;
2738
+ const cross = (vertical ? offset.x : offset.y) + a;
2739
+ d += pill(vertical, cross, (vertical ? offset.y : offset.x) + start, b - start);
2740
+ }
2741
+ }
2742
+ return d;
2743
+ });
2744
+ }
2745
+ const verticalBars = bars(true);
2746
+ const horizontalBars = bars(false);
2747
+ // src/shapes/frames.ts
2748
+ const fontFamily = "system-ui, sans-serif";
2749
+ /** Moves the code by `pad` and grows the layout by `pad` on every side. */
2750
+ const grow = ({ width, height, qr }, pad) => ({
2751
+ width: width + 2 * pad,
2752
+ height: height + 2 * pad,
2753
+ qr: {
2754
+ ...qr,
2755
+ x: qr.x + pad,
2756
+ y: qr.y + pad
2757
+ }
2758
+ });
2759
+ /** A ring of `width` modules around the code. Default colour is fg. */
2760
+ function border(o = {}) {
2761
+ const { width: w = 1, radius = 0, color = "fg" } = o;
2762
+ return (inner) => {
2763
+ const layout = grow(inner, w);
2764
+ return {
2765
+ layout,
2766
+ paths: [{
2767
+ id: "frame-border",
2768
+ d: rect(0, 0, layout.width, layout.height, radius) + rect(w, w, inner.width, inner.height, Math.max(radius - w, 0)),
2769
+ fillRule: "evenodd",
2770
+ paint: color
2771
+ }],
2772
+ texts: []
2773
+ };
2774
+ };
2775
+ }
2776
+ /** A rounded panel `padding` modules wider than the code on every side. */
2777
+ function card(o = {}) {
2778
+ const { padding = 2, radius = 2, color = "#fff" } = o;
2779
+ return (inner) => {
2780
+ const layout = grow(inner, padding);
2781
+ return {
2782
+ layout,
2783
+ paths: [{
2784
+ id: "frame-card",
2785
+ d: rect(0, 0, layout.width, layout.height, radius),
2786
+ paint: color
2787
+ }],
2788
+ texts: []
2789
+ };
2790
+ };
2791
+ }
2792
+ /**
2793
+ * A band with a label above or below the code, outside its quiet zone.
2794
+ * Long text shrinks to fit the width, down to 1 module, and the band shrinks with it.
2795
+ */
2796
+ function banner(o) {
2797
+ const { text, position = "bottom", color = "#000", textColor = "#fff" } = o;
2798
+ return ({ width, height, qr }) => {
2799
+ const fitted = fitFontSize(text, o.fontSize ?? 2, width);
2800
+ const { fontSize } = fitted;
2801
+ const warning = overflowWarning("banner text", text, fitted, width, "the banner");
2802
+ const band = fontSize * 2;
2803
+ const top = position === "top";
2804
+ const y = top ? 0 : height;
2805
+ const label = {
2806
+ text,
2807
+ x: width / 2,
2808
+ y: y + band / 2,
2809
+ fontSize,
2810
+ fontFamily,
2811
+ fontWeight: "bold",
2812
+ paint: textColor
2813
+ };
2814
+ return {
2815
+ layout: {
2816
+ width,
2817
+ height: height + band,
2818
+ qr: top ? {
2819
+ ...qr,
2820
+ y: qr.y + band
2821
+ } : qr
2822
+ },
2823
+ paths: [{
2824
+ id: "frame-banner",
2825
+ d: rect(0, y, width, band, 0),
2826
+ paint: color
2827
+ }],
2828
+ texts: [label],
2829
+ warnings: warning ? [warning] : []
2830
+ };
2831
+ };
2832
+ }
2833
+ export { QRCapacityError, QRCode, QRCodeCanvas, QRCodeSVG, Region, banner, border, card, copyToClipboard, createColorScheme, createPixelRatio, createQRCode, defineLayerShape, defineModuleShape, diamond, dots, download, drawScene, encode, finderInner, finderOuter, getFinder, horizontalBars, isDark, resolveSceneColors, rounded, sceneToSVGString, square, toCanvas, toDataURL, toPNGBlob, toSVGString, toScene, verticalBars };