qr-code-styling-node 1.6.0 → 1.7.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.
@@ -1313,6 +1313,234 @@ var QRCornerDot2 = class {
1313
1313
  }
1314
1314
  };
1315
1315
 
1316
+ // src/tools/svgDom.ts
1317
+ var SVG_NS = "http://www.w3.org/2000/svg";
1318
+ var escapeAttribute = (value) => value.replace(/[&<>"\t\n\r]/g, (char) => {
1319
+ switch (char) {
1320
+ case "&":
1321
+ return "&amp;";
1322
+ case "<":
1323
+ return "&lt;";
1324
+ case ">":
1325
+ return "&gt;";
1326
+ case '"':
1327
+ return "&quot;";
1328
+ case " ":
1329
+ return "&#x9;";
1330
+ case "\n":
1331
+ return "&#xA;";
1332
+ default:
1333
+ return "&#xD;";
1334
+ }
1335
+ });
1336
+ var VirtualSVGElement = class _VirtualSVGElement {
1337
+ constructor(tagName) {
1338
+ this.namespaceURI = SVG_NS;
1339
+ this.parentNode = null;
1340
+ this.childNodes = [];
1341
+ this._attributes = /* @__PURE__ */ new Map();
1342
+ this.tagName = tagName;
1343
+ }
1344
+ get nodeName() {
1345
+ return this.tagName;
1346
+ }
1347
+ setAttribute(name, value) {
1348
+ this._attributes.set(name, String(value));
1349
+ }
1350
+ getAttribute(name) {
1351
+ const value = this._attributes.get(name);
1352
+ return value === void 0 ? null : value;
1353
+ }
1354
+ removeAttribute(name) {
1355
+ this._attributes.delete(name);
1356
+ }
1357
+ appendChild(child) {
1358
+ if (child.parentNode) child.parentNode.removeChild(child);
1359
+ child.parentNode = this;
1360
+ this.childNodes.push(child);
1361
+ return child;
1362
+ }
1363
+ removeChild(child) {
1364
+ const index = this.childNodes.indexOf(child);
1365
+ if (index !== -1) this.childNodes.splice(index, 1);
1366
+ child.parentNode = null;
1367
+ return child;
1368
+ }
1369
+ replaceChild(newChild, oldChild) {
1370
+ const index = this.childNodes.indexOf(oldChild);
1371
+ if (index !== -1) {
1372
+ if (newChild.parentNode) newChild.parentNode.removeChild(newChild);
1373
+ this.childNodes[index] = newChild;
1374
+ newChild.parentNode = this;
1375
+ oldChild.parentNode = null;
1376
+ }
1377
+ return oldChild;
1378
+ }
1379
+ cloneNode(deep = false) {
1380
+ const clone = new _VirtualSVGElement(this.tagName);
1381
+ this._attributes.forEach((value, name) => clone.setAttribute(name, value));
1382
+ if (deep) this.childNodes.forEach((child) => clone.appendChild(child.cloneNode(true)));
1383
+ return clone;
1384
+ }
1385
+ serialize(isRoot = true) {
1386
+ let markup = `<${this.tagName}`;
1387
+ if (isRoot) markup += ` xmlns="${SVG_NS}"`;
1388
+ this._attributes.forEach((value, name) => {
1389
+ markup += ` ${name}="${escapeAttribute(value)}"`;
1390
+ });
1391
+ if (!this.childNodes.length) return `${markup}/>`;
1392
+ markup += ">";
1393
+ for (const child of this.childNodes) markup += child.serialize(false);
1394
+ return `${markup}</${this.tagName}>`;
1395
+ }
1396
+ };
1397
+ var VirtualXMLSerializer = class {
1398
+ serializeToString(node) {
1399
+ return node.serialize(true);
1400
+ }
1401
+ };
1402
+ var VirtualDocument = class {
1403
+ createElementNS(_namespace, tagName) {
1404
+ return new VirtualSVGElement(tagName);
1405
+ }
1406
+ };
1407
+ var createVirtualWindow = () => ({
1408
+ document: new VirtualDocument(),
1409
+ XMLSerializer: VirtualXMLSerializer,
1410
+ isVirtual: true
1411
+ });
1412
+ var hasBrowserDom = () => typeof window !== "undefined" && typeof document !== "undefined" && typeof document.createElementNS === "function";
1413
+
1414
+ // src/tools/imageSize.ts
1415
+ var decodeBase64 = (base64) => {
1416
+ if (typeof atob === "function") {
1417
+ const binary = atob(base64);
1418
+ const bytes = new Uint8Array(binary.length);
1419
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
1420
+ return bytes;
1421
+ }
1422
+ return new Uint8Array(Buffer.from(base64, "base64"));
1423
+ };
1424
+ var encodeBase64 = (bytes) => {
1425
+ if (typeof btoa === "function") {
1426
+ let binary = "";
1427
+ const chunk = 32768;
1428
+ for (let i = 0; i < bytes.length; i += chunk) {
1429
+ binary += String.fromCharCode.apply(null, Array.from(bytes.subarray(i, i + chunk)));
1430
+ }
1431
+ return btoa(binary);
1432
+ }
1433
+ return Buffer.from(bytes).toString("base64");
1434
+ };
1435
+ var sniffMimeType = (bytes) => {
1436
+ if (bytes[0] === 137 && bytes[1] === 80 && bytes[2] === 78 && bytes[3] === 71) return "image/png";
1437
+ if (bytes[0] === 255 && bytes[1] === 216) return "image/jpeg";
1438
+ if (bytes[0] === 71 && bytes[1] === 73 && bytes[2] === 70) return "image/gif";
1439
+ if (ascii(bytes, 0, 4) === "RIFF" && ascii(bytes, 8, 12) === "WEBP") return "image/webp";
1440
+ const head = ascii(bytes, 0, Math.min(bytes.length, 1024)).toLowerCase();
1441
+ if (head.includes("<svg")) return "image/svg+xml";
1442
+ return "application/octet-stream";
1443
+ };
1444
+ var loadImageData = async (source) => {
1445
+ var _a;
1446
+ const dataUrl = /^data:([^;,]*)((?:;[^;,]*)*?)(;base64)?,([\s\S]*)$/.exec(source);
1447
+ if (dataUrl) {
1448
+ const [, mimeType, , base64, payload] = dataUrl;
1449
+ const bytes2 = base64 ? decodeBase64(payload) : new TextEncoder().encode(decodeURIComponent(payload));
1450
+ return { bytes: bytes2, mimeType: mimeType || sniffMimeType(bytes2) };
1451
+ }
1452
+ if (typeof fetch !== "function") {
1453
+ throw new Error("Loading an image URL needs a global fetch (Node.js 18+), or pass the image as a data URL.");
1454
+ }
1455
+ const response = await fetch(source);
1456
+ if (!response.ok) throw new Error(`Failed to load image ${source}: HTTP ${response.status}`);
1457
+ const bytes = new Uint8Array(await response.arrayBuffer());
1458
+ const header = (_a = response.headers.get("content-type")) == null ? void 0 : _a.split(";")[0].trim();
1459
+ return { bytes, mimeType: header && header.startsWith("image/") ? header : sniffMimeType(bytes) };
1460
+ };
1461
+ var toDataUrl = ({ bytes, mimeType }) => `data:${mimeType};base64,${encodeBase64(bytes)}`;
1462
+ function ascii(bytes, start, end) {
1463
+ let result = "";
1464
+ for (let i = start; i < end && i < bytes.length; i++) result += String.fromCharCode(bytes[i]);
1465
+ return result;
1466
+ }
1467
+ var uint16BE = (b, i) => b[i] << 8 | b[i + 1];
1468
+ var uint16LE = (b, i) => b[i] | b[i + 1] << 8;
1469
+ var uint24LE = (b, i) => b[i] | b[i + 1] << 8 | b[i + 2] << 16;
1470
+ var uint32BE = (b, i) => (b[i] << 24 | b[i + 1] << 16 | b[i + 2] << 8 | b[i + 3]) >>> 0;
1471
+ var svgLength = (value) => {
1472
+ if (!value) return void 0;
1473
+ const match = /^\s*([\d.]+)\s*(px)?\s*$/.exec(value);
1474
+ return match ? parseFloat(match[1]) : void 0;
1475
+ };
1476
+ var svgSize = (bytes) => {
1477
+ var _a, _b;
1478
+ const text = new TextDecoder().decode(bytes);
1479
+ const tag = (_a = /<svg\b[^>]*>/i.exec(text)) == null ? void 0 : _a[0];
1480
+ if (!tag) return null;
1481
+ const attr = (name) => {
1482
+ var _a2;
1483
+ return (_a2 = new RegExp(`\\s${name}\\s*=\\s*(["'])([^"']*)\\1`, "i").exec(tag)) == null ? void 0 : _a2[2];
1484
+ };
1485
+ let width = svgLength(attr("width"));
1486
+ let height = svgLength(attr("height"));
1487
+ const viewBox = (_b = attr("viewBox")) == null ? void 0 : _b.trim().split(/[\s,]+/).map(Number);
1488
+ if (viewBox && viewBox.length === 4 && viewBox[2] > 0 && viewBox[3] > 0) {
1489
+ const ratio = viewBox[2] / viewBox[3];
1490
+ if (width === void 0 && height === void 0) {
1491
+ width = viewBox[2];
1492
+ height = viewBox[3];
1493
+ } else if (width === void 0 && height !== void 0) {
1494
+ width = height * ratio;
1495
+ } else if (height === void 0 && width !== void 0) {
1496
+ height = width / ratio;
1497
+ }
1498
+ }
1499
+ return { width: width != null ? width : 300, height: height != null ? height : 150 };
1500
+ };
1501
+ var jpegSize = (b) => {
1502
+ let i = 2;
1503
+ while (i + 9 < b.length) {
1504
+ if (b[i] !== 255) {
1505
+ i++;
1506
+ continue;
1507
+ }
1508
+ const marker = b[i + 1];
1509
+ if (marker === 216 || marker === 1 || marker >= 208 && marker <= 215) {
1510
+ i += 2;
1511
+ continue;
1512
+ }
1513
+ if (marker >= 192 && marker <= 207 && marker !== 196 && marker !== 200 && marker !== 204) {
1514
+ return { height: uint16BE(b, i + 5), width: uint16BE(b, i + 7) };
1515
+ }
1516
+ i += 2 + uint16BE(b, i + 2);
1517
+ }
1518
+ return null;
1519
+ };
1520
+ var webpSize = (b) => {
1521
+ const chunk = ascii(b, 12, 16);
1522
+ if (chunk === "VP8 ") return { width: uint16LE(b, 26) & 16383, height: uint16LE(b, 28) & 16383 };
1523
+ if (chunk === "VP8L") {
1524
+ const bits = b[21] | b[22] << 8 | b[23] << 16 | b[24] << 24;
1525
+ return { width: (bits & 16383) + 1, height: (bits >> 14 & 16383) + 1 };
1526
+ }
1527
+ if (chunk === "VP8X") return { width: uint24LE(b, 24) + 1, height: uint24LE(b, 27) + 1 };
1528
+ return null;
1529
+ };
1530
+ var getImageSize = ({ bytes, mimeType }) => {
1531
+ const type = mimeType === "application/octet-stream" ? sniffMimeType(bytes) : mimeType;
1532
+ let size = null;
1533
+ if (type === "image/png") size = { width: uint32BE(bytes, 16), height: uint32BE(bytes, 20) };
1534
+ else if (type === "image/gif") size = { width: uint16LE(bytes, 6), height: uint16LE(bytes, 8) };
1535
+ else if (type === "image/jpeg" || type === "image/jpg") size = jpegSize(bytes);
1536
+ else if (type === "image/webp") size = webpSize(bytes);
1537
+ else if (type === "image/svg+xml") size = svgSize(bytes);
1538
+ if (!size || !size.width || !size.height) {
1539
+ throw new Error(`Cannot read the size of the image (${type}). Supported: PNG, JPEG, GIF, WebP, SVG.`);
1540
+ }
1541
+ return size;
1542
+ };
1543
+
1316
1544
  // src/core/QRSVG.ts
1317
1545
  var squareMask2 = [
1318
1546
  [1, 1, 1, 1, 1, 1, 1],
@@ -1335,18 +1563,23 @@ var dotMask2 = [
1335
1563
  var QRSVG = class {
1336
1564
  //TODO don't pass all options to this class
1337
1565
  constructor(options) {
1566
+ /** True when no browser DOM or jsdom is available and the built-in virtual DOM is used. */
1567
+ this._virtual = false;
1338
1568
  var _a;
1339
1569
  if (options.jsdom) {
1340
1570
  this._window = new options.jsdom("", { resources: "usable" }).window;
1341
- } else {
1571
+ } else if (hasBrowserDom()) {
1342
1572
  this._window = window;
1573
+ } else {
1574
+ this._window = createVirtualWindow();
1575
+ this._virtual = true;
1343
1576
  }
1344
1577
  this._element = this._window.document.createElementNS("http://www.w3.org/2000/svg", "svg");
1345
1578
  this._element.setAttribute("width", String(options.width));
1346
1579
  this._element.setAttribute("height", String(options.height));
1347
1580
  this._defs = this._window.document.createElementNS("http://www.w3.org/2000/svg", "defs");
1348
1581
  this._element.appendChild(this._defs);
1349
- if (options.imageOptions.saveAsBlob) {
1582
+ if (options.imageOptions.saveAsBlob && !this._virtual) {
1350
1583
  if ((_a = options.nodeCanvas) == null ? void 0 : _a.createCanvas) {
1351
1584
  this._canvas = options.nodeCanvas.createCanvas(options.width, options.height);
1352
1585
  } else {
@@ -1644,11 +1877,23 @@ var QRSVG = class {
1644
1877
  if (ctx) {
1645
1878
  ctx.drawImage(this._image, 0, 0, this._canvas.width, this._canvas.height);
1646
1879
  this._imageUri = this._canvas.toDataURL("image/png");
1647
- console.log(this._imageUri);
1648
1880
  }
1649
1881
  }
1650
1882
  }
1883
+ async _loadImageWithoutDom() {
1884
+ const source = this._options.image;
1885
+ if (!source) throw "Image is not defined";
1886
+ const data = await loadImageData(source);
1887
+ const { width, height } = getImageSize(data);
1888
+ this._image = { width, height };
1889
+ if (this._options.imageOptions.saveAsBlob && !source.startsWith("data:")) {
1890
+ this._imageUri = toDataUrl(data);
1891
+ }
1892
+ }
1651
1893
  loadImage() {
1894
+ if (this._virtual) {
1895
+ return this._loadImageWithoutDom();
1896
+ }
1652
1897
  return new Promise((resolve, reject) => {
1653
1898
  var _a;
1654
1899
  const options = this._options;
@@ -1894,6 +2139,11 @@ var QRCodeStyling = class _QRCodeStyling {
1894
2139
  this._options = options ? sanitizeOptions(mergeDeep(QROptions_default, options)) : QROptions_default;
1895
2140
  this.update();
1896
2141
  }
2142
+ /** Canvas output needs a browser canvas or node-canvas. */
2143
+ _canUseCanvas() {
2144
+ var _a;
2145
+ return !!((_a = this._options.nodeCanvas) == null ? void 0 : _a.createCanvas) || hasBrowserDom();
2146
+ }
1897
2147
  static _clearContainer(container) {
1898
2148
  if (container) {
1899
2149
  container.innerHTML = "";
@@ -1913,6 +2163,11 @@ var QRCodeStyling = class _QRCodeStyling {
1913
2163
  await promise;
1914
2164
  return svg;
1915
2165
  } else {
2166
+ if (!this._canUseCanvas()) {
2167
+ throw new Error(
2168
+ `Rendering "${extension}" outside the browser needs node-canvas (pass { nodeCanvas: require("canvas") }) or, for png, resvg (pass { resvg: require("@resvg/resvg-js").Resvg }). SVG output needs neither.`
2169
+ );
2170
+ }
1916
2171
  let promise, canvas;
1917
2172
  if (this._canvas && this._canvasDrawingPromise) {
1918
2173
  canvas = this._canvas;
@@ -1934,7 +2189,12 @@ var QRCodeStyling = class _QRCodeStyling {
1934
2189
  this._qr = qrcode(this._options.qrOptions.typeNumber, this._options.qrOptions.errorCorrectionLevel);
1935
2190
  this._qr.addData(this._options.data, this._options.qrOptions.mode || getMode(this._options.data));
1936
2191
  this._qr.make();
1937
- if (this._options.type === drawTypes_default.canvas) {
2192
+ if (this._options.type === drawTypes_default.canvas && !this._canUseCanvas()) {
2193
+ this._canvas = void 0;
2194
+ this._canvasDrawingPromise = void 0;
2195
+ this._svg = void 0;
2196
+ this._svgDrawingPromise = void 0;
2197
+ } else if (this._options.type === drawTypes_default.canvas) {
1938
2198
  this._canvas = new QRCanvas(this._options);
1939
2199
  this._canvasDrawingPromise = this._canvas.drawQR(this._qr);
1940
2200
  this._svgDrawingPromise = void 0;
@@ -1965,9 +2225,66 @@ var QRCodeStyling = class _QRCodeStyling {
1965
2225
  }
1966
2226
  this._container = container;
1967
2227
  }
2228
+ static _serializeSVG(svg) {
2229
+ const serializer = new svg._window.XMLSerializer();
2230
+ return `<?xml version="1.0" standalone="no"?>\r
2231
+ ${serializer.serializeToString(svg.getElement())}`;
2232
+ }
2233
+ async _getSVGString() {
2234
+ const svg = await this._getQRStylingElement("svg");
2235
+ return { svgString: _QRCodeStyling._serializeSVG(svg), svg };
2236
+ }
2237
+ /**
2238
+ * resvg follows the SVG spec more strictly than browsers: it does not accept quoted url('#id')
2239
+ * references, and it hides elements whose clip-path points to a missing id. Browsers ignore both,
2240
+ * so normalize them to get the picture a browser would show. The public SVG output is unchanged.
2241
+ */
2242
+ static _normalizeSVGForResvg(svgString) {
2243
+ const ids = /* @__PURE__ */ new Set();
2244
+ svgString.replace(/\sid="([^"]+)"/g, (match, id) => {
2245
+ ids.add(id);
2246
+ return match;
2247
+ });
2248
+ return svgString.replace(
2249
+ /\sclip-path="url\('#([^']+)'\)"/g,
2250
+ (_match, id) => ids.has(id) ? ` clip-path="url(#${id})"` : ""
2251
+ ).replace(/url\('#([^']+)'\)/g, "url(#$1)");
2252
+ }
2253
+ async _rasterizeWithResvg(extension) {
2254
+ const Resvg = this._options.resvg;
2255
+ if (!Resvg) throw new Error("resvg is not configured");
2256
+ if (extension.toLowerCase() !== "png") {
2257
+ throw new Error(`resvg can only produce png, not "${extension}". Use extension "png" or pass nodeCanvas.`);
2258
+ }
2259
+ const previous = this._options.imageOptions.saveAsBlob;
2260
+ const previousSvg = this._svg;
2261
+ const previousPromise = this._svgDrawingPromise;
2262
+ let svgString;
2263
+ try {
2264
+ if (this._options.image && !previous && !this._options.image.startsWith("data:")) {
2265
+ this._options.imageOptions.saveAsBlob = true;
2266
+ this._svg = void 0;
2267
+ this._svgDrawingPromise = void 0;
2268
+ }
2269
+ ({ svgString } = await this._getSVGString());
2270
+ } finally {
2271
+ this._options.imageOptions.saveAsBlob = previous;
2272
+ this._svg = previousSvg;
2273
+ this._svgDrawingPromise = previousPromise;
2274
+ }
2275
+ const png = new Resvg(_QRCodeStyling._normalizeSVGForResvg(svgString), { fitTo: { mode: "original" } }).render().asPng();
2276
+ return typeof Buffer !== "undefined" ? Buffer.from(png) : png;
2277
+ }
1968
2278
  async getRawData(extension = "png") {
1969
2279
  if (!this._qr) throw "QR code is empty";
2280
+ if (extension.toLowerCase() !== "svg" && !this._canUseCanvas() && this._options.resvg) {
2281
+ return await this._rasterizeWithResvg(extension);
2282
+ }
1970
2283
  const element = await this._getQRStylingElement(extension);
2284
+ if (extension.toLowerCase() === "svg" && element._virtual) {
2285
+ const svgString = _QRCodeStyling._serializeSVG(element);
2286
+ return typeof Buffer !== "undefined" ? Buffer.from(svgString) : new Blob([svgString], { type: "image/svg+xml" });
2287
+ }
1971
2288
  if (extension.toLowerCase() === "svg") {
1972
2289
  const serializer = new element._window.XMLSerializer();
1973
2290
  const source = serializer.serializeToString(element.getElement());