Commit 71285982 71285982c4c894750e2b7b1c0b7927ca01735f69 by zhanghao

commit

1 parent cc1d2bfe
Showing 125 changed files with 15187 additions and 11 deletions
/// <reference types="node"/>
import {IncomingMessage} from 'http';
/**
Decompress a HTTP response if needed.
@param response - The HTTP incoming stream with compressed data.
@returns The decompressed HTTP response stream.
@example
```
import {http} from 'http';
import decompressResponse = require('decompress-response');
http.get('https://sindresorhus.com', response => {
response = decompressResponse(response);
});
```
*/
declare function decompressResponse(response: IncomingMessage): IncomingMessage;
export = decompressResponse;
'use strict';
const {Transform, PassThrough} = require('stream');
const zlib = require('zlib');
const mimicResponse = require('mimic-response');
module.exports = response => {
const contentEncoding = (response.headers['content-encoding'] || '').toLowerCase();
if (!['gzip', 'deflate', 'br'].includes(contentEncoding)) {
return response;
}
// TODO: Remove this when targeting Node.js 12.
const isBrotli = contentEncoding === 'br';
if (isBrotli && typeof zlib.createBrotliDecompress !== 'function') {
response.destroy(new Error('Brotli is not supported on Node.js < 12'));
return response;
}
let isEmpty = true;
const checker = new Transform({
transform(data, _encoding, callback) {
isEmpty = false;
callback(null, data);
},
flush(callback) {
callback();
}
});
const finalStream = new PassThrough({
autoDestroy: false,
destroy(error, callback) {
response.destroy();
callback(error);
}
});
const decompressStream = isBrotli ? zlib.createBrotliDecompress() : zlib.createUnzip();
decompressStream.once('error', error => {
if (isEmpty && !response.readable) {
finalStream.end();
return;
}
finalStream.destroy(error);
});
mimicResponse(response, finalStream);
response.pipe(checker).pipe(decompressStream).pipe(finalStream);
return finalStream;
};
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
{
"_from": "decompress-response@^6.0.0",
"_id": "decompress-response@6.0.0",
"_inBundle": false,
"_integrity": "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==",
"_location": "/decompress-response",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "decompress-response@^6.0.0",
"name": "decompress-response",
"escapedName": "decompress-response",
"rawSpec": "^6.0.0",
"saveSpec": null,
"fetchSpec": "^6.0.0"
},
"_requiredBy": [
"/simple-get"
],
"_resolved": "https://registry.npmmirror.com/decompress-response/-/decompress-response-6.0.0.tgz",
"_shasum": "ca387612ddb7e104bd16d85aab00d5ecf09c66fc",
"_spec": "decompress-response@^6.0.0",
"_where": "/Users/zhanghao/brcode/br-client/node_modules/simple-get",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "https://sindresorhus.com"
},
"bugs": {
"url": "https://github.com/sindresorhus/decompress-response/issues"
},
"bundleDependencies": false,
"dependencies": {
"mimic-response": "^3.1.0"
},
"deprecated": false,
"description": "Decompress a HTTP response if needed",
"devDependencies": {
"@types/node": "^14.0.1",
"ava": "^2.2.0",
"get-stream": "^5.0.0",
"pify": "^5.0.0",
"tsd": "^0.11.0",
"xo": "^0.30.0"
},
"engines": {
"node": ">=10"
},
"files": [
"index.js",
"index.d.ts"
],
"funding": "https://github.com/sponsors/sindresorhus",
"homepage": "https://github.com/sindresorhus/decompress-response#readme",
"keywords": [
"decompress",
"response",
"http",
"https",
"zlib",
"gzip",
"zip",
"deflate",
"unzip",
"ungzip",
"incoming",
"message",
"stream",
"compressed",
"brotli"
],
"license": "MIT",
"name": "decompress-response",
"repository": {
"type": "git",
"url": "git+https://github.com/sindresorhus/decompress-response.git"
},
"scripts": {
"test": "xo && ava && tsd"
},
"version": "6.0.0",
"xo": {
"rules": {
"@typescript-eslint/prefer-readonly-parameter-types": "off"
}
}
}
# decompress-response [![Build Status](https://travis-ci.com/sindresorhus/decompress-response.svg?branch=master)](https://travis-ci.com/sindresorhus/decompress-response)
> Decompress a HTTP response if needed
Decompresses the [response](https://nodejs.org/api/http.html#http_class_http_incomingmessage) from [`http.request`](https://nodejs.org/api/http.html#http_http_request_options_callback) if it's gzipped, deflated or compressed with Brotli, otherwise just passes it through.
Used by [`got`](https://github.com/sindresorhus/got).
## Install
```
$ npm install decompress-response
```
## Usage
```js
const http = require('http');
const decompressResponse = require('decompress-response');
http.get('https://sindresorhus.com', response => {
response = decompressResponse(response);
});
```
## API
### decompressResponse(response)
Returns the decompressed HTTP response stream.
#### response
Type: [`http.IncomingMessage`](https://nodejs.org/api/http.html#http_class_http_incomingmessage)
The HTTP incoming stream with compressed data.
---
<div align="center">
<b>
<a href="https://tidelift.com/subscription/pkg/npm-decompress-response?utm_source=npm-decompress-response&utm_medium=referral&utm_campaign=readme">Get professional support for this package with a Tidelift subscription</a>
</b>
<br>
<sub>
Tidelift helps make open source sustainable for maintainers while giving companies<br>assurances about security, maintenance, and licensing for their dependencies.
</sub>
</div>
{
"presets": ["@babel/preset-env"]
}
{
"singleQuote": true,
"write": true,
"semi": false,
"tabWidth": 2,
"printWidth": 80
}
The MIT License (MIT)
Copyright (c) 2015 Matt Way
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
# js Binary Schema Parser
Parse binary files in javascript using a schema to convert to plain objects.
Years ago I needed to parse GIF images for our **[Ruffle][1]** messaging app. While this readme describes how to parse binary files in general, our _[GIF Parser][2]_ library exhibits a full use of this library (including a _[demo][2]_). I suggest looking at the other library for a quick understanding.
Basically, you provide a schema object and some data, and it will step through the binary data, and convert it into the object defined by your schema. Included in this library is a parser for the `Uint8TypedArray`, but it is easy to add them for your own types if necessary. It can parse bytes, arrays, chunks, conditionals, loops, etc.
### How to Use
_Installation:_
npm install js-binary-schema-parser
_Create a schema and parse a file:_
import { parse, conditional } from 'js-binary-schema-parser'
import { buildStream, readByte } from 'js-binary-schema-parser/lib/parsers/uint8'
const schema = [
// part definitions...
{ someKey: readByte() }
];
// get the input file data
const data = new Uint8Array(fileArrayBuffer);
// create a stream object and parse it
const parsedObject = parse(buildStream(data), schema)
### Schemas
So far in this library there is only one built in schema, which is for the GIF format. You can import included schemas like:
import GIF from 'js-binary-schema-parser/lib/schemas/gif'
Schemas are an array of _parts_, which are objects containing a single key label, and the parser to use at that point in time. This format was chosen to ensure parse ordering was consistent. _Parts_ can also contain other parts internally, and include syntax for loops, and conditionals. You can also include your own custom functions for parsing, providing direct access to the given data stream. Below is an example of a schema using the `Uint8TypedArray` parser provided to parse the GIF format header. You can also see a full example [here][2] of parsing entire GIF files.
### Example
var gifSchema = [
{
label: 'header', // gif header
parts: [
{ label: 'signature', parser: Parsers.readString(3) },
{ label: 'version', parser: Parsers.readString(3) }
]
},{
label: 'lsd', // local screen descriptor
parts: [
{ label: 'width', parser: Parsers.readUnsigned(true) },
{ label: 'height', parser: Parsers.readUnsigned(true) },
{ label: 'gct', bits: {
exists: { index: 0 },
resolution: { index: 1, length: 3 },
sort: { index: 4 },
size: { index: 5, length: 3 }
}},
{ label: 'backgroundColorIndex', parser: Parsers.readByte() },
{ label: 'pixelAspectRatio', parser: Parsers.readByte() }
]
}
];
### Why this parser?
There are other good parsers around, like [jBinary][4], but we weren't a fan of relying on object key ordering, and defining parser types as strings. This one is also extremely small, and easily exstensible in any way you want.
### Demo
You can see a full demo **[here][2]** which uses this lib to parse GIF files for manipulation.
### Who are we?
[Matt Way][3] & [Nick Drewe][5]
[Wethrift.com][6]
[1]: https://www.producthunt.com/posts/ruffle
[2]: https://github.com/matt-way/gifuct-js
[3]: https://twitter.com/_MattWay
[4]: https://github.com/jDataView/jBinary
[5]: https://twitter.com/nickdrewe
[6]: https://wethrift.com
import fs from 'fs'
import { parse } from '../src'
import { buildStream } from '../src/parsers/uint8'
import { GIF } from '../src/schemas'
debugger
const data = fs.readFileSync('./example/dog.gif')
const result = parse(buildStream(new Uint8Array(data)), GIF)
console.log(result)
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.loop = exports.conditional = exports.parse = void 0;
var parse = function parse(stream, schema) {
var result = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
var parent = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : result;
if (Array.isArray(schema)) {
schema.forEach(function (partSchema) {
return parse(stream, partSchema, result, parent);
});
} else if (typeof schema === 'function') {
schema(stream, result, parent, parse);
} else {
var key = Object.keys(schema)[0];
if (Array.isArray(schema[key])) {
parent[key] = {};
parse(stream, schema[key], result, parent[key]);
} else {
parent[key] = schema[key](stream, result, parent, parse);
}
}
return result;
};
exports.parse = parse;
var conditional = function conditional(schema, conditionFunc) {
return function (stream, result, parent, parse) {
if (conditionFunc(stream, result, parent)) {
parse(stream, schema, result, parent);
}
};
};
exports.conditional = conditional;
var loop = function loop(schema, continueFunc) {
return function (stream, result, parent, parse) {
var arr = [];
var lastStreamPos = stream.pos;
while (continueFunc(stream, result, parent)) {
var newParent = {};
parse(stream, schema, result, newParent); // cases when whole file is parsed but no termination is there and stream position is not getting updated as well
// it falls into infinite recursion, null check to avoid the same
if (stream.pos === lastStreamPos) {
break;
}
lastStreamPos = stream.pos;
arr.push(newParent);
}
return arr;
};
};
exports.loop = loop;
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.readBits = exports.readArray = exports.readUnsigned = exports.readString = exports.peekBytes = exports.readBytes = exports.peekByte = exports.readByte = exports.buildStream = void 0;
// Default stream and parsers for Uint8TypedArray data type
var buildStream = function buildStream(uint8Data) {
return {
data: uint8Data,
pos: 0
};
};
exports.buildStream = buildStream;
var readByte = function readByte() {
return function (stream) {
return stream.data[stream.pos++];
};
};
exports.readByte = readByte;
var peekByte = function peekByte() {
var offset = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
return function (stream) {
return stream.data[stream.pos + offset];
};
};
exports.peekByte = peekByte;
var readBytes = function readBytes(length) {
return function (stream) {
return stream.data.subarray(stream.pos, stream.pos += length);
};
};
exports.readBytes = readBytes;
var peekBytes = function peekBytes(length) {
return function (stream) {
return stream.data.subarray(stream.pos, stream.pos + length);
};
};
exports.peekBytes = peekBytes;
var readString = function readString(length) {
return function (stream) {
return Array.from(readBytes(length)(stream)).map(function (value) {
return String.fromCharCode(value);
}).join('');
};
};
exports.readString = readString;
var readUnsigned = function readUnsigned(littleEndian) {
return function (stream) {
var bytes = readBytes(2)(stream);
return littleEndian ? (bytes[1] << 8) + bytes[0] : (bytes[0] << 8) + bytes[1];
};
};
exports.readUnsigned = readUnsigned;
var readArray = function readArray(byteSize, totalOrFunc) {
return function (stream, result, parent) {
var total = typeof totalOrFunc === 'function' ? totalOrFunc(stream, result, parent) : totalOrFunc;
var parser = readBytes(byteSize);
var arr = new Array(total);
for (var i = 0; i < total; i++) {
arr[i] = parser(stream);
}
return arr;
};
};
exports.readArray = readArray;
var subBitsTotal = function subBitsTotal(bits, startIndex, length) {
var result = 0;
for (var i = 0; i < length; i++) {
result += bits[startIndex + i] && Math.pow(2, length - i - 1);
}
return result;
};
var readBits = function readBits(schema) {
return function (stream) {
var _byte = readByte()(stream); // convert the byte to bit array
var bits = new Array(8);
for (var i = 0; i < 8; i++) {
bits[7 - i] = !!(_byte & 1 << i);
} // convert the bit array to values based on the schema
return Object.keys(schema).reduce(function (res, key) {
var def = schema[key];
if (def.length) {
res[key] = subBitsTotal(bits, def.index, def.length);
} else {
res[key] = bits[def.index];
}
return res;
}, {});
};
};
exports.readBits = readBits;
\ No newline at end of file
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
var _ = require("../");
var _uint = require("../parsers/uint8");
// a set of 0x00 terminated subblocks
var subBlocksSchema = {
blocks: function blocks(stream) {
var terminator = 0x00;
var chunks = [];
var streamSize = stream.data.length;
var total = 0;
for (var size = (0, _uint.readByte)()(stream); size !== terminator; size = (0, _uint.readByte)()(stream)) {
// size becomes undefined for some case when file is corrupted and terminator is not proper
// null check to avoid recursion
if (!size) break; // catch corrupted files with no terminator
if (stream.pos + size >= streamSize) {
var availableSize = streamSize - stream.pos;
chunks.push((0, _uint.readBytes)(availableSize)(stream));
total += availableSize;
break;
}
chunks.push((0, _uint.readBytes)(size)(stream));
total += size;
}
var result = new Uint8Array(total);
var offset = 0;
for (var i = 0; i < chunks.length; i++) {
result.set(chunks[i], offset);
offset += chunks[i].length;
}
return result;
}
}; // global control extension
var gceSchema = (0, _.conditional)({
gce: [{
codes: (0, _uint.readBytes)(2)
}, {
byteSize: (0, _uint.readByte)()
}, {
extras: (0, _uint.readBits)({
future: {
index: 0,
length: 3
},
disposal: {
index: 3,
length: 3
},
userInput: {
index: 6
},
transparentColorGiven: {
index: 7
}
})
}, {
delay: (0, _uint.readUnsigned)(true)
}, {
transparentColorIndex: (0, _uint.readByte)()
}, {
terminator: (0, _uint.readByte)()
}]
}, function (stream) {
var codes = (0, _uint.peekBytes)(2)(stream);
return codes[0] === 0x21 && codes[1] === 0xf9;
}); // image pipeline block
var imageSchema = (0, _.conditional)({
image: [{
code: (0, _uint.readByte)()
}, {
descriptor: [{
left: (0, _uint.readUnsigned)(true)
}, {
top: (0, _uint.readUnsigned)(true)
}, {
width: (0, _uint.readUnsigned)(true)
}, {
height: (0, _uint.readUnsigned)(true)
}, {
lct: (0, _uint.readBits)({
exists: {
index: 0
},
interlaced: {
index: 1
},
sort: {
index: 2
},
future: {
index: 3,
length: 2
},
size: {
index: 5,
length: 3
}
})
}]
}, (0, _.conditional)({
lct: (0, _uint.readArray)(3, function (stream, result, parent) {
return Math.pow(2, parent.descriptor.lct.size + 1);
})
}, function (stream, result, parent) {
return parent.descriptor.lct.exists;
}), {
data: [{
minCodeSize: (0, _uint.readByte)()
}, subBlocksSchema]
}]
}, function (stream) {
return (0, _uint.peekByte)()(stream) === 0x2c;
}); // plain text block
var textSchema = (0, _.conditional)({
text: [{
codes: (0, _uint.readBytes)(2)
}, {
blockSize: (0, _uint.readByte)()
}, {
preData: function preData(stream, result, parent) {
return (0, _uint.readBytes)(parent.text.blockSize)(stream);
}
}, subBlocksSchema]
}, function (stream) {
var codes = (0, _uint.peekBytes)(2)(stream);
return codes[0] === 0x21 && codes[1] === 0x01;
}); // application block
var applicationSchema = (0, _.conditional)({
application: [{
codes: (0, _uint.readBytes)(2)
}, {
blockSize: (0, _uint.readByte)()
}, {
id: function id(stream, result, parent) {
return (0, _uint.readString)(parent.blockSize)(stream);
}
}, subBlocksSchema]
}, function (stream) {
var codes = (0, _uint.peekBytes)(2)(stream);
return codes[0] === 0x21 && codes[1] === 0xff;
}); // comment block
var commentSchema = (0, _.conditional)({
comment: [{
codes: (0, _uint.readBytes)(2)
}, subBlocksSchema]
}, function (stream) {
var codes = (0, _uint.peekBytes)(2)(stream);
return codes[0] === 0x21 && codes[1] === 0xfe;
});
var schema = [{
header: [{
signature: (0, _uint.readString)(3)
}, {
version: (0, _uint.readString)(3)
}]
}, {
lsd: [{
width: (0, _uint.readUnsigned)(true)
}, {
height: (0, _uint.readUnsigned)(true)
}, {
gct: (0, _uint.readBits)({
exists: {
index: 0
},
resolution: {
index: 1,
length: 3
},
sort: {
index: 4
},
size: {
index: 5,
length: 3
}
})
}, {
backgroundColorIndex: (0, _uint.readByte)()
}, {
pixelAspectRatio: (0, _uint.readByte)()
}]
}, (0, _.conditional)({
gct: (0, _uint.readArray)(3, function (stream, result) {
return Math.pow(2, result.lsd.gct.size + 1);
})
}, function (stream, result) {
return result.lsd.gct.exists;
}), // content frames
{
frames: (0, _.loop)([gceSchema, applicationSchema, commentSchema, imageSchema, textSchema], function (stream) {
var nextCode = (0, _uint.peekByte)()(stream); // rather than check for a terminator, we should check for the existence
// of an ext or image block to avoid infinite loops
//var terminator = 0x3B;
//return nextCode !== terminator;
return nextCode === 0x21 || nextCode === 0x2c;
})
}];
var _default = schema;
exports["default"] = _default;
\ No newline at end of file
{
"_from": "js-binary-schema-parser@^2.0.2",
"_id": "js-binary-schema-parser@2.0.3",
"_inBundle": false,
"_integrity": "sha512-xezGJmOb4lk/M1ZZLTR/jaBHQ4gG/lqQnJqdIv4721DMggsa1bDVlHXNeHYogaIEHD9vCRv0fcL4hMA+Coarkg==",
"_location": "/js-binary-schema-parser",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "js-binary-schema-parser@^2.0.2",
"name": "js-binary-schema-parser",
"escapedName": "js-binary-schema-parser",
"rawSpec": "^2.0.2",
"saveSpec": null,
"fetchSpec": "^2.0.2"
},
"_requiredBy": [
"/vue-qr"
],
"_resolved": "https://registry.npmmirror.com/js-binary-schema-parser/-/js-binary-schema-parser-2.0.3.tgz",
"_shasum": "3d7848748e8586e63b34e8911b643f59cfb6396e",
"_spec": "js-binary-schema-parser@^2.0.2",
"_where": "/Users/zhanghao/brcode/br-client/node_modules/vue-qr",
"author": {
"name": "Matt Way"
},
"bugs": {
"url": "https://github.com/matt-way/jsBinarySchemaParser/issues"
},
"bundleDependencies": false,
"dependencies": {},
"deprecated": false,
"description": "Parse binary files with a schema into nicely readable objects",
"devDependencies": {
"@babel/cli": "^7.8.4",
"@babel/core": "^7.8.4",
"@babel/node": "^7.8.4",
"@babel/preset-env": "^7.8.4"
},
"homepage": "https://github.com/matt-way/jsBinarySchemaParser",
"keywords": [
"javascript",
"binary",
"file",
"parser",
"schema"
],
"license": "MIT",
"main": "lib/index.js",
"name": "js-binary-schema-parser",
"repository": {
"type": "git",
"url": "git+https://github.com/matt-way/jsBinarySchemaParser.git"
},
"scripts": {
"build": "babel src --out-dir lib",
"example": "babel-node ./example/index.js",
"example-debug": "babel-node --inspect-brk ./example/index.js"
},
"version": "2.0.3"
}
export const parse = (stream, schema, result = {}, parent = result) => {
if (Array.isArray(schema)) {
schema.forEach(partSchema => parse(stream, partSchema, result, parent))
} else if (typeof schema === 'function') {
schema(stream, result, parent, parse)
} else {
const key = Object.keys(schema)[0]
if (Array.isArray(schema[key])) {
parent[key] = {}
parse(stream, schema[key], result, parent[key])
} else {
parent[key] = schema[key](stream, result, parent, parse)
}
}
return result
}
export const conditional = (schema, conditionFunc) => (
stream,
result,
parent,
parse
) => {
if (conditionFunc(stream, result, parent)) {
parse(stream, schema, result, parent)
}
}
export const loop = (schema, continueFunc) => (
stream,
result,
parent,
parse
) => {
const arr = []
let lastStreamPos = stream.pos;
while (continueFunc(stream, result, parent)) {
const newParent = {}
parse(stream, schema, result, newParent)
// cases when whole file is parsed but no termination is there and stream position is not getting updated as well
// it falls into infinite recursion, null check to avoid the same
if(stream.pos === lastStreamPos) {
break
}
lastStreamPos = stream.pos
arr.push(newParent)
}
return arr
}
// Default stream and parsers for Uint8TypedArray data type
export const buildStream = uint8Data => ({
data: uint8Data,
pos: 0
})
export const readByte = () => stream => {
return stream.data[stream.pos++]
}
export const peekByte = (offset = 0) => stream => {
return stream.data[stream.pos + offset]
}
export const readBytes = length => stream => {
return stream.data.subarray(stream.pos, (stream.pos += length))
}
export const peekBytes = length => stream => {
return stream.data.subarray(stream.pos, stream.pos + length)
}
export const readString = length => stream => {
return Array.from(readBytes(length)(stream))
.map(value => String.fromCharCode(value))
.join('')
}
export const readUnsigned = littleEndian => stream => {
const bytes = readBytes(2)(stream)
return littleEndian ? (bytes[1] << 8) + bytes[0] : (bytes[0] << 8) + bytes[1]
}
export const readArray = (byteSize, totalOrFunc) => (
stream,
result,
parent
) => {
const total =
typeof totalOrFunc === 'function'
? totalOrFunc(stream, result, parent)
: totalOrFunc
const parser = readBytes(byteSize)
const arr = new Array(total)
for (var i = 0; i < total; i++) {
arr[i] = parser(stream)
}
return arr
}
const subBitsTotal = (bits, startIndex, length) => {
var result = 0
for (var i = 0; i < length; i++) {
result += bits[startIndex + i] && 2 ** (length - i - 1)
}
return result
}
export const readBits = schema => stream => {
const byte = readByte()(stream)
// convert the byte to bit array
const bits = new Array(8)
for (var i = 0; i < 8; i++) {
bits[7 - i] = !!(byte & (1 << i))
}
// convert the bit array to values based on the schema
return Object.keys(schema).reduce((res, key) => {
const def = schema[key]
if (def.length) {
res[key] = subBitsTotal(bits, def.index, def.length)
} else {
res[key] = bits[def.index]
}
return res
}, {})
}
import { conditional, loop } from '../'
import {
readByte,
peekByte,
readBytes,
peekBytes,
readString,
readUnsigned,
readArray,
readBits,
} from '../parsers/uint8'
// a set of 0x00 terminated subblocks
var subBlocksSchema = {
blocks: (stream) => {
const terminator = 0x00
const chunks = []
const streamSize = stream.data.length
var total = 0
for (
var size = readByte()(stream);
size !== terminator;
size = readByte()(stream)
) {
// size becomes undefined for some case when file is corrupted and terminator is not proper
// null check to avoid recursion
if(!size) break;
// catch corrupted files with no terminator
if (stream.pos + size >= streamSize) {
const availableSize = streamSize - stream.pos
chunks.push(readBytes(availableSize)(stream))
total += availableSize
break
}
chunks.push(readBytes(size)(stream))
total += size
}
const result = new Uint8Array(total)
var offset = 0
for (var i = 0; i < chunks.length; i++) {
result.set(chunks[i], offset)
offset += chunks[i].length
}
return result
},
}
// global control extension
const gceSchema = conditional(
{
gce: [
{ codes: readBytes(2) },
{ byteSize: readByte() },
{
extras: readBits({
future: { index: 0, length: 3 },
disposal: { index: 3, length: 3 },
userInput: { index: 6 },
transparentColorGiven: { index: 7 },
}),
},
{ delay: readUnsigned(true) },
{ transparentColorIndex: readByte() },
{ terminator: readByte() },
],
},
(stream) => {
var codes = peekBytes(2)(stream)
return codes[0] === 0x21 && codes[1] === 0xf9
}
)
// image pipeline block
const imageSchema = conditional(
{
image: [
{ code: readByte() },
{
descriptor: [
{ left: readUnsigned(true) },
{ top: readUnsigned(true) },
{ width: readUnsigned(true) },
{ height: readUnsigned(true) },
{
lct: readBits({
exists: { index: 0 },
interlaced: { index: 1 },
sort: { index: 2 },
future: { index: 3, length: 2 },
size: { index: 5, length: 3 },
}),
},
],
},
conditional(
{
lct: readArray(3, (stream, result, parent) => {
return Math.pow(2, parent.descriptor.lct.size + 1)
}),
},
(stream, result, parent) => {
return parent.descriptor.lct.exists
}
),
{ data: [{ minCodeSize: readByte() }, subBlocksSchema] },
],
},
(stream) => {
return peekByte()(stream) === 0x2c
}
)
// plain text block
const textSchema = conditional(
{
text: [
{ codes: readBytes(2) },
{ blockSize: readByte() },
{
preData: (stream, result, parent) =>
readBytes(parent.text.blockSize)(stream),
},
subBlocksSchema,
],
},
(stream) => {
var codes = peekBytes(2)(stream)
return codes[0] === 0x21 && codes[1] === 0x01
}
)
// application block
const applicationSchema = conditional(
{
application: [
{ codes: readBytes(2) },
{ blockSize: readByte() },
{ id: (stream, result, parent) => readString(parent.blockSize)(stream) },
subBlocksSchema,
],
},
(stream) => {
var codes = peekBytes(2)(stream)
return codes[0] === 0x21 && codes[1] === 0xff
}
)
// comment block
const commentSchema = conditional(
{
comment: [{ codes: readBytes(2) }, subBlocksSchema],
},
(stream) => {
var codes = peekBytes(2)(stream)
return codes[0] === 0x21 && codes[1] === 0xfe
}
)
const schema = [
{ header: [{ signature: readString(3) }, { version: readString(3) }] },
{
lsd: [
{ width: readUnsigned(true) },
{ height: readUnsigned(true) },
{
gct: readBits({
exists: { index: 0 },
resolution: { index: 1, length: 3 },
sort: { index: 4 },
size: { index: 5, length: 3 },
}),
},
{ backgroundColorIndex: readByte() },
{ pixelAspectRatio: readByte() },
],
},
conditional(
{
gct: readArray(3, (stream, result) =>
Math.pow(2, result.lsd.gct.size + 1)
),
},
(stream, result) => result.lsd.gct.exists
),
// content frames
{
frames: loop(
[gceSchema, applicationSchema, commentSchema, imageSchema, textSchema],
(stream) => {
var nextCode = peekByte()(stream)
// rather than check for a terminator, we should check for the existence
// of an ext or image block to avoid infinite loops
//var terminator = 0x3B;
//return nextCode !== terminator;
return nextCode === 0x21 || nextCode === 0x2c
}
),
},
]
export default schema
import {IncomingMessage} from 'http';
/**
Mimic a [Node.js HTTP response stream](https://nodejs.org/api/http.html#http_class_http_incomingmessage)
Makes `toStream` include the properties from `fromStream`.
@param fromStream - The stream to copy the properties from.
@param toStream - The stream to copy the properties to.
@return The same object as `toStream`.
*/
declare function mimicResponse<T extends NodeJS.ReadableStream>(
fromStream: IncomingMessage, // eslint-disable-line @typescript-eslint/prefer-readonly-parameter-types
toStream: T,
): T & IncomingMessage;
export = mimicResponse;
'use strict';
// We define these manually to ensure they're always copied
// even if they would move up the prototype chain
// https://nodejs.org/api/http.html#http_class_http_incomingmessage
const knownProperties = [
'aborted',
'complete',
'headers',
'httpVersion',
'httpVersionMinor',
'httpVersionMajor',
'method',
'rawHeaders',
'rawTrailers',
'setTimeout',
'socket',
'statusCode',
'statusMessage',
'trailers',
'url'
];
module.exports = (fromStream, toStream) => {
if (toStream._readableState.autoDestroy) {
throw new Error('The second stream must have the `autoDestroy` option set to `false`');
}
const fromProperties = new Set(Object.keys(fromStream).concat(knownProperties));
const properties = {};
for (const property of fromProperties) {
// Don't overwrite existing properties.
if (property in toStream) {
continue;
}
properties[property] = {
get() {
const value = fromStream[property];
const isFunction = typeof value === 'function';
return isFunction ? value.bind(fromStream) : value;
},
set(value) {
fromStream[property] = value;
},
enumerable: true,
configurable: false
};
}
Object.defineProperties(toStream, properties);
fromStream.once('aborted', () => {
toStream.destroy();
toStream.emit('aborted');
});
fromStream.once('close', () => {
if (fromStream.complete) {
if (toStream.readable) {
toStream.once('end', () => {
toStream.emit('close');
});
} else {
toStream.emit('close');
}
} else {
toStream.emit('close');
}
});
return toStream;
};
MIT License
Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
{
"_from": "mimic-response@^3.1.0",
"_id": "mimic-response@3.1.0",
"_inBundle": false,
"_integrity": "sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==",
"_location": "/mimic-response",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "mimic-response@^3.1.0",
"name": "mimic-response",
"escapedName": "mimic-response",
"rawSpec": "^3.1.0",
"saveSpec": null,
"fetchSpec": "^3.1.0"
},
"_requiredBy": [
"/decompress-response"
],
"_resolved": "https://registry.npmmirror.com/mimic-response/-/mimic-response-3.1.0.tgz",
"_shasum": "2d1d59af9c1b129815accc2c46a022a5ce1fa3c9",
"_spec": "mimic-response@^3.1.0",
"_where": "/Users/zhanghao/brcode/br-client/node_modules/decompress-response",
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "https://sindresorhus.com"
},
"bugs": {
"url": "https://github.com/sindresorhus/mimic-response/issues"
},
"bundleDependencies": false,
"deprecated": false,
"description": "Mimic a Node.js HTTP response stream",
"devDependencies": {
"@types/node": "^14.0.1",
"ava": "^2.4.0",
"create-test-server": "^2.4.0",
"p-event": "^4.1.0",
"pify": "^5.0.0",
"tsd": "^0.11.0",
"xo": "^0.30.0"
},
"engines": {
"node": ">=10"
},
"files": [
"index.d.ts",
"index.js"
],
"funding": "https://github.com/sponsors/sindresorhus",
"homepage": "https://github.com/sindresorhus/mimic-response#readme",
"keywords": [
"mimic",
"response",
"stream",
"http",
"https",
"request",
"get",
"core"
],
"license": "MIT",
"name": "mimic-response",
"repository": {
"type": "git",
"url": "git+https://github.com/sindresorhus/mimic-response.git"
},
"scripts": {
"test": "xo && ava && tsd"
},
"version": "3.1.0"
}
# mimic-response [![Build Status](https://travis-ci.com/sindresorhus/mimic-response.svg?branch=master)](https://travis-ci.com/sindresorhus/mimic-response)
> Mimic a [Node.js HTTP response stream](https://nodejs.org/api/http.html#http_class_http_incomingmessage)
## Install
```
$ npm install mimic-response
```
## Usage
```js
const stream = require('stream');
const mimicResponse = require('mimic-response');
const responseStream = getHttpResponseStream();
const myStream = new stream.PassThrough();
mimicResponse(responseStream, myStream);
console.log(myStream.statusCode);
//=> 200
```
## API
### mimicResponse(from, to)
**Note #1:** The `from.destroy(error)` function is not proxied. You have to call it manually:
```js
const stream = require('stream');
const mimicResponse = require('mimic-response');
const responseStream = getHttpResponseStream();
const myStream = new stream.PassThrough({
destroy(error, callback) {
responseStream.destroy();
callback(error);
}
});
myStream.destroy();
```
Please note that `myStream` and `responseStream` never throws. The error is passed to the request instead.
#### from
Type: `Stream`
[Node.js HTTP response stream.](https://nodejs.org/api/http.html#http_class_http_incomingmessage)
#### to
Type: `Stream`
Any stream.
## Related
- [mimic-fn](https://github.com/sindresorhus/mimic-fn) - Make a function mimic another one
- [clone-response](https://github.com/lukechilds/clone-response) - Clone a Node.js response stream
---
<div align="center">
<b>
<a href="https://tidelift.com/subscription/pkg/npm-mimic-response?utm_source=npm-mimic-response&utm_medium=referral&utm_campaign=readme">Get professional support for this package with a Tidelift subscription</a>
</b>
<br>
<sub>
Tidelift helps make open source sustainable for maintainers while giving companies<br>assurances about security, maintenance, and licensing for their dependencies.
</sub>
</div>
The MIT License (MIT)
Copyright © 2016 Dmitry Ivanov
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
\ No newline at end of file
# parenthesis [![Build Status](https://travis-ci.org/dy/parenthesis.svg?branch=master)](https://travis-ci.org/dy/parenthesis)
Parse parentheses from a string, return folded arrays.
[![npm install parenthesis](https://nodei.co/npm/parenthesis.png?mini=true)](https://npmjs.org/package/parenthesis/)
```js
var parse = require('parenthesis')
// Parse into nested format
parse('a(b[c{d}])')
// ['a(', ['b[', ['c{', ['d'], '}'], ']'], ')']
// Parse into flat format with cross-references
parse('a(b[c{d}])', {
brackets: ['()'],
escape: '\\',
flat: true
})
// ['a(\\1)', 'b[c{d}]']
// Stringify nested format
parse.stringify(['a(', ['b[', ['c{', ['d'], '}'], ']'], ')'])
// 'a(b[c{d}])'
// Stringify flat format with cross-references
parse.stringify(['a(\\1)', 'b[c{d}]'], {flat: true, escape: '\\'})
// 'a(b[c{d}])'
```
## API
### tokens = paren.parse(string, brackets|opts?)
Return array with tokens.
Option | Default | Meaning
---|---|---
`brackets` | `['{}', '[]', '()']` | Single brackets string or list of strings to detect brackets. Can be repeating brackets eg. `"" or ''`.
`escape` | `'___'` | Escape prefix for flat references.
`flat` | `false` | Return flat array instead of nested arrays.
### str = paren.stringify(tokens, {flat}?)
Stringify tokens back. Pass `{flat: true}` flag for flat tokens array.
## Related
* [balanced-match](http://npmjs.org/package/balanced-match)
## License
© 2018 Dmitry Yv. MIT License
declare module "parenthesis" {
namespace parens {
// One entry in the returned nested array
type Node = string | ArrayTree;
// A nested array of strings
interface ArrayTree extends Array<Node> {}
// Second-argument options used by the function
interface Opts {
// Single brackets string or list of strings to detect brackets. Can be repeating brackets eg. "" or ''.
brackets?: string | string[],
// Escape prefix for flat references.
escape?: string,
// `flat` is a boolean but since it affects return type, it's explicitly specified below
}
// Parse parentheses from a string, return folded arrays
function parse(
str: string,
opts?: string | string[] | (parens.Opts & { flat?: false })
): parens.ArrayTree;
// Parse parentheses from a string, return flat array
function parse(
str: string,
opts: (parens.Opts & { flat: true })
): string[];
// Stringify tokens back. Pass {flat: true} flag for flat tokens array.
function stringify(tokens: ArrayTree, opts?: {flat: boolean}): string;
}
// Parse parentheses from a string, return folded arrays
function parens(
str: string,
opts?: string | string[] | (parens.Opts & { flat?: false })
): parens.ArrayTree;
// Parse parentheses from a string, return flat array
function parens(
str: string,
opts: (parens.Opts & { flat: true })
): string[];
function parens(tokens: parens.ArrayTree, opts?: {flat: boolean}): string;
// imports via `import paren from "parenthesis", can call the export
// directly or use `paren.parse` / `paren.stringify`.
export = parens;
}
'use strict'
/**
* @module parenthesis
*/
function parse (str, opts) {
// pretend non-string parsed per-se
if (typeof str !== 'string') return [str]
var res = [str]
if (typeof opts === 'string' || Array.isArray(opts)) {
opts = {brackets: opts}
}
else if (!opts) opts = {}
var brackets = opts.brackets ? (Array.isArray(opts.brackets) ? opts.brackets : [opts.brackets]) : ['{}', '[]', '()']
var escape = opts.escape || '___'
var flat = !!opts.flat
brackets.forEach(function (bracket) {
// create parenthesis regex
var pRE = new RegExp(['\\', bracket[0], '[^\\', bracket[0], '\\', bracket[1], ']*\\', bracket[1]].join(''))
var ids = []
function replaceToken(token, idx, str){
// save token to res
var refId = res.push(token.slice(bracket[0].length, -bracket[1].length)) - 1
ids.push(refId)
return escape + refId + escape
}
res.forEach(function (str, i) {
var prevStr
// replace paren tokens till there’s none
var a = 0
while (str != prevStr) {
prevStr = str
str = str.replace(pRE, replaceToken)
if (a++ > 10e3) throw Error('References have circular dependency. Please, check them.')
}
res[i] = str
})
// wrap found refs to brackets
ids = ids.reverse()
res = res.map(function (str) {
ids.forEach(function (id) {
str = str.replace(new RegExp('(\\' + escape + id + '\\' + escape + ')', 'g'), bracket[0] + '$1' + bracket[1])
})
return str
})
})
var re = new RegExp('\\' + escape + '([0-9]+)' + '\\' + escape)
// transform references to tree
function nest (str, refs, escape) {
var res = [], match
var a = 0
while (match = re.exec(str)) {
if (a++ > 10e3) throw Error('Circular references in parenthesis')
res.push(str.slice(0, match.index))
res.push(nest(refs[match[1]], refs))
str = str.slice(match.index + match[0].length)
}
res.push(str)
return res
}
return flat ? res : nest(res[0], res)
}
function stringify (arg, opts) {
if (opts && opts.flat) {
var escape = opts && opts.escape || '___'
var str = arg[0], prevStr
// pretend bad string stringified with no parentheses
if (!str) return ''
var re = new RegExp('\\' + escape + '([0-9]+)' + '\\' + escape)
var a = 0
while (str != prevStr) {
if (a++ > 10e3) throw Error('Circular references in ' + arg)
prevStr = str
str = str.replace(re, replaceRef)
}
return str
}
return arg.reduce(function f (prev, curr) {
if (Array.isArray(curr)) {
curr = curr.reduce(f, '')
}
return prev + curr
}, '')
function replaceRef(match, idx){
if (arg[idx] == null) throw Error('Reference ' + idx + 'is undefined')
return arg[idx]
}
}
function parenthesis (arg, opts) {
if (Array.isArray(arg)) {
return stringify(arg, opts)
}
else {
return parse(arg, opts)
}
}
parenthesis.parse = parse
parenthesis.stringify = stringify
module.exports = parenthesis
{
"_from": "parenthesis@^3.1.5",
"_id": "parenthesis@3.1.8",
"_inBundle": false,
"_integrity": "sha512-KF/U8tk54BgQewkJPvB4s/US3VQY68BRDpH638+7O/n58TpnwiwnOtGIOsT2/i+M78s61BBpeC83STB88d8sqw==",
"_location": "/parenthesis",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "parenthesis@^3.1.5",
"name": "parenthesis",
"escapedName": "parenthesis",
"rawSpec": "^3.1.5",
"saveSpec": null,
"fetchSpec": "^3.1.5"
},
"_requiredBy": [
"/string-split-by"
],
"_resolved": "https://registry.npmmirror.com/parenthesis/-/parenthesis-3.1.8.tgz",
"_shasum": "3457fccb8f05db27572b841dad9d2630b912f125",
"_spec": "parenthesis@^3.1.5",
"_where": "/Users/zhanghao/brcode/br-client/node_modules/string-split-by",
"author": {
"name": "Dmitry Yv",
"email": "df.creative@gmail.com",
"url": "http://github.com/dy"
},
"bugs": {
"url": "https://github.com/dy/parenthesis/issues"
},
"bundleDependencies": false,
"dependencies": {},
"deprecated": false,
"description": "Parse parentheses from a string",
"devDependencies": {
"tape": "^4.9.0"
},
"files": [
"index.js",
"index.d.ts"
],
"homepage": "https://github.com/dy/parenthesis",
"keywords": [
"paren",
"parenthesis",
"parse",
"brackets",
"parser",
"regexp",
"stringify",
"tokenizer",
"replace",
"csv",
"string"
],
"license": "MIT",
"main": "index.js",
"name": "parenthesis",
"repository": {
"type": "git",
"url": "git://github.com/dy/parenthesis.git"
},
"scripts": {
"test": "node test.js",
"test:browser": "budo test.js"
},
"types": "index.d.ts",
"version": "3.1.8"
}
language: node_js
node_js:
- lts/*
The MIT License (MIT)
Copyright (c) Feross Aboukhadijeh
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# simple-concat [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url]
[travis-image]: https://img.shields.io/travis/feross/simple-concat/master.svg
[travis-url]: https://travis-ci.org/feross/simple-concat
[npm-image]: https://img.shields.io/npm/v/simple-concat.svg
[npm-url]: https://npmjs.org/package/simple-concat
[downloads-image]: https://img.shields.io/npm/dm/simple-concat.svg
[downloads-url]: https://npmjs.org/package/simple-concat
[standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg
[standard-url]: https://standardjs.com
### Super-minimalist version of [`concat-stream`](https://github.com/maxogden/concat-stream). Less than 15 lines!
## install
```
npm install simple-concat
```
## usage
This example is longer than the implementation.
```js
var s = new stream.PassThrough()
concat(s, function (err, buf) {
if (err) throw err
console.error(buf)
})
s.write('abc')
setTimeout(function () {
s.write('123')
}, 10)
setTimeout(function () {
s.write('456')
}, 20)
setTimeout(function () {
s.end('789')
}, 30)
```
## license
MIT. Copyright (c) [Feross Aboukhadijeh](http://feross.org).
/*! simple-concat. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
module.exports = function (stream, cb) {
var chunks = []
stream.on('data', function (chunk) {
chunks.push(chunk)
})
stream.once('end', function () {
if (cb) cb(null, Buffer.concat(chunks))
cb = null
})
stream.once('error', function (err) {
if (cb) cb(err)
cb = null
})
}
{
"_from": "simple-concat@^1.0.0",
"_id": "simple-concat@1.0.1",
"_inBundle": false,
"_integrity": "sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==",
"_location": "/simple-concat",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "simple-concat@^1.0.0",
"name": "simple-concat",
"escapedName": "simple-concat",
"rawSpec": "^1.0.0",
"saveSpec": null,
"fetchSpec": "^1.0.0"
},
"_requiredBy": [
"/simple-get"
],
"_resolved": "https://registry.npmmirror.com/simple-concat/-/simple-concat-1.0.1.tgz",
"_shasum": "f46976082ba35c2263f1c8ab5edfe26c41c9552f",
"_spec": "simple-concat@^1.0.0",
"_where": "/Users/zhanghao/brcode/br-client/node_modules/simple-get",
"author": {
"name": "Feross Aboukhadijeh",
"email": "feross@feross.org",
"url": "https://feross.org"
},
"bugs": {
"url": "https://github.com/feross/simple-concat/issues"
},
"bundleDependencies": false,
"dependencies": {},
"deprecated": false,
"description": "Super-minimalist version of `concat-stream`. Less than 15 lines!",
"devDependencies": {
"standard": "*",
"tape": "^5.0.1"
},
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/feross"
},
{
"type": "patreon",
"url": "https://www.patreon.com/feross"
},
{
"type": "consulting",
"url": "https://feross.org/support"
}
],
"homepage": "https://github.com/feross/simple-concat",
"keywords": [
"concat",
"concat-stream",
"concat stream"
],
"license": "MIT",
"main": "index.js",
"name": "simple-concat",
"repository": {
"type": "git",
"url": "git://github.com/feross/simple-concat.git"
},
"scripts": {
"test": "standard && tape test/*.js"
},
"version": "1.0.1"
}
var concat = require('../')
var stream = require('stream')
var test = require('tape')
test('basic', function (t) {
t.plan(2)
var s = new stream.PassThrough()
concat(s, function (err, buf) {
t.error(err)
t.deepEqual(buf, Buffer.from('abc123456789'))
})
s.write('abc')
setTimeout(function () {
s.write('123')
}, 10)
setTimeout(function () {
s.write('456')
}, 20)
setTimeout(function () {
s.end('789')
}, 30)
})
test('error', function (t) {
t.plan(2)
var s = new stream.PassThrough()
concat(s, function (err, buf) {
t.ok(err, 'got expected error')
t.ok(!buf)
})
s.write('abc')
setTimeout(function () {
s.write('123')
}, 10)
setTimeout(function () {
s.write('456')
}, 20)
setTimeout(function () {
s.emit('error', new Error('error'))
}, 30)
})
version: 2
updates:
- package-ecosystem: npm
directory: /
schedule:
interval: daily
labels:
- dependency
versioning-strategy: increase-if-necessary
- package-ecosystem: github-actions
directory: /
schedule:
interval: daily
labels:
- dependency
name: ci
'on':
- push
- pull_request
jobs:
test:
name: Node ${{ matrix.node }} / ${{ matrix.os }}
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os:
- ubuntu-latest
node:
- '14'
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with:
node-version: ${{ matrix.node }}
- run: npm install
- run: npm run build --if-present
- run: npm test
The MIT License (MIT)
Copyright (c) Feross Aboukhadijeh
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# simple-get [![ci][ci-image]][ci-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url]
[ci-image]: https://img.shields.io/github/workflow/status/feross/simple-get/ci/master
[ci-url]: https://github.com/feross/simple-get/actions
[npm-image]: https://img.shields.io/npm/v/simple-get.svg
[npm-url]: https://npmjs.org/package/simple-get
[downloads-image]: https://img.shields.io/npm/dm/simple-get.svg
[downloads-url]: https://npmjs.org/package/simple-get
[standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg
[standard-url]: https://standardjs.com
### Simplest way to make http get requests
## features
This module is the lightest possible wrapper on top of node.js `http`, but supporting these essential features:
- follows redirects
- automatically handles gzip/deflate responses
- supports HTTPS
- supports specifying a timeout
- supports convenience `url` key so there's no need to use `url.parse` on the url when specifying options
- composes well with npm packages for features like cookies, proxies, form data, & OAuth
All this in < 100 lines of code.
## install
```
npm install simple-get
```
## usage
Note, all these examples also work in the browser with [browserify](http://browserify.org/).
### simple GET request
Doesn't get easier than this:
```js
const get = require('simple-get')
get('http://example.com', function (err, res) {
if (err) throw err
console.log(res.statusCode) // 200
res.pipe(process.stdout) // `res` is a stream
})
```
### even simpler GET request
If you just want the data, and don't want to deal with streams:
```js
const get = require('simple-get')
get.concat('http://example.com', function (err, res, data) {
if (err) throw err
console.log(res.statusCode) // 200
console.log(data) // Buffer('this is the server response')
})
```
### POST, PUT, PATCH, HEAD, DELETE support
For `POST`, call `get.post` or use option `{ method: 'POST' }`.
```js
const get = require('simple-get')
const opts = {
url: 'http://example.com',
body: 'this is the POST body'
}
get.post(opts, function (err, res) {
if (err) throw err
res.pipe(process.stdout) // `res` is a stream
})
```
#### A more complex example:
```js
const get = require('simple-get')
get({
url: 'http://example.com',
method: 'POST',
body: 'this is the POST body',
// simple-get accepts all options that node.js `http` accepts
// See: http://nodejs.org/api/http.html#http_http_request_options_callback
headers: {
'user-agent': 'my cool app'
}
}, function (err, res) {
if (err) throw err
// All properties/methods from http.IncomingResponse are available,
// even if a gunzip/inflate transform stream was returned.
// See: http://nodejs.org/api/http.html#http_http_incomingmessage
res.setTimeout(10000)
console.log(res.headers)
res.on('data', function (chunk) {
// `chunk` is the decoded response, after it's been gunzipped or inflated
// (if applicable)
console.log('got a chunk of the response: ' + chunk)
}))
})
```
### JSON
You can serialize/deserialize request and response with JSON:
```js
const get = require('simple-get')
const opts = {
method: 'POST',
url: 'http://example.com',
body: {
key: 'value'
},
json: true
}
get.concat(opts, function (err, res, data) {
if (err) throw err
console.log(data.key) // `data` is an object
})
```
### Timeout
You can set a timeout (in milliseconds) on the request with the `timeout` option.
If the request takes longer than `timeout` to complete, then the entire request
will fail with an `Error`.
```js
const get = require('simple-get')
const opts = {
url: 'http://example.com',
timeout: 2000 // 2 second timeout
}
get(opts, function (err, res) {})
```
### One Quick Tip
It's a good idea to set the `'user-agent'` header so the provider can more easily
see how their resource is used.
```js
const get = require('simple-get')
const pkg = require('./package.json')
get('http://example.com', {
headers: {
'user-agent': `my-module/${pkg.version} (https://github.com/username/my-module)`
}
})
```
### Proxies
You can use the [`tunnel`](https://github.com/koichik/node-tunnel) module with the
`agent` option to work with proxies:
```js
const get = require('simple-get')
const tunnel = require('tunnel')
const opts = {
url: 'http://example.com',
agent: tunnel.httpOverHttp({
proxy: {
host: 'localhost'
}
})
}
get(opts, function (err, res) {})
```
### Cookies
You can use the [`cookie`](https://github.com/jshttp/cookie) module to include
cookies in a request:
```js
const get = require('simple-get')
const cookie = require('cookie')
const opts = {
url: 'http://example.com',
headers: {
cookie: cookie.serialize('foo', 'bar')
}
}
get(opts, function (err, res) {})
```
### Form data
You can use the [`form-data`](https://github.com/form-data/form-data) module to
create POST request with form data:
```js
const fs = require('fs')
const get = require('simple-get')
const FormData = require('form-data')
const form = new FormData()
form.append('my_file', fs.createReadStream('/foo/bar.jpg'))
const opts = {
url: 'http://example.com',
body: form
}
get.post(opts, function (err, res) {})
```
#### Or, include `application/x-www-form-urlencoded` form data manually:
```js
const get = require('simple-get')
const opts = {
url: 'http://example.com',
form: {
key: 'value'
}
}
get.post(opts, function (err, res) {})
```
### Specifically disallowing redirects
```js
const get = require('simple-get')
const opts = {
url: 'http://example.com/will-redirect-elsewhere',
followRedirects: false
}
// res.statusCode will be 301, no error thrown
get(opts, function (err, res) {})
```
### Basic Auth
```js
const user = 'someuser'
const pass = 'pa$$word'
const encodedAuth = Buffer.from(`${user}:${pass}`).toString('base64')
get('http://example.com', {
headers: {
authorization: `Basic ${encodedAuth}`
}
})
```
### OAuth
You can use the [`oauth-1.0a`](https://github.com/ddo/oauth-1.0a) module to create
a signed OAuth request:
```js
const get = require('simple-get')
const crypto = require('crypto')
const OAuth = require('oauth-1.0a')
const oauth = OAuth({
consumer: {
key: process.env.CONSUMER_KEY,
secret: process.env.CONSUMER_SECRET
},
signature_method: 'HMAC-SHA1',
hash_function: (baseString, key) => crypto.createHmac('sha1', key).update(baseString).digest('base64')
})
const token = {
key: process.env.ACCESS_TOKEN,
secret: process.env.ACCESS_TOKEN_SECRET
}
const url = 'https://api.twitter.com/1.1/statuses/home_timeline.json'
const opts = {
url: url,
headers: oauth.toHeader(oauth.authorize({url, method: 'GET'}, token)),
json: true
}
get(opts, function (err, res) {})
```
### Throttle requests
You can use [limiter](https://github.com/jhurliman/node-rate-limiter) to throttle requests. This is useful when calling an API that is rate limited.
```js
const simpleGet = require('simple-get')
const RateLimiter = require('limiter').RateLimiter
const limiter = new RateLimiter(1, 'second')
const get = (opts, cb) => limiter.removeTokens(1, () => simpleGet(opts, cb))
get.concat = (opts, cb) => limiter.removeTokens(1, () => simpleGet.concat(opts, cb))
var opts = {
url: 'http://example.com'
}
get.concat(opts, processResult)
get.concat(opts, processResult)
function processResult (err, res, data) {
if (err) throw err
console.log(data.toString())
}
```
## license
MIT. Copyright (c) [Feross Aboukhadijeh](http://feross.org).
/*! simple-get. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
module.exports = simpleGet
const concat = require('simple-concat')
const decompressResponse = require('decompress-response') // excluded from browser build
const http = require('http')
const https = require('https')
const once = require('once')
const querystring = require('querystring')
const url = require('url')
const isStream = o => o !== null && typeof o === 'object' && typeof o.pipe === 'function'
function simpleGet (opts, cb) {
opts = Object.assign({ maxRedirects: 10 }, typeof opts === 'string' ? { url: opts } : opts)
cb = once(cb)
if (opts.url) {
const { hostname, port, protocol, auth, path } = url.parse(opts.url) // eslint-disable-line node/no-deprecated-api
delete opts.url
if (!hostname && !port && !protocol && !auth) opts.path = path // Relative redirect
else Object.assign(opts, { hostname, port, protocol, auth, path }) // Absolute redirect
}
const headers = { 'accept-encoding': 'gzip, deflate' }
if (opts.headers) Object.keys(opts.headers).forEach(k => (headers[k.toLowerCase()] = opts.headers[k]))
opts.headers = headers
let body
if (opts.body) {
body = opts.json && !isStream(opts.body) ? JSON.stringify(opts.body) : opts.body
} else if (opts.form) {
body = typeof opts.form === 'string' ? opts.form : querystring.stringify(opts.form)
opts.headers['content-type'] = 'application/x-www-form-urlencoded'
}
if (body) {
if (!opts.method) opts.method = 'POST'
if (!isStream(body)) opts.headers['content-length'] = Buffer.byteLength(body)
if (opts.json && !opts.form) opts.headers['content-type'] = 'application/json'
}
delete opts.body; delete opts.form
if (opts.json) opts.headers.accept = 'application/json'
if (opts.method) opts.method = opts.method.toUpperCase()
const originalHost = opts.hostname // hostname before potential redirect
const protocol = opts.protocol === 'https:' ? https : http // Support http/https urls
const req = protocol.request(opts, res => {
if (opts.followRedirects !== false && res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
opts.url = res.headers.location // Follow 3xx redirects
delete opts.headers.host // Discard `host` header on redirect (see #32)
res.resume() // Discard response
const redirectHost = url.parse(opts.url).hostname // eslint-disable-line node/no-deprecated-api
// If redirected host is different than original host, drop headers to prevent cookie leak (#73)
if (redirectHost !== null && redirectHost !== originalHost) {
delete opts.headers.cookie
delete opts.headers.authorization
}
if (opts.method === 'POST' && [301, 302].includes(res.statusCode)) {
opts.method = 'GET' // On 301/302 redirect, change POST to GET (see #35)
delete opts.headers['content-length']; delete opts.headers['content-type']
}
if (opts.maxRedirects-- === 0) return cb(new Error('too many redirects'))
else return simpleGet(opts, cb)
}
const tryUnzip = typeof decompressResponse === 'function' && opts.method !== 'HEAD'
cb(null, tryUnzip ? decompressResponse(res) : res)
})
req.on('timeout', () => {
req.abort()
cb(new Error('Request timed out'))
})
req.on('error', cb)
if (isStream(body)) body.on('error', cb).pipe(req)
else req.end(body)
return req
}
simpleGet.concat = (opts, cb) => {
return simpleGet(opts, (err, res) => {
if (err) return cb(err)
concat(res, (err, data) => {
if (err) return cb(err)
if (opts.json) {
try {
data = JSON.parse(data.toString())
} catch (err) {
return cb(err, res, data)
}
}
cb(null, res, data)
})
})
}
;['get', 'post', 'put', 'patch', 'head', 'delete'].forEach(method => {
simpleGet[method] = (opts, cb) => {
if (typeof opts === 'string') opts = { url: opts }
return simpleGet(Object.assign({ method: method.toUpperCase() }, opts), cb)
}
})
{
"_from": "simple-get@^4.0.1",
"_id": "simple-get@4.0.1",
"_inBundle": false,
"_integrity": "sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA==",
"_location": "/simple-get",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "simple-get@^4.0.1",
"name": "simple-get",
"escapedName": "simple-get",
"rawSpec": "^4.0.1",
"saveSpec": null,
"fetchSpec": "^4.0.1"
},
"_requiredBy": [
"/vue-qr"
],
"_resolved": "https://registry.npmmirror.com/simple-get/-/simple-get-4.0.1.tgz",
"_shasum": "4a39db549287c979d352112fa03fd99fd6bc3543",
"_spec": "simple-get@^4.0.1",
"_where": "/Users/zhanghao/brcode/br-client/node_modules/vue-qr",
"author": {
"name": "Feross Aboukhadijeh",
"email": "feross@feross.org",
"url": "https://feross.org"
},
"browser": {
"decompress-response": false
},
"bugs": {
"url": "https://github.com/feross/simple-get/issues"
},
"bundleDependencies": false,
"dependencies": {
"decompress-response": "^6.0.0",
"once": "^1.3.1",
"simple-concat": "^1.0.0"
},
"deprecated": false,
"description": "Simplest way to make http get requests. Supports HTTPS, redirects, gzip/deflate, streams in < 100 lines.",
"devDependencies": {
"self-signed-https": "^1.0.5",
"standard": "*",
"string-to-stream": "^3.0.0",
"tape": "^5.0.0"
},
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/feross"
},
{
"type": "patreon",
"url": "https://www.patreon.com/feross"
},
{
"type": "consulting",
"url": "https://feross.org/support"
}
],
"homepage": "https://github.com/feross/simple-get",
"keywords": [
"request",
"http",
"GET",
"get request",
"http.get",
"redirects",
"follow redirects",
"gzip",
"deflate",
"https",
"http-https",
"stream",
"simple request",
"simple get"
],
"license": "MIT",
"main": "index.js",
"name": "simple-get",
"repository": {
"type": "git",
"url": "git://github.com/feross/simple-get.git"
},
"scripts": {
"test": "standard && tape test/*.js"
},
"version": "4.0.1"
}
{
"env": {
"browser": true,
"node": true,
"commonjs": true,
"es6": true
},
"extends": "eslint:recommended",
"rules": {
"strict": 2,
"indent": 0,
"linebreak-style": 0,
"quotes": 0,
"semi": 0,
"no-cond-assign": 1,
"no-constant-condition": 1,
"no-duplicate-case": 1,
"no-empty": 1,
"no-ex-assign": 1,
"no-extra-boolean-cast": 1,
"no-extra-semi": 1,
"no-fallthrough": 1,
"no-func-assign": 1,
"no-global-assign": 1,
"no-implicit-globals": 2,
"no-inner-declarations": ["error", "functions"],
"no-irregular-whitespace": 2,
"no-loop-func": 1,
"no-magic-numbers": ["warn", { "ignore": [1, 0, -1], "ignoreArrayIndexes": true}],
"no-multi-str": 1,
"no-mixed-spaces-and-tabs": 1,
"no-proto": 1,
"no-sequences": 1,
"no-throw-literal": 1,
"no-unmodified-loop-condition": 1,
"no-useless-call": 1,
"no-void": 1,
"no-with": 2,
"wrap-iife": 1,
"no-redeclare": 1,
"no-unused-vars": ["error", { "vars": "all", "args": "none" }],
"no-sparse-arrays": 1
}
}
language: node_js
node_js:
- '6'
- '5'
- '4'
'use strict'
var paren = require('parenthesis')
module.exports = function splitBy (string, separator, o) {
if (string == null) throw Error('First argument should be a string')
if (separator == null) throw Error('Separator should be a string or a RegExp')
if (!o) o = {}
else if (typeof o === 'string' || Array.isArray(o)) {
o = {ignore: o}
}
if (o.escape == null) o.escape = true
if (o.ignore == null) o.ignore = ['[]', '()', '{}', '<>', '""', "''", '``', '“”', '«»']
else {
if (typeof o.ignore === 'string') {o.ignore = [o.ignore]}
o.ignore = o.ignore.map(function (pair) {
// '"' → '""'
if (pair.length === 1) pair = pair + pair
return pair
})
}
var tokens = paren.parse(string, {flat: true, brackets: o.ignore})
var str = tokens[0]
var parts = str.split(separator)
// join parts separated by escape
if (o.escape) {
var cleanParts = []
for (var i = 0; i < parts.length; i++) {
var prev = parts[i]
var part = parts[i + 1]
if (prev[prev.length - 1] === '\\' && prev[prev.length - 2] !== '\\') {
cleanParts.push(prev + separator + part)
i++
}
else {
cleanParts.push(prev)
}
}
parts = cleanParts
}
// open parens pack & apply unquotes, if any
for (var i = 0; i < parts.length; i++) {
tokens[0] = parts[i]
parts[i] = paren.stringify(tokens, {flat: true})
}
return parts
}
{
"_from": "string-split-by@^1.0.0",
"_id": "string-split-by@1.0.0",
"_inBundle": false,
"_integrity": "sha512-KaJKY+hfpzNyet/emP81PJA9hTVSfxNLS9SFTWxdCnnW1/zOOwiV248+EfoX7IQFcBaOp4G5YE6xTJMF+pLg6A==",
"_location": "/string-split-by",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "string-split-by@^1.0.0",
"name": "string-split-by",
"escapedName": "string-split-by",
"rawSpec": "^1.0.0",
"saveSpec": null,
"fetchSpec": "^1.0.0"
},
"_requiredBy": [
"/vue-qr"
],
"_resolved": "https://registry.npmmirror.com/string-split-by/-/string-split-by-1.0.0.tgz",
"_shasum": "53895fb3397ebc60adab1f1e3a131f5372586812",
"_spec": "string-split-by@^1.0.0",
"_where": "/Users/zhanghao/brcode/br-client/node_modules/vue-qr",
"author": {
"name": "Dmitry Yv",
"email": "dfcreative@gmail.com"
},
"bugs": {
"url": "https://github.com/dy/string-split-by/issues"
},
"bundleDependencies": false,
"dependencies": {
"parenthesis": "^3.1.5"
},
"deprecated": false,
"description": "Split string by any separator excluding brackets, quotes and escaped characters",
"devDependencies": {
"tape": "^4.9.0"
},
"homepage": "https://github.com/dy/string-split-by#readme",
"keywords": [
"split-string",
"string-split",
"split-stirng-words",
"space",
"string",
"split"
],
"license": "MIT",
"main": "index.js",
"name": "string-split-by",
"repository": {
"type": "git",
"url": "git+https://github.com/dy/string-split-by.git"
},
"scripts": {
"test": "node test.js"
},
"version": "1.0.0"
}
# string-split-by [![unstable](https://img.shields.io/badge/stability-unstable-orange.svg)](http://github.com/badges/stability-badges) [![Build Status](https://img.shields.io/travis/dy/string-split-by.svg)](https://travis-ci.org/dy/string-split-by)
Split string by a separator with respect to brackets, quotes and escape markers. Optimized version of [string-split](https://github.com/jonschlinkert/split-string).
## Usage
[![npm install string-split-by](https://nodei.co/npm/string-split-by.png?mini=true)](https://npmjs.org/package/string-split-by/)
```js
var split = require('string-split-by')
split('a."b.c".d.{.e.f.g.}.h', '.')
// ['a', '"b.c"', 'd', '{.e.f.g.}', 'h']
split('a."b.c".d.{.e.f.g.}.h', '.', {ignore: '""'})
// ['a', '"b.c"', 'd', '{', 'e', 'f', 'g', '}', 'h']
```
## API
### parts = splitBy(string, separator, options?)
Return array with parts split from string by a separator, which can be whether _String_ or _RegExp_. Options can define:
Option | Default | Meaning
---|---|---
`ignore` | ``['"', "'", '`', '“”', '«»', '[]', '()', '{}']`` | Avoid splitting content enclosed in the character pairs. Can be a string or a list of strings.
`escape` | `true` | Avoid splitting at the escaped separator, eg. `\.` won't be separated by `'.'` separator.
## Related
* [parenthesis](http://npmjs.org/package/parenthesis)
## License
© 2018 Dmitry Yv. MIT License
'use strict';
var t = require('tape')
var split = require('.');
t('should throw an error when arguments are invalid', t => {
t.throws(() => split());
t.end()
});
t('readme', t => {
t.deepEqual(
split('a."b.c".d.{.e.f.g.}.h', '.'),
['a', '"b.c"', 'd', '{.e.f.g.}', 'h']
)
t.deepEqual(
split('a."b.c".d.{.e.f.g.}.h', '.', {ignore: '""'}),
['a', '"b.c"', 'd', '{', 'e', 'f', 'g', '}', 'h']
)
t.end()
})
t('should not split on escaped dots:', t => {
t.deepEqual(split('a.b.c\\.d', '.'), ['a', 'b', 'c\\.d']);
t.deepEqual(split('a.b.c\\.d.e', '.'), ['a', 'b', 'c\\.d', 'e']);
t.end()
});
t('should keep escaping when followed by a backslash:', t => {
t.deepEqual(split('a.b.c\\\\.d', '.'), ['a', 'b', 'c\\\\', 'd']);
t.deepEqual(split('a.b.c\\\\d', '.'), ['a', 'b', 'c\\\\d']);
t.end()
});
t('should split a string on dots by default:', t => {
t.deepEqual(split('a.b.c', '.'), ['a', 'b', 'c']);
t.end()
});
t('should respect double-quoted strings', t => {
t.deepEqual(split('"b.c"', '.'), ['"b.c"']);
t.deepEqual(split('a."b.c"', '.'), ['a', '"b.c"']);
t.deepEqual(split('a".b.c"', '.'), ['a".b.c"']);
t.deepEqual(split('a."b.c".d', '.'), ['a', '"b.c"', 'd']);
t.deepEqual(split('a."b.c".d.".e.f.g.".h', '.'), ['a', '"b.c"', 'd', '".e.f.g."', 'h']);
t.end()
});
t('should respect singlequoted strings', t => {
t.deepEqual(split('\'b.c\'', '.'), ['\'b.c\'']);
t.deepEqual(split('a.\'b.c\'', '.'), ['a', '\'b.c\'']);
t.deepEqual(split('a.\'b.c\'.d', '.'), ['a', '\'b.c\'', 'd']);
t.deepEqual(split('a.\'b.c\'.d.\'.e.f.g.\'.h', '.'), ['a', '\'b.c\'', 'd', '\'.e.f.g.\'', 'h']);
t.end()
});
t('should respect strings in backticks', t => {
t.deepEqual(split('`b.c`', '.'), ['`b.c`']);
t.deepEqual(split('a.`b.c`', '.'), ['a', '`b.c`']);
t.deepEqual(split('a.`b.c`.d', '.'), ['a', '`b.c`', 'd']);
t.deepEqual(split('a.`b.c`.d.`.e.f.g.`.h', '.'), ['a', '`b.c`', 'd', '`.e.f.g.`', 'h']);
t.end()
});
t('should respect strings in double smart-quotes: “”', t => {
t.deepEqual(split('“b.c”', '.'), ['“b.c”']);
t.deepEqual(split('a.“b.c”', '.'), ['a', '“b.c”']);
t.deepEqual(split('a.“b.c”.d', '.'), ['a', '“b.c”', 'd']);
t.deepEqual(split('a.“b.c”.d.“.e.f.g.”.h', '.'), ['a', '“b.c”', 'd', '“.e.f.g.”', 'h']);
t.end()
});
t('should retain unclosed double quotes in the results', t => {
t.deepEqual(split('a."b.c', '.'), ['a', '"b', 'c']);
t.end()
});
t('should retain unclosed single quotes in the results', t => {
t.deepEqual(split('brian\'s', '.'), ['brian\'s']);
t.deepEqual(split('a.\'b.c', '.'), ['a', '\'b', 'c']);
t.end()
});
t('should split on a custom separator', t => {
t.deepEqual(split('a/b/c', '/'), ['a', 'b', 'c']);
t.deepEqual(split('a,b,c', ','), ['a', 'b', 'c']);
t.end()
});
t('should not split on an escaped custom separator:', t => {
t.deepEqual(split('a/b/c\\/d', '/'), ['a', 'b', 'c\\/d']);
t.end()
});
t('should disable quotes support', t => {
t.deepEqual(split('a.\'b.c\'."d"', '.', {ignore: '"'}), ['a', '\'b', 'c\'', '"d"']);
t.end()
});
t('should keep single quotes', t => {
t.deepEqual(split('a.\'b.c\'."d"', '.', {ignore: '\''}), ['a', '\'b.c\'', '"d"']);
t.end()
});
t('should keep double quotes', t => {
t.deepEqual(split('a."b.c".d', '.', '"'), ['a', '"b.c"', 'd']);
t.end()
});
t('should keep “” double quotes', t => {
t.deepEqual(split('a.“b.c”.d', '.', '“”'), ['a', '“b.c”', 'd']);
t.end()
});
t('should keep backticks', t => {
t.deepEqual(split('a.`b.c`.d', '.', {ignore: '`'}), ['a', '`b.c`', 'd']);
t.end()
});
t('should allow custom quotes object', t => {
t.deepEqual(split('a.^b.c$', '.', {ignore: '^$'}), ['a', '^b.c$']);
t.deepEqual(split('a.^b.c^', '.', {ignore: '^^'}), ['a', '^b.c^']);
t.deepEqual(split('a.~b.c~', '.', {ignore: '~~'}), ['a', '~b.c~']);
t.end()
});
t('should keep escape characters', t => {
t.deepEqual(split('a.b\\.c', '.', {escape: true}), ['a', 'b\\.c']);
t.end()
});
t.skip('should throw when brackets are unclosed', t => {
t.throws(function() {
}, /unclosed/);
t.end()
});
t('should not split inside brackets', t => {
t.deepEqual(split('a.(b.c).d', '.'), ['a', '(b.c)', 'd']);
t.deepEqual(split('a.[(b.c)].d', '.'), ['a', '[(b.c)]', 'd']);
t.deepEqual(split('a.[b.c].d', '.'), ['a', '[b.c]', 'd']);
t.deepEqual(split('a.{b.c}.d', '.'), ['a', '{b.c}', 'd']);
t.deepEqual(split('a.<b.c>.d', '.'), ['a', '<b.c>', 'd']);
t.end()
});
t('should support nested brackets', t => {
t.deepEqual(split('a.{b.{c}.d}.e', '.'), ['a', '{b.{c}.d}', 'e']);
t.deepEqual(split('a.{b.{c.d}.e}.f', '.'), ['a', '{b.{c.d}.e}', 'f']);
t.deepEqual(split('a.{[b.{{c.d}}.e]}.f', '.'), ['a', '{[b.{{c.d}}.e]}', 'f']);
t.end()
});
t.skip('should support escaped brackets', t => {
t.deepEqual(split('a.\\{b.{c.c}.d}.e', '.'), ['a', '{b', '{c.c}', 'd}', 'e']);
t.deepEqual(split('a.{b.c}.\\{d.e}.f', '.'), ['a', '{b.c}', '{d', 'e}', 'f']);
t.end()
});
t('should support quoted brackets', t => {
t.deepEqual(split('a.{b.c}."{d.e}".f', '.'), ['a', '{b.c}', '"{d.e}"', 'f']);
t.deepEqual(split('a.{b.c}.{"d.e"}.f', '.'), ['a', '{b.c}', '{"d.e"}', 'f']);
t.end()
});
t('should ignore imbalanced brackets', t => {
t.deepEqual(split('a.{b.c', '.'), ['a', '{b', 'c']);
t.deepEqual(split('a.{a.{b.c}.d', '.'), ['a', '{a', '{b.c}', 'd']);
t.end()
});
{
"presets": [
[
"@babel/preset-env",
{
"modules": false
}
]
],
"plugins": [
[
"@babel/plugin-transform-runtime",
{}
],
"@babel/plugin-proposal-class-properties"
]
}
root = true
[*]
charset = utf-8
indent_style = space
indent_size = 2
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
module.exports = {
plugins: {
autoprefixer: {}
}
}
\ No newline at end of file
# Changelog
## 4.0.9 | 2022.05.24
- Fix `path-browserify` export error
## 4.0.6 | 2022.04.14
- Fix dependency error position
## 4.0.5 | 2022.04.13
- Remove `canvas` dependency
## 3.2.4 | 2022.01.19
- Update `canvas` version
## 3.2.2 | 2021.10.13
- Bugfix: components default value [#100](https://github.com/Binaryify/vue-qr/pull/100)
- Update `components` default value
## 3.2.0 | 2021.10.12
- Add `components` params [#98](https://github.com/Binaryify/vue-qr/issues/98)
## 3.1.0 | 2021.10.05
- Support Vite [#90](https://github.com/Binaryify/vue-qr/issues/90) [#96](https://github.com/Binaryify/vue-qr/issues/96)
## 3.0.0 | 2021.10.02
- Using Awesome-qr.js v2.0
- Support Vue v3.0(not support Vite yet) [#82](https://github.com/Binaryify/vue-qr/issues/82)
## 2.3.1 | 2021.05.03
- Fixed [#86](https://github.com/Binaryify/vue-qr/issues/86)
## 2.3.0 | 2020.10.05
- Support SSR
## 2.2.0
- Fixed [#65](https://github.com/Binaryify/vue-qr/issues/65) [#68](https://github.com/Binaryify/vue-qr/issues/68)
- Set `dotScale` default value to 1
## 2.1.0
- Fixed qr margin offset when logo is added (via:[https://github.com/SumiMakito/Awesome-qr.js/pull/38](https://github.com/SumiMakito/Awesome-qr.js/pull/38))
## 2.0.7
- Improve image load function
## 2.0.6
- Remove babel-polyfill [#53](https://github.com/Binaryify/vue-qr/issues/53)
- add .npmignore
## 2.0.4
- Fix dotScale defalut value bug
## 2.0.2
- Fix bug
## 2.0.2
- Update README.MD
## 2.0.1
- Fix colorLight can't set bug
- Support background color and logo background
## 2.0.0
- Refactoring
- Support gif background
The MIT License (MIT)
Copyright (c) 2013-2022 Binaryify
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
# vue-qr
<a href="https://www.npmjs.com/package/vue-qr"><img src="https://img.shields.io/npm/v/vue-qr.svg" alt="Version"></a>
<a href="https://www.npmjs.com/package/vue-qr"><img src="https://img.shields.io/npm/l/vue-qr.svg" alt="License"></a>
The Vue Component for [SumiMakito's Awesome-qr.js](https://github.com/SumiMakito/Awesome-qr.js). Support Vue2/Vue3/Vite
The only one qr code component for Vue.js you need !
### Notice
Not support IE 不支持IE浏览器
### Examples, 样例
> Try to scan these QR codes below with your smart phone.
Example 1|Example 2|Example 3|Example 4
------------ | ------------- | -------------| -------------
<img src="https://raw.githubusercontent.com/Binaryify/vue-qr/master/src/assets/result1.png" width="300"> | <img src="https://raw.githubusercontent.com/Binaryify/vue-qr/master/src/assets/result2.png" width="300"> | <img src="https://raw.githubusercontent.com/Binaryify/vue-qr/master/src/assets/result3.png" width="300"> | <img src="https://raw.githubusercontent.com/Binaryify/vue-qr/master/src/assets/result4.gif" width="300">
### Demo
Run `npm run dev` or `yarn dev`
运行 `npm run dev` or `yarn dev`
## Installation
**install with NPM**
```bash
npm install vue-qr --save
```
**Import**
```js
// vue2.0
import VueQr from 'vue-qr'
// vue3.0 (support vite)
import vueQr from 'vue-qr/src/packages/vue-qr.vue'
...
{
components: {VueQr}
}
```
## Usage
**In template**
```html
<vue-qr :bgSrc='src' :logoSrc="src2" text="Hello world!" :size="200"></vue-qr>
<vue-qr text="Hello world!" :callback="test" qid="testid"></vue-qr>
```
```js
export default {
methods:{
test(dataUrl,id){
console.log(url, id)
}
}
}
```
Parameter | Explanation
----|----
text | Contents to encode. 欲编码的内容
correctLevel| Correct Level 0-3 容错级别 0-3
size | Width as well as the height of the output QR code, includes margin. 尺寸, 长宽一致, 包含外边距
margin | Margin to add around the QR code, default 20px. 二维码图像的外边距, 默认 20px
colorDark | Color of "true" blocks. Works only when both colorDark and colorLight are set. (BYTE_DTA, BYTE_POS, BYTE_AGN, BYTE_TMG) 实点的颜色
colorLight | Color of empty space, or "false" blocks. Works only when both colorDark and colorLight are set. (BYTE_EPT) 空白区的颜色
components | Controls the appearances of parts in the QR code. Read section [ComponentOptions](#componentoptions) to learn more. 阅读 [ComponentOptions](#componentoptions) 了解更多信息。
bgSrc | Background url to embed in the QR code. 欲嵌入的背景图地址
gifBgSrc | Gif background url to embed in the QR code, If gifBackground is set, backgroundImage will be ignored. This option will affects performance. 欲嵌入的背景图 gif 地址,设置后普通的背景图将失效。设置此选项会影响性能
backgroundColor | Background color 背景色
backgroundDimming | Color mask to add above the background image. Helpful when having problems with decoding. 叠加在背景图上的颜色, 在解码有难度的时有一定帮助
logoSrc | Logo url to embed at the center of generated QR code 嵌入至二维码中心的 LOGO 地址
logoScale | Value used to scale the logo image. Larger value may result in decode failure. Size of the logo equals to `logoScale*(size-2*margin)`. Default is 0.2. 用于计算 LOGO 大小的值, 过大将导致解码失败, LOGO 尺寸计算公式 `logoScale*(size-2*margin)`, 默认 0.2
logoMargin | White margin that appears around the logo image. Default is 0. LOGO 标识周围的空白边框, 默认为0
logoBackgroundColor | Logo background color, need set logo margin. Logo 背景色,需要设置 logo margin
logoCornerRadius | Radius of the logo's corners.Default is 0 LOGO 标识及其边框的圆角半径, 默认为0
whiteMargin | If set to true, a white border will appear around the background image. Default is true. 若设为 true, 背景图外将绘制白色边框
dotScale | Value used to scale down the data dots' size. (0 < scale < 1.0) default 1 数据区域点缩小比例,默认为1
autoColor | If set to true, the dominant color of backgroundImage will be used as colorDark. Default is true. 若为 true, 背景图的主要颜色将作为实点的颜色, 即 colorDark,默认 true
binarize | If set to true, the whole image will be binarized with the given threshold, or default threshold if not specified. Default is false. 若为 true, 图像将被二值化处理, 未指定阈值则使用默认值
binarizeThreshold | Threshold used to binarize the whole image. Default is 128. (0 < threshold < 255) 二值化处理的阈值
callback | Data URI of the generated QR code will be available here. 生成的二维码 Data URI 可以在回调中取得,第一个参数为二维码 data URL, 第二个参数为 props 传过来的 qid(因为二维码生成是异步的,所以加个 id 用于排序)
bindElement | If set to true, the generated QR will bind to a HTML element automatically. Default is true. 指定是否需要自动将生成的二维码绑定到HTML上, 默认是true
## ComponentOptions
> _ComponentOptions_ controls the appearances of parts in the QR code.组件选项控制二维码中零件的外观。
```ts
type ComponentOptions = {
data?: {
scale?: number;
};
timing?: {
scale?: number;
protectors?: boolean;
};
alignment?: {
scale?: number;
protectors?: boolean;
};
cornerAlignment?: {
scale?: number;
protectors?: boolean;
};
};
```
```ts
// default ComponentOptions
{
data: {
scale: 1,
},
timing: {
scale: 1,
protectors: false,
},
alignment: {
scale: 1,
protectors: false,
},
cornerAlignment: {
scale: 1,
protectors: true,
},
}
```
### scale 比例尺
Type number?
Scale factor for blocks in the specified area of the QR code.
在 QR 码指定区域的块的比例。
### protectors
**Type** `boolean?`
Controls whether or not to draw the translucent protectors under the specified area in the QR code.控制是否在 QR 码的指定区域下绘制半透明保护器。
For more details you should definitely check out [Awesome-qr.js ](https://github.com/SumiMakito/Awesome-qr.js)
!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define("vue-qr",[],e):"object"==typeof exports?exports["vue-qr"]=e():t["vue-qr"]=e()}(this,(function(){return function(t){var e={};function r(n){if(e[n])return e[n].exports;var o=e[n]={i:n,l:!1,exports:{}};return t[n].call(o.exports,o,o.exports,r),o.l=!0,o.exports}return r.m=t,r.c=e,r.d=function(t,e,n){r.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:n})},r.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},r.t=function(t,e){if(1&e&&(t=r(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var o in t)r.d(n,o,function(e){return t[e]}.bind(null,o));return n},r.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return r.d(e,"a",e),e},r.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},r.p="/dist/",r(r.s=13)}([function(t,e){t.exports=function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")},t.exports.__esModule=!0,t.exports.default=t.exports},function(t,e){function r(t,e){for(var r=0;r<e.length;r++){var n=e[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,n.key,n)}}t.exports=function(t,e,n){return e&&r(t.prototype,e),n&&r(t,n),Object.defineProperty(t,"prototype",{writable:!1}),t},t.exports.__esModule=!0,t.exports.default=t.exports},function(t,e){function r(e){return t.exports=r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},t.exports.__esModule=!0,t.exports.default=t.exports,r(e)}t.exports=r,t.exports.__esModule=!0,t.exports.default=t.exports},function(t,e,r){t.exports=r(14)()},function(t,e,r){"use strict";r.d(e,"a",(function(){return l})),r.d(e,"b",(function(){return c})),r.d(e,"c",(function(){return p}));var n=r(0),o=r.n(n),i=r(1),a=r.n(i);function s(t){var e=encodeURI(t).toString().replace(/\%[0-9a-fA-F]{2}/g,"a");return e.length+(e.length!=Number(t)?3:0)}var u=function(){function t(e){o()(this,t),this.mode=h.MODE_8BIT_BYTE,this.parsedData=[],this.data=e;for(var r=[],n=0,i=this.data.length;n<i;n++){var a=[],s=this.data.charCodeAt(n);s>65536?(a[0]=240|(1835008&s)>>>18,a[1]=128|(258048&s)>>>12,a[2]=128|(4032&s)>>>6,a[3]=128|63&s):s>2048?(a[0]=224|(61440&s)>>>12,a[1]=128|(4032&s)>>>6,a[2]=128|63&s):s>128?(a[0]=192|(1984&s)>>>6,a[1]=128|63&s):a[0]=s,r.push(a)}this.parsedData=Array.prototype.concat.apply([],r),this.parsedData.length!=this.data.length&&(this.parsedData.unshift(191),this.parsedData.unshift(187),this.parsedData.unshift(239))}return a()(t,[{key:"getLength",value:function(){return this.parsedData.length}},{key:"write",value:function(t){for(var e=0,r=this.parsedData.length;e<r;e++)t.put(this.parsedData[e],8)}}]),t}(),l=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:-1,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:c.L;o()(this,t),this.moduleCount=0,this.dataList=[],this.typeNumber=e,this.errorCorrectLevel=r,this.moduleCount=0,this.dataList=[]}return a()(t,[{key:"addData",value:function(t){if(this.typeNumber<=0)this.typeNumber=function(t,e){for(var r=1,n=s(t),o=0,i=m.length;o<i;o++){var a=0;switch(e){case c.L:a=m[o][0];break;case c.M:a=m[o][1];break;case c.Q:a=m[o][2];break;case c.H:a=m[o][3]}if(n<=a)break;r++}if(r>m.length)throw new Error("Too long data");return r}(t,this.errorCorrectLevel);else{if(this.typeNumber>40)throw new Error("Invalid QR version: ".concat(this.typeNumber));if(!function(t,e,r){var n=s(e),o=t-1,i=0;switch(r){case c.L:i=m[o][0];break;case c.M:i=m[o][1];break;case c.Q:i=m[o][2];break;case c.H:i=m[o][3]}return n<=i}(this.typeNumber,t,this.errorCorrectLevel))throw new Error("Data is too long for QR version: ".concat(this.typeNumber))}var e=new u(t);this.dataList.push(e),this.dataCache=void 0}},{key:"isDark",value:function(t,e){if(t<0||this.moduleCount<=t||e<0||this.moduleCount<=e)throw new Error("".concat(t,",").concat(e));return this.modules[t][e]}},{key:"getModuleCount",value:function(){return this.moduleCount}},{key:"make",value:function(){this.makeImpl(!1,this.getBestMaskPattern())}},{key:"makeImpl",value:function(e,r){this.moduleCount=4*this.typeNumber+17,this.modules=new Array(this.moduleCount);for(var n=0;n<this.moduleCount;n++){this.modules[n]=new Array(this.moduleCount);for(var o=0;o<this.moduleCount;o++)this.modules[n][o]=null}this.setupPositionProbePattern(0,0),this.setupPositionProbePattern(this.moduleCount-7,0),this.setupPositionProbePattern(0,this.moduleCount-7),this.setupPositionAdjustPattern(),this.setupTimingPattern(),this.setupTypeInfo(e,r),this.typeNumber>=7&&this.setupTypeNumber(e),null==this.dataCache&&(this.dataCache=t.createData(this.typeNumber,this.errorCorrectLevel,this.dataList)),this.mapData(this.dataCache,r)}},{key:"setupPositionProbePattern",value:function(t,e){for(var r=-1;r<=7;r++)if(!(t+r<=-1||this.moduleCount<=t+r))for(var n=-1;n<=7;n++)e+n<=-1||this.moduleCount<=e+n||(this.modules[t+r][e+n]=0<=r&&r<=6&&(0==n||6==n)||0<=n&&n<=6&&(0==r||6==r)||2<=r&&r<=4&&2<=n&&n<=4)}},{key:"getBestMaskPattern",value:function(){if(Number.isInteger(this.maskPattern)&&Object.values(f).includes(this.maskPattern))return this.maskPattern;for(var t=0,e=0,r=0;r<8;r++){this.makeImpl(!0,r);var n=p.getLostPoint(this);(0==r||t>n)&&(t=n,e=r)}return e}},{key:"setupTimingPattern",value:function(){for(var t=8;t<this.moduleCount-8;t++)null==this.modules[t][6]&&(this.modules[t][6]=t%2==0);for(var e=8;e<this.moduleCount-8;e++)null==this.modules[6][e]&&(this.modules[6][e]=e%2==0)}},{key:"setupPositionAdjustPattern",value:function(){for(var t=p.getPatternPosition(this.typeNumber),e=0;e<t.length;e++)for(var r=0;r<t.length;r++){var n=t[e],o=t[r];if(null==this.modules[n][o])for(var i=-2;i<=2;i++)for(var a=-2;a<=2;a++)this.modules[n+i][o+a]=-2==i||2==i||-2==a||2==a||0==i&&0==a}}},{key:"setupTypeNumber",value:function(t){for(var e=p.getBCHTypeNumber(this.typeNumber),r=0;r<18;r++){var n=!t&&1==(e>>r&1);this.modules[Math.floor(r/3)][r%3+this.moduleCount-8-3]=n}for(r=0;r<18;r++){n=!t&&1==(e>>r&1);this.modules[r%3+this.moduleCount-8-3][Math.floor(r/3)]=n}}},{key:"setupTypeInfo",value:function(t,e){for(var r=this.errorCorrectLevel<<3|e,n=p.getBCHTypeInfo(r),o=0;o<15;o++){var i=!t&&1==(n>>o&1);o<6?this.modules[o][8]=i:o<8?this.modules[o+1][8]=i:this.modules[this.moduleCount-15+o][8]=i}for(o=0;o<15;o++){i=!t&&1==(n>>o&1);o<8?this.modules[8][this.moduleCount-o-1]=i:o<9?this.modules[8][15-o-1+1]=i:this.modules[8][15-o-1]=i}this.modules[this.moduleCount-8][8]=!t}},{key:"mapData",value:function(t,e){for(var r=-1,n=this.moduleCount-1,o=7,i=0,a=this.moduleCount-1;a>0;a-=2)for(6==a&&a--;;){for(var s=0;s<2;s++)if(null==this.modules[n][a-s]){var u=!1;i<t.length&&(u=1==(t[i]>>>o&1)),p.getMask(e,n,a-s)&&(u=!u),this.modules[n][a-s]=u,-1==--o&&(i++,o=7)}if((n+=r)<0||this.moduleCount<=n){n-=r,r=-r;break}}}}],[{key:"createData",value:function(e,r,n){for(var o=y.getRSBlocks(e,r),i=new v,a=0;a<n.length;a++){var s=n[a];i.put(s.mode,4),i.put(s.getLength(),p.getLengthInBits(s.mode,e)),s.write(i)}var u=0;for(a=0;a<o.length;a++)u+=o[a].dataCount;if(i.getLengthInBits()>8*u)throw new Error("code length overflow. (".concat(i.getLengthInBits(),">").concat(8*u,")"));for(i.getLengthInBits()+4<=8*u&&i.put(0,4);i.getLengthInBits()%8!=0;)i.putBit(!1);for(;!(i.getLengthInBits()>=8*u||(i.put(t.PAD0,8),i.getLengthInBits()>=8*u));)i.put(t.PAD1,8);return t.createBytes(i,o)}},{key:"createBytes",value:function(t,e){for(var r=0,n=0,o=0,i=new Array(e.length),a=new Array(e.length),s=0;s<e.length;s++){var u=e[s].dataCount,l=e[s].totalCount-u;n=Math.max(n,u),o=Math.max(o,l),i[s]=new Array(u);for(var c=0;c<i[s].length;c++)i[s][c]=255&t.buffer[c+r];r+=u;var h=p.getErrorCorrectPolynomial(l),f=new d(i[s],h.getLength()-1).mod(h);a[s]=new Array(h.getLength()-1);for(c=0;c<a[s].length;c++){var g=c+f.getLength()-a[s].length;a[s][c]=g>=0?f.get(g):0}}var y=0;for(c=0;c<e.length;c++)y+=e[c].totalCount;var v=new Array(y),m=0;for(c=0;c<n;c++)for(s=0;s<e.length;s++)c<i[s].length&&(v[m++]=i[s][c]);for(c=0;c<o;c++)for(s=0;s<e.length;s++)c<a[s].length&&(v[m++]=a[s][c]);return v}}]),t}();l.PAD0=236,l.PAD1=17;var c={L:1,M:0,Q:3,H:2},h={MODE_NUMBER:1,MODE_ALPHA_NUM:2,MODE_8BIT_BYTE:4,MODE_KANJI:8},f={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7},p=function(){function t(){o()(this,t)}return a()(t,null,[{key:"getBCHTypeInfo",value:function(e){for(var r=e<<10;t.getBCHDigit(r)-t.getBCHDigit(t.G15)>=0;)r^=t.G15<<t.getBCHDigit(r)-t.getBCHDigit(t.G15);return(e<<10|r)^t.G15_MASK}},{key:"getBCHTypeNumber",value:function(e){for(var r=e<<12;t.getBCHDigit(r)-t.getBCHDigit(t.G18)>=0;)r^=t.G18<<t.getBCHDigit(r)-t.getBCHDigit(t.G18);return e<<12|r}},{key:"getBCHDigit",value:function(t){for(var e=0;0!=t;)e++,t>>>=1;return e}},{key:"getPatternPosition",value:function(e){return t.PATTERN_POSITION_TABLE[e-1]}},{key:"getMask",value:function(t,e,r){switch(t){case f.PATTERN000:return(e+r)%2==0;case f.PATTERN001:return e%2==0;case f.PATTERN010:return r%3==0;case f.PATTERN011:return(e+r)%3==0;case f.PATTERN100:return(Math.floor(e/2)+Math.floor(r/3))%2==0;case f.PATTERN101:return e*r%2+e*r%3==0;case f.PATTERN110:return(e*r%2+e*r%3)%2==0;case f.PATTERN111:return(e*r%3+(e+r)%2)%2==0;default:throw new Error("bad maskPattern:".concat(t))}}},{key:"getErrorCorrectPolynomial",value:function(t){for(var e=new d([1],0),r=0;r<t;r++)e=e.multiply(new d([1,g.gexp(r)],0));return e}},{key:"getLengthInBits",value:function(t,e){if(1<=e&&e<10)switch(t){case h.MODE_NUMBER:return 10;case h.MODE_ALPHA_NUM:return 9;case h.MODE_8BIT_BYTE:case h.MODE_KANJI:return 8;default:throw new Error("mode:".concat(t))}else if(e<27)switch(t){case h.MODE_NUMBER:return 12;case h.MODE_ALPHA_NUM:return 11;case h.MODE_8BIT_BYTE:return 16;case h.MODE_KANJI:return 10;default:throw new Error("mode:".concat(t))}else{if(!(e<41))throw new Error("type:".concat(e));switch(t){case h.MODE_NUMBER:return 14;case h.MODE_ALPHA_NUM:return 13;case h.MODE_8BIT_BYTE:return 16;case h.MODE_KANJI:return 12;default:throw new Error("mode:".concat(t))}}}},{key:"getLostPoint",value:function(t){for(var e=t.getModuleCount(),r=0,n=0;n<e;n++)for(var o=0;o<e;o++){for(var i=0,a=t.isDark(n,o),s=-1;s<=1;s++)if(!(n+s<0||e<=n+s))for(var u=-1;u<=1;u++)o+u<0||e<=o+u||0==s&&0==u||a==t.isDark(n+s,o+u)&&i++;i>5&&(r+=3+i-5)}for(n=0;n<e-1;n++)for(o=0;o<e-1;o++){var l=0;t.isDark(n,o)&&l++,t.isDark(n+1,o)&&l++,t.isDark(n,o+1)&&l++,t.isDark(n+1,o+1)&&l++,0!=l&&4!=l||(r+=3)}for(n=0;n<e;n++)for(o=0;o<e-6;o++)t.isDark(n,o)&&!t.isDark(n,o+1)&&t.isDark(n,o+2)&&t.isDark(n,o+3)&&t.isDark(n,o+4)&&!t.isDark(n,o+5)&&t.isDark(n,o+6)&&(r+=40);for(o=0;o<e;o++)for(n=0;n<e-6;n++)t.isDark(n,o)&&!t.isDark(n+1,o)&&t.isDark(n+2,o)&&t.isDark(n+3,o)&&t.isDark(n+4,o)&&!t.isDark(n+5,o)&&t.isDark(n+6,o)&&(r+=40);var c=0;for(o=0;o<e;o++)for(n=0;n<e;n++)t.isDark(n,o)&&c++;return r+=10*(Math.abs(100*c/e/e-50)/5)}}]),t}();p.PATTERN_POSITION_TABLE=[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],p.G15=1335,p.G18=7973,p.G15_MASK=21522;var g=function(){function t(){o()(this,t)}return a()(t,null,[{key:"glog",value:function(e){if(e<1)throw new Error("glog(".concat(e,")"));return t.LOG_TABLE[e]}},{key:"gexp",value:function(e){for(;e<0;)e+=255;for(;e>=256;)e-=255;return t.EXP_TABLE[e]}}]),t}();g.EXP_TABLE=new Array(256),g.LOG_TABLE=new Array(256),g._constructor=function(){for(var t=0;t<8;t++)g.EXP_TABLE[t]=1<<t;for(t=8;t<256;t++)g.EXP_TABLE[t]=g.EXP_TABLE[t-4]^g.EXP_TABLE[t-5]^g.EXP_TABLE[t-6]^g.EXP_TABLE[t-8];for(t=0;t<255;t++)g.LOG_TABLE[g.EXP_TABLE[t]]=t}();var d=function(){function t(e,r){if(o()(this,t),null==e.length)throw new Error("".concat(e.length,"/").concat(r));for(var n=0;n<e.length&&0==e[n];)n++;this.num=new Array(e.length-n+r);for(var i=0;i<e.length-n;i++)this.num[i]=e[i+n]}return a()(t,[{key:"get",value:function(t){return this.num[t]}},{key:"getLength",value:function(){return this.num.length}},{key:"multiply",value:function(e){for(var r=new Array(this.getLength()+e.getLength()-1),n=0;n<this.getLength();n++)for(var o=0;o<e.getLength();o++)r[n+o]^=g.gexp(g.glog(this.get(n))+g.glog(e.get(o)));return new t(r,0)}},{key:"mod",value:function(e){if(this.getLength()-e.getLength()<0)return this;for(var r=g.glog(this.get(0))-g.glog(e.get(0)),n=new Array(this.getLength()),o=0;o<this.getLength();o++)n[o]=this.get(o);for(o=0;o<e.getLength();o++)n[o]^=g.gexp(g.glog(e.get(o))+r);return new t(n,0).mod(e)}}]),t}(),y=function(){function t(e,r){o()(this,t),this.totalCount=e,this.dataCount=r}return a()(t,null,[{key:"getRSBlocks",value:function(e,r){var n=t.getRsBlockTable(e,r);if(null==n)throw new Error("bad rs block @ typeNumber:".concat(e,"/errorCorrectLevel:").concat(r));for(var o=n.length/3,i=[],a=0;a<o;a++)for(var s=n[3*a+0],u=n[3*a+1],l=n[3*a+2],c=0;c<s;c++)i.push(new t(u,l));return i}},{key:"getRsBlockTable",value:function(e,r){switch(r){case c.L:return t.RS_BLOCK_TABLE[4*(e-1)+0];case c.M:return t.RS_BLOCK_TABLE[4*(e-1)+1];case c.Q:return t.RS_BLOCK_TABLE[4*(e-1)+2];case c.H:return t.RS_BLOCK_TABLE[4*(e-1)+3];default:return}}}]),t}();y.RS_BLOCK_TABLE=[[1,26,19],[1,26,16],[1,26,13],[1,26,9],[1,44,34],[1,44,28],[1,44,22],[1,44,16],[1,70,55],[1,70,44],[2,35,17],[2,35,13],[1,100,80],[2,50,32],[2,50,24],[4,25,9],[1,134,108],[2,67,43],[2,33,15,2,34,16],[2,33,11,2,34,12],[2,86,68],[4,43,27],[4,43,19],[4,43,15],[2,98,78],[4,49,31],[2,32,14,4,33,15],[4,39,13,1,40,14],[2,121,97],[2,60,38,2,61,39],[4,40,18,2,41,19],[4,40,14,2,41,15],[2,146,116],[3,58,36,2,59,37],[4,36,16,4,37,17],[4,36,12,4,37,13],[2,86,68,2,87,69],[4,69,43,1,70,44],[6,43,19,2,44,20],[6,43,15,2,44,16],[4,101,81],[1,80,50,4,81,51],[4,50,22,4,51,23],[3,36,12,8,37,13],[2,116,92,2,117,93],[6,58,36,2,59,37],[4,46,20,6,47,21],[7,42,14,4,43,15],[4,133,107],[8,59,37,1,60,38],[8,44,20,4,45,21],[12,33,11,4,34,12],[3,145,115,1,146,116],[4,64,40,5,65,41],[11,36,16,5,37,17],[11,36,12,5,37,13],[5,109,87,1,110,88],[5,65,41,5,66,42],[5,54,24,7,55,25],[11,36,12],[5,122,98,1,123,99],[7,73,45,3,74,46],[15,43,19,2,44,20],[3,45,15,13,46,16],[1,135,107,5,136,108],[10,74,46,1,75,47],[1,50,22,15,51,23],[2,42,14,17,43,15],[5,150,120,1,151,121],[9,69,43,4,70,44],[17,50,22,1,51,23],[2,42,14,19,43,15],[3,141,113,4,142,114],[3,70,44,11,71,45],[17,47,21,4,48,22],[9,39,13,16,40,14],[3,135,107,5,136,108],[3,67,41,13,68,42],[15,54,24,5,55,25],[15,43,15,10,44,16],[4,144,116,4,145,117],[17,68,42],[17,50,22,6,51,23],[19,46,16,6,47,17],[2,139,111,7,140,112],[17,74,46],[7,54,24,16,55,25],[34,37,13],[4,151,121,5,152,122],[4,75,47,14,76,48],[11,54,24,14,55,25],[16,45,15,14,46,16],[6,147,117,4,148,118],[6,73,45,14,74,46],[11,54,24,16,55,25],[30,46,16,2,47,17],[8,132,106,4,133,107],[8,75,47,13,76,48],[7,54,24,22,55,25],[22,45,15,13,46,16],[10,142,114,2,143,115],[19,74,46,4,75,47],[28,50,22,6,51,23],[33,46,16,4,47,17],[8,152,122,4,153,123],[22,73,45,3,74,46],[8,53,23,26,54,24],[12,45,15,28,46,16],[3,147,117,10,148,118],[3,73,45,23,74,46],[4,54,24,31,55,25],[11,45,15,31,46,16],[7,146,116,7,147,117],[21,73,45,7,74,46],[1,53,23,37,54,24],[19,45,15,26,46,16],[5,145,115,10,146,116],[19,75,47,10,76,48],[15,54,24,25,55,25],[23,45,15,25,46,16],[13,145,115,3,146,116],[2,74,46,29,75,47],[42,54,24,1,55,25],[23,45,15,28,46,16],[17,145,115],[10,74,46,23,75,47],[10,54,24,35,55,25],[19,45,15,35,46,16],[17,145,115,1,146,116],[14,74,46,21,75,47],[29,54,24,19,55,25],[11,45,15,46,46,16],[13,145,115,6,146,116],[14,74,46,23,75,47],[44,54,24,7,55,25],[59,46,16,1,47,17],[12,151,121,7,152,122],[12,75,47,26,76,48],[39,54,24,14,55,25],[22,45,15,41,46,16],[6,151,121,14,152,122],[6,75,47,34,76,48],[46,54,24,10,55,25],[2,45,15,64,46,16],[17,152,122,4,153,123],[29,74,46,14,75,47],[49,54,24,10,55,25],[24,45,15,46,46,16],[4,152,122,18,153,123],[13,74,46,32,75,47],[48,54,24,14,55,25],[42,45,15,32,46,16],[20,147,117,4,148,118],[40,75,47,7,76,48],[43,54,24,22,55,25],[10,45,15,67,46,16],[19,148,118,6,149,119],[18,75,47,31,76,48],[34,54,24,34,55,25],[20,45,15,61,46,16]];var v=function(){function t(){o()(this,t),this.buffer=[],this.length=0}return a()(t,[{key:"get",value:function(t){var e=Math.floor(t/8);return 1==(this.buffer[e]>>>7-t%8&1)}},{key:"put",value:function(t,e){for(var r=0;r<e;r++)this.putBit(1==(t>>>e-r-1&1))}},{key:"getLengthInBits",value:function(){return this.length}},{key:"putBit",value:function(t){var e=Math.floor(this.length/8);this.buffer.length<=e&&this.buffer.push(0),t&&(this.buffer[e]|=128>>>this.length%8),this.length++}}]),t}(),m=[[17,14,11,7],[32,26,20,14],[53,42,32,24],[78,62,46,34],[106,84,60,44],[134,106,74,58],[154,122,86,64],[192,152,108,84],[230,180,130,98],[271,213,151,119],[321,251,177,137],[367,287,203,155],[425,331,241,177],[458,362,258,194],[520,412,292,220],[586,450,322,250],[644,504,364,280],[718,560,394,310],[792,624,442,338],[858,666,482,382],[929,711,509,403],[1003,779,565,439],[1091,857,611,461],[1171,911,661,511],[1273,997,715,535],[1367,1059,751,593],[1465,1125,805,625],[1528,1190,868,658],[1628,1264,908,698],[1732,1370,982,742],[1840,1452,1030,790],[1952,1538,1112,842],[2068,1628,1168,898],[2188,1722,1228,958],[2303,1809,1283,983],[2431,1911,1351,1051],[2563,1989,1423,1093],[2699,2099,1499,1139],[2809,2213,1579,1219],[2953,2331,1663,1273]]},function(t,e,r){"use strict";(function(t){r.d(e,"b",(function(){return u})),r.d(e,"a",(function(){return l}));var n=r(2),o=r.n(n);function i(t){if("string"!=typeof t)throw new TypeError("Path must be a string. Received "+JSON.stringify(t))}function a(t,e){for(var r,n="",o=0,i=-1,a=0,s=0;s<=t.length;++s){if(s<t.length)r=t.charCodeAt(s);else{if(47===r)break;r=47}if(47===r){if(i===s-1||1===a);else if(i!==s-1&&2===a){if(n.length<2||2!==o||46!==n.charCodeAt(n.length-1)||46!==n.charCodeAt(n.length-2))if(n.length>2){var u=n.lastIndexOf("/");if(u!==n.length-1){-1===u?(n="",o=0):o=(n=n.slice(0,u)).length-1-n.lastIndexOf("/"),i=s,a=0;continue}}else if(2===n.length||1===n.length){n="",o=0,i=s,a=0;continue}e&&(n.length>0?n+="/..":n="..",o=2)}else n.length>0?n+="/"+t.slice(i+1,s):n=t.slice(i+1,s),o=s-i-1;i=s,a=0}else 46===r&&-1!==a?++a:a=-1}return n}var s={resolve:function(){for(var e,r="",n=!1,o=arguments.length-1;o>=-1&&!n;o--){var s;o>=0?s=arguments[o]:(void 0===e&&(e=t.cwd()),s=e),i(s),0!==s.length&&(r=s+"/"+r,n=47===s.charCodeAt(0))}return r=a(r,!n),n?r.length>0?"/"+r:"/":r.length>0?r:"."},normalize:function(t){if(i(t),0===t.length)return".";var e=47===t.charCodeAt(0),r=47===t.charCodeAt(t.length-1);return 0!==(t=a(t,!e)).length||e||(t="."),t.length>0&&r&&(t+="/"),e?"/"+t:t},isAbsolute:function(t){return i(t),t.length>0&&47===t.charCodeAt(0)},join:function(){if(0===arguments.length)return".";for(var t,e=0;e<arguments.length;++e){var r=arguments[e];i(r),r.length>0&&(void 0===t?t=r:t+="/"+r)}return void 0===t?".":s.normalize(t)},relative:function(t,e){if(i(t),i(e),t===e)return"";if((t=s.resolve(t))===(e=s.resolve(e)))return"";for(var r=1;r<t.length&&47===t.charCodeAt(r);++r);for(var n=t.length,o=n-r,a=1;a<e.length&&47===e.charCodeAt(a);++a);for(var u=e.length-a,l=o<u?o:u,c=-1,h=0;h<=l;++h){if(h===l){if(u>l){if(47===e.charCodeAt(a+h))return e.slice(a+h+1);if(0===h)return e.slice(a+h)}else o>l&&(47===t.charCodeAt(r+h)?c=h:0===h&&(c=0));break}var f=t.charCodeAt(r+h);if(f!==e.charCodeAt(a+h))break;47===f&&(c=h)}var p="";for(h=r+c+1;h<=n;++h)h!==n&&47!==t.charCodeAt(h)||(0===p.length?p+="..":p+="/..");return p.length>0?p+e.slice(a+c):(a+=c,47===e.charCodeAt(a)&&++a,e.slice(a))},_makeLong:function(t){return t},dirname:function(t){if(i(t),0===t.length)return".";for(var e=t.charCodeAt(0),r=47===e,n=-1,o=!0,a=t.length-1;a>=1;--a)if(47===(e=t.charCodeAt(a))){if(!o){n=a;break}}else o=!1;return-1===n?r?"/":".":r&&1===n?"//":t.slice(0,n)},basename:function(t,e){if(void 0!==e&&"string"!=typeof e)throw new TypeError('"ext" argument must be a string');i(t);var r,n=0,o=-1,a=!0;if(void 0!==e&&e.length>0&&e.length<=t.length){if(e.length===t.length&&e===t)return"";var s=e.length-1,u=-1;for(r=t.length-1;r>=0;--r){var l=t.charCodeAt(r);if(47===l){if(!a){n=r+1;break}}else-1===u&&(a=!1,u=r+1),s>=0&&(l===e.charCodeAt(s)?-1==--s&&(o=r):(s=-1,o=u))}return n===o?o=u:-1===o&&(o=t.length),t.slice(n,o)}for(r=t.length-1;r>=0;--r)if(47===t.charCodeAt(r)){if(!a){n=r+1;break}}else-1===o&&(a=!1,o=r+1);return-1===o?"":t.slice(n,o)},extname:function(t){i(t);for(var e=-1,r=0,n=-1,o=!0,a=0,s=t.length-1;s>=0;--s){var u=t.charCodeAt(s);if(47!==u)-1===n&&(o=!1,n=s+1),46===u?-1===e?e=s:1!==a&&(a=1):-1!==e&&(a=-1);else if(!o){r=s+1;break}}return-1===e||-1===n||0===a||1===a&&e===n-1&&e===r+1?"":t.slice(e,n)},format:function(t){if(null===t||"object"!==o()(t))throw new TypeError('The "pathObject" argument must be of type Object. Received type '+o()(t));return function(t,e){var r=e.dir||e.root,n=e.base||(e.name||"")+(e.ext||"");return r?r===e.root?r+n:r+t+n:n}("/",t)},parse:function(t){i(t);var e={root:"",dir:"",base:"",ext:"",name:""};if(0===t.length)return e;var r,n=t.charCodeAt(0),o=47===n;o?(e.root="/",r=1):r=0;for(var a=-1,s=0,u=-1,l=!0,c=t.length-1,h=0;c>=r;--c)if(47!==(n=t.charCodeAt(c)))-1===u&&(l=!1,u=c+1),46===n?-1===a?a=c:1!==h&&(h=1):-1!==a&&(h=-1);else if(!l){s=c+1;break}return-1===a||-1===u||0===h||1===h&&a===u-1&&a===s+1?-1!==u&&(e.base=e.name=0===s&&o?t.slice(1,u):t.slice(s,u)):(0===s&&o?(e.name=t.slice(1,a),e.base=t.slice(1,u)):(e.name=t.slice(s,a),e.base=t.slice(s,u)),e.ext=t.slice(a,u)),s>0?e.dir=t.slice(0,s-1):o&&(e.dir="/"),e},sep:"/",delimiter:":",win32:null,posix:null};s.posix=s;var u=s.extname,l=s.basename}).call(this,r(19))},function(t,e){function r(t,e,r,n,o,i,a){try{var s=t[i](a),u=s.value}catch(t){return void r(t)}s.done?e(u):Promise.resolve(u).then(n,o)}t.exports=function(t){return function(){var e=this,n=arguments;return new Promise((function(o,i){var a=t.apply(e,n);function s(t){r(a,o,i,s,u,"next",t)}function u(t){r(a,o,i,s,u,"throw",t)}s(void 0)}))}},t.exports.__esModule=!0,t.exports.default=t.exports},function(t,e,r){"use strict";r.d(e,"b",(function(){return w})),r.d(e,"a",(function(){return x}));const n=(t,e,r={},o=r)=>{if(Array.isArray(e))e.forEach(e=>n(t,e,r,o));else if("function"==typeof e)e(t,r,o,n);else{const i=Object.keys(e)[0];Array.isArray(e[i])?(o[i]={},n(t,e[i],r,o[i])):o[i]=e[i](t,r,o,n)}return r},o=(t,e)=>(r,n,o,i)=>{e(r,n,o)&&i(r,t,n,o)},i=(t=0)=>e=>e.data[e.pos+t],a=t=>e=>e.data.subarray(e.pos,e.pos+=t),s=t=>e=>e.data.subarray(e.pos,e.pos+t),u=t=>e=>Array.from(a(t)(e)).map(t=>String.fromCharCode(t)).join(""),l=t=>e=>{const r=a(2)(e);return t?(r[1]<<8)+r[0]:(r[0]<<8)+r[1]},c=(t,e)=>(r,n,o)=>{const i="function"==typeof e?e(r,n,o):e,s=a(t),u=new Array(i);for(var l=0;l<i;l++)u[l]=s(r);return u},h=t=>e=>{const r=(t=>t.data[t.pos++])(e),n=new Array(8);for(var o=0;o<8;o++)n[7-o]=!!(r&1<<o);return Object.keys(t).reduce((e,r)=>{const o=t[r];return o.length?e[r]=((t,e,r)=>{for(var n=0,o=0;o<r;o++)n+=t[e+o]&&2**(r-o-1);return n})(n,o.index,o.length):e[r]=n[o.index],e},{})};var f={blocks:t=>{const e=[],r=t.data.length;for(var n=0,o=(t=>t.data[t.pos++])(t);0!==o&&o;o=(t=>t.data[t.pos++])(t)){if(t.pos+o>=r){const o=r-t.pos;e.push(a(o)(t)),n+=o;break}e.push(a(o)(t)),n+=o}const i=new Uint8Array(n);for(var s=0,u=0;u<e.length;u++)i.set(e[u],s),s+=e[u].length;return i}};const p=o({gce:[{codes:a(2)},{byteSize:t=>t.data[t.pos++]},{extras:h({future:{index:0,length:3},disposal:{index:3,length:3},userInput:{index:6},transparentColorGiven:{index:7}})},{delay:l(!0)},{transparentColorIndex:t=>t.data[t.pos++]},{terminator:t=>t.data[t.pos++]}]},t=>{var e=s(2)(t);return 33===e[0]&&249===e[1]}),g=o({image:[{code:t=>t.data[t.pos++]},{descriptor:[{left:l(!0)},{top:l(!0)},{width:l(!0)},{height:l(!0)},{lct:h({exists:{index:0},interlaced:{index:1},sort:{index:2},future:{index:3,length:2},size:{index:5,length:3}})}]},o({lct:c(3,(t,e,r)=>Math.pow(2,r.descriptor.lct.size+1))},(t,e,r)=>r.descriptor.lct.exists),{data:[{minCodeSize:t=>t.data[t.pos++]},f]}]},t=>44===i()(t)),d=o({text:[{codes:a(2)},{blockSize:t=>t.data[t.pos++]},{preData:(t,e,r)=>a(r.text.blockSize)(t)},f]},t=>{var e=s(2)(t);return 33===e[0]&&1===e[1]}),y=o({application:[{codes:a(2)},{blockSize:t=>t.data[t.pos++]},{id:(t,e,r)=>u(r.blockSize)(t)},f]},t=>{var e=s(2)(t);return 33===e[0]&&255===e[1]}),v=o({comment:[{codes:a(2)},f]},t=>{var e=s(2)(t);return 33===e[0]&&254===e[1]});var m=[{header:[{signature:u(3)},{version:u(3)}]},{lsd:[{width:l(!0)},{height:l(!0)},{gct:h({exists:{index:0},resolution:{index:1,length:3},sort:{index:4},size:{index:5,length:3}})},{backgroundColorIndex:t=>t.data[t.pos++]},{pixelAspectRatio:t=>t.data[t.pos++]}]},o({gct:c(3,(t,e)=>Math.pow(2,e.lsd.gct.size+1))},(t,e)=>e.lsd.gct.exists),{frames:((t,e)=>(r,n,o,i)=>{const a=[];let s=r.pos;for(;e(r,n,o);){const e={};if(i(r,t,n,e),r.pos===s)break;s=r.pos,a.push(e)}return a})([p,y,v,g,d],t=>{var e=i()(t);return 33===e||44===e})}],w=function(t){var e=new Uint8Array(t);return n({data:e,pos:0},m)},b=function(t,e,r){if(t.image){var n=t.image,o=n.descriptor.width*n.descriptor.height,i=function(t,e,r){var n,o,i,a,s,u,l,c,h,f,p,g,d,y,v,m,w=r,b=new Array(r),x=new Array(4096),A=new Array(4096),E=new Array(4097);for(s=(o=1<<(f=t))+1,n=o+2,l=-1,i=(1<<(a=f+1))-1,c=0;c<o;c++)x[c]=0,A[c]=c;for(p=g=d=y=v=m=0,h=0;h<w;){if(0===y){if(g<a){p+=e[m]<<g,g+=8,m++;continue}if(c=p&i,p>>=a,g-=a,c>n||c==s)break;if(c==o){i=(1<<(a=f+1))-1,n=o+2,l=-1;continue}if(-1==l){E[y++]=A[c],l=c,d=c;continue}for(u=c,c==n&&(E[y++]=d,c=l);c>o;)E[y++]=A[c],c=x[c];d=255&A[c],E[y++]=d,n<4096&&(x[n]=l,A[n]=d,0==(++n&i)&&n<4096&&(a++,i+=n)),l=u}y--,b[v++]=E[y],h++}for(h=v;h<w;h++)b[h]=0;return b}(n.data.minCodeSize,n.data.blocks,o);n.descriptor.lct.interlaced&&(i=function(t,e){for(var r=new Array(t.length),n=t.length/e,o=function(n,o){var i=t.slice(o*e,(o+1)*e);r.splice.apply(r,[n*e,e].concat(i))},i=[0,4,2,1],a=[8,8,4,2],s=0,u=0;u<4;u++)for(var l=i[u];l<n;l+=a[u])o(l,s),s++;return r}(i,n.descriptor.width));var a={pixels:i,dims:{top:t.image.descriptor.top,left:t.image.descriptor.left,width:t.image.descriptor.width,height:t.image.descriptor.height}};return n.descriptor.lct&&n.descriptor.lct.exists?a.colorTable=n.lct:a.colorTable=e,t.gce&&(a.delay=10*(t.gce.delay||10),a.disposalType=t.gce.extras.disposal,t.gce.extras.transparentColorGiven&&(a.transparentIndex=t.gce.transparentColorIndex)),r&&(a.patch=function(t){for(var e=t.pixels.length,r=new Uint8ClampedArray(4*e),n=0;n<e;n++){var o=4*n,i=t.pixels[n],a=t.colorTable[i];r[o]=a[0],r[o+1]=a[1],r[o+2]=a[2],r[o+3]=i!==t.transparentIndex?255:0}return r}(a)),a}console.warn("gif frame does not have associated image.")},x=function(t,e){return t.frames.filter((function(t){return t.image})).map((function(r){return b(r,t.gct,e)}))}},function(t,e){var r;r=function(){return this}();try{r=r||new Function("return this")()}catch(t){"object"==typeof window&&(r=window)}t.exports=r},function(t,e,r){"use strict";(function(t){r.d(e,"a",(function(){return m}));var n=r(2),o=r.n(n),i=r(0),a=r.n(i),s=r(1),u=r.n(s),l=r(3),c=r.n(l),h=r(10),f=r(7),p=r(4),g=r(12),d=function(t,e,r,n){return new(r||(r=Promise))((function(o,i){function a(t){try{u(n.next(t))}catch(t){i(t)}}function s(t){try{u(n.throw(t))}catch(t){i(t)}}function u(t){var e;t.done?o(t.value):(e=t.value,e instanceof r?e:new r((function(t){t(e)}))).then(a,s)}u((n=n.apply(t,e||[])).next())}))},y=h.a.Canvas;function v(t){if(t)return new Promise((function(r,n){if("data"==t.slice(0,4)){var o=new Image;return o.onload=function(){r(o),e(o)},o.onerror=function(){n("Image load error"),e(o)},void(o.src=t)}var i=new Image;i.setAttribute("crossOrigin","Anonymous"),i.onload=function(){r(i)},i.onerror=function(){n("Image load error")},i.src=t}));function e(t){t.onload=null,t.onerror=null}}var m=function(){function e(t){a()(this,e);var r=Object.assign({},t);if(Object.keys(e.defaultOptions).forEach((function(t){t in r||Object.defineProperty(r,t,{value:e.defaultOptions[t],enumerable:!0,writable:!0})})),r.components?"object"===o()(r.components)&&Object.keys(e.defaultComponentOptions).forEach((function(t){t in r.components?Object.defineProperty(r.components,t,{value:Object.assign(Object.assign({},e.defaultComponentOptions[t]),r.components[t]),enumerable:!0,writable:!0}):Object.defineProperty(r.components,t,{value:e.defaultComponentOptions[t],enumerable:!0,writable:!0})})):r.components=e.defaultComponentOptions,null!==r.dotScale&&void 0!==r.dotScale){if(r.dotScale<=0||r.dotScale>1)throw new Error("dotScale should be in range (0, 1].");r.components.data.scale=r.dotScale,r.components.timing.scale=r.dotScale,r.components.alignment.scale=r.dotScale}this.options=r,this.canvas=new y(t.size,t.size),this.canvasContext=this.canvas.getContext("2d"),this.qrCode=new p.a(-1,this.options.correctLevel),Number.isInteger(this.options.maskPattern)&&(this.qrCode.maskPattern=this.options.maskPattern),Number.isInteger(this.options.version)&&(this.qrCode.typeNumber=this.options.version),this.qrCode.addData(this.options.text),this.qrCode.make()}return u()(e,[{key:"draw",value:function(){var t=this;return new Promise((function(e){return t._draw().then(e)}))}},{key:"_clear",value:function(){this.canvasContext.clearRect(0,0,this.canvas.width,this.canvas.height)}},{key:"_draw",value:function(){var r,n,o,i,a,s,u,l,h,m,b,x,A,E,C,k,P,_,T;return d(this,void 0,void 0,c.a.mark((function d(){var B,R,S,D,L,M,I,O,U,N,j,F,Y,z,G,H,q,$,X,Q,K,V,J,Z,W,tt,et,rt,nt,ot,it,at,st,ut,lt,ct,ht,ft,pt,gt,dt,yt,vt,mt,wt,bt,xt,At,Et,Ct,kt,Pt,_t,Tt,Bt,Rt,St,Dt,Lt,Mt,It,Ot,Ut,Nt,jt,Ft,Yt,zt,Gt,Ht,qt,$t;return c.a.wrap((function(c){for(;;)switch(c.prev=c.next){case 0:if(B=null===(r=this.qrCode)||void 0===r?void 0:r.moduleCount,R=this.options.size,((S=this.options.margin)<0||2*S>=R)&&(S=0),D=Math.ceil(S),L=R-2*S,M=this.options.whiteMargin,I=this.options.backgroundDimming,O=Math.ceil(L/B),j=new y(N=(U=O*B)+2*D,N),F=j.getContext("2d"),this._clear(),F.save(),F.translate(D,D),Y=new y(N,N),z=Y.getContext("2d"),G=null,H=[],!this.options.gifBackground){c.next=47;break}if(q=Object(f.b)(this.options.gifBackground),G=q,H=Object(f.a)(q,!0),!this.options.autoColor){c.next=45;break}$=0,X=0,Q=0,K=0,V=0;case 28:if(!(V<H[0].colorTable.length)){c.next=41;break}if(!((J=H[0].colorTable[V])[0]>200||J[1]>200||J[2]>200)){c.next=32;break}return c.abrupt("continue",38);case 32:if(0!==J[0]||0!==J[1]||0!==J[2]){c.next=34;break}return c.abrupt("continue",38);case 34:K++,$+=J[0],X+=J[1],Q+=J[2];case 38:V++,c.next=28;break;case 41:$=~~($/K),X=~~(X/K),Q=~~(Q/K),this.options.colorDark="rgb(".concat($,",").concat(X,",").concat(Q,")");case 45:c.next=61;break;case 47:if(!this.options.backgroundImage){c.next=58;break}return c.next=50,v(this.options.backgroundImage);case 50:Z=c.sent,this.options.autoColor&&(W=e._getAverageRGB(Z),this.options.colorDark="rgb(".concat(W.r,",").concat(W.g,",").concat(W.b,")")),z.drawImage(Z,0,0,Z.width,Z.height,0,0,N,N),z.rect(0,0,N,N),z.fillStyle=I,z.fill(),c.next=61;break;case 58:z.rect(0,0,N,N),z.fillStyle=this.options.colorLight,z.fill();case 61:for(tt=p.c.getPatternPosition(this.qrCode.typeNumber),et=(null===(o=null===(n=this.options.components)||void 0===n?void 0:n.data)||void 0===o?void 0:o.scale)||.4,rt=.5*(1-et),nt=0;nt<B;nt++)for(ot=0;ot<B;ot++){for(it=this.qrCode.isDark(nt,ot),at=6==nt&&ot>=8&&ot<=B-8||6==ot&&nt>=8&&nt<=B-8,st=ot<8&&(nt<8||nt>=B-8)||ot>=B-8&&nt<8||at,ut=1;ut<tt.length-1;ut++)st=st||nt>=tt[ut]-2&&nt<=tt[ut]+2&&ot>=tt[ut]-2&&ot<=tt[ut]+2;lt=ot*O+(st?0:rt*O),ct=nt*O+(st?0:rt*O),F.strokeStyle=it?this.options.colorDark:this.options.colorLight,F.lineWidth=.5,F.fillStyle=it?this.options.colorDark:this.options.colorLight,0===tt.length?st||F.fillRect(lt,ct,(st?1:et)*O,(st?1:et)*O):(ht=ot<B-4&&ot>=B-4-5&&nt<B-4&&nt>=B-4-5,st||ht||F.fillRect(lt,ct,(st?1:et)*O,(st?1:et)*O))}if(ft=tt[tt.length-1],pt=this.options.colorLight,F.fillStyle=pt,F.fillRect(0,0,8*O,8*O),F.fillRect(0,(B-8)*O,8*O,8*O),F.fillRect((B-8)*O,0,8*O,8*O),(null===(a=null===(i=this.options.components)||void 0===i?void 0:i.timing)||void 0===a?void 0:a.protectors)&&(F.fillRect(8*O,6*O,(B-8-8)*O,O),F.fillRect(6*O,8*O,O,(B-8-8)*O)),(null===(u=null===(s=this.options.components)||void 0===s?void 0:s.cornerAlignment)||void 0===u?void 0:u.protectors)&&e._drawAlignProtector(F,ft,ft,O),!(null===(h=null===(l=this.options.components)||void 0===l?void 0:l.alignment)||void 0===h?void 0:h.protectors)){c.next=99;break}gt=0;case 75:if(!(gt<tt.length)){c.next=99;break}dt=0;case 77:if(!(dt<tt.length)){c.next=96;break}if(yt=tt[dt],vt=tt[gt],6!==yt||6!==vt&&vt!==ft){c.next=84;break}return c.abrupt("continue",93);case 84:if(6!==vt||6!==yt&&yt!==ft){c.next=88;break}return c.abrupt("continue",93);case 88:if(yt!==ft||vt!==ft){c.next=92;break}return c.abrupt("continue",93);case 92:e._drawAlignProtector(F,yt,vt,O);case 93:dt++,c.next=77;break;case 96:gt++,c.next=75;break;case 99:for(F.fillStyle=this.options.colorDark,F.fillRect(0,0,7*O,O),F.fillRect((B-7)*O,0,7*O,O),F.fillRect(0,6*O,7*O,O),F.fillRect((B-7)*O,6*O,7*O,O),F.fillRect(0,(B-7)*O,7*O,O),F.fillRect(0,(B-7+6)*O,7*O,O),F.fillRect(0,0,O,7*O),F.fillRect(6*O,0,O,7*O),F.fillRect((B-7)*O,0,O,7*O),F.fillRect((B-7+6)*O,0,O,7*O),F.fillRect(0,(B-7)*O,O,7*O),F.fillRect(6*O,(B-7)*O,O,7*O),F.fillRect(2*O,2*O,3*O,3*O),F.fillRect((B-7+2)*O,2*O,3*O,3*O),F.fillRect(2*O,(B-7+2)*O,3*O,3*O),mt=(null===(b=null===(m=this.options.components)||void 0===m?void 0:m.timing)||void 0===b?void 0:b.scale)||.4,wt=.5*(1-mt),bt=0;bt<B-8;bt+=2)e._drawDot(F,8+bt,6,O,wt,mt),e._drawDot(F,6,8+bt,O,wt,mt);xt=(null===(A=null===(x=this.options.components)||void 0===x?void 0:x.cornerAlignment)||void 0===A?void 0:A.scale)||.4,At=.5*(1-xt),e._drawAlign(F,ft,ft,O,At,xt,this.options.colorDark,(null===(C=null===(E=this.options.components)||void 0===E?void 0:E.cornerAlignment)||void 0===C?void 0:C.protectors)||!1),Et=(null===(P=null===(k=this.options.components)||void 0===k?void 0:k.alignment)||void 0===P?void 0:P.scale)||.4,Ct=.5*(1-Et),kt=0;case 124:if(!(kt<tt.length)){c.next=148;break}Pt=0;case 126:if(!(Pt<tt.length)){c.next=145;break}if(_t=tt[Pt],Tt=tt[kt],6!==_t||6!==Tt&&Tt!==ft){c.next=133;break}return c.abrupt("continue",142);case 133:if(6!==Tt||6!==_t&&_t!==ft){c.next=137;break}return c.abrupt("continue",142);case 137:if(_t!==ft||Tt!==ft){c.next=141;break}return c.abrupt("continue",142);case 141:e._drawAlign(F,_t,Tt,O,Ct,Et,this.options.colorDark,(null===(T=null===(_=this.options.components)||void 0===_?void 0:_.alignment)||void 0===T?void 0:T.protectors)||!1);case 142:Pt++,c.next=126;break;case 145:kt++,c.next=124;break;case 148:if(M&&(F.fillStyle=this.options.backgroundColor,F.fillRect(-D,-D,N,D),F.fillRect(-D,U,N,D),F.fillRect(U,-D,D,N),F.fillRect(-D,-D,D,N)),!this.options.logoImage){c.next=179;break}return c.next=152,v(this.options.logoImage);case 152:Bt=c.sent,Rt=this.options.logoScale,St=this.options.logoMargin,Dt=this.options.logoCornerRadius,(Rt<=0||Rt>=1)&&(Rt=.2),St<0&&(St=0),Dt<0&&(Dt=0),It=Mt=.5*(N-(Lt=U*Rt)),F.restore(),F.fillStyle=this.options.logoBackgroundColor,F.save(),e._prepareRoundedCornerClip(F,Mt-St,It-St,Lt+2*St,Lt+2*St,Dt+St),F.clip(),Ot=F.globalCompositeOperation,F.globalCompositeOperation="destination-out",F.fill(),F.globalCompositeOperation=Ot,F.restore(),F.save(),e._prepareRoundedCornerClip(F,Mt,It,Lt,Lt,Dt),F.clip(),F.drawImage(Bt,Mt,It,Lt,Lt),F.restore(),F.save(),F.translate(D,D);case 179:if(!G){c.next=191;break}if(H.forEach((function(t){Ut||((Ut=new g.a(R,R)).setDelay(t.delay),Ut.setRepeat(0));var e=t.dims,r=e.width,n=e.height;Nt||(Nt=new y(r,n),(jt=Nt.getContext("2d")).rect(0,0,Nt.width,Nt.height),jt.fillStyle="#ffffff",jt.fill()),Ft&&zt&&r===Ft.width&&n===Ft.height||(Ft=new y(r,n),Yt=Ft.getContext("2d"),zt=Yt.createImageData(r,n)),zt.data.set(t.patch),Yt.putImageData(zt,0,0),jt.drawImage(Ft.getContext("2d").canvas,t.dims.left,t.dims.top);var o=new y(N,N),i=o.getContext("2d");i.drawImage(Nt.getContext("2d").canvas,0,0,N,N),i.rect(0,0,N,N),i.fillStyle=I,i.fill(),i.drawImage(j.getContext("2d").canvas,0,0,N,N);var a=new y(R,R),s=a.getContext("2d");s.drawImage(o.getContext("2d").canvas,0,0,R,R),Ut.addFrame(s.getImageData(0,0,a.width,a.height).data)})),Ut){c.next=183;break}throw new Error("No frames.");case 183:if(Ut.finish(),!w(this.canvas)){c.next=188;break}return Gt=Ut.stream().toFlattenUint8Array(),Ht=Gt.reduce((function(t,e){return t+String.fromCharCode(e)}),""),c.abrupt("return",Promise.resolve("data:image/gif;base64,".concat(window.btoa(Ht))));case 188:return c.abrupt("return",Promise.resolve(t.from(Ut.stream().toFlattenUint8Array())));case 191:if(z.drawImage(j.getContext("2d").canvas,0,0,N,N),F.drawImage(Y.getContext("2d").canvas,-D,-D,N,N),qt=new y(R,R),qt.getContext("2d").drawImage(j.getContext("2d").canvas,0,0,R,R),this.canvas=qt,$t=this.options.gifBackground?"gif":"png",!w(this.canvas)){c.next=200;break}return c.abrupt("return",Promise.resolve(this.canvas.toDataURL($t)));case 200:return c.abrupt("return",Promise.resolve(this.canvas.toBuffer($t)));case 201:case"end":return c.stop()}}),d,this)})))}}],[{key:"_prepareRoundedCornerClip",value:function(t,e,r,n,o,i){t.beginPath(),t.moveTo(e,r),t.arcTo(e+n,r,e+n,r+o,i),t.arcTo(e+n,r+o,e,r+o,i),t.arcTo(e,r+o,e,r,i),t.arcTo(e,r,e+n,r,i),t.closePath()}},{key:"_getAverageRGB",value:function(t){var e,r,n={r:0,g:0,b:0},o=-4,i={r:0,g:0,b:0},a=0;r=t.naturalHeight||t.height,e=t.naturalWidth||t.width;var s,u=new y(e,r).getContext("2d");if(!u)return n;u.drawImage(t,0,0);try{s=u.getImageData(0,0,e,r)}catch(t){return n}for(;(o+=20)<s.data.length;)s.data[o]>200||s.data[o+1]>200||s.data[o+2]>200||(++a,i.r+=s.data[o],i.g+=s.data[o+1],i.b+=s.data[o+2]);return i.r=~~(i.r/a),i.g=~~(i.g/a),i.b=~~(i.b/a),i}},{key:"_drawDot",value:function(t,e,r,n){var o=arguments.length>4&&void 0!==arguments[4]?arguments[4]:0,i=arguments.length>5&&void 0!==arguments[5]?arguments[5]:1;t.fillRect((e+o)*n,(r+o)*n,i*n,i*n)}},{key:"_drawAlignProtector",value:function(t,e,r,n){t.clearRect((e-2)*n,(r-2)*n,5*n,5*n),t.fillRect((e-2)*n,(r-2)*n,5*n,5*n)}},{key:"_drawAlign",value:function(t,r,n,o){var i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:0,a=arguments.length>5&&void 0!==arguments[5]?arguments[5]:1,s=arguments.length>6?arguments[6]:void 0,u=arguments.length>7?arguments[7]:void 0,l=t.fillStyle;t.fillStyle=s,new Array(4).fill(0).map((function(s,u){e._drawDot(t,r-2+u,n-2,o,i,a),e._drawDot(t,r+2,n-2+u,o,i,a),e._drawDot(t,r+2-u,n+2,o,i,a),e._drawDot(t,r-2,n+2-u,o,i,a)})),e._drawDot(t,r,n,o,i,a),u||(t.fillStyle="rgba(255, 255, 255, 0.6)",new Array(2).fill(0).map((function(s,u){e._drawDot(t,r-1+u,n-1,o,i,a),e._drawDot(t,r+1,n-1+u,o,i,a),e._drawDot(t,r+1-u,n+1,o,i,a),e._drawDot(t,r-1,n+1-u,o,i,a)}))),t.fillStyle=l}}]),e}();function w(t){try{return t instanceof HTMLElement}catch(e){return"object"===o()(t)&&1===t.nodeType&&"object"===o()(t.style)&&"object"===o()(t.ownerDocument)}}m.CorrectLevel=p.b,m.defaultComponentOptions={data:{scale:.4},timing:{scale:.5,protectors:!1},alignment:{scale:.5,protectors:!1},cornerAlignment:{scale:.5,protectors:!0}},m.defaultOptions={text:"",size:400,margin:20,colorDark:"#000000",colorLight:"rgba(255, 255, 255, 0.6)",correctLevel:p.b.M,backgroundImage:void 0,backgroundDimming:"rgba(0,0,0,0)",logoImage:void 0,logoScale:.2,logoMargin:4,logoCornerRadius:8,whiteMargin:!0,components:m.defaultComponentOptions,autoColor:!0,logoBackgroundColor:"#ffffff",backgroundColor:"#ffffff"}}).call(this,r(15).Buffer)},function(t,e,r){"use strict";var n=r(11);const{asBuffer:o,asDownload:i,asZipDownload:a,atScale:s,options:u}=n.a,l=Symbol.for("toDataURL");const{CanvasRenderingContext2D:c,CanvasGradient:h,CanvasPattern:f,Image:p,ImageData:g,Path2D:d,DOMMatrix:y,DOMRect:v,DOMPoint:m}=window,w={Canvas:class{constructor(t,e){let r=document.createElement("canvas"),n=[];for(var[c,h]of(Object.defineProperty(r,"async",{value:!0,writable:!1,enumerable:!0}),Object.entries({png:()=>o(r,"image/png"),jpg:()=>o(r,"image/jpeg"),pages:()=>n.concat(r).map(t=>t.getContext("2d"))})))Object.defineProperty(r,c,{get:h});return Object.assign(r,{width:t,height:e,newPage(...t){var{width:e,height:o}=r,i=Object.assign(document.createElement("canvas"),{width:e,height:o});i.getContext("2d").drawImage(r,0,0),n.push(i);var[e,o]=t.length?t:[e,o];return Object.assign(r,{width:e,height:o}).getContext("2d")},saveAs(t,e){e="number"==typeof e?{quality:e}:e;let r=u(this.pages,{filename:t,e}),{pattern:n,padding:o,mime:l,quality:c,matte:h,density:f,archive:p}=r,g=s(r.pages,f);return null==o?i(g[0],l,c,h,t):a(g,l,c,h,p,n,o)},toBuffer(t="png",e={}){e="number"==typeof e?{quality:e}:e;let r=u(this.pages,{extension:t,e}),{mime:n,quality:i,matte:a,pages:l,density:c}=r,h=s(l,c,a)[0];return o(h,n,i,a)},[l]:r.toDataURL.bind(r),toDataURL(t="png",e={}){e="number"==typeof e?{quality:e}:e;let n=u(this.pages,{extension:t,e}),{mime:o,quality:i,matte:a,pages:c,density:h}=n,f=s(c,h,a)[0],p=f[f===r?l:"toDataURL"](o,i);return Promise.resolve(p)}})}},loadImage:t=>new Promise((e,r)=>Object.assign(new p,{crossOrigin:"Anonymous",onload:e,onerror:r,src:t})),CanvasRenderingContext2D:c,CanvasGradient:h,CanvasPattern:f,Image:p,ImageData:g,Path2D:d,DOMMatrix:y,DOMRect:v,DOMPoint:m};e.a=w},function(t,e,r){"use strict";(function(t){var n=r(5);class o{constructor(){let e=void 0===t,r="image/png",n="image/jpeg",o="application/pdf",i="image/svg+xml";Object.assign(this,{toMime:this.toMime.bind(this),fromMime:this.fromMime.bind(this),expected:e?'"png", "jpg", or "webp"':'"png", "jpg", "pdf", or "svg"',formats:e?{png:r,jpg:n,jpeg:"image/jpeg",webp:"image/webp"}:{png:r,jpg:n,jpeg:"image/jpeg",pdf:o,svg:i},mimes:e?{[r]:"png",[n]:"jpg","image/webp":"webp"}:{[r]:"png",[n]:"jpg",[o]:"pdf",[i]:"svg"}})}toMime(t){return this.formats[(t||"").replace(/^\./,"").toLowerCase()]}fromMime(t){return this.mimes[t]}}class i{static for(t){return(new i).append(t).get()}constructor(){this.crc=-1}get(){return~this.crc}append(t){for(var e=0|this.crc,r=this.table,n=0,o=0|t.length;n<o;n++)e=e>>>8^r[255&(e^t[n])];return this.crc=e,this}}function a(t){let e=new Uint8Array(t),r=new DataView(e.buffer),n={array:e,view:r,size:t,set8:(t,e)=>(r.setUint8(t,e),n),set16:(t,e)=>(r.setUint16(t,e,!0),n),set32:(t,e)=>(r.setUint32(t,e,!0),n),bytes:(t,r)=>(e.set(r,t),n)};return n}i.prototype.table=(()=>{var t,e,r,n=[];for(t=0;t<256;t++){for(r=t,e=0;e<8;e++)r=1&r?r>>>1^3988292384:r>>>1;n[t]=r}return n})();class s{constructor(t){let e=new Date;Object.assign(this,{directory:t,offset:0,files:[],time:(e.getHours()<<6|e.getMinutes())<<5|e.getSeconds()/2,date:(e.getFullYear()-1980<<4|e.getMonth()+1)<<5|e.getDate()}),this.add(t)}async add(t,e){let r=!e,n=s.encoder.encode(`${this.directory}/${r?"":t}`),o=new Uint8Array(r?0:await e.arrayBuffer()),u=30+n.length,l=u+o.length,{offset:c}=this,h=a(26).set32(0,134742036).set16(6,this.time).set16(8,this.date).set32(10,i.for(o)).set32(14,o.length).set32(18,o.length).set16(22,n.length);c+=u;let f=a(u+o.length+16).set32(0,67324752).bytes(4,h.array).bytes(30,n).bytes(u,o);c+=o.length,f.set32(l,134695760).bytes(l+4,h.array.slice(10,22)),c+=16,this.files.push({offset:c,folder:r,name:n,header:h,payload:f}),this.offset=c}toBuffer(){let t=this.files.reduce((t,{name:e})=>46+e.length+t,0),e=a(t+22),r=0;for(var{offset:n,name:o,header:i,folder:s}of this.files)e.set32(r,33639248).set16(r+4,20).bytes(r+6,i.array).set8(r+38,s?16:0).set32(r+42,n).bytes(r+46,o),r+=46+o.length;e.set32(r,101010256).set16(r+8,this.files.length).set16(r+10,this.files.length).set32(r+12,t).set32(r+16,this.offset);let u=new Uint8Array(this.offset+e.size),l=0;for(var{payload:c}of this.files)u.set(c.array,l),l+=c.size;return u.set(e.array,l),u}get blob(){return new Blob([this.toBuffer()],{type:"application/zip"})}}s.encoder=new TextEncoder;const u=(t,e,r,n)=>{if(n){let{width:e,height:r}=t,o=Object.assign(document.createElement("canvas"),{width:e,height:r}),i=o.getContext("2d");i.fillStyle=n,i.fillRect(0,0,e,r),i.drawImage(t,0,0),t=o}return new Promise((n,o)=>t.toBlob(n,e,r))},l=(t,e)=>{const r=window.URL.createObjectURL(e),n=document.createElement("a");n.style.display="none",n.href=r,n.setAttribute("download",t),void 0===n.download&&n.setAttribute("target","_blank"),document.body.appendChild(n),n.click(),document.body.removeChild(n),setTimeout(()=>window.URL.revokeObjectURL(r),100)},c={asBuffer:(...t)=>u(...t).then(t=>t.arrayBuffer()),asDownload:async(t,e,r,n,o)=>{l(o,await u(t,e,r,n))},asZipDownload:async(t,e,r,o,i,a,c)=>{let h=Object(n.a)(i,".zip")||"archive",f=new s(h);await Promise.all(t.map(async(t,n)=>{let i=(t=>a.replace("{}",String(t+1).padStart(c,"0")))(n);await f.add(i,await u(t,e,r,o))})),l(h+".zip",f.blob)},atScale:(t,e,r)=>t.map(t=>{if(1==e&&!r)return t.canvas;let n=document.createElement("canvas"),o=n.getContext("2d"),i=t.canvas?t.canvas:t;return n.width=i.width*e,n.height=i.height*e,r&&(o.fillStyle=r,o.fillRect(0,0,n.width,n.height)),o.scale(e,e),o.drawImage(i,0,0),n}),options:function(t,{filename:e="",extension:r="",format:i,page:a,quality:s,matte:u,density:l,outline:c,archive:h}={}){var{fromMime:f,toMime:p,expected:g}=new o,d=(h=h||"canvas",i||r.replace(/@\d+x$/i,"")||Object(n.b)(e)),y=(i=f(p(d)||d),p(i)),v=t.length;if(!d)throw new Error("Cannot determine image format (use a filename extension or 'format' argument)");if(!i)throw new Error(`Unsupported file format "${d}" (expected ${g})`);if(!v)throw new RangeError("Canvas has no associated contexts (try calling getContext or newPage first)");let m,w,b=e.replace(/{(\d*)}/g,(t,e)=>(w=!0,e=parseInt(e,10),m=isFinite(e)?e:isFinite(m)?m:-1,"{}")),x=a>0?a-1:a<0?v+a:void 0;if(isFinite(x)&&x<0||x>=v)throw new RangeError(1==v?`Canvas only has a ‘page 1’ (${x} is out of bounds)`:`Canvas has pages 1–${v} (${x} is out of bounds)`);if(t=isFinite(x)?[t[x]]:w||"pdf"==i?t:t.slice(-1),void 0===s)s=.92;else if("number"!=typeof s||!isFinite(s)||s<0||s>1)throw new TypeError("The quality option must be an number in the 0.0–1.0 range");if(void 0===l){let t=(r||Object(n.a)(e,d)).match(/@(\d+)x$/i);l=t?parseInt(t[1],10):1}else if("number"!=typeof l||!Number.isInteger(l)||l<1)throw new TypeError("The density option must be a non-negative integer");return void 0===c?c=!0:"svg"==i&&(c=!!c),{filename:e,pattern:b,format:i,mime:y,pages:t,padding:m,quality:s,matte:u,density:l,outline:c,archive:h}}};e.a=c}).call(this,r(8))},function(t,e,r){"use strict";var n=function(t,e){var r,n,o,i,a;function s(t,e,n,o,i){r[e][0]-=t*(r[e][0]-n)/1024,r[e][1]-=t*(r[e][1]-o)/1024,r[e][2]-=t*(r[e][2]-i)/1024}function u(t,e,n,o,i){for(var s,u,l=Math.abs(e-t),c=Math.min(e+t,256),h=e+1,f=e-1,p=1;h<c||f>l;)u=a[p++],h<c&&((s=r[h++])[0]-=u*(s[0]-n)/(1<<18),s[1]-=u*(s[1]-o)/(1<<18),s[2]-=u*(s[2]-i)/(1<<18)),f>l&&((s=r[f--])[0]-=u*(s[0]-n)/(1<<18),s[1]-=u*(s[1]-o)/(1<<18),s[2]-=u*(s[2]-i)/(1<<18))}function l(t,e,n){var a,s,u,l,c,h=~(1<<31),f=h,p=-1,g=p;for(a=0;a<256;a++)s=r[a],(u=Math.abs(s[0]-t)+Math.abs(s[1]-e)+Math.abs(s[2]-n))<h&&(h=u,p=a),(l=u-(o[a]>>12))<f&&(f=l,g=a),c=i[a]>>10,i[a]-=c,o[a]+=c<<10;return i[p]+=64,o[p]-=65536,g}this.buildColormap=function(){!function(){var t,e;for(r=[],n=new Int32Array(256),o=new Int32Array(256),i=new Int32Array(256),a=new Int32Array(32),t=0;t<256;t++)e=(t<<12)/256,r[t]=new Float64Array([e,e,e,0]),i[t]=256,o[t]=0}(),function(){var r,n,o,i,c,h,f=t.length,p=30+(e-1)/3,g=f/(3*e),d=~~(g/100),y=1024,v=2048,m=v>>6;for(m<=1&&(m=0),r=0;r<m;r++)a[r]=y*(256*(m*m-r*r)/(m*m));f<1509?(e=1,n=3):n=f%499!=0?1497:f%491!=0?1473:f%487!=0?1461:1509;var w=0;for(r=0;r<g;)if(s(y,h=l(o=(255&t[w])<<4,i=(255&t[w+1])<<4,c=(255&t[w+2])<<4),o,i,c),0!==m&&u(m,h,o,i,c),(w+=n)>=f&&(w-=f),0===d&&(d=1),++r%d==0)for(y-=y/p,(m=(v-=v/30)>>6)<=1&&(m=0),h=0;h<m;h++)a[h]=y*(256*(m*m-h*h)/(m*m))}(),function(){for(var t=0;t<256;t++)r[t][0]>>=4,r[t][1]>>=4,r[t][2]>>=4,r[t][3]=t}(),function(){var t,e,o,i,a,s,u=0,l=0;for(t=0;t<256;t++){for(a=t,s=(o=r[t])[1],e=t+1;e<256;e++)(i=r[e])[1]<s&&(a=e,s=i[1]);if(i=r[a],t!=a&&(e=i[0],i[0]=o[0],o[0]=e,e=i[1],i[1]=o[1],o[1]=e,e=i[2],i[2]=o[2],o[2]=e,e=i[3],i[3]=o[3],o[3]=e),s!=u){for(n[u]=l+t>>1,e=u+1;e<s;e++)n[e]=t;u=s,l=t}}for(n[u]=l+255>>1,e=u+1;e<256;e++)n[e]=255}()},this.getColormap=function(){for(var t=[],e=[],n=0;n<256;n++)e[r[n][3]]=n;for(var o=0,i=0;i<256;i++){var a=e[i];t[o++]=r[a][0],t[o++]=r[a][1],t[o++]=r[a][2]}return t},this.lookupRGB=function(t,e,o){for(var i,a,s,u=1e3,l=-1,c=n[e],h=c-1;c<256||h>=0;)c<256&&((s=(a=r[c])[1]-e)>=u?c=256:(c++,s<0&&(s=-s),(i=a[0]-t)<0&&(i=-i),(s+=i)<u&&((i=a[2]-o)<0&&(i=-i),(s+=i)<u&&(u=s,l=a[3])))),h>=0&&((s=e-(a=r[h])[1])>=u?h=-1:(h--,s<0&&(s=-s),(i=a[0]-t)<0&&(i=-i),(s+=i)<u&&((i=a[2]-o)<0&&(i=-i),(s+=i)<u&&(u=s,l=a[3]))));return l}},o=[0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535];var i=function(t,e,r,n){var i,a,s,u,l,c,h,f,p,g=Math.max(2,n),d=new Uint8Array(256),y=new Int32Array(5003),v=new Int32Array(5003),m=0,w=0,b=!1;function x(t,e){d[a++]=t,a>=254&&C(e)}function A(t){E(5003),w=l+2,b=!0,_(l,t)}function E(t){for(var e=0;e<t;++e)y[e]=-1}function C(t){a>0&&(t.writeByte(a),t.writeBytes(d,0,a),a=0)}function k(t){return(1<<t)-1}function P(){return 0===h?-1:(--h,255&r[f++])}function _(t,e){for(i&=o[m],m>0?i|=t<<m:i=t,m+=p;m>=8;)x(255&i,e),i>>=8,m-=8;if((w>s||b)&&(b?(s=k(p=u),b=!1):(++p,s=12==p?4096:k(p))),t==c){for(;m>0;)x(255&i,e),i>>=8,m-=8;C(e)}}this.encode=function(r){r.writeByte(g),h=t*e,f=0,function(t,e){var r,n,o,i,h,f;for(b=!1,s=k(p=u=t),c=(l=1<<t-1)+1,w=l+2,a=0,i=P(),f=0,r=5003;r<65536;r*=2)++f;f=8-f,E(5003),_(l,e);t:for(;-1!=(n=P());)if(r=(n<<12)+i,y[o=n<<f^i]!==r){if(y[o]>=0){h=5003-o,0===o&&(h=1);do{if((o-=h)<0&&(o+=5003),y[o]===r){i=v[o];continue t}}while(y[o]>=0)}_(i,e),i=n,w<4096?(v[o]=w++,y[o]=r):A(e)}else i=v[o];_(i,e),_(c,e)}(g+1,r),r.writeByte(0)}};function a(){this.page=-1,this.pages=[],this.newPage()}a.pageSize=4096,a.charMap={};for(var s=0;s<256;s++)a.charMap[s]=String.fromCharCode(s);function u(t,e){this.width=~~t,this.height=~~e,this.transparent=null,this.transIndex=0,this.repeat=-1,this.delay=0,this.image=null,this.pixels=null,this.indexedPixels=null,this.colorDepth=null,this.colorTab=null,this.neuQuant=null,this.usedEntry=new Array,this.palSize=7,this.dispose=-1,this.firstFrame=!0,this.sample=10,this.dither=!1,this.globalPalette=!1,this.out=new a}a.prototype.newPage=function(){this.pages[++this.page]=new Uint8Array(a.pageSize),this.cursor=0},a.prototype.getData=function(){for(var t="",e=0;e<this.pages.length;e++)for(var r=0;r<a.pageSize;r++)t+=a.charMap[this.pages[e][r]];return t},a.prototype.toFlattenUint8Array=function(){for(var t=[],e=0;e<this.pages.length;e++)if(e===this.pages.length-1){var r=Uint8Array.from(this.pages[e].slice(0,this.cursor));t.push(r)}else t.push(this.pages[e]);var n=new Uint8Array(t.reduce((function(t,e){return t+e.length}),0));return t.reduce((function(t,e){return n.set(e,t),t+e.length}),0),n},a.prototype.writeByte=function(t){this.cursor>=a.pageSize&&this.newPage(),this.pages[this.page][this.cursor++]=t},a.prototype.writeUTFBytes=function(t){for(var e=t.length,r=0;r<e;r++)this.writeByte(t.charCodeAt(r))},a.prototype.writeBytes=function(t,e,r){for(var n=r||t.length,o=e||0;o<n;o++)this.writeByte(t[o])},u.prototype.setDelay=function(t){this.delay=Math.round(t/10)},u.prototype.setFrameRate=function(t){this.delay=Math.round(100/t)},u.prototype.setDispose=function(t){t>=0&&(this.dispose=t)},u.prototype.setRepeat=function(t){this.repeat=t},u.prototype.setTransparent=function(t){this.transparent=t},u.prototype.addFrame=function(t){this.image=t,this.colorTab=this.globalPalette&&this.globalPalette.slice?this.globalPalette:null,this.getImagePixels(),this.analyzePixels(),!0===this.globalPalette&&(this.globalPalette=this.colorTab),this.firstFrame&&(this.writeHeader(),this.writeLSD(),this.writePalette(),this.repeat>=0&&this.writeNetscapeExt()),this.writeGraphicCtrlExt(),this.writeImageDesc(),this.firstFrame||this.globalPalette||this.writePalette(),this.writePixels(),this.firstFrame=!1},u.prototype.finish=function(){this.out.writeByte(59)},u.prototype.setQuality=function(t){t<1&&(t=1),this.sample=t},u.prototype.setDither=function(t){!0===t&&(t="FloydSteinberg"),this.dither=t},u.prototype.setGlobalPalette=function(t){this.globalPalette=t},u.prototype.getGlobalPalette=function(){return this.globalPalette&&this.globalPalette.slice&&this.globalPalette.slice(0)||this.globalPalette},u.prototype.writeHeader=function(){this.out.writeUTFBytes("GIF89a")},u.prototype.analyzePixels=function(){this.colorTab||(this.neuQuant=new n(this.pixels,this.sample),this.neuQuant.buildColormap(),this.colorTab=this.neuQuant.getColormap()),this.dither?this.ditherPixels(this.dither.replace("-serpentine",""),null!==this.dither.match(/-serpentine/)):this.indexPixels(),this.pixels=null,this.colorDepth=8,this.palSize=7,null!==this.transparent&&(this.transIndex=this.findClosest(this.transparent,!0))},u.prototype.indexPixels=function(t){var e=this.pixels.length/3;this.indexedPixels=new Uint8Array(e);for(var r=0,n=0;n<e;n++){var o=this.findClosestRGB(255&this.pixels[r++],255&this.pixels[r++],255&this.pixels[r++]);this.usedEntry[o]=!0,this.indexedPixels[n]=o}},u.prototype.ditherPixels=function(t,e){var r={FalseFloydSteinberg:[[3/8,1,0],[3/8,0,1],[2/8,1,1]],FloydSteinberg:[[7/16,1,0],[3/16,-1,1],[5/16,0,1],[1/16,1,1]],Stucki:[[8/42,1,0],[4/42,2,0],[2/42,-2,1],[4/42,-1,1],[8/42,0,1],[4/42,1,1],[2/42,2,1],[1/42,-2,2],[2/42,-1,2],[4/42,0,2],[2/42,1,2],[1/42,2,2]],Atkinson:[[1/8,1,0],[1/8,2,0],[1/8,-1,1],[1/8,0,1],[1/8,1,1],[1/8,0,2]]};if(!t||!r[t])throw"Unknown dithering kernel: "+t;var n=r[t],o=0,i=this.height,a=this.width,s=this.pixels,u=e?-1:1;this.indexedPixels=new Uint8Array(this.pixels.length/3);for(var l=0;l<i;l++){e&&(u*=-1);for(var c=1==u?0:a-1,h=1==u?a:0;c!==h;c+=u){var f=3*(o=l*a+c),p=s[f],g=s[f+1],d=s[f+2];f=this.findClosestRGB(p,g,d),this.usedEntry[f]=!0,this.indexedPixels[o]=f,f*=3;for(var y=p-this.colorTab[f],v=g-this.colorTab[f+1],m=d-this.colorTab[f+2],w=1==u?0:n.length-1,b=1==u?n.length:0;w!==b;w+=u){var x=n[w][1],A=n[w][2];if(x+c>=0&&x+c<a&&A+l>=0&&A+l<i){var E=n[w][0];f=o+x+A*a,s[f*=3]=Math.max(0,Math.min(255,s[f]+y*E)),s[f+1]=Math.max(0,Math.min(255,s[f+1]+v*E)),s[f+2]=Math.max(0,Math.min(255,s[f+2]+m*E))}}}}},u.prototype.findClosest=function(t,e){return this.findClosestRGB((16711680&t)>>16,(65280&t)>>8,255&t,e)},u.prototype.findClosestRGB=function(t,e,r,n){if(null===this.colorTab)return-1;if(this.neuQuant&&!n)return this.neuQuant.lookupRGB(t,e,r);for(var o=0,i=16777216,a=this.colorTab.length,s=0,u=0;s<a;u++){var l=t-(255&this.colorTab[s++]),c=e-(255&this.colorTab[s++]),h=r-(255&this.colorTab[s++]),f=l*l+c*c+h*h;(!n||this.usedEntry[u])&&f<i&&(i=f,o=u)}return o},u.prototype.getImagePixels=function(){var t=this.width,e=this.height;this.pixels=new Uint8Array(t*e*3);for(var r=this.image,n=0,o=0,i=0;i<e;i++)for(var a=0;a<t;a++)this.pixels[o++]=r[n++],this.pixels[o++]=r[n++],this.pixels[o++]=r[n++],n++},u.prototype.writeGraphicCtrlExt=function(){var t,e;this.out.writeByte(33),this.out.writeByte(249),this.out.writeByte(4),null===this.transparent?(t=0,e=0):(t=1,e=2),this.dispose>=0&&(e=7&this.dispose),e<<=2,this.out.writeByte(0|e|t),this.writeShort(this.delay),this.out.writeByte(this.transIndex),this.out.writeByte(0)},u.prototype.writeImageDesc=function(){this.out.writeByte(44),this.writeShort(0),this.writeShort(0),this.writeShort(this.width),this.writeShort(this.height),this.firstFrame||this.globalPalette?this.out.writeByte(0):this.out.writeByte(128|this.palSize)},u.prototype.writeLSD=function(){this.writeShort(this.width),this.writeShort(this.height),this.out.writeByte(240|this.palSize),this.out.writeByte(0),this.out.writeByte(0)},u.prototype.writeNetscapeExt=function(){this.out.writeByte(33),this.out.writeByte(255),this.out.writeByte(11),this.out.writeUTFBytes("NETSCAPE2.0"),this.out.writeByte(3),this.out.writeByte(1),this.writeShort(this.repeat),this.out.writeByte(0)},u.prototype.writePalette=function(){this.out.writeBytes(this.colorTab);for(var t=768-this.colorTab.length,e=0;e<t;e++)this.out.writeByte(0)},u.prototype.writeShort=function(t){this.out.writeByte(255&t),this.out.writeByte(t>>8&255)},u.prototype.writePixels=function(){new i(this.width,this.height,this.indexedPixels,this.colorDepth).encode(this.out)},u.prototype.stream=function(){return this.out};e.a=u},function(t,e,r){t.exports=r(20)},function(t,e,r){var n=r(2).default;function o(){"use strict";
/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */t.exports=o=function(){return e},t.exports.__esModule=!0,t.exports.default=t.exports;var e={},r=Object.prototype,i=r.hasOwnProperty,a="function"==typeof Symbol?Symbol:{},s=a.iterator||"@@iterator",u=a.asyncIterator||"@@asyncIterator",l=a.toStringTag||"@@toStringTag";function c(t,e,r){return Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}),t[e]}try{c({},"")}catch(t){c=function(t,e,r){return t[e]=r}}function h(t,e,r,n){var o=e&&e.prototype instanceof g?e:g,i=Object.create(o.prototype),a=new P(n||[]);return i._invoke=function(t,e,r){var n="suspendedStart";return function(o,i){if("executing"===n)throw new Error("Generator is already running");if("completed"===n){if("throw"===o)throw i;return T()}for(r.method=o,r.arg=i;;){var a=r.delegate;if(a){var s=E(a,r);if(s){if(s===p)continue;return s}}if("next"===r.method)r.sent=r._sent=r.arg;else if("throw"===r.method){if("suspendedStart"===n)throw n="completed",r.arg;r.dispatchException(r.arg)}else"return"===r.method&&r.abrupt("return",r.arg);n="executing";var u=f(t,e,r);if("normal"===u.type){if(n=r.done?"completed":"suspendedYield",u.arg===p)continue;return{value:u.arg,done:r.done}}"throw"===u.type&&(n="completed",r.method="throw",r.arg=u.arg)}}}(t,r,a),i}function f(t,e,r){try{return{type:"normal",arg:t.call(e,r)}}catch(t){return{type:"throw",arg:t}}}e.wrap=h;var p={};function g(){}function d(){}function y(){}var v={};c(v,s,(function(){return this}));var m=Object.getPrototypeOf,w=m&&m(m(_([])));w&&w!==r&&i.call(w,s)&&(v=w);var b=y.prototype=g.prototype=Object.create(v);function x(t){["next","throw","return"].forEach((function(e){c(t,e,(function(t){return this._invoke(e,t)}))}))}function A(t,e){var r;this._invoke=function(o,a){function s(){return new e((function(r,s){!function r(o,a,s,u){var l=f(t[o],t,a);if("throw"!==l.type){var c=l.arg,h=c.value;return h&&"object"==n(h)&&i.call(h,"__await")?e.resolve(h.__await).then((function(t){r("next",t,s,u)}),(function(t){r("throw",t,s,u)})):e.resolve(h).then((function(t){c.value=t,s(c)}),(function(t){return r("throw",t,s,u)}))}u(l.arg)}(o,a,r,s)}))}return r=r?r.then(s,s):s()}}function E(t,e){var r=t.iterator[e.method];if(void 0===r){if(e.delegate=null,"throw"===e.method){if(t.iterator.return&&(e.method="return",e.arg=void 0,E(t,e),"throw"===e.method))return p;e.method="throw",e.arg=new TypeError("The iterator does not provide a 'throw' method")}return p}var n=f(r,t.iterator,e.arg);if("throw"===n.type)return e.method="throw",e.arg=n.arg,e.delegate=null,p;var o=n.arg;return o?o.done?(e[t.resultName]=o.value,e.next=t.nextLoc,"return"!==e.method&&(e.method="next",e.arg=void 0),e.delegate=null,p):o:(e.method="throw",e.arg=new TypeError("iterator result is not an object"),e.delegate=null,p)}function C(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function k(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function P(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(C,this),this.reset(!0)}function _(t){if(t){var e=t[s];if(e)return e.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var r=-1,n=function e(){for(;++r<t.length;)if(i.call(t,r))return e.value=t[r],e.done=!1,e;return e.value=void 0,e.done=!0,e};return n.next=n}}return{next:T}}function T(){return{value:void 0,done:!0}}return d.prototype=y,c(b,"constructor",y),c(y,"constructor",d),d.displayName=c(y,l,"GeneratorFunction"),e.isGeneratorFunction=function(t){var e="function"==typeof t&&t.constructor;return!!e&&(e===d||"GeneratorFunction"===(e.displayName||e.name))},e.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,y):(t.__proto__=y,c(t,l,"GeneratorFunction")),t.prototype=Object.create(b),t},e.awrap=function(t){return{__await:t}},x(A.prototype),c(A.prototype,u,(function(){return this})),e.AsyncIterator=A,e.async=function(t,r,n,o,i){void 0===i&&(i=Promise);var a=new A(h(t,r,n,o),i);return e.isGeneratorFunction(r)?a:a.next().then((function(t){return t.done?t.value:a.next()}))},x(b),c(b,l,"Generator"),c(b,s,(function(){return this})),c(b,"toString",(function(){return"[object Generator]"})),e.keys=function(t){var e=[];for(var r in t)e.push(r);return e.reverse(),function r(){for(;e.length;){var n=e.pop();if(n in t)return r.value=n,r.done=!1,r}return r.done=!0,r}},e.values=_,P.prototype={constructor:P,reset:function(t){if(this.prev=0,this.next=0,this.sent=this._sent=void 0,this.done=!1,this.delegate=null,this.method="next",this.arg=void 0,this.tryEntries.forEach(k),!t)for(var e in this)"t"===e.charAt(0)&&i.call(this,e)&&!isNaN(+e.slice(1))&&(this[e]=void 0)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(t){if(this.done)throw t;var e=this;function r(r,n){return a.type="throw",a.arg=t,e.next=r,n&&(e.method="next",e.arg=void 0),!!n}for(var n=this.tryEntries.length-1;n>=0;--n){var o=this.tryEntries[n],a=o.completion;if("root"===o.tryLoc)return r("end");if(o.tryLoc<=this.prev){var s=i.call(o,"catchLoc"),u=i.call(o,"finallyLoc");if(s&&u){if(this.prev<o.catchLoc)return r(o.catchLoc,!0);if(this.prev<o.finallyLoc)return r(o.finallyLoc)}else if(s){if(this.prev<o.catchLoc)return r(o.catchLoc,!0)}else{if(!u)throw new Error("try statement without catch or finally");if(this.prev<o.finallyLoc)return r(o.finallyLoc)}}}},abrupt:function(t,e){for(var r=this.tryEntries.length-1;r>=0;--r){var n=this.tryEntries[r];if(n.tryLoc<=this.prev&&i.call(n,"finallyLoc")&&this.prev<n.finallyLoc){var o=n;break}}o&&("break"===t||"continue"===t)&&o.tryLoc<=e&&e<=o.finallyLoc&&(o=null);var a=o?o.completion:{};return a.type=t,a.arg=e,o?(this.method="next",this.next=o.finallyLoc,p):this.complete(a)},complete:function(t,e){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&e&&(this.next=e),p},finish:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.finallyLoc===t)return this.complete(r.completion,r.afterLoc),k(r),p}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var r=this.tryEntries[e];if(r.tryLoc===t){var n=r.completion;if("throw"===n.type){var o=n.arg;k(r)}return o}}throw new Error("illegal catch attempt")},delegateYield:function(t,e,r){return this.delegate={iterator:_(t),resultName:e,nextLoc:r},"next"===this.method&&(this.arg=void 0),p}},e}t.exports=o,t.exports.__esModule=!0,t.exports.default=t.exports},function(t,e,r){"use strict";(function(t){
/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh <http://feross.org>
* @license MIT
*/
var n=r(16),o=r(17),i=r(18);function a(){return u.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function s(t,e){if(a()<e)throw new RangeError("Invalid typed array length");return u.TYPED_ARRAY_SUPPORT?(t=new Uint8Array(e)).__proto__=u.prototype:(null===t&&(t=new u(e)),t.length=e),t}function u(t,e,r){if(!(u.TYPED_ARRAY_SUPPORT||this instanceof u))return new u(t,e,r);if("number"==typeof t){if("string"==typeof e)throw new Error("If encoding is specified then the first argument must be a string");return h(this,t)}return l(this,t,e,r)}function l(t,e,r,n){if("number"==typeof e)throw new TypeError('"value" argument must not be a number');return"undefined"!=typeof ArrayBuffer&&e instanceof ArrayBuffer?function(t,e,r,n){if(e.byteLength,r<0||e.byteLength<r)throw new RangeError("'offset' is out of bounds");if(e.byteLength<r+(n||0))throw new RangeError("'length' is out of bounds");e=void 0===r&&void 0===n?new Uint8Array(e):void 0===n?new Uint8Array(e,r):new Uint8Array(e,r,n);u.TYPED_ARRAY_SUPPORT?(t=e).__proto__=u.prototype:t=f(t,e);return t}(t,e,r,n):"string"==typeof e?function(t,e,r){"string"==typeof r&&""!==r||(r="utf8");if(!u.isEncoding(r))throw new TypeError('"encoding" must be a valid string encoding');var n=0|g(e,r),o=(t=s(t,n)).write(e,r);o!==n&&(t=t.slice(0,o));return t}(t,e,r):function(t,e){if(u.isBuffer(e)){var r=0|p(e.length);return 0===(t=s(t,r)).length||e.copy(t,0,0,r),t}if(e){if("undefined"!=typeof ArrayBuffer&&e.buffer instanceof ArrayBuffer||"length"in e)return"number"!=typeof e.length||(n=e.length)!=n?s(t,0):f(t,e);if("Buffer"===e.type&&i(e.data))return f(t,e.data)}var n;throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")}(t,e)}function c(t){if("number"!=typeof t)throw new TypeError('"size" argument must be a number');if(t<0)throw new RangeError('"size" argument must not be negative')}function h(t,e){if(c(e),t=s(t,e<0?0:0|p(e)),!u.TYPED_ARRAY_SUPPORT)for(var r=0;r<e;++r)t[r]=0;return t}function f(t,e){var r=e.length<0?0:0|p(e.length);t=s(t,r);for(var n=0;n<r;n+=1)t[n]=255&e[n];return t}function p(t){if(t>=a())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+a().toString(16)+" bytes");return 0|t}function g(t,e){if(u.isBuffer(t))return t.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(t)||t instanceof ArrayBuffer))return t.byteLength;"string"!=typeof t&&(t=""+t);var r=t.length;if(0===r)return 0;for(var n=!1;;)switch(e){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":case void 0:return F(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return Y(t).length;default:if(n)return F(t).length;e=(""+e).toLowerCase(),n=!0}}function d(t,e,r){var n=!1;if((void 0===e||e<0)&&(e=0),e>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(e>>>=0))return"";for(t||(t="utf8");;)switch(t){case"hex":return B(this,e,r);case"utf8":case"utf-8":return P(this,e,r);case"ascii":return _(this,e,r);case"latin1":case"binary":return T(this,e,r);case"base64":return k(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return R(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}function y(t,e,r){var n=t[e];t[e]=t[r],t[r]=n}function v(t,e,r,n,o){if(0===t.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,isNaN(r)&&(r=o?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(o)return-1;r=t.length-1}else if(r<0){if(!o)return-1;r=0}if("string"==typeof e&&(e=u.from(e,n)),u.isBuffer(e))return 0===e.length?-1:m(t,e,r,n,o);if("number"==typeof e)return e&=255,u.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?o?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):m(t,[e],r,n,o);throw new TypeError("val must be string, number or Buffer")}function m(t,e,r,n,o){var i,a=1,s=t.length,u=e.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(t.length<2||e.length<2)return-1;a=2,s/=2,u/=2,r/=2}function l(t,e){return 1===a?t[e]:t.readUInt16BE(e*a)}if(o){var c=-1;for(i=r;i<s;i++)if(l(t,i)===l(e,-1===c?0:i-c)){if(-1===c&&(c=i),i-c+1===u)return c*a}else-1!==c&&(i-=i-c),c=-1}else for(r+u>s&&(r=s-u),i=r;i>=0;i--){for(var h=!0,f=0;f<u;f++)if(l(t,i+f)!==l(e,f)){h=!1;break}if(h)return i}return-1}function w(t,e,r,n){r=Number(r)||0;var o=t.length-r;n?(n=Number(n))>o&&(n=o):n=o;var i=e.length;if(i%2!=0)throw new TypeError("Invalid hex string");n>i/2&&(n=i/2);for(var a=0;a<n;++a){var s=parseInt(e.substr(2*a,2),16);if(isNaN(s))return a;t[r+a]=s}return a}function b(t,e,r,n){return z(F(e,t.length-r),t,r,n)}function x(t,e,r,n){return z(function(t){for(var e=[],r=0;r<t.length;++r)e.push(255&t.charCodeAt(r));return e}(e),t,r,n)}function A(t,e,r,n){return x(t,e,r,n)}function E(t,e,r,n){return z(Y(e),t,r,n)}function C(t,e,r,n){return z(function(t,e){for(var r,n,o,i=[],a=0;a<t.length&&!((e-=2)<0);++a)r=t.charCodeAt(a),n=r>>8,o=r%256,i.push(o),i.push(n);return i}(e,t.length-r),t,r,n)}function k(t,e,r){return 0===e&&r===t.length?n.fromByteArray(t):n.fromByteArray(t.slice(e,r))}function P(t,e,r){r=Math.min(t.length,r);for(var n=[],o=e;o<r;){var i,a,s,u,l=t[o],c=null,h=l>239?4:l>223?3:l>191?2:1;if(o+h<=r)switch(h){case 1:l<128&&(c=l);break;case 2:128==(192&(i=t[o+1]))&&(u=(31&l)<<6|63&i)>127&&(c=u);break;case 3:i=t[o+1],a=t[o+2],128==(192&i)&&128==(192&a)&&(u=(15&l)<<12|(63&i)<<6|63&a)>2047&&(u<55296||u>57343)&&(c=u);break;case 4:i=t[o+1],a=t[o+2],s=t[o+3],128==(192&i)&&128==(192&a)&&128==(192&s)&&(u=(15&l)<<18|(63&i)<<12|(63&a)<<6|63&s)>65535&&u<1114112&&(c=u)}null===c?(c=65533,h=1):c>65535&&(c-=65536,n.push(c>>>10&1023|55296),c=56320|1023&c),n.push(c),o+=h}return function(t){var e=t.length;if(e<=4096)return String.fromCharCode.apply(String,t);var r="",n=0;for(;n<e;)r+=String.fromCharCode.apply(String,t.slice(n,n+=4096));return r}(n)}e.Buffer=u,e.SlowBuffer=function(t){+t!=t&&(t=0);return u.alloc(+t)},e.INSPECT_MAX_BYTES=50,u.TYPED_ARRAY_SUPPORT=void 0!==t.TYPED_ARRAY_SUPPORT?t.TYPED_ARRAY_SUPPORT:function(){try{var t=new Uint8Array(1);return t.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===t.foo()&&"function"==typeof t.subarray&&0===t.subarray(1,1).byteLength}catch(t){return!1}}(),e.kMaxLength=a(),u.poolSize=8192,u._augment=function(t){return t.__proto__=u.prototype,t},u.from=function(t,e,r){return l(null,t,e,r)},u.TYPED_ARRAY_SUPPORT&&(u.prototype.__proto__=Uint8Array.prototype,u.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&&u[Symbol.species]===u&&Object.defineProperty(u,Symbol.species,{value:null,configurable:!0})),u.alloc=function(t,e,r){return function(t,e,r,n){return c(e),e<=0?s(t,e):void 0!==r?"string"==typeof n?s(t,e).fill(r,n):s(t,e).fill(r):s(t,e)}(null,t,e,r)},u.allocUnsafe=function(t){return h(null,t)},u.allocUnsafeSlow=function(t){return h(null,t)},u.isBuffer=function(t){return!(null==t||!t._isBuffer)},u.compare=function(t,e){if(!u.isBuffer(t)||!u.isBuffer(e))throw new TypeError("Arguments must be Buffers");if(t===e)return 0;for(var r=t.length,n=e.length,o=0,i=Math.min(r,n);o<i;++o)if(t[o]!==e[o]){r=t[o],n=e[o];break}return r<n?-1:n<r?1:0},u.isEncoding=function(t){switch(String(t).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},u.concat=function(t,e){if(!i(t))throw new TypeError('"list" argument must be an Array of Buffers');if(0===t.length)return u.alloc(0);var r;if(void 0===e)for(e=0,r=0;r<t.length;++r)e+=t[r].length;var n=u.allocUnsafe(e),o=0;for(r=0;r<t.length;++r){var a=t[r];if(!u.isBuffer(a))throw new TypeError('"list" argument must be an Array of Buffers');a.copy(n,o),o+=a.length}return n},u.byteLength=g,u.prototype._isBuffer=!0,u.prototype.swap16=function(){var t=this.length;if(t%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var e=0;e<t;e+=2)y(this,e,e+1);return this},u.prototype.swap32=function(){var t=this.length;if(t%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var e=0;e<t;e+=4)y(this,e,e+3),y(this,e+1,e+2);return this},u.prototype.swap64=function(){var t=this.length;if(t%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var e=0;e<t;e+=8)y(this,e,e+7),y(this,e+1,e+6),y(this,e+2,e+5),y(this,e+3,e+4);return this},u.prototype.toString=function(){var t=0|this.length;return 0===t?"":0===arguments.length?P(this,0,t):d.apply(this,arguments)},u.prototype.equals=function(t){if(!u.isBuffer(t))throw new TypeError("Argument must be a Buffer");return this===t||0===u.compare(this,t)},u.prototype.inspect=function(){var t="",r=e.INSPECT_MAX_BYTES;return this.length>0&&(t=this.toString("hex",0,r).match(/.{2}/g).join(" "),this.length>r&&(t+=" ... ")),"<Buffer "+t+">"},u.prototype.compare=function(t,e,r,n,o){if(!u.isBuffer(t))throw new TypeError("Argument must be a Buffer");if(void 0===e&&(e=0),void 0===r&&(r=t?t.length:0),void 0===n&&(n=0),void 0===o&&(o=this.length),e<0||r>t.length||n<0||o>this.length)throw new RangeError("out of range index");if(n>=o&&e>=r)return 0;if(n>=o)return-1;if(e>=r)return 1;if(this===t)return 0;for(var i=(o>>>=0)-(n>>>=0),a=(r>>>=0)-(e>>>=0),s=Math.min(i,a),l=this.slice(n,o),c=t.slice(e,r),h=0;h<s;++h)if(l[h]!==c[h]){i=l[h],a=c[h];break}return i<a?-1:a<i?1:0},u.prototype.includes=function(t,e,r){return-1!==this.indexOf(t,e,r)},u.prototype.indexOf=function(t,e,r){return v(this,t,e,r,!0)},u.prototype.lastIndexOf=function(t,e,r){return v(this,t,e,r,!1)},u.prototype.write=function(t,e,r,n){if(void 0===e)n="utf8",r=this.length,e=0;else if(void 0===r&&"string"==typeof e)n=e,r=this.length,e=0;else{if(!isFinite(e))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");e|=0,isFinite(r)?(r|=0,void 0===n&&(n="utf8")):(n=r,r=void 0)}var o=this.length-e;if((void 0===r||r>o)&&(r=o),t.length>0&&(r<0||e<0)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var i=!1;;)switch(n){case"hex":return w(this,t,e,r);case"utf8":case"utf-8":return b(this,t,e,r);case"ascii":return x(this,t,e,r);case"latin1":case"binary":return A(this,t,e,r);case"base64":return E(this,t,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return C(this,t,e,r);default:if(i)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),i=!0}},u.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function _(t,e,r){var n="";r=Math.min(t.length,r);for(var o=e;o<r;++o)n+=String.fromCharCode(127&t[o]);return n}function T(t,e,r){var n="";r=Math.min(t.length,r);for(var o=e;o<r;++o)n+=String.fromCharCode(t[o]);return n}function B(t,e,r){var n=t.length;(!e||e<0)&&(e=0),(!r||r<0||r>n)&&(r=n);for(var o="",i=e;i<r;++i)o+=j(t[i]);return o}function R(t,e,r){for(var n=t.slice(e,r),o="",i=0;i<n.length;i+=2)o+=String.fromCharCode(n[i]+256*n[i+1]);return o}function S(t,e,r){if(t%1!=0||t<0)throw new RangeError("offset is not uint");if(t+e>r)throw new RangeError("Trying to access beyond buffer length")}function D(t,e,r,n,o,i){if(!u.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>o||e<i)throw new RangeError('"value" argument is out of bounds');if(r+n>t.length)throw new RangeError("Index out of range")}function L(t,e,r,n){e<0&&(e=65535+e+1);for(var o=0,i=Math.min(t.length-r,2);o<i;++o)t[r+o]=(e&255<<8*(n?o:1-o))>>>8*(n?o:1-o)}function M(t,e,r,n){e<0&&(e=4294967295+e+1);for(var o=0,i=Math.min(t.length-r,4);o<i;++o)t[r+o]=e>>>8*(n?o:3-o)&255}function I(t,e,r,n,o,i){if(r+n>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function O(t,e,r,n,i){return i||I(t,0,r,4),o.write(t,e,r,n,23,4),r+4}function U(t,e,r,n,i){return i||I(t,0,r,8),o.write(t,e,r,n,52,8),r+8}u.prototype.slice=function(t,e){var r,n=this.length;if((t=~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),(e=void 0===e?n:~~e)<0?(e+=n)<0&&(e=0):e>n&&(e=n),e<t&&(e=t),u.TYPED_ARRAY_SUPPORT)(r=this.subarray(t,e)).__proto__=u.prototype;else{var o=e-t;r=new u(o,void 0);for(var i=0;i<o;++i)r[i]=this[i+t]}return r},u.prototype.readUIntLE=function(t,e,r){t|=0,e|=0,r||S(t,e,this.length);for(var n=this[t],o=1,i=0;++i<e&&(o*=256);)n+=this[t+i]*o;return n},u.prototype.readUIntBE=function(t,e,r){t|=0,e|=0,r||S(t,e,this.length);for(var n=this[t+--e],o=1;e>0&&(o*=256);)n+=this[t+--e]*o;return n},u.prototype.readUInt8=function(t,e){return e||S(t,1,this.length),this[t]},u.prototype.readUInt16LE=function(t,e){return e||S(t,2,this.length),this[t]|this[t+1]<<8},u.prototype.readUInt16BE=function(t,e){return e||S(t,2,this.length),this[t]<<8|this[t+1]},u.prototype.readUInt32LE=function(t,e){return e||S(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},u.prototype.readUInt32BE=function(t,e){return e||S(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},u.prototype.readIntLE=function(t,e,r){t|=0,e|=0,r||S(t,e,this.length);for(var n=this[t],o=1,i=0;++i<e&&(o*=256);)n+=this[t+i]*o;return n>=(o*=128)&&(n-=Math.pow(2,8*e)),n},u.prototype.readIntBE=function(t,e,r){t|=0,e|=0,r||S(t,e,this.length);for(var n=e,o=1,i=this[t+--n];n>0&&(o*=256);)i+=this[t+--n]*o;return i>=(o*=128)&&(i-=Math.pow(2,8*e)),i},u.prototype.readInt8=function(t,e){return e||S(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},u.prototype.readInt16LE=function(t,e){e||S(t,2,this.length);var r=this[t]|this[t+1]<<8;return 32768&r?4294901760|r:r},u.prototype.readInt16BE=function(t,e){e||S(t,2,this.length);var r=this[t+1]|this[t]<<8;return 32768&r?4294901760|r:r},u.prototype.readInt32LE=function(t,e){return e||S(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},u.prototype.readInt32BE=function(t,e){return e||S(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},u.prototype.readFloatLE=function(t,e){return e||S(t,4,this.length),o.read(this,t,!0,23,4)},u.prototype.readFloatBE=function(t,e){return e||S(t,4,this.length),o.read(this,t,!1,23,4)},u.prototype.readDoubleLE=function(t,e){return e||S(t,8,this.length),o.read(this,t,!0,52,8)},u.prototype.readDoubleBE=function(t,e){return e||S(t,8,this.length),o.read(this,t,!1,52,8)},u.prototype.writeUIntLE=function(t,e,r,n){(t=+t,e|=0,r|=0,n)||D(this,t,e,r,Math.pow(2,8*r)-1,0);var o=1,i=0;for(this[e]=255&t;++i<r&&(o*=256);)this[e+i]=t/o&255;return e+r},u.prototype.writeUIntBE=function(t,e,r,n){(t=+t,e|=0,r|=0,n)||D(this,t,e,r,Math.pow(2,8*r)-1,0);var o=r-1,i=1;for(this[e+o]=255&t;--o>=0&&(i*=256);)this[e+o]=t/i&255;return e+r},u.prototype.writeUInt8=function(t,e,r){return t=+t,e|=0,r||D(this,t,e,1,255,0),u.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),this[e]=255&t,e+1},u.prototype.writeUInt16LE=function(t,e,r){return t=+t,e|=0,r||D(this,t,e,2,65535,0),u.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8):L(this,t,e,!0),e+2},u.prototype.writeUInt16BE=function(t,e,r){return t=+t,e|=0,r||D(this,t,e,2,65535,0),u.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=255&t):L(this,t,e,!1),e+2},u.prototype.writeUInt32LE=function(t,e,r){return t=+t,e|=0,r||D(this,t,e,4,4294967295,0),u.TYPED_ARRAY_SUPPORT?(this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=255&t):M(this,t,e,!0),e+4},u.prototype.writeUInt32BE=function(t,e,r){return t=+t,e|=0,r||D(this,t,e,4,4294967295,0),u.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t):M(this,t,e,!1),e+4},u.prototype.writeIntLE=function(t,e,r,n){if(t=+t,e|=0,!n){var o=Math.pow(2,8*r-1);D(this,t,e,r,o-1,-o)}var i=0,a=1,s=0;for(this[e]=255&t;++i<r&&(a*=256);)t<0&&0===s&&0!==this[e+i-1]&&(s=1),this[e+i]=(t/a>>0)-s&255;return e+r},u.prototype.writeIntBE=function(t,e,r,n){if(t=+t,e|=0,!n){var o=Math.pow(2,8*r-1);D(this,t,e,r,o-1,-o)}var i=r-1,a=1,s=0;for(this[e+i]=255&t;--i>=0&&(a*=256);)t<0&&0===s&&0!==this[e+i+1]&&(s=1),this[e+i]=(t/a>>0)-s&255;return e+r},u.prototype.writeInt8=function(t,e,r){return t=+t,e|=0,r||D(this,t,e,1,127,-128),u.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),t<0&&(t=255+t+1),this[e]=255&t,e+1},u.prototype.writeInt16LE=function(t,e,r){return t=+t,e|=0,r||D(this,t,e,2,32767,-32768),u.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8):L(this,t,e,!0),e+2},u.prototype.writeInt16BE=function(t,e,r){return t=+t,e|=0,r||D(this,t,e,2,32767,-32768),u.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=255&t):L(this,t,e,!1),e+2},u.prototype.writeInt32LE=function(t,e,r){return t=+t,e|=0,r||D(this,t,e,4,2147483647,-2147483648),u.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24):M(this,t,e,!0),e+4},u.prototype.writeInt32BE=function(t,e,r){return t=+t,e|=0,r||D(this,t,e,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),u.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t):M(this,t,e,!1),e+4},u.prototype.writeFloatLE=function(t,e,r){return O(this,t,e,!0,r)},u.prototype.writeFloatBE=function(t,e,r){return O(this,t,e,!1,r)},u.prototype.writeDoubleLE=function(t,e,r){return U(this,t,e,!0,r)},u.prototype.writeDoubleBE=function(t,e,r){return U(this,t,e,!1,r)},u.prototype.copy=function(t,e,r,n){if(r||(r=0),n||0===n||(n=this.length),e>=t.length&&(e=t.length),e||(e=0),n>0&&n<r&&(n=r),n===r)return 0;if(0===t.length||0===this.length)return 0;if(e<0)throw new RangeError("targetStart out of bounds");if(r<0||r>=this.length)throw new RangeError("sourceStart out of bounds");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),t.length-e<n-r&&(n=t.length-e+r);var o,i=n-r;if(this===t&&r<e&&e<n)for(o=i-1;o>=0;--o)t[o+e]=this[o+r];else if(i<1e3||!u.TYPED_ARRAY_SUPPORT)for(o=0;o<i;++o)t[o+e]=this[o+r];else Uint8Array.prototype.set.call(t,this.subarray(r,r+i),e);return i},u.prototype.fill=function(t,e,r,n){if("string"==typeof t){if("string"==typeof e?(n=e,e=0,r=this.length):"string"==typeof r&&(n=r,r=this.length),1===t.length){var o=t.charCodeAt(0);o<256&&(t=o)}if(void 0!==n&&"string"!=typeof n)throw new TypeError("encoding must be a string");if("string"==typeof n&&!u.isEncoding(n))throw new TypeError("Unknown encoding: "+n)}else"number"==typeof t&&(t&=255);if(e<0||this.length<e||this.length<r)throw new RangeError("Out of range index");if(r<=e)return this;var i;if(e>>>=0,r=void 0===r?this.length:r>>>0,t||(t=0),"number"==typeof t)for(i=e;i<r;++i)this[i]=t;else{var a=u.isBuffer(t)?t:F(new u(t,n).toString()),s=a.length;for(i=0;i<r-e;++i)this[i+e]=a[i%s]}return this};var N=/[^+\/0-9A-Za-z-_]/g;function j(t){return t<16?"0"+t.toString(16):t.toString(16)}function F(t,e){var r;e=e||1/0;for(var n=t.length,o=null,i=[],a=0;a<n;++a){if((r=t.charCodeAt(a))>55295&&r<57344){if(!o){if(r>56319){(e-=3)>-1&&i.push(239,191,189);continue}if(a+1===n){(e-=3)>-1&&i.push(239,191,189);continue}o=r;continue}if(r<56320){(e-=3)>-1&&i.push(239,191,189),o=r;continue}r=65536+(o-55296<<10|r-56320)}else o&&(e-=3)>-1&&i.push(239,191,189);if(o=null,r<128){if((e-=1)<0)break;i.push(r)}else if(r<2048){if((e-=2)<0)break;i.push(r>>6|192,63&r|128)}else if(r<65536){if((e-=3)<0)break;i.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((e-=4)<0)break;i.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return i}function Y(t){return n.toByteArray(function(t){if((t=function(t){return t.trim?t.trim():t.replace(/^\s+|\s+$/g,"")}(t).replace(N,"")).length<2)return"";for(;t.length%4!=0;)t+="=";return t}(t))}function z(t,e,r,n){for(var o=0;o<n&&!(o+r>=e.length||o>=t.length);++o)e[o+r]=t[o];return o}}).call(this,r(8))},function(t,e,r){"use strict";e.byteLength=function(t){var e=l(t),r=e[0],n=e[1];return 3*(r+n)/4-n},e.toByteArray=function(t){var e,r,n=l(t),a=n[0],s=n[1],u=new i(function(t,e,r){return 3*(e+r)/4-r}(0,a,s)),c=0,h=s>0?a-4:a;for(r=0;r<h;r+=4)e=o[t.charCodeAt(r)]<<18|o[t.charCodeAt(r+1)]<<12|o[t.charCodeAt(r+2)]<<6|o[t.charCodeAt(r+3)],u[c++]=e>>16&255,u[c++]=e>>8&255,u[c++]=255&e;2===s&&(e=o[t.charCodeAt(r)]<<2|o[t.charCodeAt(r+1)]>>4,u[c++]=255&e);1===s&&(e=o[t.charCodeAt(r)]<<10|o[t.charCodeAt(r+1)]<<4|o[t.charCodeAt(r+2)]>>2,u[c++]=e>>8&255,u[c++]=255&e);return u},e.fromByteArray=function(t){for(var e,r=t.length,o=r%3,i=[],a=0,s=r-o;a<s;a+=16383)i.push(c(t,a,a+16383>s?s:a+16383));1===o?(e=t[r-1],i.push(n[e>>2]+n[e<<4&63]+"==")):2===o&&(e=(t[r-2]<<8)+t[r-1],i.push(n[e>>10]+n[e>>4&63]+n[e<<2&63]+"="));return i.join("")};for(var n=[],o=[],i="undefined"!=typeof Uint8Array?Uint8Array:Array,a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",s=0,u=a.length;s<u;++s)n[s]=a[s],o[a.charCodeAt(s)]=s;function l(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");return-1===r&&(r=e),[r,r===e?0:4-r%4]}function c(t,e,r){for(var o,i,a=[],s=e;s<r;s+=3)o=(t[s]<<16&16711680)+(t[s+1]<<8&65280)+(255&t[s+2]),a.push(n[(i=o)>>18&63]+n[i>>12&63]+n[i>>6&63]+n[63&i]);return a.join("")}o["-".charCodeAt(0)]=62,o["_".charCodeAt(0)]=63},function(t,e){
/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
e.read=function(t,e,r,n,o){var i,a,s=8*o-n-1,u=(1<<s)-1,l=u>>1,c=-7,h=r?o-1:0,f=r?-1:1,p=t[e+h];for(h+=f,i=p&(1<<-c)-1,p>>=-c,c+=s;c>0;i=256*i+t[e+h],h+=f,c-=8);for(a=i&(1<<-c)-1,i>>=-c,c+=n;c>0;a=256*a+t[e+h],h+=f,c-=8);if(0===i)i=1-l;else{if(i===u)return a?NaN:1/0*(p?-1:1);a+=Math.pow(2,n),i-=l}return(p?-1:1)*a*Math.pow(2,i-n)},e.write=function(t,e,r,n,o,i){var a,s,u,l=8*i-o-1,c=(1<<l)-1,h=c>>1,f=23===o?Math.pow(2,-24)-Math.pow(2,-77):0,p=n?0:i-1,g=n?1:-1,d=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(s=isNaN(e)?1:0,a=c):(a=Math.floor(Math.log(e)/Math.LN2),e*(u=Math.pow(2,-a))<1&&(a--,u*=2),(e+=a+h>=1?f/u:f*Math.pow(2,1-h))*u>=2&&(a++,u/=2),a+h>=c?(s=0,a=c):a+h>=1?(s=(e*u-1)*Math.pow(2,o),a+=h):(s=e*Math.pow(2,h-1)*Math.pow(2,o),a=0));o>=8;t[r+p]=255&s,p+=g,s/=256,o-=8);for(a=a<<o|s,l+=o;l>0;t[r+p]=255&a,p+=g,a/=256,l-=8);t[r+p-g]|=128*d}},function(t,e){var r={}.toString;t.exports=Array.isArray||function(t){return"[object Array]"==r.call(t)}},function(t,e){var r,n,o=t.exports={};function i(){throw new Error("setTimeout has not been defined")}function a(){throw new Error("clearTimeout has not been defined")}function s(t){if(r===setTimeout)return setTimeout(t,0);if((r===i||!r)&&setTimeout)return r=setTimeout,setTimeout(t,0);try{return r(t,0)}catch(e){try{return r.call(null,t,0)}catch(e){return r.call(this,t,0)}}}!function(){try{r="function"==typeof setTimeout?setTimeout:i}catch(t){r=i}try{n="function"==typeof clearTimeout?clearTimeout:a}catch(t){n=a}}();var u,l=[],c=!1,h=-1;function f(){c&&u&&(c=!1,u.length?l=u.concat(l):h=-1,l.length&&p())}function p(){if(!c){var t=s(f);c=!0;for(var e=l.length;e;){for(u=l,l=[];++h<e;)u&&u[h].run();h=-1,e=l.length}u=null,c=!1,function(t){if(n===clearTimeout)return clearTimeout(t);if((n===a||!n)&&clearTimeout)return n=clearTimeout,clearTimeout(t);try{n(t)}catch(e){try{return n.call(null,t)}catch(e){return n.call(this,t)}}}(t)}}function g(t,e){this.fun=t,this.array=e}function d(){}o.nextTick=function(t){var e=new Array(arguments.length-1);if(arguments.length>1)for(var r=1;r<arguments.length;r++)e[r-1]=arguments[r];l.push(new g(t,e)),1!==l.length||c||s(p)},g.prototype.run=function(){this.fun.apply(null,this.array)},o.title="browser",o.browser=!0,o.env={},o.argv=[],o.version="",o.versions={},o.on=d,o.addListener=d,o.once=d,o.off=d,o.removeListener=d,o.removeAllListeners=d,o.emit=d,o.prependListener=d,o.prependOnceListener=d,o.listeners=function(t){return[]},o.binding=function(t){throw new Error("process.binding is not supported")},o.cwd=function(){return"/"},o.chdir=function(t){throw new Error("process.chdir is not supported")},o.umask=function(){return 0}},function(t,e,r){"use strict";r.r(e);var n=r(6),o=r.n(n),i=r(3),a=r.n(i);function s(t){return""===t?t:"true"===t||"1"==t}var u=function(t,e){return new Promise((function(e,r){var n=new XMLHttpRequest;n.responseType="blob",n.onload=function(){var t=new FileReader;t.onloadend=function(){e(t.result)},t.readAsArrayBuffer(n.response)},n.open("GET",t),n.send()}))},l=r(9);var c=function(t,e,r,n,o,i,a,s){var u,l="function"==typeof t?t.options:t;if(e&&(l.render=e,l.staticRenderFns=r,l._compiled=!0),n&&(l.functional=!0),i&&(l._scopeId="data-v-"+i),a?(u=function(t){(t=t||this.$vnode&&this.$vnode.ssrContext||this.parent&&this.parent.$vnode&&this.parent.$vnode.ssrContext)||"undefined"==typeof __VUE_SSR_CONTEXT__||(t=__VUE_SSR_CONTEXT__),o&&o.call(this,t),t&&t._registeredComponents&&t._registeredComponents.add(a)},l._ssrRegister=u):o&&(u=s?function(){o.call(this,(l.functional?this.parent:this).$root.$options.shadowRoot)}:o),u)if(l.functional){l._injectStyles=u;var c=l.render;l.render=function(t,e){return u.call(e),c(t,e)}}else{var h=l.beforeCreate;l.beforeCreate=h?[].concat(h,u):[u]}return{exports:t,options:l}}({props:{text:{type:String,required:!0},qid:{type:String},correctLevel:{type:Number,default:1},size:{type:Number,default:200},margin:{type:Number,default:20},colorDark:{type:String,default:"#000000"},colorLight:{type:String,default:"#FFFFFF"},bgSrc:{type:String,default:void 0},background:{type:String,default:"rgba(0,0,0,0)"},backgroundDimming:{type:String,default:"rgba(0,0,0,0)"},logoSrc:{type:String,default:void 0},logoBackgroundColor:{type:String,default:"rgba(255,255,255,1)"},gifBgSrc:{type:String,default:void 0},logoScale:{type:Number,default:.2},logoMargin:{type:Number,default:0},logoCornerRadius:{type:Number,default:8},whiteMargin:{type:[Boolean,String],default:!0},dotScale:{type:Number,default:1},autoColor:{type:[Boolean,String],default:!0},binarize:{type:[Boolean,String],default:!1},binarizeThreshold:{type:Number,default:128},callback:{type:Function,default:function(){}},bindElement:{type:Boolean,default:!0},backgroundColor:{type:String,default:"#FFFFFF"},components:{default:function(){return{data:{scale:1},timing:{scale:1,protectors:!1},alignment:{scale:1,protectors:!1},cornerAlignment:{scale:1,protectors:!0}}}}},name:"vue-qr",data:function(){return{imgUrl:""}},watch:{$props:{deep:!0,handler:function(){this.main()}}},mounted:function(){this.main()},methods:{main:function(){var t=this;return o()(a.a.mark((function e(){var r,n,o,i;return a.a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(!t.gifBgSrc){e.next=7;break}return e.next=3,u(t.gifBgSrc);case 3:return r=e.sent,n=t.logoSrc,t.render(void 0,n,r),e.abrupt("return");case 7:o=t.bgSrc,i=t.logoSrc,t.render(o,i);case 10:case"end":return e.stop()}}),e)})))()},render:function(t,e,r){var n=this;return o()(a.a.mark((function o(){var i;return a.a.wrap((function(o){for(;;)switch(o.prev=o.next){case 0:i=n,new l.a({gifBackground:r,text:i.text,size:i.size,margin:i.margin,colorDark:i.colorDark,colorLight:i.colorLight,backgroundColor:i.backgroundColor,backgroundImage:t,backgroundDimming:i.backgroundDimming,logoImage:e,logoScale:i.logoScale,logoBackgroundColor:i.logoBackgroundColor,correctLevel:i.correctLevel,logoMargin:i.logoMargin,logoCornerRadius:i.logoCornerRadius,whiteMargin:s(i.whiteMargin),dotScale:i.dotScale,autoColor:s(i.autoColor),binarize:s(i.binarize),binarizeThreshold:i.binarizeThreshold,components:i.components}).draw().then((function(t){n.imgUrl=t,i.callback&&i.callback(t,i.qid)}));case 2:case"end":return o.stop()}}),o)})))()}}},(function(){var t=this.$createElement,e=this._self._c||t;return this.bindElement?e("img",{staticStyle:{display:"inline-block"},attrs:{src:this.imgUrl}}):this._e()}),[],!1,null,null,null).exports;c.install=function(t){return t.component(c.name,c)};var h=c,f=[h];"undefined"!=typeof window&&window.Vue&&function(t){f.map((function(e){t.component(e.name,e)}))}(window.Vue);e.default=h}])}));
//# sourceMappingURL=vue-qr.js.map
This diff could not be displayed because it is too large.
<div id="app">
</div>
<script src="./node_modules/vue/dist/vue.js"></script>
<script src="/dist/vue-qr.js"></script>
tidelift: "npm/brace-expansion"
patreon: juliangruber
MIT License
Copyright (c) 2013 Julian Gruber <julian@juliangruber.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
# brace-expansion
[Brace expansion](https://www.gnu.org/software/bash/manual/html_node/Brace-Expansion.html),
as known from sh/bash, in JavaScript.
[![build status](https://secure.travis-ci.org/juliangruber/brace-expansion.svg)](http://travis-ci.org/juliangruber/brace-expansion)
[![downloads](https://img.shields.io/npm/dm/brace-expansion.svg)](https://www.npmjs.org/package/brace-expansion)
[![Greenkeeper badge](https://badges.greenkeeper.io/juliangruber/brace-expansion.svg)](https://greenkeeper.io/)
[![testling badge](https://ci.testling.com/juliangruber/brace-expansion.png)](https://ci.testling.com/juliangruber/brace-expansion)
## Example
```js
var expand = require('brace-expansion');
expand('file-{a,b,c}.jpg')
// => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg']
expand('-v{,,}')
// => ['-v', '-v', '-v']
expand('file{0..2}.jpg')
// => ['file0.jpg', 'file1.jpg', 'file2.jpg']
expand('file-{a..c}.jpg')
// => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg']
expand('file{2..0}.jpg')
// => ['file2.jpg', 'file1.jpg', 'file0.jpg']
expand('file{0..4..2}.jpg')
// => ['file0.jpg', 'file2.jpg', 'file4.jpg']
expand('file-{a..e..2}.jpg')
// => ['file-a.jpg', 'file-c.jpg', 'file-e.jpg']
expand('file{00..10..5}.jpg')
// => ['file00.jpg', 'file05.jpg', 'file10.jpg']
expand('{{A..C},{a..c}}')
// => ['A', 'B', 'C', 'a', 'b', 'c']
expand('ppp{,config,oe{,conf}}')
// => ['ppp', 'pppconfig', 'pppoe', 'pppoeconf']
```
## API
```js
var expand = require('brace-expansion');
```
### var expanded = expand(str)
Return an array of all possible and valid expansions of `str`. If none are
found, `[str]` is returned.
Valid expansions are:
```js
/^(.*,)+(.+)?$/
// {a,b,...}
```
A comma separated list of options, like `{a,b}` or `{a,{b,c}}` or `{,a,}`.
```js
/^-?\d+\.\.-?\d+(\.\.-?\d+)?$/
// {x..y[..incr]}
```
A numeric sequence from `x` to `y` inclusive, with optional increment.
If `x` or `y` start with a leading `0`, all the numbers will be padded
to have equal length. Negative numbers and backwards iteration work too.
```js
/^-?\d+\.\.-?\d+(\.\.-?\d+)?$/
// {x..y[..incr]}
```
An alphabetic sequence from `x` to `y` inclusive, with optional increment.
`x` and `y` must be exactly one character, and if given, `incr` must be a
number.
For compatibility reasons, the string `${` is not eligible for brace expansion.
## Installation
With [npm](https://npmjs.org) do:
```bash
npm install brace-expansion
```
## Contributors
- [Julian Gruber](https://github.com/juliangruber)
- [Isaac Z. Schlueter](https://github.com/isaacs)
## Sponsors
This module is proudly supported by my [Sponsors](https://github.com/juliangruber/sponsors)!
Do you want to support modules like this to improve their quality, stability and weigh in on new features? Then please consider donating to my [Patreon](https://www.patreon.com/juliangruber). Not sure how much of my modules you're using? Try [feross/thanks](https://github.com/feross/thanks)!
## Security contact information
To report a security vulnerability, please use the
[Tidelift security contact](https://tidelift.com/security).
Tidelift will coordinate the fix and disclosure.
## License
(MIT)
Copyright (c) 2013 Julian Gruber &lt;julian@juliangruber.com&gt;
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
var balanced = require('balanced-match');
module.exports = expandTop;
var escSlash = '\0SLASH'+Math.random()+'\0';
var escOpen = '\0OPEN'+Math.random()+'\0';
var escClose = '\0CLOSE'+Math.random()+'\0';
var escComma = '\0COMMA'+Math.random()+'\0';
var escPeriod = '\0PERIOD'+Math.random()+'\0';
function numeric(str) {
return parseInt(str, 10) == str
? parseInt(str, 10)
: str.charCodeAt(0);
}
function escapeBraces(str) {
return str.split('\\\\').join(escSlash)
.split('\\{').join(escOpen)
.split('\\}').join(escClose)
.split('\\,').join(escComma)
.split('\\.').join(escPeriod);
}
function unescapeBraces(str) {
return str.split(escSlash).join('\\')
.split(escOpen).join('{')
.split(escClose).join('}')
.split(escComma).join(',')
.split(escPeriod).join('.');
}
// Basically just str.split(","), but handling cases
// where we have nested braced sections, which should be
// treated as individual members, like {a,{b,c},d}
function parseCommaParts(str) {
if (!str)
return [''];
var parts = [];
var m = balanced('{', '}', str);
if (!m)
return str.split(',');
var pre = m.pre;
var body = m.body;
var post = m.post;
var p = pre.split(',');
p[p.length-1] += '{' + body + '}';
var postParts = parseCommaParts(post);
if (post.length) {
p[p.length-1] += postParts.shift();
p.push.apply(p, postParts);
}
parts.push.apply(parts, p);
return parts;
}
function expandTop(str) {
if (!str)
return [];
// I don't know why Bash 4.3 does this, but it does.
// Anything starting with {} will have the first two bytes preserved
// but *only* at the top level, so {},a}b will not expand to anything,
// but a{},b}c will be expanded to [a}c,abc].
// One could argue that this is a bug in Bash, but since the goal of
// this module is to match Bash's rules, we escape a leading {}
if (str.substr(0, 2) === '{}') {
str = '\\{\\}' + str.substr(2);
}
return expand(escapeBraces(str), true).map(unescapeBraces);
}
function embrace(str) {
return '{' + str + '}';
}
function isPadded(el) {
return /^-?0\d/.test(el);
}
function lte(i, y) {
return i <= y;
}
function gte(i, y) {
return i >= y;
}
function expand(str, isTop) {
var expansions = [];
var m = balanced('{', '}', str);
if (!m) return [str];
// no need to expand pre, since it is guaranteed to be free of brace-sets
var pre = m.pre;
var post = m.post.length
? expand(m.post, false)
: [''];
if (/\$$/.test(m.pre)) {
for (var k = 0; k < post.length; k++) {
var expansion = pre+ '{' + m.body + '}' + post[k];
expansions.push(expansion);
}
} else {
var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
var isSequence = isNumericSequence || isAlphaSequence;
var isOptions = m.body.indexOf(',') >= 0;
if (!isSequence && !isOptions) {
// {a},b}
if (m.post.match(/,.*\}/)) {
str = m.pre + '{' + m.body + escClose + m.post;
return expand(str);
}
return [str];
}
var n;
if (isSequence) {
n = m.body.split(/\.\./);
} else {
n = parseCommaParts(m.body);
if (n.length === 1) {
// x{{a,b}}y ==> x{a}y x{b}y
n = expand(n[0], false).map(embrace);
if (n.length === 1) {
return post.map(function(p) {
return m.pre + n[0] + p;
});
}
}
}
// at this point, n is the parts, and we know it's not a comma set
// with a single entry.
var N;
if (isSequence) {
var x = numeric(n[0]);
var y = numeric(n[1]);
var width = Math.max(n[0].length, n[1].length)
var incr = n.length == 3
? Math.abs(numeric(n[2]))
: 1;
var test = lte;
var reverse = y < x;
if (reverse) {
incr *= -1;
test = gte;
}
var pad = n.some(isPadded);
N = [];
for (var i = x; test(i, y); i += incr) {
var c;
if (isAlphaSequence) {
c = String.fromCharCode(i);
if (c === '\\')
c = '';
} else {
c = String(i);
if (pad) {
var need = width - c.length;
if (need > 0) {
var z = new Array(need + 1).join('0');
if (i < 0)
c = '-' + z + c.slice(1);
else
c = z + c;
}
}
}
N.push(c);
}
} else {
N = [];
for (var j = 0; j < n.length; j++) {
N.push.apply(N, expand(n[j], false));
}
}
for (var j = 0; j < N.length; j++) {
for (var k = 0; k < post.length; k++) {
var expansion = pre + N[j] + post[k];
if (!isTop || isSequence || expansion)
expansions.push(expansion);
}
}
}
return expansions;
}
{
"_from": "brace-expansion@^2.0.1",
"_id": "brace-expansion@2.0.1",
"_inBundle": false,
"_integrity": "sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==",
"_location": "/vue-qr/brace-expansion",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "brace-expansion@^2.0.1",
"name": "brace-expansion",
"escapedName": "brace-expansion",
"rawSpec": "^2.0.1",
"saveSpec": null,
"fetchSpec": "^2.0.1"
},
"_requiredBy": [
"/vue-qr/minimatch"
],
"_resolved": "https://registry.npmmirror.com/brace-expansion/-/brace-expansion-2.0.1.tgz",
"_shasum": "1edc459e0f0c548486ecf9fc99f2221364b9a0ae",
"_spec": "brace-expansion@^2.0.1",
"_where": "/Users/zhanghao/brcode/br-client/node_modules/vue-qr/node_modules/minimatch",
"author": {
"name": "Julian Gruber",
"email": "mail@juliangruber.com",
"url": "http://juliangruber.com"
},
"bugs": {
"url": "https://github.com/juliangruber/brace-expansion/issues"
},
"bundleDependencies": false,
"dependencies": {
"balanced-match": "^1.0.0"
},
"deprecated": false,
"description": "Brace expansion as known from sh/bash",
"devDependencies": {
"@c4312/matcha": "^1.3.1",
"tape": "^4.6.0"
},
"homepage": "https://github.com/juliangruber/brace-expansion",
"keywords": [],
"license": "MIT",
"main": "index.js",
"name": "brace-expansion",
"repository": {
"type": "git",
"url": "git://github.com/juliangruber/brace-expansion.git"
},
"scripts": {
"bench": "matcha test/perf/bench.js",
"gentest": "bash test/generate.sh",
"test": "tape test/*.js"
},
"testling": {
"files": "test/*.js",
"browsers": [
"ie/8..latest",
"firefox/20..latest",
"firefox/nightly",
"chrome/25..latest",
"chrome/canary",
"opera/12..latest",
"opera/next",
"safari/5.1..latest",
"ipad/6.0..latest",
"iphone/6.0..latest",
"android-browser/4.2..latest"
]
},
"version": "2.0.1"
}
The ISC License
Copyright (c) 2009-2022 Isaac Z. Schlueter and Contributors
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
# Glob
Match files using the patterns the shell uses, like stars and stuff.
[![Build Status](https://travis-ci.org/isaacs/node-glob.svg?branch=master)](https://travis-ci.org/isaacs/node-glob/) [![Build Status](https://ci.appveyor.com/api/projects/status/kd7f3yftf7unxlsx?svg=true)](https://ci.appveyor.com/project/isaacs/node-glob) [![Coverage Status](https://coveralls.io/repos/isaacs/node-glob/badge.svg?branch=master&service=github)](https://coveralls.io/github/isaacs/node-glob?branch=master)
This is a glob implementation in JavaScript. It uses the `minimatch`
library to do its matching.
![a fun cartoon logo made of glob characters](logo/glob.png)
## Usage
Install with npm
```
npm i glob
```
```javascript
var glob = require("glob")
// options is optional
glob("**/*.js", options, function (er, files) {
// files is an array of filenames.
// If the `nonull` option is set, and nothing
// was found, then files is ["**/*.js"]
// er is an error object or null.
})
```
## Glob Primer
"Globs" are the patterns you type when you do stuff like `ls *.js` on
the command line, or put `build/*` in a `.gitignore` file.
Before parsing the path part patterns, braced sections are expanded
into a set. Braced sections start with `{` and end with `}`, with any
number of comma-delimited sections within. Braced sections may contain
slash characters, so `a{/b/c,bcd}` would expand into `a/b/c` and `abcd`.
The following characters have special magic meaning when used in a
path portion:
* `*` Matches 0 or more characters in a single path portion
* `?` Matches 1 character
* `[...]` Matches a range of characters, similar to a RegExp range.
If the first character of the range is `!` or `^` then it matches
any character not in the range.
* `!(pattern|pattern|pattern)` Matches anything that does not match
any of the patterns provided.
* `?(pattern|pattern|pattern)` Matches zero or one occurrence of the
patterns provided.
* `+(pattern|pattern|pattern)` Matches one or more occurrences of the
patterns provided.
* `*(a|b|c)` Matches zero or more occurrences of the patterns provided
* `@(pattern|pat*|pat?erN)` Matches exactly one of the patterns
provided
* `**` If a "globstar" is alone in a path portion, then it matches
zero or more directories and subdirectories searching for matches.
It does not crawl symlinked directories.
### Dots
If a file or directory path portion has a `.` as the first character,
then it will not match any glob pattern unless that pattern's
corresponding path part also has a `.` as its first character.
For example, the pattern `a/.*/c` would match the file at `a/.b/c`.
However the pattern `a/*/c` would not, because `*` does not start with
a dot character.
You can make glob treat dots as normal characters by setting
`dot:true` in the options.
### Basename Matching
If you set `matchBase:true` in the options, and the pattern has no
slashes in it, then it will seek for any file anywhere in the tree
with a matching basename. For example, `*.js` would match
`test/simple/basic.js`.
### Empty Sets
If no matching files are found, then an empty array is returned. This
differs from the shell, where the pattern itself is returned. For
example:
$ echo a*s*d*f
a*s*d*f
To get the bash-style behavior, set the `nonull:true` in the options.
### See Also:
* `man sh`
* `man bash` (Search for "Pattern Matching")
* `man 3 fnmatch`
* `man 5 gitignore`
* [minimatch documentation](https://github.com/isaacs/minimatch)
## glob.hasMagic(pattern, [options])
Returns `true` if there are any special characters in the pattern, and
`false` otherwise.
Note that the options affect the results. If `noext:true` is set in
the options object, then `+(a|b)` will not be considered a magic
pattern. If the pattern has a brace expansion, like `a/{b/c,x/y}`
then that is considered magical, unless `nobrace:true` is set in the
options.
## glob(pattern, [options], cb)
* `pattern` `{String}` Pattern to be matched
* `options` `{Object}`
* `cb` `{Function}`
* `err` `{Error | null}`
* `matches` `{Array<String>}` filenames found matching the pattern
Perform an asynchronous glob search.
## glob.sync(pattern, [options])
* `pattern` `{String}` Pattern to be matched
* `options` `{Object}`
* return: `{Array<String>}` filenames found matching the pattern
Perform a synchronous glob search.
## Class: glob.Glob
Create a Glob object by instantiating the `glob.Glob` class.
```javascript
var Glob = require("glob").Glob
var mg = new Glob(pattern, options, cb)
```
It's an EventEmitter, and starts walking the filesystem to find matches
immediately.
### new glob.Glob(pattern, [options], [cb])
* `pattern` `{String}` pattern to search for
* `options` `{Object}`
* `cb` `{Function}` Called when an error occurs, or matches are found
* `err` `{Error | null}`
* `matches` `{Array<String>}` filenames found matching the pattern
Note that if the `sync` flag is set in the options, then matches will
be immediately available on the `g.found` member.
### Properties
* `minimatch` The minimatch object that the glob uses.
* `options` The options object passed in.
* `aborted` Boolean which is set to true when calling `abort()`. There
is no way at this time to continue a glob search after aborting, but
you can re-use the statCache to avoid having to duplicate syscalls.
* `cache` Convenience object. Each field has the following possible
values:
* `false` - Path does not exist
* `true` - Path exists
* `'FILE'` - Path exists, and is not a directory
* `'DIR'` - Path exists, and is a directory
* `[file, entries, ...]` - Path exists, is a directory, and the
array value is the results of `fs.readdir`
* `statCache` Cache of `fs.stat` results, to prevent statting the same
path multiple times.
* `symlinks` A record of which paths are symbolic links, which is
relevant in resolving `**` patterns.
* `realpathCache` An optional object which is passed to `fs.realpath`
to minimize unnecessary syscalls. It is stored on the instantiated
Glob object, and may be re-used.
### Events
* `end` When the matching is finished, this is emitted with all the
matches found. If the `nonull` option is set, and no match was found,
then the `matches` list contains the original pattern. The matches
are sorted, unless the `nosort` flag is set.
* `match` Every time a match is found, this is emitted with the specific
thing that matched. It is not deduplicated or resolved to a realpath.
* `error` Emitted when an unexpected error is encountered, or whenever
any fs error occurs if `options.strict` is set.
* `abort` When `abort()` is called, this event is raised.
### Methods
* `pause` Temporarily stop the search
* `resume` Resume the search
* `abort` Stop the search forever
### Options
All the options that can be passed to Minimatch can also be passed to
Glob to change pattern matching behavior. Also, some have been added,
or have glob-specific ramifications.
All options are false by default, unless otherwise noted.
All options are added to the Glob object, as well.
If you are running many `glob` operations, you can pass a Glob object
as the `options` argument to a subsequent operation to shortcut some
`stat` and `readdir` calls. At the very least, you may pass in shared
`symlinks`, `statCache`, `realpathCache`, and `cache` options, so that
parallel glob operations will be sped up by sharing information about
the filesystem.
* `cwd` The current working directory in which to search. Defaults
to `process.cwd()`.
* `root` The place where patterns starting with `/` will be mounted
onto. Defaults to `path.resolve(options.cwd, "/")` (`/` on Unix
systems, and `C:\` or some such on Windows.)
* `dot` Include `.dot` files in normal matches and `globstar` matches.
Note that an explicit dot in a portion of the pattern will always
match dot files.
* `nomount` By default, a pattern starting with a forward-slash will be
"mounted" onto the root setting, so that a valid filesystem path is
returned. Set this flag to disable that behavior.
* `mark` Add a `/` character to directory matches. Note that this
requires additional stat calls.
* `nosort` Don't sort the results.
* `stat` Set to true to stat *all* results. This reduces performance
somewhat, and is completely unnecessary, unless `readdir` is presumed
to be an untrustworthy indicator of file existence.
* `silent` When an unusual error is encountered when attempting to
read a directory, a warning will be printed to stderr. Set the
`silent` option to true to suppress these warnings.
* `strict` When an unusual error is encountered when attempting to
read a directory, the process will just continue on in search of
other matches. Set the `strict` option to raise an error in these
cases.
* `cache` See `cache` property above. Pass in a previously generated
cache object to save some fs calls.
* `statCache` A cache of results of filesystem information, to prevent
unnecessary stat calls. While it should not normally be necessary
to set this, you may pass the statCache from one glob() call to the
options object of another, if you know that the filesystem will not
change between calls. (See "Race Conditions" below.)
* `symlinks` A cache of known symbolic links. You may pass in a
previously generated `symlinks` object to save `lstat` calls when
resolving `**` matches.
* `sync` DEPRECATED: use `glob.sync(pattern, opts)` instead.
* `nounique` In some cases, brace-expanded patterns can result in the
same file showing up multiple times in the result set. By default,
this implementation prevents duplicates in the result set. Set this
flag to disable that behavior.
* `nonull` Set to never return an empty set, instead returning a set
containing the pattern itself. This is the default in glob(3).
* `debug` Set to enable debug logging in minimatch and glob.
* `nobrace` Do not expand `{a,b}` and `{1..3}` brace sets.
* `noglobstar` Do not match `**` against multiple filenames. (Ie,
treat it as a normal `*` instead.)
* `noext` Do not match `+(a|b)` "extglob" patterns.
* `nocase` Perform a case-insensitive match. Note: on
case-insensitive filesystems, non-magic patterns will match by
default, since `stat` and `readdir` will not raise errors.
* `matchBase` Perform a basename-only match if the pattern does not
contain any slash characters. That is, `*.js` would be treated as
equivalent to `**/*.js`, matching all js files in all directories.
* `nodir` Do not match directories, only files. (Note: to match
*only* directories, simply put a `/` at the end of the pattern.)
* `ignore` Add a pattern or an array of glob patterns to exclude matches.
Note: `ignore` patterns are *always* in `dot:true` mode, regardless
of any other settings.
* `follow` Follow symlinked directories when expanding `**` patterns.
Note that this can result in a lot of duplicate references in the
presence of cyclic links.
* `realpath` Set to true to call `fs.realpath` on all of the results.
In the case of a symlink that cannot be resolved, the full absolute
path to the matched entry is returned (though it will usually be a
broken symlink)
* `absolute` Set to true to always receive absolute paths for matched
files. Unlike `realpath`, this also affects the values returned in
the `match` event.
* `fs` File-system object with Node's `fs` API. By default, the built-in
`fs` module will be used. Set to a volume provided by a library like
`memfs` to avoid using the "real" file-system.
## Comparisons to other fnmatch/glob implementations
While strict compliance with the existing standards is a worthwhile
goal, some discrepancies exist between node-glob and other
implementations, and are intentional.
The double-star character `**` is supported by default, unless the
`noglobstar` flag is set. This is supported in the manner of bsdglob
and bash 4.3, where `**` only has special significance if it is the only
thing in a path part. That is, `a/**/b` will match `a/x/y/b`, but
`a/**b` will not.
Note that symlinked directories are not crawled as part of a `**`,
though their contents may match against subsequent portions of the
pattern. This prevents infinite loops and duplicates and the like.
If an escaped pattern has no matches, and the `nonull` flag is set,
then glob returns the pattern as-provided, rather than
interpreting the character escapes. For example,
`glob.match([], "\\*a\\?")` will return `"\\*a\\?"` rather than
`"*a?"`. This is akin to setting the `nullglob` option in bash, except
that it does not resolve escaped pattern characters.
If brace expansion is not disabled, then it is performed before any
other interpretation of the glob pattern. Thus, a pattern like
`+(a|{b),c)}`, which would not be valid in bash or zsh, is expanded
**first** into the set of `+(a|b)` and `+(a|c)`, and those patterns are
checked for validity. Since those two are valid, matching proceeds.
### Comments and Negation
Previously, this module let you mark a pattern as a "comment" if it
started with a `#` character, or a "negated" pattern if it started
with a `!` character.
These options were deprecated in version 5, and removed in version 6.
To specify things that should not match, use the `ignore` option.
## Windows
**Please only use forward-slashes in glob expressions.**
Though windows uses either `/` or `\` as its path separator, only `/`
characters are used by this glob implementation. You must use
forward-slashes **only** in glob expressions. Back-slashes will always
be interpreted as escape characters, not path separators.
Results from absolute patterns such as `/foo/*` are mounted onto the
root setting using `path.join`. On windows, this will by default result
in `/foo/*` matching `C:\foo\bar.txt`.
## Race Conditions
Glob searching, by its very nature, is susceptible to race conditions,
since it relies on directory walking and such.
As a result, it is possible that a file that exists when glob looks for
it may have been deleted or modified by the time it returns the result.
As part of its internal implementation, this program caches all stat
and readdir calls that it makes, in order to cut down on system
overhead. However, this also makes it even more susceptible to races,
especially if the cache or statCache objects are reused between glob
calls.
Users are thus advised not to use a glob result as a guarantee of
filesystem state in the face of rapid changes. For the vast majority
of operations, this is never a problem.
## Glob Logo
Glob's logo was created by [Tanya Brassie](http://tanyabrassie.com/). Logo files can be found [here](https://github.com/isaacs/node-glob/tree/master/logo).
The logo is licensed under a [Creative Commons Attribution-ShareAlike 4.0 International License](https://creativecommons.org/licenses/by-sa/4.0/).
## Contributing
Any change to behavior (including bugfixes) must come with a test.
Patches that fail tests or reduce performance will be rejected.
```
# to run tests
npm test
# to re-generate test fixtures
npm run test-regen
# to benchmark against bash/zsh
npm run bench
# to profile javascript
npm run prof
```
![](oh-my-glob.gif)
exports.setopts = setopts
exports.ownProp = ownProp
exports.makeAbs = makeAbs
exports.finish = finish
exports.mark = mark
exports.isIgnored = isIgnored
exports.childrenIgnored = childrenIgnored
function ownProp (obj, field) {
return Object.prototype.hasOwnProperty.call(obj, field)
}
var fs = require("fs")
var path = require("path")
var minimatch = require("minimatch")
var isAbsolute = require("path").isAbsolute
var Minimatch = minimatch.Minimatch
function alphasort (a, b) {
return a.localeCompare(b, 'en')
}
function setupIgnores (self, options) {
self.ignore = options.ignore || []
if (!Array.isArray(self.ignore))
self.ignore = [self.ignore]
if (self.ignore.length) {
self.ignore = self.ignore.map(ignoreMap)
}
}
// ignore patterns are always in dot:true mode.
function ignoreMap (pattern) {
var gmatcher = null
if (pattern.slice(-3) === '/**') {
var gpattern = pattern.replace(/(\/\*\*)+$/, '')
gmatcher = new Minimatch(gpattern, { dot: true })
}
return {
matcher: new Minimatch(pattern, { dot: true }),
gmatcher: gmatcher
}
}
function setopts (self, pattern, options) {
if (!options)
options = {}
// base-matching: just use globstar for that.
if (options.matchBase && -1 === pattern.indexOf("/")) {
if (options.noglobstar) {
throw new Error("base matching requires globstar")
}
pattern = "**/" + pattern
}
self.silent = !!options.silent
self.pattern = pattern
self.strict = options.strict !== false
self.realpath = !!options.realpath
self.realpathCache = options.realpathCache || Object.create(null)
self.follow = !!options.follow
self.dot = !!options.dot
self.mark = !!options.mark
self.nodir = !!options.nodir
if (self.nodir)
self.mark = true
self.sync = !!options.sync
self.nounique = !!options.nounique
self.nonull = !!options.nonull
self.nosort = !!options.nosort
self.nocase = !!options.nocase
self.stat = !!options.stat
self.noprocess = !!options.noprocess
self.absolute = !!options.absolute
self.fs = options.fs || fs
self.maxLength = options.maxLength || Infinity
self.cache = options.cache || Object.create(null)
self.statCache = options.statCache || Object.create(null)
self.symlinks = options.symlinks || Object.create(null)
setupIgnores(self, options)
self.changedCwd = false
var cwd = process.cwd()
if (!ownProp(options, "cwd"))
self.cwd = path.resolve(cwd)
else {
self.cwd = path.resolve(options.cwd)
self.changedCwd = self.cwd !== cwd
}
self.root = options.root || path.resolve(self.cwd, "/")
self.root = path.resolve(self.root)
// TODO: is an absolute `cwd` supposed to be resolved against `root`?
// e.g. { cwd: '/test', root: __dirname } === path.join(__dirname, '/test')
self.cwdAbs = isAbsolute(self.cwd) ? self.cwd : makeAbs(self, self.cwd)
self.nomount = !!options.nomount
if (process.platform === "win32") {
self.root = self.root.replace(/\\/g, "/")
self.cwd = self.cwd.replace(/\\/g, "/")
self.cwdAbs = self.cwdAbs.replace(/\\/g, "/")
}
// disable comments and negation in Minimatch.
// Note that they are not supported in Glob itself anyway.
options.nonegate = true
options.nocomment = true
// always treat \ in patterns as escapes, not path separators
options.allowWindowsEscape = true
self.minimatch = new Minimatch(pattern, options)
self.options = self.minimatch.options
}
function finish (self) {
var nou = self.nounique
var all = nou ? [] : Object.create(null)
for (var i = 0, l = self.matches.length; i < l; i ++) {
var matches = self.matches[i]
if (!matches || Object.keys(matches).length === 0) {
if (self.nonull) {
// do like the shell, and spit out the literal glob
var literal = self.minimatch.globSet[i]
if (nou)
all.push(literal)
else
all[literal] = true
}
} else {
// had matches
var m = Object.keys(matches)
if (nou)
all.push.apply(all, m)
else
m.forEach(function (m) {
all[m] = true
})
}
}
if (!nou)
all = Object.keys(all)
if (!self.nosort)
all = all.sort(alphasort)
// at *some* point we statted all of these
if (self.mark) {
for (var i = 0; i < all.length; i++) {
all[i] = self._mark(all[i])
}
if (self.nodir) {
all = all.filter(function (e) {
var notDir = !(/\/$/.test(e))
var c = self.cache[e] || self.cache[makeAbs(self, e)]
if (notDir && c)
notDir = c !== 'DIR' && !Array.isArray(c)
return notDir
})
}
}
if (self.ignore.length)
all = all.filter(function(m) {
return !isIgnored(self, m)
})
self.found = all
}
function mark (self, p) {
var abs = makeAbs(self, p)
var c = self.cache[abs]
var m = p
if (c) {
var isDir = c === 'DIR' || Array.isArray(c)
var slash = p.slice(-1) === '/'
if (isDir && !slash)
m += '/'
else if (!isDir && slash)
m = m.slice(0, -1)
if (m !== p) {
var mabs = makeAbs(self, m)
self.statCache[mabs] = self.statCache[abs]
self.cache[mabs] = self.cache[abs]
}
}
return m
}
// lotta situps...
function makeAbs (self, f) {
var abs = f
if (f.charAt(0) === '/') {
abs = path.join(self.root, f)
} else if (isAbsolute(f) || f === '') {
abs = f
} else if (self.changedCwd) {
abs = path.resolve(self.cwd, f)
} else {
abs = path.resolve(f)
}
if (process.platform === 'win32')
abs = abs.replace(/\\/g, '/')
return abs
}
// Return true, if pattern ends with globstar '**', for the accompanying parent directory.
// Ex:- If node_modules/** is the pattern, add 'node_modules' to ignore list along with it's contents
function isIgnored (self, path) {
if (!self.ignore.length)
return false
return self.ignore.some(function(item) {
return item.matcher.match(path) || !!(item.gmatcher && item.gmatcher.match(path))
})
}
function childrenIgnored (self, path) {
if (!self.ignore.length)
return false
return self.ignore.some(function(item) {
return !!(item.gmatcher && item.gmatcher.match(path))
})
}
// Approach:
//
// 1. Get the minimatch set
// 2. For each pattern in the set, PROCESS(pattern, false)
// 3. Store matches per-set, then uniq them
//
// PROCESS(pattern, inGlobStar)
// Get the first [n] items from pattern that are all strings
// Join these together. This is PREFIX.
// If there is no more remaining, then stat(PREFIX) and
// add to matches if it succeeds. END.
//
// If inGlobStar and PREFIX is symlink and points to dir
// set ENTRIES = []
// else readdir(PREFIX) as ENTRIES
// If fail, END
//
// with ENTRIES
// If pattern[n] is GLOBSTAR
// // handle the case where the globstar match is empty
// // by pruning it out, and testing the resulting pattern
// PROCESS(pattern[0..n] + pattern[n+1 .. $], false)
// // handle other cases.
// for ENTRY in ENTRIES (not dotfiles)
// // attach globstar + tail onto the entry
// // Mark that this entry is a globstar match
// PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true)
//
// else // not globstar
// for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot)
// Test ENTRY against pattern[n]
// If fails, continue
// If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $])
//
// Caveat:
// Cache all stats and readdirs results to minimize syscall. Since all
// we ever care about is existence and directory-ness, we can just keep
// `true` for files, and [children,...] for directories, or `false` for
// things that don't exist.
module.exports = glob
var rp = require('fs.realpath')
var minimatch = require('minimatch')
var Minimatch = minimatch.Minimatch
var inherits = require('inherits')
var EE = require('events').EventEmitter
var path = require('path')
var assert = require('assert')
var isAbsolute = require('path').isAbsolute
var globSync = require('./sync.js')
var common = require('./common.js')
var setopts = common.setopts
var ownProp = common.ownProp
var inflight = require('inflight')
var util = require('util')
var childrenIgnored = common.childrenIgnored
var isIgnored = common.isIgnored
var once = require('once')
function glob (pattern, options, cb) {
if (typeof options === 'function') cb = options, options = {}
if (!options) options = {}
if (options.sync) {
if (cb)
throw new TypeError('callback provided to sync glob')
return globSync(pattern, options)
}
return new Glob(pattern, options, cb)
}
glob.sync = globSync
var GlobSync = glob.GlobSync = globSync.GlobSync
// old api surface
glob.glob = glob
function extend (origin, add) {
if (add === null || typeof add !== 'object') {
return origin
}
var keys = Object.keys(add)
var i = keys.length
while (i--) {
origin[keys[i]] = add[keys[i]]
}
return origin
}
glob.hasMagic = function (pattern, options_) {
var options = extend({}, options_)
options.noprocess = true
var g = new Glob(pattern, options)
var set = g.minimatch.set
if (!pattern)
return false
if (set.length > 1)
return true
for (var j = 0; j < set[0].length; j++) {
if (typeof set[0][j] !== 'string')
return true
}
return false
}
glob.Glob = Glob
inherits(Glob, EE)
function Glob (pattern, options, cb) {
if (typeof options === 'function') {
cb = options
options = null
}
if (options && options.sync) {
if (cb)
throw new TypeError('callback provided to sync glob')
return new GlobSync(pattern, options)
}
if (!(this instanceof Glob))
return new Glob(pattern, options, cb)
setopts(this, pattern, options)
this._didRealPath = false
// process each pattern in the minimatch set
var n = this.minimatch.set.length
// The matches are stored as {<filename>: true,...} so that
// duplicates are automagically pruned.
// Later, we do an Object.keys() on these.
// Keep them as a list so we can fill in when nonull is set.
this.matches = new Array(n)
if (typeof cb === 'function') {
cb = once(cb)
this.on('error', cb)
this.on('end', function (matches) {
cb(null, matches)
})
}
var self = this
this._processing = 0
this._emitQueue = []
this._processQueue = []
this.paused = false
if (this.noprocess)
return this
if (n === 0)
return done()
var sync = true
for (var i = 0; i < n; i ++) {
this._process(this.minimatch.set[i], i, false, done)
}
sync = false
function done () {
--self._processing
if (self._processing <= 0) {
if (sync) {
process.nextTick(function () {
self._finish()
})
} else {
self._finish()
}
}
}
}
Glob.prototype._finish = function () {
assert(this instanceof Glob)
if (this.aborted)
return
if (this.realpath && !this._didRealpath)
return this._realpath()
common.finish(this)
this.emit('end', this.found)
}
Glob.prototype._realpath = function () {
if (this._didRealpath)
return
this._didRealpath = true
var n = this.matches.length
if (n === 0)
return this._finish()
var self = this
for (var i = 0; i < this.matches.length; i++)
this._realpathSet(i, next)
function next () {
if (--n === 0)
self._finish()
}
}
Glob.prototype._realpathSet = function (index, cb) {
var matchset = this.matches[index]
if (!matchset)
return cb()
var found = Object.keys(matchset)
var self = this
var n = found.length
if (n === 0)
return cb()
var set = this.matches[index] = Object.create(null)
found.forEach(function (p, i) {
// If there's a problem with the stat, then it means that
// one or more of the links in the realpath couldn't be
// resolved. just return the abs value in that case.
p = self._makeAbs(p)
rp.realpath(p, self.realpathCache, function (er, real) {
if (!er)
set[real] = true
else if (er.syscall === 'stat')
set[p] = true
else
self.emit('error', er) // srsly wtf right here
if (--n === 0) {
self.matches[index] = set
cb()
}
})
})
}
Glob.prototype._mark = function (p) {
return common.mark(this, p)
}
Glob.prototype._makeAbs = function (f) {
return common.makeAbs(this, f)
}
Glob.prototype.abort = function () {
this.aborted = true
this.emit('abort')
}
Glob.prototype.pause = function () {
if (!this.paused) {
this.paused = true
this.emit('pause')
}
}
Glob.prototype.resume = function () {
if (this.paused) {
this.emit('resume')
this.paused = false
if (this._emitQueue.length) {
var eq = this._emitQueue.slice(0)
this._emitQueue.length = 0
for (var i = 0; i < eq.length; i ++) {
var e = eq[i]
this._emitMatch(e[0], e[1])
}
}
if (this._processQueue.length) {
var pq = this._processQueue.slice(0)
this._processQueue.length = 0
for (var i = 0; i < pq.length; i ++) {
var p = pq[i]
this._processing--
this._process(p[0], p[1], p[2], p[3])
}
}
}
}
Glob.prototype._process = function (pattern, index, inGlobStar, cb) {
assert(this instanceof Glob)
assert(typeof cb === 'function')
if (this.aborted)
return
this._processing++
if (this.paused) {
this._processQueue.push([pattern, index, inGlobStar, cb])
return
}
//console.error('PROCESS %d', this._processing, pattern)
// Get the first [n] parts of pattern that are all strings.
var n = 0
while (typeof pattern[n] === 'string') {
n ++
}
// now n is the index of the first one that is *not* a string.
// see if there's anything else
var prefix
switch (n) {
// if not, then this is rather simple
case pattern.length:
this._processSimple(pattern.join('/'), index, cb)
return
case 0:
// pattern *starts* with some non-trivial item.
// going to readdir(cwd), but not include the prefix in matches.
prefix = null
break
default:
// pattern has some string bits in the front.
// whatever it starts with, whether that's 'absolute' like /foo/bar,
// or 'relative' like '../baz'
prefix = pattern.slice(0, n).join('/')
break
}
var remain = pattern.slice(n)
// get the list of entries.
var read
if (prefix === null)
read = '.'
else if (isAbsolute(prefix) ||
isAbsolute(pattern.map(function (p) {
return typeof p === 'string' ? p : '[*]'
}).join('/'))) {
if (!prefix || !isAbsolute(prefix))
prefix = '/' + prefix
read = prefix
} else
read = prefix
var abs = this._makeAbs(read)
//if ignored, skip _processing
if (childrenIgnored(this, read))
return cb()
var isGlobStar = remain[0] === minimatch.GLOBSTAR
if (isGlobStar)
this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb)
else
this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb)
}
Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) {
var self = this
this._readdir(abs, inGlobStar, function (er, entries) {
return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb)
})
}
Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {
// if the abs isn't a dir, then nothing can match!
if (!entries)
return cb()
// It will only match dot entries if it starts with a dot, or if
// dot is set. Stuff like @(.foo|.bar) isn't allowed.
var pn = remain[0]
var negate = !!this.minimatch.negate
var rawGlob = pn._glob
var dotOk = this.dot || rawGlob.charAt(0) === '.'
var matchedEntries = []
for (var i = 0; i < entries.length; i++) {
var e = entries[i]
if (e.charAt(0) !== '.' || dotOk) {
var m
if (negate && !prefix) {
m = !e.match(pn)
} else {
m = e.match(pn)
}
if (m)
matchedEntries.push(e)
}
}
//console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries)
var len = matchedEntries.length
// If there are no matched entries, then nothing matches.
if (len === 0)
return cb()
// if this is the last remaining pattern bit, then no need for
// an additional stat *unless* the user has specified mark or
// stat explicitly. We know they exist, since readdir returned
// them.
if (remain.length === 1 && !this.mark && !this.stat) {
if (!this.matches[index])
this.matches[index] = Object.create(null)
for (var i = 0; i < len; i ++) {
var e = matchedEntries[i]
if (prefix) {
if (prefix !== '/')
e = prefix + '/' + e
else
e = prefix + e
}
if (e.charAt(0) === '/' && !this.nomount) {
e = path.join(this.root, e)
}
this._emitMatch(index, e)
}
// This was the last one, and no stats were needed
return cb()
}
// now test all matched entries as stand-ins for that part
// of the pattern.
remain.shift()
for (var i = 0; i < len; i ++) {
var e = matchedEntries[i]
var newPattern
if (prefix) {
if (prefix !== '/')
e = prefix + '/' + e
else
e = prefix + e
}
this._process([e].concat(remain), index, inGlobStar, cb)
}
cb()
}
Glob.prototype._emitMatch = function (index, e) {
if (this.aborted)
return
if (isIgnored(this, e))
return
if (this.paused) {
this._emitQueue.push([index, e])
return
}
var abs = isAbsolute(e) ? e : this._makeAbs(e)
if (this.mark)
e = this._mark(e)
if (this.absolute)
e = abs
if (this.matches[index][e])
return
if (this.nodir) {
var c = this.cache[abs]
if (c === 'DIR' || Array.isArray(c))
return
}
this.matches[index][e] = true
var st = this.statCache[abs]
if (st)
this.emit('stat', e, st)
this.emit('match', e)
}
Glob.prototype._readdirInGlobStar = function (abs, cb) {
if (this.aborted)
return
// follow all symlinked directories forever
// just proceed as if this is a non-globstar situation
if (this.follow)
return this._readdir(abs, false, cb)
var lstatkey = 'lstat\0' + abs
var self = this
var lstatcb = inflight(lstatkey, lstatcb_)
if (lstatcb)
self.fs.lstat(abs, lstatcb)
function lstatcb_ (er, lstat) {
if (er && er.code === 'ENOENT')
return cb()
var isSym = lstat && lstat.isSymbolicLink()
self.symlinks[abs] = isSym
// If it's not a symlink or a dir, then it's definitely a regular file.
// don't bother doing a readdir in that case.
if (!isSym && lstat && !lstat.isDirectory()) {
self.cache[abs] = 'FILE'
cb()
} else
self._readdir(abs, false, cb)
}
}
Glob.prototype._readdir = function (abs, inGlobStar, cb) {
if (this.aborted)
return
cb = inflight('readdir\0'+abs+'\0'+inGlobStar, cb)
if (!cb)
return
//console.error('RD %j %j', +inGlobStar, abs)
if (inGlobStar && !ownProp(this.symlinks, abs))
return this._readdirInGlobStar(abs, cb)
if (ownProp(this.cache, abs)) {
var c = this.cache[abs]
if (!c || c === 'FILE')
return cb()
if (Array.isArray(c))
return cb(null, c)
}
var self = this
self.fs.readdir(abs, readdirCb(this, abs, cb))
}
function readdirCb (self, abs, cb) {
return function (er, entries) {
if (er)
self._readdirError(abs, er, cb)
else
self._readdirEntries(abs, entries, cb)
}
}
Glob.prototype._readdirEntries = function (abs, entries, cb) {
if (this.aborted)
return
// if we haven't asked to stat everything, then just
// assume that everything in there exists, so we can avoid
// having to stat it a second time.
if (!this.mark && !this.stat) {
for (var i = 0; i < entries.length; i ++) {
var e = entries[i]
if (abs === '/')
e = abs + e
else
e = abs + '/' + e
this.cache[e] = true
}
}
this.cache[abs] = entries
return cb(null, entries)
}
Glob.prototype._readdirError = function (f, er, cb) {
if (this.aborted)
return
// handle errors, and cache the information
switch (er.code) {
case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205
case 'ENOTDIR': // totally normal. means it *does* exist.
var abs = this._makeAbs(f)
this.cache[abs] = 'FILE'
if (abs === this.cwdAbs) {
var error = new Error(er.code + ' invalid cwd ' + this.cwd)
error.path = this.cwd
error.code = er.code
this.emit('error', error)
this.abort()
}
break
case 'ENOENT': // not terribly unusual
case 'ELOOP':
case 'ENAMETOOLONG':
case 'UNKNOWN':
this.cache[this._makeAbs(f)] = false
break
default: // some unusual error. Treat as failure.
this.cache[this._makeAbs(f)] = false
if (this.strict) {
this.emit('error', er)
// If the error is handled, then we abort
// if not, we threw out of here
this.abort()
}
if (!this.silent)
console.error('glob error', er)
break
}
return cb()
}
Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) {
var self = this
this._readdir(abs, inGlobStar, function (er, entries) {
self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb)
})
}
Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) {
//console.error('pgs2', prefix, remain[0], entries)
// no entries means not a dir, so it can never have matches
// foo.txt/** doesn't match foo.txt
if (!entries)
return cb()
// test without the globstar, and with every child both below
// and replacing the globstar.
var remainWithoutGlobStar = remain.slice(1)
var gspref = prefix ? [ prefix ] : []
var noGlobStar = gspref.concat(remainWithoutGlobStar)
// the noGlobStar pattern exits the inGlobStar state
this._process(noGlobStar, index, false, cb)
var isSym = this.symlinks[abs]
var len = entries.length
// If it's a symlink, and we're in a globstar, then stop
if (isSym && inGlobStar)
return cb()
for (var i = 0; i < len; i++) {
var e = entries[i]
if (e.charAt(0) === '.' && !this.dot)
continue
// these two cases enter the inGlobStar state
var instead = gspref.concat(entries[i], remainWithoutGlobStar)
this._process(instead, index, true, cb)
var below = gspref.concat(entries[i], remain)
this._process(below, index, true, cb)
}
cb()
}
Glob.prototype._processSimple = function (prefix, index, cb) {
// XXX review this. Shouldn't it be doing the mounting etc
// before doing stat? kinda weird?
var self = this
this._stat(prefix, function (er, exists) {
self._processSimple2(prefix, index, er, exists, cb)
})
}
Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) {
//console.error('ps2', prefix, exists)
if (!this.matches[index])
this.matches[index] = Object.create(null)
// If it doesn't exist, then just mark the lack of results
if (!exists)
return cb()
if (prefix && isAbsolute(prefix) && !this.nomount) {
var trail = /[\/\\]$/.test(prefix)
if (prefix.charAt(0) === '/') {
prefix = path.join(this.root, prefix)
} else {
prefix = path.resolve(this.root, prefix)
if (trail)
prefix += '/'
}
}
if (process.platform === 'win32')
prefix = prefix.replace(/\\/g, '/')
// Mark this as a match
this._emitMatch(index, prefix)
cb()
}
// Returns either 'DIR', 'FILE', or false
Glob.prototype._stat = function (f, cb) {
var abs = this._makeAbs(f)
var needDir = f.slice(-1) === '/'
if (f.length > this.maxLength)
return cb()
if (!this.stat && ownProp(this.cache, abs)) {
var c = this.cache[abs]
if (Array.isArray(c))
c = 'DIR'
// It exists, but maybe not how we need it
if (!needDir || c === 'DIR')
return cb(null, c)
if (needDir && c === 'FILE')
return cb()
// otherwise we have to stat, because maybe c=true
// if we know it exists, but not what it is.
}
var exists
var stat = this.statCache[abs]
if (stat !== undefined) {
if (stat === false)
return cb(null, stat)
else {
var type = stat.isDirectory() ? 'DIR' : 'FILE'
if (needDir && type === 'FILE')
return cb()
else
return cb(null, type, stat)
}
}
var self = this
var statcb = inflight('stat\0' + abs, lstatcb_)
if (statcb)
self.fs.lstat(abs, statcb)
function lstatcb_ (er, lstat) {
if (lstat && lstat.isSymbolicLink()) {
// If it's a symlink, then treat it as the target, unless
// the target does not exist, then treat it as a file.
return self.fs.stat(abs, function (er, stat) {
if (er)
self._stat2(f, abs, null, lstat, cb)
else
self._stat2(f, abs, er, stat, cb)
})
} else {
self._stat2(f, abs, er, lstat, cb)
}
}
}
Glob.prototype._stat2 = function (f, abs, er, stat, cb) {
if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) {
this.statCache[abs] = false
return cb()
}
var needDir = f.slice(-1) === '/'
this.statCache[abs] = stat
if (abs.slice(-1) === '/' && stat && !stat.isDirectory())
return cb(null, false, stat)
var c = true
if (stat)
c = stat.isDirectory() ? 'DIR' : 'FILE'
this.cache[abs] = this.cache[abs] || c
if (needDir && c === 'FILE')
return cb()
return cb(null, c, stat)
}
{
"_from": "glob@^8.0.1",
"_id": "glob@8.0.3",
"_inBundle": false,
"_integrity": "sha512-ull455NHSHI/Y1FqGaaYFaLGkNMMJbavMrEGFXG/PGrg6y7sutWHUHrz6gy6WEBH6akM1M414dWKCNs+IhKdiQ==",
"_location": "/vue-qr/glob",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "glob@^8.0.1",
"name": "glob",
"escapedName": "glob",
"rawSpec": "^8.0.1",
"saveSpec": null,
"fetchSpec": "^8.0.1"
},
"_requiredBy": [
"/vue-qr"
],
"_resolved": "https://registry.npmmirror.com/glob/-/glob-8.0.3.tgz",
"_shasum": "415c6eb2deed9e502c68fa44a272e6da6eeca42e",
"_spec": "glob@^8.0.1",
"_where": "/Users/zhanghao/brcode/br-client/node_modules/vue-qr",
"author": {
"name": "Isaac Z. Schlueter",
"email": "i@izs.me",
"url": "http://blog.izs.me/"
},
"bugs": {
"url": "https://github.com/isaacs/node-glob/issues"
},
"bundleDependencies": false,
"dependencies": {
"fs.realpath": "^1.0.0",
"inflight": "^1.0.4",
"inherits": "2",
"minimatch": "^5.0.1",
"once": "^1.3.0"
},
"deprecated": false,
"description": "a little globber",
"devDependencies": {
"memfs": "^3.2.0",
"mkdirp": "0",
"rimraf": "^2.2.8",
"tap": "^16.0.1",
"tick": "0.0.6"
},
"engines": {
"node": ">=12"
},
"files": [
"glob.js",
"sync.js",
"common.js"
],
"funding": {
"url": "https://github.com/sponsors/isaacs"
},
"homepage": "https://github.com/isaacs/node-glob#readme",
"license": "ISC",
"main": "glob.js",
"name": "glob",
"repository": {
"type": "git",
"url": "git://github.com/isaacs/node-glob.git"
},
"scripts": {
"bench": "bash benchmark.sh",
"benchclean": "node benchclean.js",
"prepublish": "npm run benchclean",
"prof": "bash prof.sh && cat profile.txt",
"profclean": "rm -f v8.log profile.txt",
"test": "tap",
"test-regen": "npm run profclean && TEST_REGEN=1 node test/00-setup.js"
},
"tap": {
"before": "test/00-setup.js",
"after": "test/zz-cleanup.js",
"statements": 90,
"branches": 90,
"functions": 90,
"lines": 90,
"jobs": 1
},
"version": "8.0.3"
}
module.exports = globSync
globSync.GlobSync = GlobSync
var rp = require('fs.realpath')
var minimatch = require('minimatch')
var Minimatch = minimatch.Minimatch
var Glob = require('./glob.js').Glob
var util = require('util')
var path = require('path')
var assert = require('assert')
var isAbsolute = require('path').isAbsolute
var common = require('./common.js')
var setopts = common.setopts
var ownProp = common.ownProp
var childrenIgnored = common.childrenIgnored
var isIgnored = common.isIgnored
function globSync (pattern, options) {
if (typeof options === 'function' || arguments.length === 3)
throw new TypeError('callback provided to sync glob\n'+
'See: https://github.com/isaacs/node-glob/issues/167')
return new GlobSync(pattern, options).found
}
function GlobSync (pattern, options) {
if (!pattern)
throw new Error('must provide pattern')
if (typeof options === 'function' || arguments.length === 3)
throw new TypeError('callback provided to sync glob\n'+
'See: https://github.com/isaacs/node-glob/issues/167')
if (!(this instanceof GlobSync))
return new GlobSync(pattern, options)
setopts(this, pattern, options)
if (this.noprocess)
return this
var n = this.minimatch.set.length
this.matches = new Array(n)
for (var i = 0; i < n; i ++) {
this._process(this.minimatch.set[i], i, false)
}
this._finish()
}
GlobSync.prototype._finish = function () {
assert.ok(this instanceof GlobSync)
if (this.realpath) {
var self = this
this.matches.forEach(function (matchset, index) {
var set = self.matches[index] = Object.create(null)
for (var p in matchset) {
try {
p = self._makeAbs(p)
var real = rp.realpathSync(p, self.realpathCache)
set[real] = true
} catch (er) {
if (er.syscall === 'stat')
set[self._makeAbs(p)] = true
else
throw er
}
}
})
}
common.finish(this)
}
GlobSync.prototype._process = function (pattern, index, inGlobStar) {
assert.ok(this instanceof GlobSync)
// Get the first [n] parts of pattern that are all strings.
var n = 0
while (typeof pattern[n] === 'string') {
n ++
}
// now n is the index of the first one that is *not* a string.
// See if there's anything else
var prefix
switch (n) {
// if not, then this is rather simple
case pattern.length:
this._processSimple(pattern.join('/'), index)
return
case 0:
// pattern *starts* with some non-trivial item.
// going to readdir(cwd), but not include the prefix in matches.
prefix = null
break
default:
// pattern has some string bits in the front.
// whatever it starts with, whether that's 'absolute' like /foo/bar,
// or 'relative' like '../baz'
prefix = pattern.slice(0, n).join('/')
break
}
var remain = pattern.slice(n)
// get the list of entries.
var read
if (prefix === null)
read = '.'
else if (isAbsolute(prefix) ||
isAbsolute(pattern.map(function (p) {
return typeof p === 'string' ? p : '[*]'
}).join('/'))) {
if (!prefix || !isAbsolute(prefix))
prefix = '/' + prefix
read = prefix
} else
read = prefix
var abs = this._makeAbs(read)
//if ignored, skip processing
if (childrenIgnored(this, read))
return
var isGlobStar = remain[0] === minimatch.GLOBSTAR
if (isGlobStar)
this._processGlobStar(prefix, read, abs, remain, index, inGlobStar)
else
this._processReaddir(prefix, read, abs, remain, index, inGlobStar)
}
GlobSync.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) {
var entries = this._readdir(abs, inGlobStar)
// if the abs isn't a dir, then nothing can match!
if (!entries)
return
// It will only match dot entries if it starts with a dot, or if
// dot is set. Stuff like @(.foo|.bar) isn't allowed.
var pn = remain[0]
var negate = !!this.minimatch.negate
var rawGlob = pn._glob
var dotOk = this.dot || rawGlob.charAt(0) === '.'
var matchedEntries = []
for (var i = 0; i < entries.length; i++) {
var e = entries[i]
if (e.charAt(0) !== '.' || dotOk) {
var m
if (negate && !prefix) {
m = !e.match(pn)
} else {
m = e.match(pn)
}
if (m)
matchedEntries.push(e)
}
}
var len = matchedEntries.length
// If there are no matched entries, then nothing matches.
if (len === 0)
return
// if this is the last remaining pattern bit, then no need for
// an additional stat *unless* the user has specified mark or
// stat explicitly. We know they exist, since readdir returned
// them.
if (remain.length === 1 && !this.mark && !this.stat) {
if (!this.matches[index])
this.matches[index] = Object.create(null)
for (var i = 0; i < len; i ++) {
var e = matchedEntries[i]
if (prefix) {
if (prefix.slice(-1) !== '/')
e = prefix + '/' + e
else
e = prefix + e
}
if (e.charAt(0) === '/' && !this.nomount) {
e = path.join(this.root, e)
}
this._emitMatch(index, e)
}
// This was the last one, and no stats were needed
return
}
// now test all matched entries as stand-ins for that part
// of the pattern.
remain.shift()
for (var i = 0; i < len; i ++) {
var e = matchedEntries[i]
var newPattern
if (prefix)
newPattern = [prefix, e]
else
newPattern = [e]
this._process(newPattern.concat(remain), index, inGlobStar)
}
}
GlobSync.prototype._emitMatch = function (index, e) {
if (isIgnored(this, e))
return
var abs = this._makeAbs(e)
if (this.mark)
e = this._mark(e)
if (this.absolute) {
e = abs
}
if (this.matches[index][e])
return
if (this.nodir) {
var c = this.cache[abs]
if (c === 'DIR' || Array.isArray(c))
return
}
this.matches[index][e] = true
if (this.stat)
this._stat(e)
}
GlobSync.prototype._readdirInGlobStar = function (abs) {
// follow all symlinked directories forever
// just proceed as if this is a non-globstar situation
if (this.follow)
return this._readdir(abs, false)
var entries
var lstat
var stat
try {
lstat = this.fs.lstatSync(abs)
} catch (er) {
if (er.code === 'ENOENT') {
// lstat failed, doesn't exist
return null
}
}
var isSym = lstat && lstat.isSymbolicLink()
this.symlinks[abs] = isSym
// If it's not a symlink or a dir, then it's definitely a regular file.
// don't bother doing a readdir in that case.
if (!isSym && lstat && !lstat.isDirectory())
this.cache[abs] = 'FILE'
else
entries = this._readdir(abs, false)
return entries
}
GlobSync.prototype._readdir = function (abs, inGlobStar) {
var entries
if (inGlobStar && !ownProp(this.symlinks, abs))
return this._readdirInGlobStar(abs)
if (ownProp(this.cache, abs)) {
var c = this.cache[abs]
if (!c || c === 'FILE')
return null
if (Array.isArray(c))
return c
}
try {
return this._readdirEntries(abs, this.fs.readdirSync(abs))
} catch (er) {
this._readdirError(abs, er)
return null
}
}
GlobSync.prototype._readdirEntries = function (abs, entries) {
// if we haven't asked to stat everything, then just
// assume that everything in there exists, so we can avoid
// having to stat it a second time.
if (!this.mark && !this.stat) {
for (var i = 0; i < entries.length; i ++) {
var e = entries[i]
if (abs === '/')
e = abs + e
else
e = abs + '/' + e
this.cache[e] = true
}
}
this.cache[abs] = entries
// mark and cache dir-ness
return entries
}
GlobSync.prototype._readdirError = function (f, er) {
// handle errors, and cache the information
switch (er.code) {
case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205
case 'ENOTDIR': // totally normal. means it *does* exist.
var abs = this._makeAbs(f)
this.cache[abs] = 'FILE'
if (abs === this.cwdAbs) {
var error = new Error(er.code + ' invalid cwd ' + this.cwd)
error.path = this.cwd
error.code = er.code
throw error
}
break
case 'ENOENT': // not terribly unusual
case 'ELOOP':
case 'ENAMETOOLONG':
case 'UNKNOWN':
this.cache[this._makeAbs(f)] = false
break
default: // some unusual error. Treat as failure.
this.cache[this._makeAbs(f)] = false
if (this.strict)
throw er
if (!this.silent)
console.error('glob error', er)
break
}
}
GlobSync.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) {
var entries = this._readdir(abs, inGlobStar)
// no entries means not a dir, so it can never have matches
// foo.txt/** doesn't match foo.txt
if (!entries)
return
// test without the globstar, and with every child both below
// and replacing the globstar.
var remainWithoutGlobStar = remain.slice(1)
var gspref = prefix ? [ prefix ] : []
var noGlobStar = gspref.concat(remainWithoutGlobStar)
// the noGlobStar pattern exits the inGlobStar state
this._process(noGlobStar, index, false)
var len = entries.length
var isSym = this.symlinks[abs]
// If it's a symlink, and we're in a globstar, then stop
if (isSym && inGlobStar)
return
for (var i = 0; i < len; i++) {
var e = entries[i]
if (e.charAt(0) === '.' && !this.dot)
continue
// these two cases enter the inGlobStar state
var instead = gspref.concat(entries[i], remainWithoutGlobStar)
this._process(instead, index, true)
var below = gspref.concat(entries[i], remain)
this._process(below, index, true)
}
}
GlobSync.prototype._processSimple = function (prefix, index) {
// XXX review this. Shouldn't it be doing the mounting etc
// before doing stat? kinda weird?
var exists = this._stat(prefix)
if (!this.matches[index])
this.matches[index] = Object.create(null)
// If it doesn't exist, then just mark the lack of results
if (!exists)
return
if (prefix && isAbsolute(prefix) && !this.nomount) {
var trail = /[\/\\]$/.test(prefix)
if (prefix.charAt(0) === '/') {
prefix = path.join(this.root, prefix)
} else {
prefix = path.resolve(this.root, prefix)
if (trail)
prefix += '/'
}
}
if (process.platform === 'win32')
prefix = prefix.replace(/\\/g, '/')
// Mark this as a match
this._emitMatch(index, prefix)
}
// Returns either 'DIR', 'FILE', or false
GlobSync.prototype._stat = function (f) {
var abs = this._makeAbs(f)
var needDir = f.slice(-1) === '/'
if (f.length > this.maxLength)
return false
if (!this.stat && ownProp(this.cache, abs)) {
var c = this.cache[abs]
if (Array.isArray(c))
c = 'DIR'
// It exists, but maybe not how we need it
if (!needDir || c === 'DIR')
return c
if (needDir && c === 'FILE')
return false
// otherwise we have to stat, because maybe c=true
// if we know it exists, but not what it is.
}
var exists
var stat = this.statCache[abs]
if (!stat) {
var lstat
try {
lstat = this.fs.lstatSync(abs)
} catch (er) {
if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) {
this.statCache[abs] = false
return false
}
}
if (lstat && lstat.isSymbolicLink()) {
try {
stat = this.fs.statSync(abs)
} catch (er) {
stat = lstat
}
} else {
stat = lstat
}
}
this.statCache[abs] = stat
var c = true
if (stat)
c = stat.isDirectory() ? 'DIR' : 'FILE'
this.cache[abs] = this.cache[abs] || c
if (needDir && c === 'FILE')
return false
return c
}
GlobSync.prototype._mark = function (p) {
return common.mark(this, p)
}
GlobSync.prototype._makeAbs = function (f) {
return common.makeAbs(this, f)
}
The ISC License
Copyright (c) 2011-2022 Isaac Z. Schlueter and Contributors
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
# minimatch
A minimal matching utility.
[![Build Status](https://travis-ci.org/isaacs/minimatch.svg?branch=master)](http://travis-ci.org/isaacs/minimatch)
This is the matching library used internally by npm.
It works by converting glob expressions into JavaScript `RegExp`
objects.
## Usage
```javascript
var minimatch = require("minimatch")
minimatch("bar.foo", "*.foo") // true!
minimatch("bar.foo", "*.bar") // false!
minimatch("bar.foo", "*.+(bar|foo)", { debug: true }) // true, and noisy!
```
## Features
Supports these glob features:
* Brace Expansion
* Extended glob matching
* "Globstar" `**` matching
See:
* `man sh`
* `man bash`
* `man 3 fnmatch`
* `man 5 gitignore`
## Windows
**Please only use forward-slashes in glob expressions.**
Though windows uses either `/` or `\` as its path separator, only `/`
characters are used by this glob implementation. You must use
forward-slashes **only** in glob expressions. Back-slashes in patterns
will always be interpreted as escape characters, not path separators.
Note that `\` or `/` _will_ be interpreted as path separators in paths on
Windows, and will match against `/` in glob expressions.
So just always use `/` in patterns.
## Minimatch Class
Create a minimatch object by instantiating the `minimatch.Minimatch` class.
```javascript
var Minimatch = require("minimatch").Minimatch
var mm = new Minimatch(pattern, options)
```
### Properties
* `pattern` The original pattern the minimatch object represents.
* `options` The options supplied to the constructor.
* `set` A 2-dimensional array of regexp or string expressions.
Each row in the
array corresponds to a brace-expanded pattern. Each item in the row
corresponds to a single path-part. For example, the pattern
`{a,b/c}/d` would expand to a set of patterns like:
[ [ a, d ]
, [ b, c, d ] ]
If a portion of the pattern doesn't have any "magic" in it
(that is, it's something like `"foo"` rather than `fo*o?`), then it
will be left as a string rather than converted to a regular
expression.
* `regexp` Created by the `makeRe` method. A single regular expression
expressing the entire pattern. This is useful in cases where you wish
to use the pattern somewhat like `fnmatch(3)` with `FNM_PATH` enabled.
* `negate` True if the pattern is negated.
* `comment` True if the pattern is a comment.
* `empty` True if the pattern is `""`.
### Methods
* `makeRe` Generate the `regexp` member if necessary, and return it.
Will return `false` if the pattern is invalid.
* `match(fname)` Return true if the filename matches the pattern, or
false otherwise.
* `matchOne(fileArray, patternArray, partial)` Take a `/`-split
filename, and match it against a single row in the `regExpSet`. This
method is mainly for internal use, but is exposed so that it can be
used by a glob-walker that needs to avoid excessive filesystem calls.
All other methods are internal, and will be called as necessary.
### minimatch(path, pattern, options)
Main export. Tests a path against the pattern using the options.
```javascript
var isJS = minimatch(file, "*.js", { matchBase: true })
```
### minimatch.filter(pattern, options)
Returns a function that tests its
supplied argument, suitable for use with `Array.filter`. Example:
```javascript
var javascripts = fileList.filter(minimatch.filter("*.js", {matchBase: true}))
```
### minimatch.match(list, pattern, options)
Match against the list of
files, in the style of fnmatch or glob. If nothing is matched, and
options.nonull is set, then return a list containing the pattern itself.
```javascript
var javascripts = minimatch.match(fileList, "*.js", {matchBase: true})
```
### minimatch.makeRe(pattern, options)
Make a regular expression object from the pattern.
## Options
All options are `false` by default.
### debug
Dump a ton of stuff to stderr.
### nobrace
Do not expand `{a,b}` and `{1..3}` brace sets.
### noglobstar
Disable `**` matching against multiple folder names.
### dot
Allow patterns to match filenames starting with a period, even if
the pattern does not explicitly have a period in that spot.
Note that by default, `a/**/b` will **not** match `a/.d/b`, unless `dot`
is set.
### noext
Disable "extglob" style patterns like `+(a|b)`.
### nocase
Perform a case-insensitive match.
### nonull
When a match is not found by `minimatch.match`, return a list containing
the pattern itself if this option is set. When not set, an empty list
is returned if there are no matches.
### matchBase
If set, then patterns without slashes will be matched
against the basename of the path if it contains slashes. For example,
`a?b` would match the path `/xyz/123/acb`, but not `/xyz/acb/123`.
### nocomment
Suppress the behavior of treating `#` at the start of a pattern as a
comment.
### nonegate
Suppress the behavior of treating a leading `!` character as negation.
### flipNegate
Returns from negate expressions the same as if they were not negated.
(Ie, true on a hit, false on a miss.)
### partial
Compare a partial path to a pattern. As long as the parts of the path that
are present are not contradicted by the pattern, it will be treated as a
match. This is useful in applications where you're walking through a
folder structure, and don't yet have the full path, but want to ensure that
you do not walk down paths that can never be a match.
For example,
```js
minimatch('/a/b', '/a/*/c/d', { partial: true }) // true, might be /a/b/c/d
minimatch('/a/b', '/**/d', { partial: true }) // true, might be /a/b/.../d
minimatch('/x/y/z', '/a/**/z', { partial: true }) // false, because x !== a
```
### windowsPathsNoEscape
Use `\\` as a path separator _only_, and _never_ as an escape
character. If set, all `\\` characters are replaced with `/` in
the pattern. Note that this makes it **impossible** to match
against paths containing literal glob pattern characters, but
allows matching with patterns constructed using `path.join()` and
`path.resolve()` on Windows platforms, mimicking the (buggy!)
behavior of earlier versions on Windows. Please use with
caution, and be mindful of [the caveat about Windows
paths](#windows).
For legacy reasons, this is also set if
`options.allowWindowsEscape` is set to the exact value `false`.
## Comparisons to other fnmatch/glob implementations
While strict compliance with the existing standards is a worthwhile
goal, some discrepancies exist between minimatch and other
implementations, and are intentional.
If the pattern starts with a `!` character, then it is negated. Set the
`nonegate` flag to suppress this behavior, and treat leading `!`
characters normally. This is perhaps relevant if you wish to start the
pattern with a negative extglob pattern like `!(a|B)`. Multiple `!`
characters at the start of a pattern will negate the pattern multiple
times.
If a pattern starts with `#`, then it is treated as a comment, and
will not match anything. Use `\#` to match a literal `#` at the
start of a line, or set the `nocomment` flag to suppress this behavior.
The double-star character `**` is supported by default, unless the
`noglobstar` flag is set. This is supported in the manner of bsdglob
and bash 4.1, where `**` only has special significance if it is the only
thing in a path part. That is, `a/**/b` will match `a/x/y/b`, but
`a/**b` will not.
If an escaped pattern has no matches, and the `nonull` flag is set,
then minimatch.match returns the pattern as-provided, rather than
interpreting the character escapes. For example,
`minimatch.match([], "\\*a\\?")` will return `"\\*a\\?"` rather than
`"*a?"`. This is akin to setting the `nullglob` option in bash, except
that it does not resolve escaped pattern characters.
If brace expansion is not disabled, then it is performed before any
other interpretation of the glob pattern. Thus, a pattern like
`+(a|{b),c)}`, which would not be valid in bash or zsh, is expanded
**first** into the set of `+(a|b)` and `+(a|c)`, and those patterns are
checked for validity. Since those two are valid, matching proceeds.
Note that `fnmatch(3)` in libc is an extremely naive string comparison
matcher, which does not do anything special for slashes. This library is
designed to be used in glob searching and file walkers, and so it does do
special things with `/`. Thus, `foo*` will not match `foo/bar` in this
library, even though it would in `fnmatch(3)`.
const isWindows = typeof process === 'object' &&
process &&
process.platform === 'win32'
module.exports = isWindows ? { sep: '\\' } : { sep: '/' }
const minimatch = module.exports = (p, pattern, options = {}) => {
assertValidPattern(pattern)
// shortcut: comments match nothing.
if (!options.nocomment && pattern.charAt(0) === '#') {
return false
}
return new Minimatch(pattern, options).match(p)
}
module.exports = minimatch
const path = require('./lib/path.js')
minimatch.sep = path.sep
const GLOBSTAR = Symbol('globstar **')
minimatch.GLOBSTAR = GLOBSTAR
const expand = require('brace-expansion')
const plTypes = {
'!': { open: '(?:(?!(?:', close: '))[^/]*?)'},
'?': { open: '(?:', close: ')?' },
'+': { open: '(?:', close: ')+' },
'*': { open: '(?:', close: ')*' },
'@': { open: '(?:', close: ')' }
}
// any single thing other than /
// don't need to escape / when using new RegExp()
const qmark = '[^/]'
// * => any number of characters
const star = qmark + '*?'
// ** when dots are allowed. Anything goes, except .. and .
// not (^ or / followed by one or two dots followed by $ or /),
// followed by anything, any number of times.
const twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?'
// not a ^ or / followed by a dot,
// followed by anything, any number of times.
const twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?'
// "abc" -> { a:true, b:true, c:true }
const charSet = s => s.split('').reduce((set, c) => {
set[c] = true
return set
}, {})
// characters that need to be escaped in RegExp.
const reSpecials = charSet('().*{}+?[]^$\\!')
// characters that indicate we have to add the pattern start
const addPatternStartSet = charSet('[.(')
// normalizes slashes.
const slashSplit = /\/+/
minimatch.filter = (pattern, options = {}) =>
(p, i, list) => minimatch(p, pattern, options)
const ext = (a, b = {}) => {
const t = {}
Object.keys(a).forEach(k => t[k] = a[k])
Object.keys(b).forEach(k => t[k] = b[k])
return t
}
minimatch.defaults = def => {
if (!def || typeof def !== 'object' || !Object.keys(def).length) {
return minimatch
}
const orig = minimatch
const m = (p, pattern, options) => orig(p, pattern, ext(def, options))
m.Minimatch = class Minimatch extends orig.Minimatch {
constructor (pattern, options) {
super(pattern, ext(def, options))
}
}
m.Minimatch.defaults = options => orig.defaults(ext(def, options)).Minimatch
m.filter = (pattern, options) => orig.filter(pattern, ext(def, options))
m.defaults = options => orig.defaults(ext(def, options))
m.makeRe = (pattern, options) => orig.makeRe(pattern, ext(def, options))
m.braceExpand = (pattern, options) => orig.braceExpand(pattern, ext(def, options))
m.match = (list, pattern, options) => orig.match(list, pattern, ext(def, options))
return m
}
// Brace expansion:
// a{b,c}d -> abd acd
// a{b,}c -> abc ac
// a{0..3}d -> a0d a1d a2d a3d
// a{b,c{d,e}f}g -> abg acdfg acefg
// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg
//
// Invalid sets are not expanded.
// a{2..}b -> a{2..}b
// a{b}c -> a{b}c
minimatch.braceExpand = (pattern, options) => braceExpand(pattern, options)
const braceExpand = (pattern, options = {}) => {
assertValidPattern(pattern)
// Thanks to Yeting Li <https://github.com/yetingli> for
// improving this regexp to avoid a ReDOS vulnerability.
if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) {
// shortcut. no need to expand.
return [pattern]
}
return expand(pattern)
}
const MAX_PATTERN_LENGTH = 1024 * 64
const assertValidPattern = pattern => {
if (typeof pattern !== 'string') {
throw new TypeError('invalid pattern')
}
if (pattern.length > MAX_PATTERN_LENGTH) {
throw new TypeError('pattern is too long')
}
}
// parse a component of the expanded set.
// At this point, no pattern may contain "/" in it
// so we're going to return a 2d array, where each entry is the full
// pattern, split on '/', and then turned into a regular expression.
// A regexp is made at the end which joins each array with an
// escaped /, and another full one which joins each regexp with |.
//
// Following the lead of Bash 4.1, note that "**" only has special meaning
// when it is the *only* thing in a path portion. Otherwise, any series
// of * is equivalent to a single *. Globstar behavior is enabled by
// default, and can be disabled by setting options.noglobstar.
const SUBPARSE = Symbol('subparse')
minimatch.makeRe = (pattern, options) =>
new Minimatch(pattern, options || {}).makeRe()
minimatch.match = (list, pattern, options = {}) => {
const mm = new Minimatch(pattern, options)
list = list.filter(f => mm.match(f))
if (mm.options.nonull && !list.length) {
list.push(pattern)
}
return list
}
// replace stuff like \* with *
const globUnescape = s => s.replace(/\\(.)/g, '$1')
const regExpEscape = s => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&')
class Minimatch {
constructor (pattern, options) {
assertValidPattern(pattern)
if (!options) options = {}
this.options = options
this.set = []
this.pattern = pattern
this.windowsPathsNoEscape = !!options.windowsPathsNoEscape ||
options.allowWindowsEscape === false
if (this.windowsPathsNoEscape) {
this.pattern = this.pattern.replace(/\\/g, '/')
}
this.regexp = null
this.negate = false
this.comment = false
this.empty = false
this.partial = !!options.partial
// make the set of regexps etc.
this.make()
}
debug () {}
make () {
const pattern = this.pattern
const options = this.options
// empty patterns and comments match nothing.
if (!options.nocomment && pattern.charAt(0) === '#') {
this.comment = true
return
}
if (!pattern) {
this.empty = true
return
}
// step 1: figure out negation, etc.
this.parseNegate()
// step 2: expand braces
let set = this.globSet = this.braceExpand()
if (options.debug) this.debug = (...args) => console.error(...args)
this.debug(this.pattern, set)
// step 3: now we have a set, so turn each one into a series of path-portion
// matching patterns.
// These will be regexps, except in the case of "**", which is
// set to the GLOBSTAR object for globstar behavior,
// and will not contain any / characters
set = this.globParts = set.map(s => s.split(slashSplit))
this.debug(this.pattern, set)
// glob --> regexps
set = set.map((s, si, set) => s.map(this.parse, this))
this.debug(this.pattern, set)
// filter out everything that didn't compile properly.
set = set.filter(s => s.indexOf(false) === -1)
this.debug(this.pattern, set)
this.set = set
}
parseNegate () {
if (this.options.nonegate) return
const pattern = this.pattern
let negate = false
let negateOffset = 0
for (let i = 0; i < pattern.length && pattern.charAt(i) === '!'; i++) {
negate = !negate
negateOffset++
}
if (negateOffset) this.pattern = pattern.substr(negateOffset)
this.negate = negate
}
// set partial to true to test if, for example,
// "/a/b" matches the start of "/*/b/*/d"
// Partial means, if you run out of file before you run
// out of pattern, then that's fine, as long as all
// the parts match.
matchOne (file, pattern, partial) {
var options = this.options
this.debug('matchOne',
{ 'this': this, file: file, pattern: pattern })
this.debug('matchOne', file.length, pattern.length)
for (var fi = 0,
pi = 0,
fl = file.length,
pl = pattern.length
; (fi < fl) && (pi < pl)
; fi++, pi++) {
this.debug('matchOne loop')
var p = pattern[pi]
var f = file[fi]
this.debug(pattern, p, f)
// should be impossible.
// some invalid regexp stuff in the set.
/* istanbul ignore if */
if (p === false) return false
if (p === GLOBSTAR) {
this.debug('GLOBSTAR', [pattern, p, f])
// "**"
// a/**/b/**/c would match the following:
// a/b/x/y/z/c
// a/x/y/z/b/c
// a/b/x/b/x/c
// a/b/c
// To do this, take the rest of the pattern after
// the **, and see if it would match the file remainder.
// If so, return success.
// If not, the ** "swallows" a segment, and try again.
// This is recursively awful.
//
// a/**/b/**/c matching a/b/x/y/z/c
// - a matches a
// - doublestar
// - matchOne(b/x/y/z/c, b/**/c)
// - b matches b
// - doublestar
// - matchOne(x/y/z/c, c) -> no
// - matchOne(y/z/c, c) -> no
// - matchOne(z/c, c) -> no
// - matchOne(c, c) yes, hit
var fr = fi
var pr = pi + 1
if (pr === pl) {
this.debug('** at the end')
// a ** at the end will just swallow the rest.
// We have found a match.
// however, it will not swallow /.x, unless
// options.dot is set.
// . and .. are *never* matched by **, for explosively
// exponential reasons.
for (; fi < fl; fi++) {
if (file[fi] === '.' || file[fi] === '..' ||
(!options.dot && file[fi].charAt(0) === '.')) return false
}
return true
}
// ok, let's see if we can swallow whatever we can.
while (fr < fl) {
var swallowee = file[fr]
this.debug('\nglobstar while', file, fr, pattern, pr, swallowee)
// XXX remove this slice. Just pass the start index.
if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) {
this.debug('globstar found match!', fr, fl, swallowee)
// found a match.
return true
} else {
// can't swallow "." or ".." ever.
// can only swallow ".foo" when explicitly asked.
if (swallowee === '.' || swallowee === '..' ||
(!options.dot && swallowee.charAt(0) === '.')) {
this.debug('dot detected!', file, fr, pattern, pr)
break
}
// ** swallows a segment, and continue.
this.debug('globstar swallow a segment, and continue')
fr++
}
}
// no match was found.
// However, in partial mode, we can't say this is necessarily over.
// If there's more *pattern* left, then
/* istanbul ignore if */
if (partial) {
// ran out of file
this.debug('\n>>> no match, partial?', file, fr, pattern, pr)
if (fr === fl) return true
}
return false
}
// something other than **
// non-magic patterns just have to match exactly
// patterns with magic have been turned into regexps.
var hit
if (typeof p === 'string') {
hit = f === p
this.debug('string match', p, f, hit)
} else {
hit = f.match(p)
this.debug('pattern match', p, f, hit)
}
if (!hit) return false
}
// Note: ending in / means that we'll get a final ""
// at the end of the pattern. This can only match a
// corresponding "" at the end of the file.
// If the file ends in /, then it can only match a
// a pattern that ends in /, unless the pattern just
// doesn't have any more for it. But, a/b/ should *not*
// match "a/b/*", even though "" matches against the
// [^/]*? pattern, except in partial mode, where it might
// simply not be reached yet.
// However, a/b/ should still satisfy a/*
// now either we fell off the end of the pattern, or we're done.
if (fi === fl && pi === pl) {
// ran out of pattern and filename at the same time.
// an exact hit!
return true
} else if (fi === fl) {
// ran out of file, but still had pattern left.
// this is ok if we're doing the match as part of
// a glob fs traversal.
return partial
} else /* istanbul ignore else */ if (pi === pl) {
// ran out of pattern, still have file left.
// this is only acceptable if we're on the very last
// empty segment of a file with a trailing slash.
// a/* should match a/b/
return (fi === fl - 1) && (file[fi] === '')
}
// should be unreachable.
/* istanbul ignore next */
throw new Error('wtf?')
}
braceExpand () {
return braceExpand(this.pattern, this.options)
}
parse (pattern, isSub) {
assertValidPattern(pattern)
const options = this.options
// shortcuts
if (pattern === '**') {
if (!options.noglobstar)
return GLOBSTAR
else
pattern = '*'
}
if (pattern === '') return ''
let re = ''
let hasMagic = !!options.nocase
let escaping = false
// ? => one single character
const patternListStack = []
const negativeLists = []
let stateChar
let inClass = false
let reClassStart = -1
let classStart = -1
let cs
let pl
let sp
// . and .. never match anything that doesn't start with .,
// even when options.dot is set.
const patternStart = pattern.charAt(0) === '.' ? '' // anything
// not (start or / followed by . or .. followed by / or end)
: options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))'
: '(?!\\.)'
const clearStateChar = () => {
if (stateChar) {
// we had some state-tracking character
// that wasn't consumed by this pass.
switch (stateChar) {
case '*':
re += star
hasMagic = true
break
case '?':
re += qmark
hasMagic = true
break
default:
re += '\\' + stateChar
break
}
this.debug('clearStateChar %j %j', stateChar, re)
stateChar = false
}
}
for (let i = 0, c; (i < pattern.length) && (c = pattern.charAt(i)); i++) {
this.debug('%s\t%s %s %j', pattern, i, re, c)
// skip over any that are escaped.
if (escaping) {
/* istanbul ignore next - completely not allowed, even escaped. */
if (c === '/') {
return false
}
if (reSpecials[c]) {
re += '\\'
}
re += c
escaping = false
continue
}
switch (c) {
/* istanbul ignore next */
case '/': {
// Should already be path-split by now.
return false
}
case '\\':
clearStateChar()
escaping = true
continue
// the various stateChar values
// for the "extglob" stuff.
case '?':
case '*':
case '+':
case '@':
case '!':
this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c)
// all of those are literals inside a class, except that
// the glob [!a] means [^a] in regexp
if (inClass) {
this.debug(' in class')
if (c === '!' && i === classStart + 1) c = '^'
re += c
continue
}
// if we already have a stateChar, then it means
// that there was something like ** or +? in there.
// Handle the stateChar, then proceed with this one.
this.debug('call clearStateChar %j', stateChar)
clearStateChar()
stateChar = c
// if extglob is disabled, then +(asdf|foo) isn't a thing.
// just clear the statechar *now*, rather than even diving into
// the patternList stuff.
if (options.noext) clearStateChar()
continue
case '(':
if (inClass) {
re += '('
continue
}
if (!stateChar) {
re += '\\('
continue
}
patternListStack.push({
type: stateChar,
start: i - 1,
reStart: re.length,
open: plTypes[stateChar].open,
close: plTypes[stateChar].close
})
// negation is (?:(?!js)[^/]*)
re += stateChar === '!' ? '(?:(?!(?:' : '(?:'
this.debug('plType %j %j', stateChar, re)
stateChar = false
continue
case ')':
if (inClass || !patternListStack.length) {
re += '\\)'
continue
}
clearStateChar()
hasMagic = true
pl = patternListStack.pop()
// negation is (?:(?!js)[^/]*)
// The others are (?:<pattern>)<type>
re += pl.close
if (pl.type === '!') {
negativeLists.push(pl)
}
pl.reEnd = re.length
continue
case '|':
if (inClass || !patternListStack.length) {
re += '\\|'
continue
}
clearStateChar()
re += '|'
continue
// these are mostly the same in regexp and glob
case '[':
// swallow any state-tracking char before the [
clearStateChar()
if (inClass) {
re += '\\' + c
continue
}
inClass = true
classStart = i
reClassStart = re.length
re += c
continue
case ']':
// a right bracket shall lose its special
// meaning and represent itself in
// a bracket expression if it occurs
// first in the list. -- POSIX.2 2.8.3.2
if (i === classStart + 1 || !inClass) {
re += '\\' + c
continue
}
// handle the case where we left a class open.
// "[z-a]" is valid, equivalent to "\[z-a\]"
// split where the last [ was, make sure we don't have
// an invalid re. if so, re-walk the contents of the
// would-be class to re-translate any characters that
// were passed through as-is
// TODO: It would probably be faster to determine this
// without a try/catch and a new RegExp, but it's tricky
// to do safely. For now, this is safe and works.
cs = pattern.substring(classStart + 1, i)
try {
RegExp('[' + cs + ']')
} catch (er) {
// not a valid class!
sp = this.parse(cs, SUBPARSE)
re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]'
hasMagic = hasMagic || sp[1]
inClass = false
continue
}
// finish up the class.
hasMagic = true
inClass = false
re += c
continue
default:
// swallow any state char that wasn't consumed
clearStateChar()
if (reSpecials[c] && !(c === '^' && inClass)) {
re += '\\'
}
re += c
break
} // switch
} // for
// handle the case where we left a class open.
// "[abc" is valid, equivalent to "\[abc"
if (inClass) {
// split where the last [ was, and escape it
// this is a huge pita. We now have to re-walk
// the contents of the would-be class to re-translate
// any characters that were passed through as-is
cs = pattern.substr(classStart + 1)
sp = this.parse(cs, SUBPARSE)
re = re.substr(0, reClassStart) + '\\[' + sp[0]
hasMagic = hasMagic || sp[1]
}
// handle the case where we had a +( thing at the *end*
// of the pattern.
// each pattern list stack adds 3 chars, and we need to go through
// and escape any | chars that were passed through as-is for the regexp.
// Go through and escape them, taking care not to double-escape any
// | chars that were already escaped.
for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) {
let tail
tail = re.slice(pl.reStart + pl.open.length)
this.debug('setting tail', re, pl)
// maybe some even number of \, then maybe 1 \, followed by a |
tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, (_, $1, $2) => {
/* istanbul ignore else - should already be done */
if (!$2) {
// the | isn't already escaped, so escape it.
$2 = '\\'
}
// need to escape all those slashes *again*, without escaping the
// one that we need for escaping the | character. As it works out,
// escaping an even number of slashes can be done by simply repeating
// it exactly after itself. That's why this trick works.
//
// I am sorry that you have to see this.
return $1 + $1 + $2 + '|'
})
this.debug('tail=%j\n %s', tail, tail, pl, re)
const t = pl.type === '*' ? star
: pl.type === '?' ? qmark
: '\\' + pl.type
hasMagic = true
re = re.slice(0, pl.reStart) + t + '\\(' + tail
}
// handle trailing things that only matter at the very end.
clearStateChar()
if (escaping) {
// trailing \\
re += '\\\\'
}
// only need to apply the nodot start if the re starts with
// something that could conceivably capture a dot
const addPatternStart = addPatternStartSet[re.charAt(0)]
// Hack to work around lack of negative lookbehind in JS
// A pattern like: *.!(x).!(y|z) needs to ensure that a name
// like 'a.xyz.yz' doesn't match. So, the first negative
// lookahead, has to look ALL the way ahead, to the end of
// the pattern.
for (let n = negativeLists.length - 1; n > -1; n--) {
const nl = negativeLists[n]
const nlBefore = re.slice(0, nl.reStart)
const nlFirst = re.slice(nl.reStart, nl.reEnd - 8)
let nlAfter = re.slice(nl.reEnd)
const nlLast = re.slice(nl.reEnd - 8, nl.reEnd) + nlAfter
// Handle nested stuff like *(*.js|!(*.json)), where open parens
// mean that we should *not* include the ) in the bit that is considered
// "after" the negated section.
const openParensBefore = nlBefore.split('(').length - 1
let cleanAfter = nlAfter
for (let i = 0; i < openParensBefore; i++) {
cleanAfter = cleanAfter.replace(/\)[+*?]?/, '')
}
nlAfter = cleanAfter
const dollar = nlAfter === '' && isSub !== SUBPARSE ? '$' : ''
re = nlBefore + nlFirst + nlAfter + dollar + nlLast
}
// if the re is not "" at this point, then we need to make sure
// it doesn't match against an empty path part.
// Otherwise a/* will match a/, which it should not.
if (re !== '' && hasMagic) {
re = '(?=.)' + re
}
if (addPatternStart) {
re = patternStart + re
}
// parsing just a piece of a larger pattern.
if (isSub === SUBPARSE) {
return [re, hasMagic]
}
// skip the regexp for non-magical patterns
// unescape anything in it, though, so that it'll be
// an exact match against a file etc.
if (!hasMagic) {
return globUnescape(pattern)
}
const flags = options.nocase ? 'i' : ''
try {
return Object.assign(new RegExp('^' + re + '$', flags), {
_glob: pattern,
_src: re,
})
} catch (er) /* istanbul ignore next - should be impossible */ {
// If it was an invalid regular expression, then it can't match
// anything. This trick looks for a character after the end of
// the string, which is of course impossible, except in multi-line
// mode, but it's not a /m regex.
return new RegExp('$.')
}
}
makeRe () {
if (this.regexp || this.regexp === false) return this.regexp
// at this point, this.set is a 2d array of partial
// pattern strings, or "**".
//
// It's better to use .match(). This function shouldn't
// be used, really, but it's pretty convenient sometimes,
// when you just want to work with a regex.
const set = this.set
if (!set.length) {
this.regexp = false
return this.regexp
}
const options = this.options
const twoStar = options.noglobstar ? star
: options.dot ? twoStarDot
: twoStarNoDot
const flags = options.nocase ? 'i' : ''
// coalesce globstars and regexpify non-globstar patterns
// if it's the only item, then we just do one twoStar
// if it's the first, and there are more, prepend (\/|twoStar\/)? to next
// if it's the last, append (\/twoStar|) to previous
// if it's in the middle, append (\/|\/twoStar\/) to previous
// then filter out GLOBSTAR symbols
let re = set.map(pattern => {
pattern = pattern.map(p =>
typeof p === 'string' ? regExpEscape(p)
: p === GLOBSTAR ? GLOBSTAR
: p._src
).reduce((set, p) => {
if (!(set[set.length - 1] === GLOBSTAR && p === GLOBSTAR)) {
set.push(p)
}
return set
}, [])
pattern.forEach((p, i) => {
if (p !== GLOBSTAR || pattern[i-1] === GLOBSTAR) {
return
}
if (i === 0) {
if (pattern.length > 1) {
pattern[i+1] = '(?:\\\/|' + twoStar + '\\\/)?' + pattern[i+1]
} else {
pattern[i] = twoStar
}
} else if (i === pattern.length - 1) {
pattern[i-1] += '(?:\\\/|' + twoStar + ')?'
} else {
pattern[i-1] += '(?:\\\/|\\\/' + twoStar + '\\\/)' + pattern[i+1]
pattern[i+1] = GLOBSTAR
}
})
return pattern.filter(p => p !== GLOBSTAR).join('/')
}).join('|')
// must match entire pattern
// ending in a * or ** will make it less strict.
re = '^(?:' + re + ')$'
// can match anything, as long as it's not this.
if (this.negate) re = '^(?!' + re + ').*$'
try {
this.regexp = new RegExp(re, flags)
} catch (ex) /* istanbul ignore next - should be impossible */ {
this.regexp = false
}
return this.regexp
}
match (f, partial = this.partial) {
this.debug('match', f, this.pattern)
// short-circuit in the case of busted things.
// comments, etc.
if (this.comment) return false
if (this.empty) return f === ''
if (f === '/' && partial) return true
const options = this.options
// windows: need to use /, not \
if (path.sep !== '/') {
f = f.split(path.sep).join('/')
}
// treat the test path as a set of pathparts.
f = f.split(slashSplit)
this.debug(this.pattern, 'split', f)
// just ONE of the pattern sets in this.set needs to match
// in order for it to be valid. If negating, then just one
// match means that we have failed.
// Either way, return on the first hit.
const set = this.set
this.debug(this.pattern, 'set', set)
// Find the basename of the path by looking for the last non-empty segment
let filename
for (let i = f.length - 1; i >= 0; i--) {
filename = f[i]
if (filename) break
}
for (let i = 0; i < set.length; i++) {
const pattern = set[i]
let file = f
if (options.matchBase && pattern.length === 1) {
file = [filename]
}
const hit = this.matchOne(file, pattern, partial)
if (hit) {
if (options.flipNegate) return true
return !this.negate
}
}
// didn't get any hits. this is success if it's a negative
// pattern, failure otherwise.
if (options.flipNegate) return false
return this.negate
}
static defaults (def) {
return minimatch.defaults(def).Minimatch
}
}
minimatch.Minimatch = Minimatch
{
"_from": "minimatch@^5.0.1",
"_id": "minimatch@5.1.0",
"_inBundle": false,
"_integrity": "sha512-9TPBGGak4nHfGZsPBohm9AWg6NoT7QTCehS3BIJABslyZbzxfV78QM2Y6+i741OPZIafFAaiiEMh5OyIrJPgtg==",
"_location": "/vue-qr/minimatch",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "minimatch@^5.0.1",
"name": "minimatch",
"escapedName": "minimatch",
"rawSpec": "^5.0.1",
"saveSpec": null,
"fetchSpec": "^5.0.1"
},
"_requiredBy": [
"/vue-qr/glob"
],
"_resolved": "https://registry.npmmirror.com/minimatch/-/minimatch-5.1.0.tgz",
"_shasum": "1717b464f4971b144f6aabe8f2d0b8e4511e09c7",
"_spec": "minimatch@^5.0.1",
"_where": "/Users/zhanghao/brcode/br-client/node_modules/vue-qr/node_modules/glob",
"author": {
"name": "Isaac Z. Schlueter",
"email": "i@izs.me",
"url": "http://blog.izs.me"
},
"bugs": {
"url": "https://github.com/isaacs/minimatch/issues"
},
"bundleDependencies": false,
"dependencies": {
"brace-expansion": "^2.0.1"
},
"deprecated": false,
"description": "a glob matcher in javascript",
"devDependencies": {
"tap": "^15.1.6"
},
"engines": {
"node": ">=10"
},
"files": [
"minimatch.js",
"lib"
],
"homepage": "https://github.com/isaacs/minimatch#readme",
"license": "ISC",
"main": "minimatch.js",
"name": "minimatch",
"repository": {
"type": "git",
"url": "git://github.com/isaacs/minimatch.git"
},
"scripts": {
"postversion": "npm publish",
"prepublishOnly": "git push origin --follow-tags",
"preversion": "npm test",
"snap": "tap",
"test": "tap"
},
"version": "5.1.0"
}
{
"_from": "vue-qr",
"_id": "vue-qr@4.0.9",
"_inBundle": false,
"_integrity": "sha512-pAISV94T0MNEYA3NGjykUpsXRE2QfaNxlu9ZhEL6CERgqNc21hJYuP3hRVzAWfBQlgO18DPmZTbrFerJC3+Ikw==",
"_location": "/vue-qr",
"_phantomChildren": {
"balanced-match": "1.0.0",
"fs.realpath": "1.0.0",
"inflight": "1.0.6",
"inherits": "2.0.4",
"once": "1.4.0"
},
"_requested": {
"type": "tag",
"registry": true,
"raw": "vue-qr",
"name": "vue-qr",
"escapedName": "vue-qr",
"rawSpec": "",
"saveSpec": null,
"fetchSpec": "latest"
},
"_requiredBy": [
"#USER",
"/"
],
"_resolved": "https://registry.npmmirror.com/vue-qr/-/vue-qr-4.0.9.tgz",
"_shasum": "6cb965dd0c5a0dff947e6ef582ef149b0780b986",
"_spec": "vue-qr",
"_where": "/Users/zhanghao/brcode/br-client",
"author": {
"name": "Binaryify"
},
"browserslist": [
"> 1%",
"last 2 versions",
"not ie <= 8"
],
"bugs": {
"url": "https://github.com/Binaryify/vue-qr/issues"
},
"bundleDependencies": false,
"dependencies": {
"glob": "^8.0.1",
"js-binary-schema-parser": "^2.0.2",
"simple-get": "^4.0.1",
"string-split-by": "^1.0.0"
},
"deprecated": false,
"description": "The Vue 2.x component of Awesome-qr.js",
"devDependencies": {
"@babel/cli": "^7.11.6",
"@babel/core": "^7.11.6",
"@babel/plugin-proposal-class-properties": "^7.16.7",
"@babel/plugin-transform-runtime": "^7.11.5",
"@babel/preset-env": "^7.11.5",
"@babel/preset-stage-0": "^7.8.3",
"babel-loader": "^8.1.0",
"babel-plugin-lodash": "^3.3.4",
"cross-env": "^7.0.2",
"css-loader": "^4.3.0",
"file-loader": "^6.1.0",
"uuid": "^8.3.1",
"vue": "^2.6.12",
"vue-loader": "^15.9.3",
"vue-template-compiler": "^2.6.12",
"webpack": "^4.44.2",
"webpack-cli": "^3.3.12",
"webpack-dev-server": "^3.11.0"
},
"homepage": "https://github.com/Binaryify/vue-qr#readme",
"keywords": [
"vue-qr",
"vue qr",
"vue qrcode",
"qr",
"vue"
],
"license": "MIT",
"main": "dist/vue-qr.js",
"name": "vue-qr",
"repository": {
"type": "git",
"url": "git+https://github.com/Binaryify/vue-qr.git"
},
"scripts": {
"build": "cross-env NODE_ENV=production webpack --progress --hide-modules",
"dev": "cross-env NODE_ENV=development webpack-dev-server --open --hot --host 0.0.0.0"
},
"version": "4.0.9"
}
// 'path' module extracted from Node.js v8.11.1 (only the posix part)
// transplited with Babel
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict';
function assertPath(path) {
if (typeof path !== 'string') {
throw new TypeError('Path must be a string. Received ' + JSON.stringify(path));
}
}
// Resolves . and .. elements in a path with directory names
function normalizeStringPosix(path, allowAboveRoot) {
var res = '';
var lastSegmentLength = 0;
var lastSlash = -1;
var dots = 0;
var code;
for (var i = 0; i <= path.length; ++i) {
if (i < path.length)
code = path.charCodeAt(i);
else if (code === 47 /*/*/)
break;
else
code = 47 /*/*/;
if (code === 47 /*/*/) {
if (lastSlash === i - 1 || dots === 1) {
// NOOP
} else if (lastSlash !== i - 1 && dots === 2) {
if (res.length < 2 || lastSegmentLength !== 2 || res.charCodeAt(res.length - 1) !== 46 /*.*/ || res.charCodeAt(res.length - 2) !== 46 /*.*/) {
if (res.length > 2) {
var lastSlashIndex = res.lastIndexOf('/');
if (lastSlashIndex !== res.length - 1) {
if (lastSlashIndex === -1) {
res = '';
lastSegmentLength = 0;
} else {
res = res.slice(0, lastSlashIndex);
lastSegmentLength = res.length - 1 - res.lastIndexOf('/');
}
lastSlash = i;
dots = 0;
continue;
}
} else if (res.length === 2 || res.length === 1) {
res = '';
lastSegmentLength = 0;
lastSlash = i;
dots = 0;
continue;
}
}
if (allowAboveRoot) {
if (res.length > 0)
res += '/..';
else
res = '..';
lastSegmentLength = 2;
}
} else {
if (res.length > 0)
res += '/' + path.slice(lastSlash + 1, i);
else
res = path.slice(lastSlash + 1, i);
lastSegmentLength = i - lastSlash - 1;
}
lastSlash = i;
dots = 0;
} else if (code === 46 /*.*/ && dots !== -1) {
++dots;
} else {
dots = -1;
}
}
return res;
}
function _format(sep, pathObject) {
var dir = pathObject.dir || pathObject.root;
var base = pathObject.base || (pathObject.name || '') + (pathObject.ext || '');
if (!dir) {
return base;
}
if (dir === pathObject.root) {
return dir + base;
}
return dir + sep + base;
}
var posix = {
// path.resolve([from ...], to)
resolve: function resolve() {
var resolvedPath = '';
var resolvedAbsolute = false;
var cwd;
for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
var path;
if (i >= 0)
path = arguments[i];
else {
if (cwd === undefined)
cwd = process.cwd();
path = cwd;
}
assertPath(path);
// Skip empty entries
if (path.length === 0) {
continue;
}
resolvedPath = path + '/' + resolvedPath;
resolvedAbsolute = path.charCodeAt(0) === 47 /*/*/;
}
// At this point the path should be resolved to a full absolute path, but
// handle relative paths to be safe (might happen when process.cwd() fails)
// Normalize the path
resolvedPath = normalizeStringPosix(resolvedPath, !resolvedAbsolute);
if (resolvedAbsolute) {
if (resolvedPath.length > 0)
return '/' + resolvedPath;
else
return '/';
} else if (resolvedPath.length > 0) {
return resolvedPath;
} else {
return '.';
}
},
normalize: function normalize(path) {
assertPath(path);
if (path.length === 0) return '.';
var isAbsolute = path.charCodeAt(0) === 47 /*/*/;
var trailingSeparator = path.charCodeAt(path.length - 1) === 47 /*/*/;
// Normalize the path
path = normalizeStringPosix(path, !isAbsolute);
if (path.length === 0 && !isAbsolute) path = '.';
if (path.length > 0 && trailingSeparator) path += '/';
if (isAbsolute) return '/' + path;
return path;
},
isAbsolute: function isAbsolute(path) {
assertPath(path);
return path.length > 0 && path.charCodeAt(0) === 47 /*/*/;
},
join: function join() {
if (arguments.length === 0)
return '.';
var joined;
for (var i = 0; i < arguments.length; ++i) {
var arg = arguments[i];
assertPath(arg);
if (arg.length > 0) {
if (joined === undefined)
joined = arg;
else
joined += '/' + arg;
}
}
if (joined === undefined)
return '.';
return posix.normalize(joined);
},
relative: function relative(from, to) {
assertPath(from);
assertPath(to);
if (from === to) return '';
from = posix.resolve(from);
to = posix.resolve(to);
if (from === to) return '';
// Trim any leading backslashes
var fromStart = 1;
for (; fromStart < from.length; ++fromStart) {
if (from.charCodeAt(fromStart) !== 47 /*/*/)
break;
}
var fromEnd = from.length;
var fromLen = fromEnd - fromStart;
// Trim any leading backslashes
var toStart = 1;
for (; toStart < to.length; ++toStart) {
if (to.charCodeAt(toStart) !== 47 /*/*/)
break;
}
var toEnd = to.length;
var toLen = toEnd - toStart;
// Compare paths to find the longest common path from root
var length = fromLen < toLen ? fromLen : toLen;
var lastCommonSep = -1;
var i = 0;
for (; i <= length; ++i) {
if (i === length) {
if (toLen > length) {
if (to.charCodeAt(toStart + i) === 47 /*/*/) {
// We get here if `from` is the exact base path for `to`.
// For example: from='/foo/bar'; to='/foo/bar/baz'
return to.slice(toStart + i + 1);
} else if (i === 0) {
// We get here if `from` is the root
// For example: from='/'; to='/foo'
return to.slice(toStart + i);
}
} else if (fromLen > length) {
if (from.charCodeAt(fromStart + i) === 47 /*/*/) {
// We get here if `to` is the exact base path for `from`.
// For example: from='/foo/bar/baz'; to='/foo/bar'
lastCommonSep = i;
} else if (i === 0) {
// We get here if `to` is the root.
// For example: from='/foo'; to='/'
lastCommonSep = 0;
}
}
break;
}
var fromCode = from.charCodeAt(fromStart + i);
var toCode = to.charCodeAt(toStart + i);
if (fromCode !== toCode)
break;
else if (fromCode === 47 /*/*/)
lastCommonSep = i;
}
var out = '';
// Generate the relative path based on the path difference between `to`
// and `from`
for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {
if (i === fromEnd || from.charCodeAt(i) === 47 /*/*/) {
if (out.length === 0)
out += '..';
else
out += '/..';
}
}
// Lastly, append the rest of the destination (`to`) path that comes after
// the common path parts
if (out.length > 0)
return out + to.slice(toStart + lastCommonSep);
else {
toStart += lastCommonSep;
if (to.charCodeAt(toStart) === 47 /*/*/)
++toStart;
return to.slice(toStart);
}
},
_makeLong: function _makeLong(path) {
return path;
},
dirname: function dirname(path) {
assertPath(path);
if (path.length === 0) return '.';
var code = path.charCodeAt(0);
var hasRoot = code === 47 /*/*/;
var end = -1;
var matchedSlash = true;
for (var i = path.length - 1; i >= 1; --i) {
code = path.charCodeAt(i);
if (code === 47 /*/*/) {
if (!matchedSlash) {
end = i;
break;
}
} else {
// We saw the first non-path separator
matchedSlash = false;
}
}
if (end === -1) return hasRoot ? '/' : '.';
if (hasRoot && end === 1) return '//';
return path.slice(0, end);
},
basename: function basename(path, ext) {
if (ext !== undefined && typeof ext !== 'string') throw new TypeError('"ext" argument must be a string');
assertPath(path);
var start = 0;
var end = -1;
var matchedSlash = true;
var i;
if (ext !== undefined && ext.length > 0 && ext.length <= path.length) {
if (ext.length === path.length && ext === path) return '';
var extIdx = ext.length - 1;
var firstNonSlashEnd = -1;
for (i = path.length - 1; i >= 0; --i) {
var code = path.charCodeAt(i);
if (code === 47 /*/*/) {
// If we reached a path separator that was not part of a set of path
// separators at the end of the string, stop now
if (!matchedSlash) {
start = i + 1;
break;
}
} else {
if (firstNonSlashEnd === -1) {
// We saw the first non-path separator, remember this index in case
// we need it if the extension ends up not matching
matchedSlash = false;
firstNonSlashEnd = i + 1;
}
if (extIdx >= 0) {
// Try to match the explicit extension
if (code === ext.charCodeAt(extIdx)) {
if (--extIdx === -1) {
// We matched the extension, so mark this as the end of our path
// component
end = i;
}
} else {
// Extension does not match, so our result is the entire path
// component
extIdx = -1;
end = firstNonSlashEnd;
}
}
}
}
if (start === end) end = firstNonSlashEnd;else if (end === -1) end = path.length;
return path.slice(start, end);
} else {
for (i = path.length - 1; i >= 0; --i) {
if (path.charCodeAt(i) === 47 /*/*/) {
// If we reached a path separator that was not part of a set of path
// separators at the end of the string, stop now
if (!matchedSlash) {
start = i + 1;
break;
}
} else if (end === -1) {
// We saw the first non-path separator, mark this as the end of our
// path component
matchedSlash = false;
end = i + 1;
}
}
if (end === -1) return '';
return path.slice(start, end);
}
},
extname: function extname(path) {
assertPath(path);
var startDot = -1;
var startPart = 0;
var end = -1;
var matchedSlash = true;
// Track the state of characters (if any) we see before our first dot and
// after any path separator we find
var preDotState = 0;
for (var i = path.length - 1; i >= 0; --i) {
var code = path.charCodeAt(i);
if (code === 47 /*/*/) {
// If we reached a path separator that was not part of a set of path
// separators at the end of the string, stop now
if (!matchedSlash) {
startPart = i + 1;
break;
}
continue;
}
if (end === -1) {
// We saw the first non-path separator, mark this as the end of our
// extension
matchedSlash = false;
end = i + 1;
}
if (code === 46 /*.*/) {
// If this is our first dot, mark it as the start of our extension
if (startDot === -1)
startDot = i;
else if (preDotState !== 1)
preDotState = 1;
} else if (startDot !== -1) {
// We saw a non-dot and non-path separator before our dot, so we should
// have a good chance at having a non-empty extension
preDotState = -1;
}
}
if (startDot === -1 || end === -1 ||
// We saw a non-dot character immediately before the dot
preDotState === 0 ||
// The (right-most) trimmed path component is exactly '..'
preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {
return '';
}
return path.slice(startDot, end);
},
format: function format(pathObject) {
if (pathObject === null || typeof pathObject !== 'object') {
throw new TypeError('The "pathObject" argument must be of type Object. Received type ' + typeof pathObject);
}
return _format('/', pathObject);
},
parse: function parse(path) {
assertPath(path);
var ret = { root: '', dir: '', base: '', ext: '', name: '' };
if (path.length === 0) return ret;
var code = path.charCodeAt(0);
var isAbsolute = code === 47 /*/*/;
var start;
if (isAbsolute) {
ret.root = '/';
start = 1;
} else {
start = 0;
}
var startDot = -1;
var startPart = 0;
var end = -1;
var matchedSlash = true;
var i = path.length - 1;
// Track the state of characters (if any) we see before our first dot and
// after any path separator we find
var preDotState = 0;
// Get non-dir info
for (; i >= start; --i) {
code = path.charCodeAt(i);
if (code === 47 /*/*/) {
// If we reached a path separator that was not part of a set of path
// separators at the end of the string, stop now
if (!matchedSlash) {
startPart = i + 1;
break;
}
continue;
}
if (end === -1) {
// We saw the first non-path separator, mark this as the end of our
// extension
matchedSlash = false;
end = i + 1;
}
if (code === 46 /*.*/) {
// If this is our first dot, mark it as the start of our extension
if (startDot === -1) startDot = i;else if (preDotState !== 1) preDotState = 1;
} else if (startDot !== -1) {
// We saw a non-dot and non-path separator before our dot, so we should
// have a good chance at having a non-empty extension
preDotState = -1;
}
}
if (startDot === -1 || end === -1 ||
// We saw a non-dot character immediately before the dot
preDotState === 0 ||
// The (right-most) trimmed path component is exactly '..'
preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {
if (end !== -1) {
if (startPart === 0 && isAbsolute) ret.base = ret.name = path.slice(1, end);else ret.base = ret.name = path.slice(startPart, end);
}
} else {
if (startPart === 0 && isAbsolute) {
ret.name = path.slice(1, startDot);
ret.base = path.slice(1, end);
} else {
ret.name = path.slice(startPart, startDot);
ret.base = path.slice(startPart, end);
}
ret.ext = path.slice(startDot, end);
}
if (startPart > 0) ret.dir = path.slice(0, startPart - 1);else if (isAbsolute) ret.dir = '/';
return ret;
},
sep: '/',
delimiter: ':',
win32: null,
posix: null
};
posix.posix = posix;
export const extname = posix.extname;
export const basename = posix.basename;
export default posix;
"use strict";
// const {asBuffer, asDownload, asZipDownload, atScale, options} = require('./io')
import io from "./io";
const { asBuffer, asDownload, asZipDownload, atScale, options } = io;
//
// Browser equivalents of the skia-canvas convenience initializers and polyfills for
// the Canvas object’s newPage & export methods
//
const _toURL_ = Symbol.for("toDataURL");
const loadImage = src =>
new Promise((onload, onerror) =>
Object.assign(new Image(), {
crossOrigin: "Anonymous",
onload,
onerror,
src
})
);
class Canvas {
constructor(width, height) {
// alert(1)
let elt = document.createElement("canvas"),
pages = [];
Object.defineProperty(elt, "async", {
value: true,
writable: false,
enumerable: true
});
for (var [prop, get] of Object.entries({
png: () => asBuffer(elt, "image/png"),
jpg: () => asBuffer(elt, "image/jpeg"),
pages: () => pages.concat(elt).map(c => c.getContext("2d"))
}))
Object.defineProperty(elt, prop, { get });
return Object.assign(elt, {
width,
height,
newPage(...size) {
var { width, height } = elt,
page = Object.assign(document.createElement("canvas"), {
width,
height
});
page.getContext("2d").drawImage(elt, 0, 0);
pages.push(page);
var [width, height] = size.length ? size : [width, height];
return Object.assign(elt, { width, height }).getContext("2d");
},
saveAs(filename, args) {
args = typeof args == "number" ? { quality: args } : args;
let opts = options(this.pages, { filename, ...args }),
{ pattern, padding, mime, quality, matte, density, archive } = opts,
pages = atScale(opts.pages, density);
return padding == undefined
? asDownload(pages[0], mime, quality, matte, filename)
: asZipDownload(
pages,
mime,
quality,
matte,
archive,
pattern,
padding
);
},
toBuffer(extension = "png", args = {}) {
args = typeof args == "number" ? { quality: args } : args;
let opts = options(this.pages, { extension, ...args }),
{ mime, quality, matte, pages, density } = opts,
canvas = atScale(pages, density, matte)[0];
return asBuffer(canvas, mime, quality, matte);
},
[_toURL_]: elt.toDataURL.bind(elt),
toDataURL(extension = "png", args = {}) {
args = typeof args == "number" ? { quality: args } : args;
let opts = options(this.pages, { extension, ...args }),
{ mime, quality, matte, pages, density } = opts,
canvas = atScale(pages, density, matte)[0],
url = canvas[canvas === elt ? _toURL_ : "toDataURL"](mime, quality);
return Promise.resolve(url);
}
});
}
}
const {
CanvasRenderingContext2D,
CanvasGradient,
CanvasPattern,
Image,
ImageData,
Path2D,
DOMMatrix,
DOMRect,
DOMPoint
} = window;
// module.exports = {
// Canvas,
// loadImage,
// CanvasRenderingContext2D,
// CanvasGradient,
// CanvasPattern,
// Image,
// ImageData,
// Path2D,
// DOMMatrix,
// DOMRect,
// DOMPoint
// };
const obj = {
Canvas,
loadImage,
CanvasRenderingContext2D,
CanvasGradient,
CanvasPattern,
Image,
ImageData,
Path2D,
DOMMatrix,
DOMRect,
DOMPoint
};
export default obj;
"use strict";
//
// Parsers for properties that take CSS-style strings as values
//
// -- Font & Variant --------------------------------------------------------------------
// https://developer.mozilla.org/en-US/docs/Web/CSS/font-variant
// https://www.w3.org/TR/css-fonts-3/#font-size-prop
import splitBy from "string-split-by";
var m,
cache = { font: {}, variant: {} };
const styleRE = /^(normal|italic|oblique)$/,
smallcapsRE = /^(normal|small-caps)$/,
stretchRE = /^(normal|(semi-|extra-|ultra-)?(condensed|expanded))$/,
namedSizeRE = /(?:xx?-)?small|smaller|medium|larger|(?:xx?-)?large|normal/,
numSizeRE = /^([\d\.]+)(px|pt|pc|in|cm|mm|%|em|ex|ch|rem|q)/,
namedWeightRE = /^(normal|bold(er)?|lighter)$/,
numWeightRE = /^(1000|\d{1,3})$/,
parameterizedRE = /([\w\-]+)\((.*?)\)/,
unquote = s => s.replace(/^(['"])(.*?)\1$/, "$2"),
isSize = s => namedSizeRE.test(s) || numSizeRE.test(s),
isWeight = s => namedWeightRE.test(s) || numWeightRE.test(s);
function parseFont(str) {
if (cache.font[str] === undefined) {
try {
if (typeof str !== "string")
throw new Error("Font specification must be a string");
if (!str) throw new Error("Font specification cannot be an empty string");
let font = {
style: "normal",
variant: "normal",
weight: "normal",
stretch: "normal"
},
value = str.replace(/\s*\/\*s/, "/"),
tokens = splitBy(value, /\s+/),
token;
while ((token = tokens.shift())) {
let match = styleRE.test(token)
? "style"
: smallcapsRE.test(token)
? "variant"
: stretchRE.test(token)
? "stretch"
: isWeight(token)
? "weight"
: isSize(token)
? "size"
: null;
switch (match) {
case "style":
case "variant":
case "stretch":
case "weight":
font[match] = token;
break;
case "size":
// size is the pivot point between the style fields and the family name stack,
// so start processing what's been collected
let [emSize, leading] = splitBy(token, "/"),
size = parseSize(emSize),
lineHeight = parseSize(
(leading || "1.2").replace(/(\d)$/, "$1em"),
size
),
weight = parseWeight(font.weight),
family = splitBy(tokens.join(" "), /\s*,\s*/).map(unquote),
features =
font.variant == "small-caps" ? { on: ["smcp", "onum"] } : {},
{ style, stretch, variant } = font;
// make sure all the numeric fields have legitimate values
let invalid = !isFinite(size)
? `font size "${emSize}"`
: !isFinite(lineHeight)
? `line height "${leading}"`
: !isFinite(weight)
? `font weight "${font.weight}"`
: family.length == 0
? `font family "${tokens.join(", ")}"`
: false;
if (!invalid) {
// include a re-stringified version of the decoded/absified values
return (cache.font[str] = Object.assign(font, {
size,
lineHeight,
weight,
family,
features,
canonical: [
style,
variant !== style && variant,
[variant, style].indexOf(weight) == -1 && weight,
[variant, style, weight].indexOf(stretch) == -1 && stretch,
`${size}px/${lineHeight}px`,
family.map(nm => (nm.match(/\s/) ? `"${nm}"` : nm)).join(", ")
]
.filter(Boolean)
.join(" ")
}));
}
throw new Error(`Invalid ${invalid}`);
default:
throw new Error(`Unrecognized font attribute "${token}"`);
}
}
throw new Error("Could not find a font size value");
} catch (e) {
// console.warn(Object.assign(e, {name:"Warning"}))
cache.font[str] = null;
}
}
return cache.font[str];
}
function parseSize(str, emSize = 16) {
if ((m = numSizeRE.exec(str))) {
let [size, unit] = [parseFloat(m[1]), m[2]];
return (
size *
(unit == "px"
? 1
: unit == "pt"
? 1 / 0.75
: unit == "%"
? emSize / 100
: unit == "pc"
? 16
: unit == "in"
? 96
: unit == "cm"
? 96.0 / 2.54
: unit == "mm"
? 96.0 / 25.4
: unit == "q"
? 96 / 25.4 / 4
: unit.match("r?em")
? emSize
: NaN)
);
}
if ((m = namedSizeRE.exec(str))) {
return emSize * (sizeMap[m[0]] || 1.0);
}
return NaN;
}
function parseWeight(str) {
return (m = numWeightRE.exec(str))
? parseInt(m[0]) || NaN
: (m = namedWeightRE.exec(str))
? weightMap[m[0]]
: NaN;
}
function parseVariant(str) {
if (cache.variant[str] === undefined) {
let variants = [],
features = { on: [], off: [] };
for (let token of splitBy(str, /\s+/)) {
if (token == "normal") {
return { variants: [token], features: { on: [], off: [] } };
} else if (token in featureMap) {
featureMap[token].forEach(feat => {
if (feat[0] == "-") features.off.push(feat.slice(1));
else features.on.push(feat);
});
variants.push(token);
} else if ((m = parameterizedRE.exec(token))) {
let subPattern = alternatesMap[m[1]],
subValue = Math.max(0, Math.min(99, parseInt(m[2], 10))),
[feat, val] = subPattern
.replace(/##/, subValue < 10 ? "0" + subValue : subValue)
.replace(/#/, Math.min(9, subValue))
.split(" ");
if (typeof val == "undefined") features.on.push(feat);
else features[feat] = parseInt(val, 10);
variants.push(`${m[1]}(${subValue})`);
} else {
throw new Error(`Invalid font variant "${token}"`);
}
}
cache.variant[str] = { variant: variants.join(" "), features: features };
}
return cache.variant[str];
}
// -- Image Filters -----------------------------------------------------------------------
// https://developer.mozilla.org/en-US/docs/Web/CSS/filter
var plainFilterRE = /(blur|hue-rotate|brightness|contrast|grayscale|invert|opacity|saturate|sepia)\((.*?)\)/,
shadowFilterRE = /drop-shadow\((.*)\)/,
percentValueRE = /^(\+|-)?\d+%$/,
angleValueRE = /([\d\.]+)(deg|g?rad|turn)/;
function parseFilter(str) {
let filters = {};
let canonical = [];
for (var spec of splitBy(str, /\s+/) || []) {
if ((m = shadowFilterRE.exec(spec))) {
let kind = "drop-shadow",
args = m[1].trim().split(/\s+/),
lengths = args.slice(0, 3),
color = args.slice(3).join(" "),
dims = lengths.map(s => parseSize(s)).filter(isFinite);
if (dims.length == 3 && !!color) {
filters[kind] = [...dims, color];
canonical.push(
`${kind}(${lengths.join(" ")} ${color.replace(/ /g, "")})`
);
}
} else if ((m = plainFilterRE.exec(spec))) {
let [kind, arg] = m.slice(1);
let val =
kind == "blur"
? parseSize(arg)
: kind == "hue-rotate"
? parseAngle(arg)
: parsePercentage(arg);
if (isFinite(val)) {
filters[kind] = val;
canonical.push(`${kind}(${arg.trim()})`);
}
}
}
return str.trim() == "none"
? { canonical: "none", filters }
: canonical.length
? { canonical: canonical.join(" "), filters }
: null;
}
function parsePercentage(str) {
return percentValueRE.test(str.trim()) ? parseInt(str, 10) / 100 : NaN;
}
function parseAngle(str) {
if ((m = angleValueRE.exec(str.trim()))) {
let [amt, unit] = [parseFloat(m[1]), m[2]];
return unit == "deg"
? amt
: unit == "rad"
? (360 * amt) / (2 * Math.PI)
: unit == "grad"
? (360 * amt) / 400
: unit == "turn"
? 360 * amt
: NaN;
}
}
//
// Font attribute keywords & corresponding values
//
const weightMap = {
lighter: 300,
normal: 400,
bold: 700,
bolder: 800
};
const sizeMap = {
"xx-small": 3 / 5,
"x-small": 3 / 4,
small: 8 / 9,
smaller: 8 / 9,
large: 6 / 5,
larger: 6 / 5,
"x-large": 3 / 2,
"xx-large": 2 / 1,
normal: 1.2 // special case for lineHeight
};
const featureMap = {
normal: [],
// font-variant-ligatures
"common-ligatures": ["liga", "clig"],
"no-common-ligatures": ["-liga", "-clig"],
"discretionary-ligatures": ["dlig"],
"no-discretionary-ligatures": ["-dlig"],
"historical-ligatures": ["hlig"],
"no-historical-ligatures": ["-hlig"],
contextual: ["calt"],
"no-contextual": ["-calt"],
// font-variant-position
super: ["sups"],
sub: ["subs"],
// font-variant-caps
"small-caps": ["smcp"],
"all-small-caps": ["c2sc", "smcp"],
"petite-caps": ["pcap"],
"all-petite-caps": ["c2pc", "pcap"],
unicase: ["unic"],
"titling-caps": ["titl"],
// font-variant-numeric
"lining-nums": ["lnum"],
"oldstyle-nums": ["onum"],
"proportional-nums": ["pnum"],
"tabular-nums": ["tnum"],
"diagonal-fractions": ["frac"],
"stacked-fractions": ["afrc"],
ordinal: ["ordn"],
"slashed-zero": ["zero"],
// font-variant-east-asian
jis78: ["jp78"],
jis83: ["jp83"],
jis90: ["jp90"],
jis04: ["jp04"],
simplified: ["smpl"],
traditional: ["trad"],
"full-width": ["fwid"],
"proportional-width": ["pwid"],
ruby: ["ruby"],
// font-variant-alternates (non-parameterized)
"historical-forms": ["hist"]
};
const alternatesMap = {
stylistic: "salt #",
styleset: "ss##",
"character-variant": "cv##",
swash: "swsh #",
ornaments: "ornm #",
annotation: "nalt #"
};
// module.exports = {
// font: parseFont,
// variant: parseVariant,
// size: parseSize,
// filter: parseFilter
// };
export default {
font: parseFont,
variant: parseVariant,
size: parseSize,
filter: parseFilter
};
"use strict";
import { inspect } from "util";
// const { inspect } = require("util");
/*
* vendored in order to fix its dependence on the window global [cds 2020/08/04]
* otherwise unchanged from https://github.com/jarek-foksa/geometry-polyfill/tree/f36bbc8f4bc43539d980687904ce46c8e915543d
*/
// @info
// DOMPoint polyfill
// @src
// https://drafts.fxtf.org/geometry/#DOMPoint
// https://github.com/chromium/chromium/blob/master/third_party/blink/renderer/core/geometry/dom_point_read_only.cc
class DOMPoint {
constructor(x = 0, y = 0, z = 0, w = 1) {
this.x = x;
this.y = y;
this.z = z;
this.w = w;
}
static fromPoint(otherPoint) {
return new DOMPoint(
otherPoint.x,
otherPoint.y,
otherPoint.z !== undefined ? otherPoint.z : 0,
otherPoint.w !== undefined ? otherPoint.w : 1
);
}
matrixTransform(matrix) {
if (
(matrix.is2D || matrix instanceof SVGMatrix) &&
this.z === 0 &&
this.w === 1
) {
return new DOMPoint(
this.x * matrix.a + this.y * matrix.c + matrix.e,
this.x * matrix.b + this.y * matrix.d + matrix.f,
0,
1
);
} else {
return new DOMPoint(
this.x * matrix.m11 +
this.y * matrix.m21 +
this.z * matrix.m31 +
this.w * matrix.m41,
this.x * matrix.m12 +
this.y * matrix.m22 +
this.z * matrix.m32 +
this.w * matrix.m42,
this.x * matrix.m13 +
this.y * matrix.m23 +
this.z * matrix.m33 +
this.w * matrix.m43,
this.x * matrix.m14 +
this.y * matrix.m24 +
this.z * matrix.m34 +
this.w * matrix.m44
);
}
}
toJSON() {
return {
x: this.x,
y: this.y,
z: this.z,
w: this.w
};
}
}
// @info
// DOMRect polyfill
// @src
// https://drafts.fxtf.org/geometry/#DOMRect
// https://github.com/chromium/chromium/blob/master/third_party/blink/renderer/core/geometry/dom_rect_read_only.cc
class DOMRect {
constructor(x = 0, y = 0, width = 0, height = 0) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
static fromRect(otherRect) {
return new DOMRect(
otherRect.x,
otherRect.y,
otherRect.width,
otherRect.height
);
}
get top() {
return this.y;
}
get left() {
return this.x;
}
get right() {
return this.x + this.width;
}
get bottom() {
return this.y + this.height;
}
toJSON() {
return {
x: this.x,
y: this.y,
width: this.width,
height: this.height,
top: this.top,
left: this.left,
right: this.right,
bottom: this.bottom
};
}
}
for (let propertyName of ["top", "right", "bottom", "left"]) {
let propertyDescriptor = Object.getOwnPropertyDescriptor(
DOMRect.prototype,
propertyName
);
propertyDescriptor.enumerable = true;
Object.defineProperty(DOMRect.prototype, propertyName, propertyDescriptor);
}
// @info
// DOMMatrix polyfill (SVG 2)
// @src
// https://github.com/chromium/chromium/blob/master/third_party/blink/renderer/core/geometry/dom_matrix_read_only.cc
// https://github.com/tocharomera/generativecanvas/blob/master/node-canvas/lib/DOMMatrix.js
const M11 = 0,
M12 = 1,
M13 = 2,
M14 = 3;
const M21 = 4,
M22 = 5,
M23 = 6,
M24 = 7;
const M31 = 8,
M32 = 9,
M33 = 10,
M34 = 11;
const M41 = 12,
M42 = 13,
M43 = 14,
M44 = 15;
const A = M11,
B = M12;
const C = M21,
D = M22;
const E = M41,
F = M42;
const DEGREE_PER_RAD = 180 / Math.PI;
const RAD_PER_DEGREE = Math.PI / 180;
const $values = Symbol();
const $is2D = Symbol();
let parseMatrix = init => {
let parsed = init.replace(/matrix\(/, "");
parsed = parsed.split(/,/, 7);
if (parsed.length !== 6) {
throw new Error(`Failed to parse ${init}`);
}
parsed = parsed.map(parseFloat);
return [
parsed[0],
parsed[1],
0,
0,
parsed[2],
parsed[3],
0,
0,
0,
0,
1,
0,
parsed[4],
parsed[5],
0,
1
];
};
let parseMatrix3d = init => {
let parsed = init.replace(/matrix3d\(/, "");
parsed = parsed.split(/,/, 17);
if (parsed.length !== 16) {
throw new Error(`Failed to parse ${init}`);
}
return parsed.map(parseFloat);
};
let parseTransform = tform => {
let type = tform.split(/\(/, 1)[0];
if (type === "matrix") {
return parseMatrix(tform);
} else if (type === "matrix3d") {
return parseMatrix3d(tform);
} else {
throw new Error(`${type} parsing not implemented`);
}
};
let setNumber2D = (receiver, index, value) => {
if (typeof value !== "number") {
throw new TypeError("Expected number");
}
receiver[$values][index] = value;
};
let setNumber3D = (receiver, index, value) => {
if (typeof value !== "number") {
throw new TypeError("Expected number");
}
if (index === M33 || index === M44) {
if (value !== 1) {
receiver[$is2D] = false;
}
} else if (value !== 0) {
receiver[$is2D] = false;
}
receiver[$values][index] = value;
};
let newInstance = values => {
let instance = Object.create(DOMMatrix.prototype);
instance.constructor = DOMMatrix;
instance[$is2D] = true;
instance[$values] = values;
return instance;
};
let multiply = (first, second) => {
let dest = new Float64Array(16);
for (let i = 0; i < 4; i++) {
for (let j = 0; j < 4; j++) {
let sum = 0;
for (let k = 0; k < 4; k++) {
sum += first[i * 4 + k] * second[k * 4 + j];
}
dest[i * 4 + j] = sum;
}
}
return dest;
};
class DOMMatrix {
get m11() {
return this[$values][M11];
}
set m11(value) {
setNumber2D(this, M11, value);
}
get m12() {
return this[$values][M12];
}
set m12(value) {
setNumber2D(this, M12, value);
}
get m13() {
return this[$values][M13];
}
set m13(value) {
setNumber3D(this, M13, value);
}
get m14() {
return this[$values][M14];
}
set m14(value) {
setNumber3D(this, M14, value);
}
get m21() {
return this[$values][M21];
}
set m21(value) {
setNumber2D(this, M21, value);
}
get m22() {
return this[$values][M22];
}
set m22(value) {
setNumber2D(this, M22, value);
}
get m23() {
return this[$values][M23];
}
set m23(value) {
setNumber3D(this, M23, value);
}
get m24() {
return this[$values][M24];
}
set m24(value) {
setNumber3D(this, M24, value);
}
get m31() {
return this[$values][M31];
}
set m31(value) {
setNumber3D(this, M31, value);
}
get m32() {
return this[$values][M32];
}
set m32(value) {
setNumber3D(this, M32, value);
}
get m33() {
return this[$values][M33];
}
set m33(value) {
setNumber3D(this, M33, value);
}
get m34() {
return this[$values][M34];
}
set m34(value) {
setNumber3D(this, M34, value);
}
get m41() {
return this[$values][M41];
}
set m41(value) {
setNumber2D(this, M41, value);
}
get m42() {
return this[$values][M42];
}
set m42(value) {
setNumber2D(this, M42, value);
}
get m43() {
return this[$values][M43];
}
set m43(value) {
setNumber3D(this, M43, value);
}
get m44() {
return this[$values][M44];
}
set m44(value) {
setNumber3D(this, M44, value);
}
get a() {
return this[$values][A];
}
set a(value) {
setNumber2D(this, A, value);
}
get b() {
return this[$values][B];
}
set b(value) {
setNumber2D(this, B, value);
}
get c() {
return this[$values][C];
}
set c(value) {
setNumber2D(this, C, value);
}
get d() {
return this[$values][D];
}
set d(value) {
setNumber2D(this, D, value);
}
get e() {
return this[$values][E];
}
set e(value) {
setNumber2D(this, E, value);
}
get f() {
return this[$values][F];
}
set f(value) {
setNumber2D(this, F, value);
}
get is2D() {
return this[$is2D];
}
get isIdentity() {
let values = this[$values];
return (
values[M11] === 1 &&
values[M12] === 0 &&
values[M13] === 0 &&
values[M14] === 0 &&
values[M21] === 0 &&
values[M22] === 1 &&
values[M23] === 0 &&
values[M24] === 0 &&
values[M31] === 0 &&
values[M32] === 0 &&
values[M33] === 1 &&
values[M34] === 0 &&
values[M41] === 0 &&
values[M42] === 0 &&
values[M43] === 0 &&
values[M44] === 1
);
}
static fromMatrix(init) {
if (init instanceof DOMMatrix) {
return new DOMMatrix(init[$values]);
} else if (init instanceof SVGMatrix) {
return new DOMMatrix([init.a, init.b, init.c, init.d, init.e, init.f]);
} else {
throw new TypeError("Expected DOMMatrix");
}
}
static fromFloat32Array(init) {
if (!(init instanceof Float32Array))
throw new TypeError("Expected Float32Array");
return new DOMMatrix(init);
}
static fromFloat64Array(init) {
if (!(init instanceof Float64Array))
throw new TypeError("Expected Float64Array");
return new DOMMatrix(init);
}
// @type
// (Float64Array) => void
constructor(init) {
this[$is2D] = true;
this[$values] = new Float64Array([
1,
0,
0,
0,
0,
1,
0,
0,
0,
0,
1,
0,
0,
0,
0,
1
]);
// Parse CSS transformList
if (typeof init === "string") {
if (init === "") {
return;
} else {
let tforms = init.split(/\)\s+/, 20).map(parseTransform);
if (tforms.length === 0) {
return;
}
init = tforms[0];
for (let i = 1; i < tforms.length; i++) {
init = multiply(tforms[i], init);
}
}
}
let i = 0;
if (init && init.length === 6) {
setNumber2D(this, A, init[i++]);
setNumber2D(this, B, init[i++]);
setNumber2D(this, C, init[i++]);
setNumber2D(this, D, init[i++]);
setNumber2D(this, E, init[i++]);
setNumber2D(this, F, init[i++]);
} else if (init && init.length === 16) {
setNumber2D(this, M11, init[i++]);
setNumber2D(this, M12, init[i++]);
setNumber3D(this, M13, init[i++]);
setNumber3D(this, M14, init[i++]);
setNumber2D(this, M21, init[i++]);
setNumber2D(this, M22, init[i++]);
setNumber3D(this, M23, init[i++]);
setNumber3D(this, M24, init[i++]);
setNumber3D(this, M31, init[i++]);
setNumber3D(this, M32, init[i++]);
setNumber3D(this, M33, init[i++]);
setNumber3D(this, M34, init[i++]);
setNumber2D(this, M41, init[i++]);
setNumber2D(this, M42, init[i++]);
setNumber3D(this, M43, init[i++]);
setNumber3D(this, M44, init[i]);
} else if (init !== undefined) {
throw new TypeError("Expected string or array.");
}
}
dump() {
let mat = this[$values];
console.log([
mat.slice(0, 4),
mat.slice(4, 8),
mat.slice(8, 12),
mat.slice(12, 16)
]);
}
[inspect.custom](depth, options) {
if (depth < 0) return "[DOMMatrix]";
let { a, b, c, d, e, f, is2D, isIdentity } = this;
if (this.is2D) {
return `DOMMatrix ${inspect(
{ a, b, c, d, e, f, is2D, isIdentity },
{ colors: true }
)}`;
} else {
let {
m11,
m12,
m13,
m14,
m21,
m22,
m23,
m24,
m31,
m32,
m33,
m34,
m41,
m42,
m43,
m44,
is2D,
isIdentity
} = this;
return `DOMMatrix ${inspect(
{
a,
b,
c,
d,
e,
f,
m11,
m12,
m13,
m14,
m21,
m22,
m23,
m24,
m31,
m32,
m33,
m34,
m41,
m42,
m43,
m44,
is2D,
isIdentity
},
{ colors: true }
)}`;
}
}
multiply(other) {
return newInstance(this[$values]).multiplySelf(other);
}
multiplySelf(other) {
this[$values] = multiply(other[$values], this[$values]);
if (!other.is2D) {
this[$is2D] = false;
}
return this;
}
preMultiplySelf(other) {
this[$values] = multiply(this[$values], other[$values]);
if (!other.is2D) {
this[$is2D] = false;
}
return this;
}
translate(tx, ty, tz) {
return newInstance(this[$values]).translateSelf(tx, ty, tz);
}
translateSelf(tx = 0, ty = 0, tz = 0) {
this[$values] = multiply(
[1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, tx, ty, tz, 1],
this[$values]
);
if (tz !== 0) {
this[$is2D] = false;
}
return this;
}
scale(scaleX, scaleY, scaleZ, originX, originY, originZ) {
return newInstance(this[$values]).scaleSelf(
scaleX,
scaleY,
scaleZ,
originX,
originY,
originZ
);
}
scale3d(scale, originX, originY, originZ) {
return newInstance(this[$values]).scale3dSelf(
scale,
originX,
originY,
originZ
);
}
scale3dSelf(scale, originX, originY, originZ) {
return this.scaleSelf(scale, scale, scale, originX, originY, originZ);
}
scaleSelf(scaleX, scaleY, scaleZ, originX, originY, originZ) {
// Not redundant with translate's checks because we need to negate the values later.
if (typeof originX !== "number") originX = 0;
if (typeof originY !== "number") originY = 0;
if (typeof originZ !== "number") originZ = 0;
this.translateSelf(originX, originY, originZ);
if (typeof scaleX !== "number") scaleX = 1;
if (typeof scaleY !== "number") scaleY = scaleX;
if (typeof scaleZ !== "number") scaleZ = 1;
this[$values] = multiply(
[scaleX, 0, 0, 0, 0, scaleY, 0, 0, 0, 0, scaleZ, 0, 0, 0, 0, 1],
this[$values]
);
this.translateSelf(-originX, -originY, -originZ);
if (scaleZ !== 1 || originZ !== 0) {
this[$is2D] = false;
}
return this;
}
rotateFromVector(x, y) {
return newInstance(this[$values]).rotateFromVectorSelf(x, y);
}
rotateFromVectorSelf(x = 0, y = 0) {
let theta = x === 0 && y === 0 ? 0 : Math.atan2(y, x) * DEGREE_PER_RAD;
return this.rotateSelf(theta);
}
rotate(rotX, rotY, rotZ) {
return newInstance(this[$values]).rotateSelf(rotX, rotY, rotZ);
}
rotateSelf(rotX, rotY, rotZ) {
if (rotY === undefined && rotZ === undefined) {
rotZ = rotX;
rotX = rotY = 0;
}
if (typeof rotY !== "number") rotY = 0;
if (typeof rotZ !== "number") rotZ = 0;
if (rotX !== 0 || rotY !== 0) {
this[$is2D] = false;
}
rotX *= RAD_PER_DEGREE;
rotY *= RAD_PER_DEGREE;
rotZ *= RAD_PER_DEGREE;
let c = Math.cos(rotZ);
let s = Math.sin(rotZ);
this[$values] = multiply(
[c, s, 0, 0, -s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1],
this[$values]
);
c = Math.cos(rotY);
s = Math.sin(rotY);
this[$values] = multiply(
[c, 0, -s, 0, 0, 1, 0, 0, s, 0, c, 0, 0, 0, 0, 1],
this[$values]
);
c = Math.cos(rotX);
s = Math.sin(rotX);
this[$values] = multiply(
[1, 0, 0, 0, 0, c, s, 0, 0, -s, c, 0, 0, 0, 0, 1],
this[$values]
);
return this;
}
rotateAxisAngle(x, y, z, angle) {
return newInstance(this[$values]).rotateAxisAngleSelf(x, y, z, angle);
}
rotateAxisAngleSelf(x = 0, y = 0, z = 0, angle = 0) {
let length = Math.sqrt(x * x + y * y + z * z);
if (length === 0) {
return this;
}
if (length !== 1) {
x /= length;
y /= length;
z /= length;
}
angle *= RAD_PER_DEGREE;
let c = Math.cos(angle);
let s = Math.sin(angle);
let t = 1 - c;
let tx = t * x;
let ty = t * y;
this[$values] = multiply(
[
tx * x + c,
tx * y + s * z,
tx * z - s * y,
0,
tx * y - s * z,
ty * y + c,
ty * z + s * x,
0,
tx * z + s * y,
ty * z - s * x,
t * z * z + c,
0,
0,
0,
0,
1
],
this[$values]
);
if (x !== 0 || y !== 0) {
this[$is2D] = false;
}
return this;
}
skewX(sx) {
return newInstance(this[$values]).skewXSelf(sx);
}
skewXSelf(sx) {
if (typeof sx !== "number") {
return this;
}
let t = Math.tan(sx * RAD_PER_DEGREE);
this[$values] = multiply(
[1, 0, 0, 0, t, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1],
this[$values]
);
return this;
}
skewY(sy) {
return newInstance(this[$values]).skewYSelf(sy);
}
skewYSelf(sy) {
if (typeof sy !== "number") {
return this;
}
let t = Math.tan(sy * RAD_PER_DEGREE);
this[$values] = multiply(
[1, t, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1],
this[$values]
);
return this;
}
flipX() {
return newInstance(
multiply([-1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1], this[$values])
);
}
flipY() {
return newInstance(
multiply([1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1], this[$values])
);
}
inverse() {
return newInstance(this[$values]).invertSelf();
}
invertSelf() {
if (this[$is2D]) {
let det =
this[$values][A] * this[$values][D] -
this[$values][B] * this[$values][C];
// Invertable
if (det !== 0) {
let result = new DOMMatrix();
result.a = this[$values][D] / det;
result.b = -this[$values][B] / det;
result.c = -this[$values][C] / det;
result.d = this[$values][A] / det;
result.e =
(this[$values][C] * this[$values][F] -
this[$values][D] * this[$values][E]) /
det;
result.f =
(this[$values][B] * this[$values][E] -
this[$values][A] * this[$values][F]) /
det;
return result;
}
// Not invertable
else {
this[$is2D] = false;
this[$values] = [
NaN,
NaN,
NaN,
NaN,
NaN,
NaN,
NaN,
NaN,
NaN,
NaN,
NaN,
NaN,
NaN,
NaN,
NaN,
NaN
];
}
} else {
throw new Error("3D matrix inversion is not implemented.");
}
}
setMatrixValue(transformList) {
let temp = new DOMMatrix(transformList);
this[$values] = temp[$values];
this[$is2D] = temp[$is2D];
return this;
}
transformPoint(point) {
let x = point.x;
let y = point.y;
let z = point.z;
let w = point.w;
let values = this[$values];
let nx =
values[M11] * x + values[M21] * y + values[M31] * z + values[M41] * w;
let ny =
values[M12] * x + values[M22] * y + values[M32] * z + values[M42] * w;
let nz =
values[M13] * x + values[M23] * y + values[M33] * z + values[M43] * w;
let nw =
values[M14] * x + values[M24] * y + values[M34] * z + values[M44] * w;
return new DOMPoint(nx, ny, nz, nw);
}
toFloat32Array() {
return Float32Array.from(this[$values]);
}
toFloat64Array() {
return this[$values].slice(0);
}
toJSON() {
return {
a: this.a,
b: this.b,
c: this.c,
d: this.d,
e: this.e,
f: this.f,
m11: this.m11,
m12: this.m12,
m13: this.m13,
m14: this.m14,
m21: this.m21,
m22: this.m22,
m23: this.m23,
m24: this.m24,
m31: this.m31,
m32: this.m32,
m33: this.m33,
m34: this.m34,
m41: this.m41,
m42: this.m42,
m43: this.m43,
m44: this.m44,
is2D: this.is2D,
isIdentity: this.isIdentity
};
}
toString() {
if (this.is2D) {
return `matrix(${this.a}, ${this.b}, ${this.c}, ${this.d}, ${this.e}, ${this.f})`;
} else {
return `matrix3d(${this[$values].join(", ")})`;
}
}
}
for (let propertyName of [
"a",
"b",
"c",
"d",
"e",
"f",
"m11",
"m12",
"m13",
"m14",
"m21",
"m22",
"m23",
"m24",
"m31",
"m32",
"m33",
"m34",
"m41",
"m42",
"m43",
"m44",
"is2D",
"isIdentity"
]) {
let propertyDescriptor = Object.getOwnPropertyDescriptor(
DOMMatrix.prototype,
propertyName
);
propertyDescriptor.enumerable = true;
Object.defineProperty(DOMMatrix.prototype, propertyName, propertyDescriptor);
}
// module.exports = {DOMPoint, DOMMatrix, DOMRect}
const obj = { DOMPoint, DOMMatrix, DOMRect };
export default obj;
/// <reference lib="dom"/>
/// <reference types="node" />
export function loadImage(src: string | Buffer): Promise<Image>
export class DOMMatrix extends globalThis.DOMMatrix {}
export class DOMPoint extends globalThis.DOMPoint {}
export class DOMRect extends globalThis.DOMRect {}
export class Image extends globalThis.Image {}
export class ImageData extends globalThis.ImageData {}
export class CanvasGradient extends globalThis.CanvasGradient {}
export class CanvasPattern extends globalThis.CanvasPattern {}
export class CanvasTexture {}
//
// Canvas
//
export type ExportFormat = "png" | "jpg" | "jpeg" | "pdf" | "svg";
export interface RenderOptions {
/** Page to export: Defaults to 1 (i.e., first page) */
page?: number
/** Background color to draw beneath transparent parts of the canvas */
matte?: string
/** Number of pixels per grid ‘point’ (defaults to 1) */
density?: number
/** Quality for lossy encodings like JPEG (0.0–1.0) */
quality?: number
/** Convert text to paths for SVG exports */
outline?: boolean
}
export interface SaveOptions extends RenderOptions {
/** Image format to use */
format?: ExportFormat
}
export class Canvas {
/** @internal */
constructor(width?: number, height?: number)
static contexts: WeakMap<Canvas, readonly CanvasRenderingContext2D[]>
/**
* @deprecated Use the saveAsSync, toBufferSync, and toDataURLSync methods
* instead of setting the async property to false
*/
async: boolean
width: number
height: number
getContext(type?: "2d"): CanvasRenderingContext2D
newPage(width?: number, height?: number): CanvasRenderingContext2D
readonly pages: CanvasRenderingContext2D[]
saveAs(filename: string, options?: SaveOptions): Promise<void>
toBuffer(format: ExportFormat, options?: RenderOptions): Promise<Buffer>
toDataURL(format: ExportFormat, options?: RenderOptions): Promise<string>
saveAsSync(filename: string, options?: SaveOptions): void
toBufferSync(format: ExportFormat, options?: RenderOptions): Buffer
toDataURLSync(format: ExportFormat, options?: RenderOptions): string
get pdf(): Promise<Buffer>
get svg(): Promise<Buffer>
get jpg(): Promise<Buffer>
get png(): Promise<Buffer>
}
//
// Context
//
type Offset = [x: number, y: number] | number
export interface CreateTextureOptions {
/** The 2D shape to be drawn in a repeating grid with the specified spacing (if omitted, parallel lines will be used) */
path?: Path2D
/** The lineWidth with which to stroke the path (if omitted, the path will be filled instead) */
line?: number
/** The color to use for stroking/filling the path */
color?: string
/** The orientation of the pattern grid in radians */
angle?: number
/** The amount by which to shift the pattern relative to the canvas origin */
offset?: Offset
}
export type CanvasImageSource = Canvas | Image;
interface CanvasDrawImage {
drawImage(image: CanvasImageSource, dx: number, dy: number): void;
drawImage(image: CanvasImageSource, dx: number, dy: number, dw: number, dh: number): void;
drawImage(image: CanvasImageSource, sx: number, sy: number, sw: number, sh: number, dx: number, dy: number, dw: number, dh: number): void;
drawCanvas(image: Canvas, dx: number, dy: number): void;
drawCanvas(image: Canvas, dx: number, dy: number, dw: number, dh: number): void;
drawCanvas(image: Canvas, sx: number, sy: number, sw: number, sh: number, dx: number, dy: number, dw: number, dh: number): void;
}
interface CanvasFillStrokeStyles {
fillStyle: string | CanvasGradient | CanvasPattern | CanvasTexture;
strokeStyle: string | CanvasGradient | CanvasPattern | CanvasTexture;
createConicGradient(startAngle: number, x: number, y: number): CanvasGradient;
createLinearGradient(x0: number, y0: number, x1: number, y1: number): CanvasGradient;
createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number, r1: number): CanvasGradient;
createPattern(image: CanvasImageSource, repetition: string | null): CanvasPattern | null;
createTexture(spacing: Offset, options?: CreateTextureOptions): CanvasTexture
}
type QuadOrRect = [x1:number, y1:number, x2:number, y2:number, x3:number, y3:number, x4:number, y4:number] |
[left:number, top:number, right:number, bottom:number] | [width:number, height:number]
export interface CanvasRenderingContext2D extends CanvasCompositing, CanvasDrawImage, CanvasDrawPath, CanvasFillStrokeStyles, CanvasFilters, CanvasImageData, CanvasImageSmoothing, CanvasPath, CanvasPathDrawingStyles, CanvasRect, CanvasShadowStyles, CanvasState, CanvasText, CanvasTextDrawingStyles, CanvasTransform, CanvasUserInterface {
readonly canvas: Canvas;
fontVariant: string;
textTracking: number;
textWrap: boolean;
lineDashMarker: Path2D | null;
lineDashFit: "move" | "turn" | "follow";
get currentTransform(): DOMMatrix
set currentTransform(matrix: DOMMatrix)
createProjection(quad: QuadOrRect, basis?: QuadOrRect): DOMMatrix
conicCurveTo(cpx: number, cpy: number, x: number, y: number, weight: number): void
// getContextAttributes(): CanvasRenderingContext2DSettings;
fillText(text: string, x: number, y:number, maxWidth?: number): void
strokeText(text: string, x: number, y:number, maxWidth?: number): void
measureText(text: string, maxWidth?: number): TextMetrics
outlineText(text: string): Path2D
}
//
// Bézier Paths
//
export interface Path2DBounds {
readonly top: number
readonly left: number
readonly bottom: number
readonly right: number
readonly width: number
readonly height: number
}
export type Path2DEdge = [verb: string, ...args: number[]]
export class Path2D extends globalThis.Path2D {
d: string
readonly bounds: Path2DBounds
readonly edges: readonly Path2DEdge[]
contains(x: number, y: number): boolean
conicCurveTo(
cpx: number,
cpy: number,
x: number,
y: number,
weight: number
): void
complement(otherPath: Path2D): Path2D
difference(otherPath: Path2D): Path2D
intersect(otherPath: Path2D): Path2D
union(otherPath: Path2D): Path2D
xor(otherPath: Path2D): Path2D
interpolate(otherPath: Path2D, weight: number): Path2D
jitter(segmentLength: number, amount: number, seed?: number): Path2D
offset(dx: number, dy: number): Path2D
points(step?: number): readonly [x: number, y: number][]
round(radius: number): Path2D
simplify(rule?: "nonzero" | "evenodd"): Path2D
transform(...args: [matrix: DOMMatrix] | [a: number, b: number, c: number, d: number, e: number, f: number]): Path2D;
trim(start: number, end: number, inverted?: boolean): Path2D;
trim(start: number, inverted?: boolean): Path2D;
unwind(): Path2D
}
//
// Typography
//
export interface TextMetrics extends globalThis.TextMetrics {
lines: TextMetricsLine[]
}
export interface TextMetricsLine {
readonly x: number
readonly y: number
readonly width: number
readonly height: number
readonly baseline: number
readonly startIndex: number
readonly endIndex: number
}
export interface FontFamily {
family: string
weights: number[]
widths: string[]
styles: string[]
}
export interface Font {
family: string
weight: number
style: string
width: string
file: string
}
export interface FontLibrary {
families: readonly string[]
family(name: string): FontFamily | undefined
has(familyName: string): boolean
use(familyName: string, fontPaths?: string | readonly string[]): Font[]
use(fontPaths: readonly string[]): Font[]
use(
families: Record<string, readonly string[] | string>
): Record<string, Font[] | Font>
}
export const FontLibrary: FontLibrary
"use strict";
import fs from "fs";
import { EventEmitter } from "events";
import { inspect } from "util";
import { sync as glob, hasMagic } from "glob";
import get from "simple-get";
import geometry from "./geometry";
import css from "./css";
import io from "./io";
const REPR = inspect.custom;
// const fs = require("fs"),
// { EventEmitter } = require("events"),
// { inspect } = require("util"),
// { sync: glob, hasMagic } = require("glob"),
// get = require("simple-get"),
// geometry = require("./geometry"),
// css = require("./css"),
// io = require("./io"),
// REPR = inspect.custom;
//
// Neon <-> Node interface
//
const ø = Symbol.for("📦"), // the attr containing the boxed struct
core = obj => (obj || {})[ø], // dereference the boxed struct
wrap = (type, struct) => {
// create new instance for struct
let obj = internal(Object.create(type.prototype), ø, struct);
return struct && internal(obj, "native", neon[type.name]);
},
neon = Object.entries(require("./v6")).reduce((api, [name, fn]) => {
let [_, struct, getset, attr] = name.match(/(.*?)_(?:([sg]et)_)?(.*)/),
cls = api[struct] || (api[struct] = {}),
slot = getset ? cls[attr] || (cls[attr] = {}) : cls;
slot[getset || attr] = fn;
return api;
}, {});
class RustClass {
constructor(type) {
internal(this, "native", neon[type.name]);
}
alloc(...args) {
return this.init("new", ...args);
}
init(fn, ...args) {
return internal(this, ø, this.native[fn](null, ...args));
}
ref(key, val) {
return arguments.length > 1
? (this[Symbol.for(key)] = val)
: this[Symbol.for(key)];
}
prop(attr, val) {
let getset = arguments.length > 1 ? "set" : "get";
return this.native[attr][getset](this[ø], val);
}
ƒ(fn, ...args) {
try {
return this.native[fn](this[ø], ...args);
} catch (error) {
Error.captureStackTrace(error, this.ƒ);
throw error;
}
}
}
// shorthands for attaching read-only attributes
const readOnly = (obj, attr, value) =>
Object.defineProperty(obj, attr, {
value,
writable: false,
enumerable: true
});
const internal = (obj, attr, value) =>
Object.defineProperty(obj, attr, {
value,
writable: false,
enumerable: false
});
// convert arguments list to a string of type abbreviations
function signature(args) {
return args
.map(v =>
Array.isArray(v)
? "a"
: { string: "s", number: "n", object: "o" }[typeof v] || "x"
)
.join("");
}
const toString = val =>
typeof val == "string" ? val : new String(val).toString();
//
// Helpers to reconcile Skia and DOMMatrix’s disagreement about row/col orientation
//
function toSkMatrix(jsMatrix) {
if (Array.isArray(jsMatrix) && jsMatrix.length == 6) {
var [a, b, c, d, e, f, m14, m24, m44] = jsMatrix.concat(0, 0, 1);
} else if (jsMatrix instanceof geometry.DOMMatrix) {
var { a, b, c, d, e, f, m14, m24, m44 } = jsMatrix;
}
return [a, c, e, b, d, f, m14, m24, m44];
}
function fromSkMatrix(skMatrix) {
let [a, b, c, d, e, f, p0, p1, p2] = skMatrix;
return new geometry.DOMMatrix([
a,
d,
0,
p0,
b,
e,
0,
p1,
0,
0,
1,
0,
c,
f,
0,
p2
]);
}
//
// The Canvas API
//
class Canvas extends RustClass {
static parent = new WeakMap();
static contexts = new WeakMap();
constructor(width, height) {
super(Canvas).alloc();
Canvas.contexts.set(this, []);
Object.assign(this, { width, height });
}
getContext(kind) {
return kind == "2d" ? Canvas.contexts.get(this)[0] || this.newPage() : null;
}
get width() {
return this.prop("width");
}
set width(w) {
this.prop(
"width",
typeof w == "number" && !Number.isNaN(w) && w >= 0 ? w : 300
);
if (Canvas.contexts.get(this)[0])
this.getContext("2d").ƒ("resetSize", core(this));
}
get height() {
return this.prop("height");
}
set height(h) {
this.prop(
"height",
(h = typeof h == "number" && !Number.isNaN(h) && h >= 0 ? h : 150)
);
if (Canvas.contexts.get(this)[0])
this.getContext("2d").ƒ("resetSize", core(this));
}
newPage(width, height) {
let ctx = new CanvasRenderingContext2D(core(this));
Canvas.parent.set(ctx, this);
Canvas.contexts.get(this).unshift(ctx);
if (arguments.length == 2) {
Object.assign(this, { width, height });
}
return ctx;
}
get pages() {
return Canvas.contexts
.get(this)
.slice()
.reverse();
}
get png() {
return this.toBuffer("png");
}
get jpg() {
return this.toBuffer("jpg");
}
get pdf() {
return this.toBuffer("pdf");
}
get svg() {
return this.toBuffer("svg");
}
get async() {
return this.prop("async");
}
set async(flag) {
if (!flag) {
process.emitWarning(
"Use the saveAsSync, toBufferSync, and toDataURLSync methods instead of setting the Canvas `async` property to false",
"DeprecationWarning"
);
}
this.prop("async", flag);
}
saveAs(filename, opts = {}) {
if (!this.async) return this.saveAsSync(...arguments); // support while deprecated
opts = typeof opts == "number" ? { quality: opts } : opts;
let {
format,
quality,
pages,
padding,
pattern,
density,
outline,
matte
} = io.options(this.pages, { filename, ...opts }),
args = [
pages.map(core),
pattern,
padding,
format,
quality,
density,
outline,
matte
],
worker = new EventEmitter();
this.ƒ("save", (result, msg) => worker.emit(result, msg), ...args);
return new Promise((res, rej) =>
worker.once("ok", res).once("err", msg => rej(new Error(msg)))
);
}
saveAsSync(filename, opts = {}) {
opts = typeof opts == "number" ? { quality: opts } : opts;
let {
format,
quality,
pages,
padding,
pattern,
density,
outline,
matte
} = io.options(this.pages, { filename, ...opts });
this.ƒ(
"saveSync",
pages.map(core),
pattern,
padding,
format,
quality,
density,
outline,
matte
);
}
toBuffer(extension = "png", opts = {}) {
if (!this.async) return this.toBufferSync(...arguments); // support while deprecated
opts = typeof opts == "number" ? { quality: opts } : opts;
let { format, quality, pages, density, outline, matte } = io.options(
this.pages,
{ extension, ...opts }
),
args = [pages.map(core), format, quality, density, outline, matte],
worker = new EventEmitter();
this.ƒ("toBuffer", (result, msg) => worker.emit(result, msg), ...args);
return new Promise((res, rej) =>
worker.once("ok", res).once("err", msg => rej(new Error(msg)))
);
}
toBufferSync(extension = "png", opts = {}) {
opts = typeof opts == "number" ? { quality: opts } : opts;
let { format, quality, pages, density, outline, matte } = io.options(
this.pages,
{ extension, ...opts }
);
return this.ƒ(
"toBufferSync",
pages.map(core),
format,
quality,
density,
outline,
matte
);
}
toDataURL(extension = "png", opts = {}) {
if (!this.async) return this.toDataURLSync(...arguments); // support while deprecated
opts = typeof opts == "number" ? { quality: opts } : opts;
let { mime } = io.options(this.pages, { extension, ...opts }),
buffer = this.toBuffer(extension, opts);
return buffer.then(
data => `data:${mime};base64,${data.toString("base64")}`
);
}
toDataURLSync(extension = "png", opts = {}) {
opts = typeof opts == "number" ? { quality: opts } : opts;
let { mime } = io.options(this.pages, { extension, ...opts }),
buffer = this.toBufferSync(extension, opts);
return `data:${mime};base64,${buffer.toString("base64")}`;
}
[REPR](depth, options) {
let { width, height, async, pages } = this;
return `Canvas ${inspect({ width, height, async, pages }, options)}`;
}
}
class CanvasGradient extends RustClass {
constructor(style, ...coords) {
super(CanvasGradient);
style = (style || "").toLowerCase();
if (["linear", "radial", "conic"].includes(style))
this.init(style, ...coords);
else
throw new Error(
`Function is not a constructor (use CanvasRenderingContext2D's "createConicGradient", "createLinearGradient", and "createRadialGradient" methods instead)`
);
}
addColorStop(offset, color) {
if (offset >= 0 && offset <= 1) this.ƒ("addColorStop", offset, color);
else throw new Error("Color stop offsets must be between 0.0 and 1.0");
}
[REPR](depth, options) {
return `CanvasGradient (${this.ƒ("repr")})`;
}
}
class CanvasPattern extends RustClass {
constructor(src, repeat) {
super(CanvasPattern);
if (src instanceof Image) {
this.init("from_image", core(src), repeat);
} else if (src instanceof Canvas) {
let ctx = src.getContext("2d");
this.init("from_canvas", core(ctx), repeat);
} else {
throw new Error("CanvasPatterns require a source Image or a Canvas");
}
}
setTransform(matrix) {
if (arguments.length > 1) matrix = [...arguments];
this.ƒ("setTransform", toSkMatrix(matrix));
}
[REPR](depth, options) {
return `CanvasPattern (${this.ƒ("repr")})`;
}
}
class CanvasTexture extends RustClass {
constructor(spacing, { path, line, color, angle, offset = 0 } = {}) {
super(CanvasTexture);
let [x, y] =
typeof offset == "number" ? [offset, offset] : offset.slice(0, 2);
let [h, v] =
typeof spacing == "number" ? [spacing, spacing] : spacing.slice(0, 2);
path = core(path);
line = line != null ? line : path ? 0 : 1;
angle = angle != null ? angle : path ? 0 : -Math.PI / 4;
this.alloc(path, color, line, angle, h, v, x, y);
}
[REPR](depth, options) {
return `CanvasTexture (${this.ƒ("repr")})`;
}
}
class CanvasRenderingContext2D extends RustClass {
constructor(canvas) {
try {
super(CanvasRenderingContext2D).alloc(canvas);
} catch (e) {
throw new TypeError(
`Function is not a constructor (use Canvas's "getContext" method instead)`
);
}
}
get canvas() {
return Canvas.parent.get(this);
}
// -- grid state ------------------------------------------------------------
save() {
this.ƒ("save");
}
restore() {
this.ƒ("restore");
}
get currentTransform() {
return fromSkMatrix(this.prop("currentTransform"));
}
set currentTransform(matrix) {
this.prop("currentTransform", toSkMatrix(matrix));
}
resetTransform() {
this.ƒ("resetTransform");
}
getTransform() {
return this.currentTransform;
}
setTransform(matrix) {
this.currentTransform = arguments.length > 1 ? [...arguments] : matrix;
}
transform(a, b, c, d, e, f) {
this.ƒ("transform", ...arguments);
}
translate(x, y) {
this.ƒ("translate", ...arguments);
}
scale(x, y) {
this.ƒ("scale", ...arguments);
}
rotate(angle) {
this.ƒ("rotate", ...arguments);
}
createProjection(quad, basis) {
return fromSkMatrix(
this.ƒ("createProjection", [quad].flat(), [basis].flat())
);
}
// -- bézier paths ----------------------------------------------------------
beginPath() {
this.ƒ("beginPath");
}
rect(x, y, width, height) {
this.ƒ("rect", ...arguments);
}
arc(x, y, radius, startAngle, endAngle, isCCW) {
this.ƒ("arc", ...arguments);
}
ellipse(x, y, xRadius, yRadius, rotation, startAngle, endAngle, isCCW) {
this.ƒ("ellipse", ...arguments);
}
moveTo(x, y) {
this.ƒ("moveTo", ...arguments);
}
lineTo(x, y) {
this.ƒ("lineTo", ...arguments);
}
arcTo(x1, y1, x2, y2, radius) {
this.ƒ("arcTo", ...arguments);
}
bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y) {
this.ƒ("bezierCurveTo", ...arguments);
}
quadraticCurveTo(cpx, cpy, x, y) {
this.ƒ("quadraticCurveTo", ...arguments);
}
conicCurveTo(cpx, cpy, x, y, weight) {
this.ƒ("conicCurveTo", ...arguments);
}
closePath() {
this.ƒ("closePath");
}
isPointInPath(x, y) {
return this.ƒ("isPointInPath", ...arguments);
}
isPointInStroke(x, y) {
return this.ƒ("isPointInStroke", ...arguments);
}
// -- using paths -----------------------------------------------------------
fill(path, rule) {
if (path instanceof Path2D) this.ƒ("fill", core(path), rule);
else this.ƒ("fill", path); // 'path' is the optional winding-rule
}
stroke(path, rule) {
if (path instanceof Path2D) this.ƒ("stroke", core(path), rule);
else this.ƒ("stroke", path); // 'path' is the optional winding-rule
}
clip(path, rule) {
if (path instanceof Path2D) this.ƒ("clip", core(path), rule);
else this.ƒ("clip", path); // 'path' is the optional winding-rule
}
// -- shaders ---------------------------------------------------------------
createPattern(image, repetition) {
return new CanvasPattern(...arguments);
}
createLinearGradient(x0, y0, x1, y1) {
return new CanvasGradient("Linear", ...arguments);
}
createRadialGradient(x0, y0, r0, x1, y1, r1) {
return new CanvasGradient("Radial", ...arguments);
}
createConicGradient(startAngle, x, y) {
return new CanvasGradient("Conic", ...arguments);
}
createTexture(spacing, options) {
return new CanvasTexture(spacing, options);
}
// -- fill & stroke ---------------------------------------------------------
fillRect(x, y, width, height) {
this.ƒ("fillRect", ...arguments);
}
strokeRect(x, y, width, height) {
this.ƒ("strokeRect", ...arguments);
}
clearRect(x, y, width, height) {
this.ƒ("clearRect", ...arguments);
}
set fillStyle(style) {
let isShader =
style instanceof CanvasPattern ||
style instanceof CanvasGradient ||
style instanceof CanvasTexture,
[ref, val] = isShader ? [style, core(style)] : [null, style];
this.ref("fill", ref);
this.prop("fillStyle", val);
}
get fillStyle() {
let style = this.prop("fillStyle");
return style === null ? this.ref("fill") : style;
}
set strokeStyle(style) {
let isShader =
style instanceof CanvasPattern ||
style instanceof CanvasGradient ||
style instanceof CanvasTexture,
[ref, val] = isShader ? [style, core(style)] : [null, style];
this.ref("stroke", ref);
this.prop("strokeStyle", val);
}
get strokeStyle() {
let style = this.prop("strokeStyle");
return style === null ? this.ref("stroke") : style;
}
// -- line style ------------------------------------------------------------
getLineDash() {
return this.ƒ("getLineDash");
}
setLineDash(segments) {
this.ƒ("setLineDash", segments);
}
get lineCap() {
return this.prop("lineCap");
}
set lineCap(style) {
this.prop("lineCap", style);
}
get lineDashFit() {
return this.prop("lineDashFit");
}
set lineDashFit(style) {
this.prop("lineDashFit", style);
}
get lineDashMarker() {
return wrap(Path2D, this.prop("lineDashMarker"));
}
set lineDashMarker(path) {
this.prop("lineDashMarker", path instanceof Path2D ? core(path) : path);
}
get lineDashOffset() {
return this.prop("lineDashOffset");
}
set lineDashOffset(offset) {
this.prop("lineDashOffset", offset);
}
get lineJoin() {
return this.prop("lineJoin");
}
set lineJoin(style) {
this.prop("lineJoin", style);
}
get lineWidth() {
return this.prop("lineWidth");
}
set lineWidth(width) {
this.prop("lineWidth", width);
}
get miterLimit() {
return this.prop("miterLimit");
}
set miterLimit(limit) {
this.prop("miterLimit", limit);
}
// -- imagery ---------------------------------------------------------------
get imageSmoothingEnabled() {
return this.prop("imageSmoothingEnabled");
}
set imageSmoothingEnabled(flag) {
this.prop("imageSmoothingEnabled", !!flag);
}
get imageSmoothingQuality() {
return this.prop("imageSmoothingQuality");
}
set imageSmoothingQuality(level) {
this.prop("imageSmoothingQuality", level);
}
putImageData(imageData, ...coords) {
this.ƒ("putImageData", imageData, ...coords);
}
createImageData(width, height) {
return new ImageData(width, height);
}
getImageData(x, y, width, height) {
let w = Math.floor(width),
h = Math.floor(height),
buffer = this.ƒ("getImageData", x, y, w, h);
return new ImageData(buffer, w, h);
}
drawImage(image, ...coords) {
if (image instanceof Canvas) {
this.ƒ("drawImage", core(image.getContext("2d")), ...coords);
} else if (image instanceof Image) {
this.ƒ("drawImage", core(image), ...coords);
} else {
throw new Error("Expected an Image or a Canvas argument");
}
}
drawCanvas(image, ...coords) {
if (image instanceof Canvas) {
this.ƒ("drawCanvas", core(image.getContext("2d")), ...coords);
} else {
this.drawImage(image, ...coords);
}
}
// -- typography ------------------------------------------------------------
get font() {
return this.prop("font");
}
set font(str) {
this.prop("font", css.font(str));
}
get textAlign() {
return this.prop("textAlign");
}
set textAlign(mode) {
this.prop("textAlign", mode);
}
get textBaseline() {
return this.prop("textBaseline");
}
set textBaseline(mode) {
this.prop("textBaseline", mode);
}
get direction() {
return this.prop("direction");
}
set direction(mode) {
this.prop("direction", mode);
}
measureText(text, maxWidth) {
text = this.textWrap ? text : text + "\u200b"; // include trailing whitespace by default
let [metrics, ...lines] = this.ƒ("measureText", toString(text), maxWidth);
return new TextMetrics(metrics, lines);
}
fillText(text, x, y, maxWidth) {
this.ƒ("fillText", toString(text), x, y, maxWidth);
}
strokeText(text, x, y, maxWidth) {
this.ƒ("strokeText", toString(text), x, y, maxWidth);
}
outlineText(text) {
let path = this.ƒ("outlineText", toString(text));
return path ? wrap(Path2D, path) : null;
}
// -- non-standard typography extensions --------------------------------------------
get fontVariant() {
return this.prop("fontVariant");
}
set fontVariant(str) {
this.prop("fontVariant", css.variant(str));
}
get textTracking() {
return this.prop("textTracking");
}
set textTracking(ems) {
this.prop("textTracking", ems);
}
get textWrap() {
return this.prop("textWrap");
}
set textWrap(flag) {
this.prop("textWrap", !!flag);
}
// -- effects ---------------------------------------------------------------
get globalCompositeOperation() {
return this.prop("globalCompositeOperation");
}
set globalCompositeOperation(blend) {
this.prop("globalCompositeOperation", blend);
}
get globalAlpha() {
return this.prop("globalAlpha");
}
set globalAlpha(alpha) {
this.prop("globalAlpha", alpha);
}
get shadowBlur() {
return this.prop("shadowBlur");
}
set shadowBlur(level) {
this.prop("shadowBlur", level);
}
get shadowColor() {
return this.prop("shadowColor");
}
set shadowColor(color) {
this.prop("shadowColor", color);
}
get shadowOffsetX() {
return this.prop("shadowOffsetX");
}
set shadowOffsetX(x) {
this.prop("shadowOffsetX", x);
}
get shadowOffsetY() {
return this.prop("shadowOffsetY");
}
set shadowOffsetY(y) {
this.prop("shadowOffsetY", y);
}
get filter() {
return this.prop("filter");
}
set filter(str) {
this.prop("filter", css.filter(str));
}
[REPR](depth, options) {
let props = [
"canvas",
"currentTransform",
"fillStyle",
"strokeStyle",
"font",
"fontVariant",
"direction",
"textAlign",
"textBaseline",
"textTracking",
"textWrap",
"globalAlpha",
"globalCompositeOperation",
"imageSmoothingEnabled",
"imageSmoothingQuality",
"filter",
"shadowBlur",
"shadowColor",
"shadowOffsetX",
"shadowOffsetY",
"lineCap",
"lineDashOffset",
"lineJoin",
"lineWidth",
"miterLimit"
];
let info = {};
if (depth > 0) {
for (var prop of props) {
try {
info[prop] = this[prop];
} catch {
info[prop] = undefined;
}
}
}
return `CanvasRenderingContext2D ${inspect(info, options)}`;
}
}
const _expand = paths =>
[paths]
.flat(2)
.map(pth => (hasMagic(pth) ? glob(pth) : pth))
.flat();
class FontLibrary extends RustClass {
constructor() {
super(FontLibrary);
}
get families() {
return this.prop("families");
}
has(familyName) {
return this.ƒ("has", familyName);
}
family(name) {
return this.ƒ("family", name);
}
use(...args) {
let sig = signature(args);
if (sig == "o") {
let results = {};
for (let [alias, paths] of Object.entries(args.shift())) {
results[alias] = this.ƒ("addFamily", alias, _expand(paths));
}
return results;
} else if (sig.match(/^s?[as]$/)) {
let fonts = _expand(args.pop());
let alias = args.shift();
return this.ƒ("addFamily", alias, fonts);
} else {
throw new Error(
"Expected an array of file paths or an object mapping family names to font files"
);
}
}
}
class Image extends RustClass {
constructor() {
super(Image).alloc();
}
get complete() {
return this.prop("complete");
}
get height() {
return this.prop("height");
}
get width() {
return this.prop("width");
}
get src() {
return this.prop("src");
}
set src(src) {
var noop = () => {},
onload = img => fetch.emit("ok", img),
onerror = err => fetch.emit("err", err),
passthrough = fn => arg => {
(fn || noop)(arg);
delete this._fetch;
},
data;
if (this._fetch) this._fetch.removeAllListeners();
let fetch = (this._fetch = new EventEmitter()
.once("ok", passthrough(this.onload))
.once("err", passthrough(this.onerror)));
if (Buffer.isBuffer(src)) {
[data, src] = [src, ""];
} else if (typeof src != "string") {
return;
} else if (/^\s*data:/.test(src)) {
// data URI
let split = src.indexOf(","),
enc = src.lastIndexOf("base64", split) !== -1 ? "base64" : "utf8",
content = src.slice(split + 1);
data = Buffer.from(content, enc);
} else if (/^\s*https?:\/\//.test(src)) {
// remote URL
get.concat(src, (err, res, data) => {
let code = (res || {}).statusCode;
if (err) onerror(err);
else if (code < 200 || code >= 300) {
onerror(
new Error(`Failed to load image from "${src}" (error ${code})`)
);
} else {
if (this.prop("data", data)) onload(this);
else onerror(new Error("Could not decode image data"));
}
});
} else {
// local file path
data = fs.readFileSync(src);
}
this.prop("src", src);
if (data) {
if (this.prop("data", data)) onload(this);
else onerror(new Error("Could not decode image data"));
}
}
decode() {
return this._fetch
? new Promise((res, rej) => this._fetch.once("ok", res).once("err", rej))
: this.complete
? Promise.resolve(this)
: Promise.reject(new Error("Missing Source URL"));
}
[REPR](depth, options) {
let { width, height, complete, src } = this;
options.maxStringLength = src.match(/^data:/) ? 128 : Infinity;
return `Image ${inspect({ width, height, complete, src }, options)}`;
}
}
class ImageData {
constructor(...args) {
if (args[0] instanceof ImageData) {
var { data, width, height } = args[0];
} else if (
args[0] instanceof Uint8ClampedArray ||
args[0] instanceof Buffer
) {
var [data, width, height] = args;
height = height || data.length / width / 4;
if (data.length / 4 != width * height) {
throw new Error("ImageData dimensions must match buffer length");
}
} else {
var [width, height] = args;
}
if (
!Number.isInteger(width) ||
!Number.isInteger(height) ||
width < 0 ||
height < 0
) {
throw new Error("ImageData dimensions must be positive integers");
}
readOnly(this, "width", width);
readOnly(this, "height", height);
readOnly(
this,
"data",
new Uint8ClampedArray((data && data.buffer) || width * height * 4)
);
}
[REPR](depth, options) {
let { width, height, data } = this;
return `ImageData ${inspect({ width, height, data }, options)}`;
}
}
class Path2D extends RustClass {
static op(operation, path, other) {
return wrap(Path2D, path.ƒ("op", core(other), operation));
}
static interpolate(path, other, weight) {
return wrap(Path2D, path.ƒ("interpolate", core(other), weight));
}
static effect(effect, path, ...args) {
return wrap(Path2D, path.ƒ(effect, ...args));
}
constructor(source) {
super(Path2D);
if (source instanceof Path2D) this.init("from_path", core(source));
else if (typeof source == "string") this.init("from_svg", source);
else this.alloc();
}
// dimensions & contents
get bounds() {
return this.ƒ("bounds");
}
get edges() {
return this.ƒ("edges");
}
get d() {
return this.prop("d");
}
set d(svg) {
return this.prop("d", svg);
}
contains(x, y) {
return this.ƒ("contains", x, y);
}
points(step = 1) {
return this.jitter(step, 0)
.edges.map(([verb, ...pts]) => pts.slice(-2))
.filter(pt => pt.length);
}
// concatenation
addPath(path, matrix) {
if (!(path instanceof Path2D)) throw new Error("Expected a Path2D object");
if (matrix) matrix = toSkMatrix(matrix);
this.ƒ("addPath", core(path), matrix);
}
// line segments
moveTo(x, y) {
this.ƒ("moveTo", ...arguments);
}
lineTo(x, y) {
this.ƒ("lineTo", ...arguments);
}
closePath() {
this.ƒ("closePath");
}
arcTo(x1, y1, x2, y2, radius) {
this.ƒ("arcTo", ...arguments);
}
bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y) {
this.ƒ("bezierCurveTo", ...arguments);
}
quadraticCurveTo(cpx, cpy, x, y) {
this.ƒ("quadraticCurveTo", ...arguments);
}
conicCurveTo(cpx, cpy, x, y, weight) {
this.ƒ("conicCurveTo", ...arguments);
}
// shape primitives
ellipse(x, y, radiusX, radiusY, rotation, startAngle, endAngle, isCCW) {
this.ƒ("ellipse", ...arguments);
}
rect(x, y, width, height) {
this.ƒ("rect", ...arguments);
}
arc(x, y, radius, startAngle, endAngle) {
this.ƒ("arc", ...arguments);
}
// tween similar paths
interpolate(path, weight) {
return Path2D.interpolate(this, path, weight);
}
// boolean operations
complement(path) {
return Path2D.op("complement", this, path);
}
difference(path) {
return Path2D.op("difference", this, path);
}
intersect(path) {
return Path2D.op("intersect", this, path);
}
union(path) {
return Path2D.op("union", this, path);
}
xor(path) {
return Path2D.op("xor", this, path);
}
// path effects
jitter(len, amt, seed) {
return Path2D.effect("jitter", this, ...arguments);
}
simplify(rule) {
return Path2D.effect("simplify", this, rule);
}
unwind() {
return Path2D.effect("unwind", this);
}
round(radius) {
return Path2D.effect("round", this, radius);
}
offset(dx, dy) {
return Path2D.effect("offset", this, dx, dy);
}
transform(matrix) {
let terms = arguments.length > 1 ? [...arguments] : matrix;
return Path2D.effect("transform", this, toSkMatrix(terms));
}
trim(...rng) {
if (typeof rng[1] != "number") {
if (rng[0] > 0) rng.unshift(0);
else if (rng[0] < 0) rng.splice(1, 0, 1);
}
if (rng[0] < 0) rng[0] = Math.max(-1, rng[0]) + 1;
if (rng[1] < 0) rng[1] = Math.max(-1, rng[1]) + 1;
return Path2D.effect("trim", this, ...rng);
}
[REPR](depth, options) {
let { d, bounds, edges } = this;
return `Path2D ${inspect({ d, bounds, edges }, options)}`;
}
}
class TextMetrics {
constructor(
[
width,
left,
right,
ascent,
descent,
fontAscent,
fontDescent,
emAscent,
emDescent,
hanging,
alphabetic,
ideographic
],
lines
) {
readOnly(this, "width", width);
readOnly(this, "actualBoundingBoxLeft", left);
readOnly(this, "actualBoundingBoxRight", right);
readOnly(this, "actualBoundingBoxAscent", ascent);
readOnly(this, "actualBoundingBoxDescent", descent);
readOnly(this, "fontBoundingBoxAscent", fontAscent);
readOnly(this, "fontBoundingBoxDescent", fontDescent);
readOnly(this, "emHeightAscent", emAscent);
readOnly(this, "emHeightDescent", emDescent);
readOnly(this, "hangingBaseline", hanging);
readOnly(this, "alphabeticBaseline", alphabetic);
readOnly(this, "ideographicBaseline", ideographic);
readOnly(
this,
"lines",
lines.map(([x, y, width, height, baseline, startIndex, endIndex]) => ({
x,
y,
width,
height,
baseline,
startIndex,
endIndex
}))
);
}
}
const loadImage = src => Object.assign(new Image(), { src }).decode();
// module.exports = {
// Canvas,
// CanvasGradient,
// CanvasPattern,
// CanvasRenderingContext2D,
// CanvasTexture,
// TextMetrics,
// Image,
// ImageData,
// Path2D,
// loadImage,
// ...geometry,
// FontLibrary: new FontLibrary()
// };
const obj = {
Canvas,
CanvasGradient,
CanvasPattern,
CanvasRenderingContext2D,
CanvasTexture,
TextMetrics,
Image,
ImageData,
Path2D,
loadImage,
...geometry,
FontLibrary: new FontLibrary()
};
export default obj;
"use strict";
// const { basename, extname } = require("path");
import { basename, extname } from "../../path-browserify/index.js";
//
// Mime type <-> File extension mappings
//
class Format {
constructor() {
let isWeb = (() => typeof global == "undefined")(),
png = "image/png",
jpg = "image/jpeg",
jpeg = "image/jpeg",
webp = "image/webp",
pdf = "application/pdf",
svg = "image/svg+xml";
Object.assign(this, {
toMime: this.toMime.bind(this),
fromMime: this.fromMime.bind(this),
expected: isWeb
? `"png", "jpg", or "webp"`
: `"png", "jpg", "pdf", or "svg"`,
formats: isWeb ? { png, jpg, jpeg, webp } : { png, jpg, jpeg, pdf, svg },
mimes: isWeb
? { [png]: "png", [jpg]: "jpg", [webp]: "webp" }
: { [png]: "png", [jpg]: "jpg", [pdf]: "pdf", [svg]: "svg" }
});
}
toMime(ext) {
return this.formats[(ext || "").replace(/^\./, "").toLowerCase()];
}
fromMime(mime) {
return this.mimes[mime];
}
}
//
// Validation of the options dict shared by the Canvas saveAs, toBuffer, and toDataURL methods
//
function options(
pages,
{
filename = "",
extension = "",
format,
page,
quality,
matte,
density,
outline,
archive
} = {}
) {
var { fromMime, toMime, expected } = new Format(),
archive = archive || "canvas",
ext = format || extension.replace(/@\d+x$/i, "") || extname(filename),
format = fromMime(toMime(ext) || ext),
mime = toMime(format),
pp = pages.length;
if (!ext)
throw new Error(
`Cannot determine image format (use a filename extension or 'format' argument)`
);
if (!format)
throw new Error(`Unsupported file format "${ext}" (expected ${expected})`);
if (!pp)
throw new RangeError(
`Canvas has no associated contexts (try calling getContext or newPage first)`
);
let padding,
isSequence,
pattern = filename.replace(/{(\d*)}/g, (_, width) => {
isSequence = true;
width = parseInt(width, 10);
padding = isFinite(width) ? width : isFinite(padding) ? padding : -1;
return "{}";
});
// allow negative indexing if a specific page is specified
let idx = page > 0 ? page - 1 : page < 0 ? pp + page : undefined;
if ((isFinite(idx) && idx < 0) || idx >= pp)
throw new RangeError(
pp == 1
? `Canvas only has a ‘page 1’ (${idx} is out of bounds)`
: `Canvas has pages 1–${pp} (${idx} is out of bounds)`
);
pages = isFinite(idx)
? [pages[idx]]
: isSequence || format == "pdf"
? pages
: pages.slice(-1); // default to the 'current' context
if (quality === undefined) {
quality = 0.92;
} else {
if (
typeof quality != "number" ||
!isFinite(quality) ||
quality < 0 ||
quality > 1
) {
throw new TypeError(
"The quality option must be an number in the 0.0–1.0 range"
);
}
}
if (density === undefined) {
let m = (extension || basename(filename, ext)).match(/@(\d+)x$/i);
density = m ? parseInt(m[1], 10) : 1;
} else if (
typeof density != "number" ||
!Number.isInteger(density) ||
density < 1
) {
throw new TypeError("The density option must be a non-negative integer");
}
if (outline === undefined) {
outline = true;
} else if (format == "svg") {
outline = !!outline;
}
return {
filename,
pattern,
format,
mime,
pages,
padding,
quality,
matte,
density,
outline,
archive
};
}
//
// Zip (pace Phil Katz & q.v. https://github.com/jimmywarting/StreamSaver.js)
//
class Crc32 {
static for(data) {
return new Crc32().append(data).get();
}
constructor() {
this.crc = -1;
}
get() {
return ~this.crc;
}
append(data) {
var crc = this.crc | 0,
table = this.table;
for (var offset = 0, len = data.length | 0; offset < len; offset++) {
crc = (crc >>> 8) ^ table[(crc ^ data[offset]) & 0xff];
}
this.crc = crc;
return this;
}
}
Crc32.prototype.table = (() => {
var i,
j,
t,
table = [];
for (i = 0; i < 256; i++) {
t = i;
for (j = 0; j < 8; j++) {
t = t & 1 ? (t >>> 1) ^ 0xedb88320 : t >>> 1;
}
table[i] = t;
}
return table;
})();
function calloc(size) {
let array = new Uint8Array(size),
view = new DataView(array.buffer),
buf = {
array,
view,
size,
set8(at, to) {
view.setUint8(at, to);
return buf;
},
set16(at, to) {
view.setUint16(at, to, true);
return buf;
},
set32(at, to) {
view.setUint32(at, to, true);
return buf;
},
bytes(at, to) {
array.set(to, at);
return buf;
}
};
return buf;
}
// const TextEncoder=require('util').TextEncoder
class Zip {
constructor(directory) {
let now = new Date();
Object.assign(this, {
directory,
offset: 0,
files: [],
time:
(((now.getHours() << 6) | now.getMinutes()) << 5) |
(now.getSeconds() / 2),
date:
((((now.getFullYear() - 1980) << 4) | (now.getMonth() + 1)) << 5) |
now.getDate()
});
this.add(directory);
}
async add(filename, blob) {
let folder = !blob,
name = Zip.encoder.encode(`${this.directory}/${folder ? "" : filename}`),
data = new Uint8Array(folder ? 0 : await blob.arrayBuffer()),
preamble = 30 + name.length,
descriptor = preamble + data.length,
postamble = 16,
{ offset } = this;
let header = calloc(26)
.set32(0, 0x08080014) // zip version
.set16(6, this.time) // time
.set16(8, this.date) // date
.set32(10, Crc32.for(data)) // checksum
.set32(14, data.length) // compressed size (w/ zero compression)
.set32(18, data.length) // un-compressed size
.set16(22, name.length); // filename length (utf8 bytes)
offset += preamble;
let payload = calloc(preamble + data.length + postamble)
.set32(0, 0x04034b50) // local header signature
.bytes(4, header.array) // ...header fields...
.bytes(30, name) // filename
.bytes(preamble, data); // blob bytes
offset += data.length;
payload
.set32(descriptor, 0x08074b50) // signature
.bytes(descriptor + 4, header.array.slice(10, 22)); // length & filemame
offset += postamble;
this.files.push({ offset, folder, name, header, payload });
this.offset = offset;
}
toBuffer() {
// central directory record
let length = this.files.reduce(
(len, { name }) => 46 + name.length + len,
0
),
cdr = calloc(length + 22),
index = 0;
for (var { offset, name, header, folder } of this.files) {
cdr
.set32(index, 0x02014b50) // archive file signature
.set16(index + 4, 0x0014) // version
.bytes(index + 6, header.array) // ...header fields...
.set8(index + 38, folder ? 0x10 : 0) // is_dir flag
.set32(index + 42, offset) // file offset
.bytes(index + 46, name); // filename
index += 46 + name.length;
}
cdr
.set32(index, 0x06054b50) // signature
.set16(index + 8, this.files.length) // № files per-segment
.set16(index + 10, this.files.length) // № files this segment
.set32(index + 12, length) // central directory length
.set32(index + 16, this.offset); // file-offset of directory
// concatenated zipfile data
let output = new Uint8Array(this.offset + cdr.size),
cursor = 0;
for (var { payload } of this.files) {
output.set(payload.array, cursor);
cursor += payload.size;
}
output.set(cdr.array, cursor);
return output;
}
get blob() {
return new Blob([this.toBuffer()], { type: "application/zip" });
}
}
Zip.encoder = new TextEncoder();
//
// Browser helpers for converting canvas elements to blobs/buffers/files/zips
//
const asBlob = (canvas, mime, quality, matte) => {
if (matte) {
let { width, height } = canvas,
comp = Object.assign(document.createElement("canvas"), { width, height }),
ctx = comp.getContext("2d");
ctx.fillStyle = matte;
ctx.fillRect(0, 0, width, height);
ctx.drawImage(canvas, 0, 0);
canvas = comp;
}
return new Promise((res, rej) => canvas.toBlob(res, mime, quality));
};
const asBuffer = (...args) => asBlob(...args).then(b => b.arrayBuffer());
const asDownload = async (canvas, mime, quality, matte, filename) => {
_download(filename, await asBlob(canvas, mime, quality, matte));
};
const asZipDownload = async (
pages,
mime,
quality,
matte,
archive,
pattern,
padding
) => {
let filenames = i =>
pattern.replace("{}", String(i + 1).padStart(padding, "0")),
folder = basename(archive, ".zip") || "archive",
zip = new Zip(folder);
await Promise.all(
pages.map(async (page, i) => {
let filename = filenames(i); // serialize filename(s) before awaiting
await zip.add(filename, await asBlob(page, mime, quality, matte));
})
);
_download(`${folder}.zip`, zip.blob);
};
const _download = (filename, blob) => {
const href = window.URL.createObjectURL(blob),
link = document.createElement("a");
link.style.display = "none";
link.href = href;
link.setAttribute("download", filename);
if (typeof link.download === "undefined") {
link.setAttribute("target", "_blank");
}
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
setTimeout(() => window.URL.revokeObjectURL(href), 100);
};
const atScale = (pages, density, matte) =>
pages.map(page => {
if (density == 1 && !matte) return page.canvas;
let scaled = document.createElement("canvas"),
ctx = scaled.getContext("2d"),
src = page.canvas ? page.canvas : page;
scaled.width = src.width * density;
scaled.height = src.height * density;
if (matte) {
ctx.fillStyle = matte;
ctx.fillRect(0, 0, scaled.width, scaled.height);
}
ctx.scale(density, density);
ctx.drawImage(src, 0, 0);
return scaled;
});
const obj = { asBuffer, asDownload, asZipDownload, atScale, options };
export default obj;
// module.exports = { asBuffer, asDownload, asZipDownload, atScale, options };
{
"name": "skia-canvas",
"version": "0.9.29",
"description": "A canvas environment for Node",
"author": "Christian Swinehart <drafting@samizdat.co>",
"license": "MIT",
"repository": {
"type": "git",
"url": "git+https://github.com/samizdatco/skia-canvas.git"
},
"bugs": {
"url": "https://github.com/samizdatco/skia-canvas/issues"
},
"homepage": "https://github.com/samizdatco/skia-canvas#readme",
"main": "lib",
"browser": {
"lib": "./lib/browser.js",
"path": "path-browserify"
},
"scripts": {
"build": "cargo-cp-artifact -nc lib/v6/index.node -- cargo build --message-format=json-render-diagnostics",
"install": "node-pre-gyp install || npm run build -- --release",
"package": "node-pre-gyp package",
"upload": "node-pre-gyp publish",
"test": "jest"
},
"dependencies": {
"@mapbox/node-pre-gyp": "^1.0.8",
"cargo-cp-artifact": "^0.1",
"glob": "^7.2.0",
"path-browserify": "^1.0.1",
"simple-get": "^4.0.1",
"string-split-by": "^1.0.0"
},
"devDependencies": {
"@types/jest": "^27.4.0",
"@types/node": "^17.0.15",
"aws-sdk": "^2.1069.0",
"express": "^4.17.2",
"jest": "^27.5.0",
"lodash": "^4.17.21",
"nodemon": "^2.0.15",
"tmp": "^0.2.1"
},
"files": [
"lib"
],
"binary": {
"module_name": "index",
"module_path": "./lib/v{napi_build_version}",
"remote_path": "./v{version}",
"package_name": "{platform}-{arch}-{node_napi_label}-{libc}.tar.gz",
"host": "https://skia-canvas.s3.us-east-1.amazonaws.com",
"napi_versions": [
6
]
},
"keywords": [
"skia",
"canvas",
"offscreen",
"headless",
"graphic",
"graphics",
"image",
"images",
"compositing",
"render",
"pdf",
"svg",
"rust"
]
}
<template>
<div>
<vue-qr
text="123456789012345"
:components="{
cornerAlignment: {
scale: 0.5,
protectors: true
}
}"
></vue-qr>
<vue-qr
text="123456789012345"
:components="{
cornerAlignment: {
scale: 1,
protectors: true
}
}"
></vue-qr>
<vue-qr
text="test"
colorDark="#28D905"
colorLight="#EB0303"
backgroundColor="#EB0303"
:margin="0"
:bindElement="true"
:callback="test"
></vue-qr>
<vue-qr
text="hello world"
:correctLevel="0"
backgroundColor="rgb(255,0,0)"
></vue-qr>
<vue-qr
text="hello world"
:correctLevel="1"
colorLight="rgb(255,0,0)"
></vue-qr>
<vue-qr
text="hello world"
:correctLevel="1"
colorLight="rgb(0,255,0)"
></vue-qr>
<vue-qr text="hello world" :correctLevel="2"></vue-qr>
<vue-qr
:bgSrc="src"
:logoSrc="src2"
text="Hello world!"
:size="260"
:margin="0"
:dotScale="0.5"
></vue-qr>
<vue-qr
:bgSrc="src"
:logoSrc="src2"
text="Hello world!"
:size="260"
:margin="50"
:dotScale="0.5"
></vue-qr>
<vue-qr
:bgSrc="src"
:logoSrc="src2"
text="Hello world!"
:size="260"
:margin="0"
:dotScale="0.5"
logoBackgroundColor="rgb(255,0,0)"
:logoMargin="10"
></vue-qr>
<vue-qr text="testdsfhsidufhiusdhfi" :bgSrc="src"></vue-qr>
<vue-qr :text="time + ''"></vue-qr>
<vue-qr
:bgSrc="src3"
text="Hello world!"
:size="260"
:margin="0"
:dotScale="0.6"
></vue-qr>
<vue-qr
:bgSrc="src4"
text="Hello world!"
:size="300"
:dotScale="0.5"
></vue-qr>
<vue-qr
text="Hello world!"
:callback="test"
qid="testid"
:size="300"
></vue-qr>
<vue-qr
text="test test test test test test "
:gifBgSrc="gifBgSrc1"
:size="300"
:dotScale="0.4"
:logoSrc="src2"
></vue-qr>
<vue-qr
text="test test test test test test "
:gifBgSrc="gifBgSrc2"
:size="300"
></vue-qr>
<vue-qr
text="test test test test test "
:gifBgSrc="gifBgSrc2"
:size="300"
backgroundDimming="rgb(255,0,0)"
colorDark="rgb(0,0,0)"
:dotScale="0.5"
></vue-qr>
<vue-qr text="test"></vue-qr>
</div>
</template>
<script>
import vueQr from "./packages/vue-qr";
import src from "./assets/bg1.png";
import src2 from "./assets/avatar.png";
import src3 from "./assets/bg2.jpg";
import src4 from "./assets/bg3.jpg";
import gifBgSrc1 from "./assets/dog.gif";
import gifBgSrc2 from "./assets/scare.gif";
export default {
mounted() {
setInterval(() => {
this.time++;
}, 1000);
},
data() {
return {
src,
src2,
src3,
src4,
time: 0,
gifBgSrc1,
gifBgSrc2
};
},
components: {
vueQr
},
methods: {
test(url, id) {
console.log(url, id);
}
}
};
</script>
import vueQr from './packages/index.js';
const components = [
vueQr
]
const install = function(Vue, opts = {}) {
components.map(component => {
Vue.component(component.name, component);
})
}
/* 支持使用标签的方式引入 */
if (typeof window !== 'undefined' && window.Vue) {
install(window.Vue);
}
export default vueQr
/// <reference types="node" />
export declare type ComponentOptions = {
/**
* Component options for data/ECC.
*/
data?: {
/**
* Scale factor for data/ECC dots.
* @default 0.4
*/
scale?: number;
};
/**
* Component options for timing patterns.
*/
timing?: {
/**
* Scale factor for timing patterns.
* @default 0.5
*/
scale?: number;
/**
* Protector for timing patterns.
* @default false
*/
protectors?: boolean;
};
/**
* Component options for alignment patterns.
*/
alignment?: {
/**
* Scale factor for alignment patterns.
* @default 0.5
*/
scale?: number;
/**
* Protector for alignment patterns.
* @default false
*/
protectors?: boolean;
};
/**
* Component options for alignment pattern on the bottom-right corner.
*/
cornerAlignment?: {
/**
* Scale factor for alignment pattern on the bottom-right corner.
* @default 0.5
*/
scale?: number;
/**
* Protector for alignment pattern on the bottom-right corner.
* @default true
*/
protectors?: boolean;
};
};
export declare type Options = {
/**
* Text to be encoded in the QR code.
*/
text: string;
/**
* Size of the QR code in pixel.
*
* @defaultValue 400
*/
size?: number;
/**
* Size of margins around the QR code body in pixel.
*
* @defaultValue 20
*/
margin?: number;
/**
* Error correction level of the QR code.
*
* Accepts a value provided by _QRErrorCorrectLevel_.
*
* For more information, please refer to [https://www.qrcode.com/en/about/error_correction.html](https://www.qrcode.com/en/about/error_correction.html).
*
* @defaultValue 0
*/
correctLevel?: number;
/**
* **This is an advanced option.**
*
* Specify the mask pattern to be used in QR code encoding.
*
* Accepts a value provided by _QRMaskPattern_.
*
* To find out all eight mask patterns, please refer to [https://en.wikipedia.org/wiki/File:QR_Code_Mask_Patterns.svg](https://en.wikipedia.org/wiki/File:QR_Code_Mask_Patterns.svg)
*
* For more information, please refer to [https://en.wikiversity.org/wiki/Reed%E2%80%93Solomon_codes_for_coders#Masking](https://en.wikiversity.org/wiki/Reed%E2%80%93Solomon_codes_for_coders#Masking).
*/
maskPattern?: number;
/**
* **This is an advanced option.**
*
* Specify the version to be used in QR code encoding.
*
* Accepts an integer in range [1, 40].
*
* For more information, please refer to [https://www.qrcode.com/en/about/version.html](https://www.qrcode.com/en/about/version.html).
*/
version?: number;
/**
* Options to control components in the QR code.
*
* @deafultValue undefined
*/
components?: ComponentOptions;
/**
* Color of the blocks on the QR code.
*
* Accepts a CSS &lt;color&gt;.
*
* For more information about CSS &lt;color&gt;, please refer to [https://developer.mozilla.org/en-US/docs/Web/CSS/color_value](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value).
*
* @defaultValue "#000000"
*/
colorDark?: string;
/**
* Color of the empty areas on the QR code.
*
* Accepts a CSS &lt;color&gt;.
*
* For more information about CSS &lt;color&gt;, please refer to [https://developer.mozilla.org/en-US/docs/Web/CSS/color_value](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value).
*
* @defaultValue "#ffffff"
*/
colorLight?: string;
/**
* Automatically calculate the _colorLight_ value from the QR code's background.
*
* @defaultValue true
*/
autoColor?: boolean;
/**
* Background image to be used in the QR code.
*
* Accepts a `data:` string in web browsers or a Buffer in Node.js.
*
* @defaultValue undefined
*/
backgroundImage?: string | Buffer;
/**
* Color of the dimming mask above the background image.
*
* Accepts a CSS &lt;color&gt;.
*
* For more information about CSS &lt;color&gt;, please refer to [https://developer.mozilla.org/en-US/docs/Web/CSS/color_value](https://developer.mozilla.org/en-US/docs/Web/CSS/color_value).
*
* @defaultValue "rgba(0, 0, 0, 0)"
*/
backgroundDimming?: string;
/**
* GIF background image to be used in the QR code.
*
* @defaultValue undefined
*/
gifBackground?: ArrayBuffer;
/**
* Use a white margin instead of a transparent one which reveals the background of the QR code on margins.
*
* @defaultValue true
*/
whiteMargin?: boolean;
/**
* Logo image to be displayed at the center of the QR code.
*
* Accepts a `data:` string in web browsers or a Buffer in Node.js.
*
* When set to `undefined` or `null`, the logo is disabled.
*
* @defaultValue undefined
*/
logoImage?: string | Buffer;
/**
* Ratio of the logo size to the QR code size.
*
* @defaultValue 0.2
*/
logoScale?: number;
/**
* Size of margins around the logo image in pixels.
*
* @defaultValue 6
*/
logoMargin?: number;
/**
* Corner radius of the logo image in pixels.
*
* @defaultValue 8
*/
logoCornerRadius?: number;
/**
* @deprecated
*
* Ratio of the real size to the full size of the blocks.
*
* This can be helpful when you want to make more parts of the background visible.
*
* @deafultValue 0.4
*/
dotScale?: number;
logoBackgroundColor: string;
backgroundColor: string;
};
export declare class AwesomeQR {
private canvas;
private canvasContext;
private qrCode?;
private options;
static CorrectLevel: {
L: number;
M: number;
Q: number;
H: number;
};
private static defaultComponentOptions;
static defaultOptions: Options;
constructor(options: Partial<Options>);
draw(): Promise<Buffer | ArrayBuffer | string | undefined>;
private _clear;
private static _prepareRoundedCornerClip;
private static _getAverageRGB;
private static _drawDot;
private static _drawAlignProtector;
private static _drawAlign;
private _draw;
}
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
import canvas from "../../packages/skia-canvas-lib/lib/browser";
const { Canvas } = canvas;
import { decompressFrames, parseGIF } from "./gifuct-js/index";
import { QRCodeModel, QRErrorCorrectLevel, QRUtil } from "./qrcode";
import GIFEncoder from "./gif.js/GIFEncoder";
const defaultScale = 0.4;
function loadImage(url) {
if (!url) {
return undefined;
}
function cleanup(img) {
img.onload = null;
img.onerror = null;
}
return new Promise(function (resolve, reject) {
if (url.slice(0, 4) == 'data') {
let img = new Image();
img.onload = function () {
resolve(img);
cleanup(img);
};
img.onerror = function () {
reject('Image load error');
cleanup(img);
};
img.src = url;
return;
}
let img = new Image();
img.setAttribute("crossOrigin", 'Anonymous');
img.onload = function () {
resolve(img);
};
img.onerror = function () {
reject('Image load error');
};
img.src = url;
});
}
export class AwesomeQR {
constructor(options) {
const _options = Object.assign({}, options);
Object.keys(AwesomeQR.defaultOptions).forEach((k) => {
if (!(k in _options)) {
Object.defineProperty(_options, k, { value: AwesomeQR.defaultOptions[k], enumerable: true, writable: true });
}
});
if (!_options.components) {
_options.components = AwesomeQR.defaultComponentOptions;
}
else if (typeof _options.components === "object") {
Object.keys(AwesomeQR.defaultComponentOptions).forEach((k) => {
if (!(k in _options.components)) {
Object.defineProperty(_options.components, k, {
value: AwesomeQR.defaultComponentOptions[k],
enumerable: true,
writable: true,
});
}
else {
Object.defineProperty(_options.components, k, {
value: Object.assign(Object.assign({}, AwesomeQR.defaultComponentOptions[k]), _options.components[k]),
enumerable: true,
writable: true,
});
}
});
}
if (_options.dotScale !== null && _options.dotScale !== undefined) {
if (_options.dotScale <= 0 || _options.dotScale > 1) {
throw new Error("dotScale should be in range (0, 1].");
}
_options.components.data.scale = _options.dotScale;
_options.components.timing.scale = _options.dotScale;
_options.components.alignment.scale = _options.dotScale;
}
this.options = _options;
this.canvas = new Canvas(options.size, options.size);
this.canvasContext = this.canvas.getContext("2d");
this.qrCode = new QRCodeModel(-1, this.options.correctLevel);
if (Number.isInteger(this.options.maskPattern)) {
this.qrCode.maskPattern = this.options.maskPattern;
}
if (Number.isInteger(this.options.version)) {
this.qrCode.typeNumber = this.options.version;
}
this.qrCode.addData(this.options.text);
this.qrCode.make();
}
draw() {
return new Promise((resolve) => this._draw().then(resolve));
}
_clear() {
this.canvasContext.clearRect(0, 0, this.canvas.width, this.canvas.height);
}
static _prepareRoundedCornerClip(canvasContext, x, y, w, h, r) {
canvasContext.beginPath();
canvasContext.moveTo(x, y);
canvasContext.arcTo(x + w, y, x + w, y + h, r);
canvasContext.arcTo(x + w, y + h, x, y + h, r);
canvasContext.arcTo(x, y + h, x, y, r);
canvasContext.arcTo(x, y, x + w, y, r);
canvasContext.closePath();
}
static _getAverageRGB(image) {
const blockSize = 5;
const defaultRGB = {
r: 0,
g: 0,
b: 0,
};
let width, height;
let i = -4;
const rgb = {
r: 0,
g: 0,
b: 0,
};
let count = 0;
height = image.naturalHeight || image.height;
width = image.naturalWidth || image.width;
const canvas = new Canvas(width, height);
const context = canvas.getContext("2d");
if (!context) {
return defaultRGB;
}
context.drawImage(image, 0, 0);
let data;
try {
data = context.getImageData(0, 0, width, height);
}
catch (e) {
return defaultRGB;
}
while ((i += blockSize * 4) < data.data.length) {
if (data.data[i] > 200 || data.data[i + 1] > 200 || data.data[i + 2] > 200)
continue;
++count;
rgb.r += data.data[i];
rgb.g += data.data[i + 1];
rgb.b += data.data[i + 2];
}
rgb.r = ~~(rgb.r / count);
rgb.g = ~~(rgb.g / count);
rgb.b = ~~(rgb.b / count);
return rgb;
}
static _drawDot(canvasContext, centerX, centerY, nSize, xyOffset = 0, dotScale = 1) {
canvasContext.fillRect((centerX + xyOffset) * nSize, (centerY + xyOffset) * nSize, dotScale * nSize, dotScale * nSize);
}
static _drawAlignProtector(canvasContext, centerX, centerY, nSize) {
canvasContext.clearRect((centerX - 2) * nSize, (centerY - 2) * nSize, 5 * nSize, 5 * nSize);
canvasContext.fillRect((centerX - 2) * nSize, (centerY - 2) * nSize, 5 * nSize, 5 * nSize);
}
static _drawAlign(canvasContext, centerX, centerY, nSize, xyOffset = 0, dotScale = 1, colorDark, hasProtector) {
const oldFillStyle = canvasContext.fillStyle;
canvasContext.fillStyle = colorDark;
new Array(4).fill(0).map((_, i) => {
AwesomeQR._drawDot(canvasContext, centerX - 2 + i, centerY - 2, nSize, xyOffset, dotScale);
AwesomeQR._drawDot(canvasContext, centerX + 2, centerY - 2 + i, nSize, xyOffset, dotScale);
AwesomeQR._drawDot(canvasContext, centerX + 2 - i, centerY + 2, nSize, xyOffset, dotScale);
AwesomeQR._drawDot(canvasContext, centerX - 2, centerY + 2 - i, nSize, xyOffset, dotScale);
});
AwesomeQR._drawDot(canvasContext, centerX, centerY, nSize, xyOffset, dotScale);
if (!hasProtector) {
canvasContext.fillStyle = "rgba(255, 255, 255, 0.6)";
new Array(2).fill(0).map((_, i) => {
AwesomeQR._drawDot(canvasContext, centerX - 1 + i, centerY - 1, nSize, xyOffset, dotScale);
AwesomeQR._drawDot(canvasContext, centerX + 1, centerY - 1 + i, nSize, xyOffset, dotScale);
AwesomeQR._drawDot(canvasContext, centerX + 1 - i, centerY + 1, nSize, xyOffset, dotScale);
AwesomeQR._drawDot(canvasContext, centerX - 1, centerY + 1 - i, nSize, xyOffset, dotScale);
});
}
canvasContext.fillStyle = oldFillStyle;
}
_draw() {
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u;
return __awaiter(this, void 0, void 0, function* () {
const nCount = (_a = this.qrCode) === null || _a === void 0 ? void 0 : _a.moduleCount;
const rawSize = this.options.size;
let rawMargin = this.options.margin;
if (rawMargin < 0 || rawMargin * 2 >= rawSize) {
rawMargin = 0;
}
const margin = Math.ceil(rawMargin);
const rawViewportSize = rawSize - 2 * rawMargin;
const whiteMargin = this.options.whiteMargin;
const backgroundDimming = this.options.backgroundDimming;
const nSize = Math.ceil(rawViewportSize / nCount);
const viewportSize = nSize * nCount;
const size = viewportSize + 2 * margin;
const mainCanvas = new Canvas(size, size);
const mainCanvasContext = mainCanvas.getContext("2d");
this._clear();
// Translate to make the top and left margins off the viewport
mainCanvasContext.save();
mainCanvasContext.translate(margin, margin);
const backgroundCanvas = new Canvas(size, size);
const backgroundCanvasContext = backgroundCanvas.getContext("2d");
let parsedGIFBackground = null;
let gifFrames = [];
if (!!this.options.gifBackground) {
const gif = parseGIF(this.options.gifBackground);
parsedGIFBackground = gif;
gifFrames = decompressFrames(gif, true);
if (this.options.autoColor) {
let r = 0, g = 0, b = 0;
let count = 0;
for (let i = 0; i < gifFrames[0].colorTable.length; i++) {
const c = gifFrames[0].colorTable[i];
if (c[0] > 200 || c[1] > 200 || c[2] > 200)
continue;
if (c[0] === 0 && c[1] === 0 && c[2] === 0)
continue;
count++;
r += c[0];
g += c[1];
b += c[2];
}
r = ~~(r / count);
g = ~~(g / count);
b = ~~(b / count);
this.options.colorDark = `rgb(${r},${g},${b})`;
}
}
else if (!!this.options.backgroundImage) {
const backgroundImage = yield loadImage(this.options.backgroundImage);
if (this.options.autoColor) {
const avgRGB = AwesomeQR._getAverageRGB(backgroundImage);
this.options.colorDark = `rgb(${avgRGB.r},${avgRGB.g},${avgRGB.b})`;
}
backgroundCanvasContext.drawImage(backgroundImage, 0, 0, backgroundImage.width, backgroundImage.height, 0, 0, size, size);
backgroundCanvasContext.rect(0, 0, size, size);
backgroundCanvasContext.fillStyle = backgroundDimming;
backgroundCanvasContext.fill();
}
else {
backgroundCanvasContext.rect(0, 0, size, size);
backgroundCanvasContext.fillStyle = this.options.colorLight;
backgroundCanvasContext.fill();
}
const alignmentPatternCenters = QRUtil.getPatternPosition(this.qrCode.typeNumber);
const dataScale = ((_c = (_b = this.options.components) === null || _b === void 0 ? void 0 : _b.data) === null || _c === void 0 ? void 0 : _c.scale) || defaultScale;
const dataXyOffset = (1 - dataScale) * 0.5;
for (let row = 0; row < nCount; row++) {
for (let col = 0; col < nCount; col++) {
const bIsDark = this.qrCode.isDark(row, col);
const isBlkPosCtr = (col < 8 && (row < 8 || row >= nCount - 8)) || (col >= nCount - 8 && row < 8);
const isTiming = (row == 6 && col >= 8 && col <= nCount - 8) || (col == 6 && row >= 8 && row <= nCount - 8);
let isProtected = isBlkPosCtr || isTiming;
for (let i = 1; i < alignmentPatternCenters.length - 1; i++) {
isProtected =
isProtected ||
(row >= alignmentPatternCenters[i] - 2 &&
row <= alignmentPatternCenters[i] + 2 &&
col >= alignmentPatternCenters[i] - 2 &&
col <= alignmentPatternCenters[i] + 2);
}
const nLeft = col * nSize + (isProtected ? 0 : dataXyOffset * nSize);
const nTop = row * nSize + (isProtected ? 0 : dataXyOffset * nSize);
mainCanvasContext.strokeStyle = bIsDark ? this.options.colorDark : this.options.colorLight;
mainCanvasContext.lineWidth = 0.5;
mainCanvasContext.fillStyle = bIsDark ? this.options.colorDark : this.options.colorLight;
if (alignmentPatternCenters.length === 0) {
if (!isProtected) {
mainCanvasContext.fillRect(nLeft, nTop, (isProtected ? (isBlkPosCtr ? 1 : 1) : dataScale) * nSize, (isProtected ? (isBlkPosCtr ? 1 : 1) : dataScale) * nSize);
}
}
else {
const inAgnRange = col < nCount - 4 && col >= nCount - 4 - 5 && row < nCount - 4 && row >= nCount - 4 - 5;
if (!isProtected && !inAgnRange) {
// if align pattern list is empty, then it means that we don't need to leave room for the align patterns
mainCanvasContext.fillRect(nLeft, nTop, (isProtected ? (isBlkPosCtr ? 1 : 1) : dataScale) * nSize, (isProtected ? (isBlkPosCtr ? 1 : 1) : dataScale) * nSize);
}
}
}
}
const cornerAlignmentCenter = alignmentPatternCenters[alignmentPatternCenters.length - 1];
// - PROTECTORS
const protectorStyle = this.options.colorLight;
// - FINDER PROTECTORS
mainCanvasContext.fillStyle = protectorStyle;
mainCanvasContext.fillRect(0, 0, 8 * nSize, 8 * nSize);
mainCanvasContext.fillRect(0, (nCount - 8) * nSize, 8 * nSize, 8 * nSize);
mainCanvasContext.fillRect((nCount - 8) * nSize, 0, 8 * nSize, 8 * nSize);
// - TIMING PROTECTORS
if ((_e = (_d = this.options.components) === null || _d === void 0 ? void 0 : _d.timing) === null || _e === void 0 ? void 0 : _e.protectors) {
mainCanvasContext.fillRect(8 * nSize, 6 * nSize, (nCount - 8 - 8) * nSize, nSize);
mainCanvasContext.fillRect(6 * nSize, 8 * nSize, nSize, (nCount - 8 - 8) * nSize);
}
// - CORNER ALIGNMENT PROTECTORS
if ((_g = (_f = this.options.components) === null || _f === void 0 ? void 0 : _f.cornerAlignment) === null || _g === void 0 ? void 0 : _g.protectors) {
AwesomeQR._drawAlignProtector(mainCanvasContext, cornerAlignmentCenter, cornerAlignmentCenter, nSize);
}
// - ALIGNMENT PROTECTORS
if ((_j = (_h = this.options.components) === null || _h === void 0 ? void 0 : _h.alignment) === null || _j === void 0 ? void 0 : _j.protectors) {
for (let i = 0; i < alignmentPatternCenters.length; i++) {
for (let j = 0; j < alignmentPatternCenters.length; j++) {
const agnX = alignmentPatternCenters[j];
const agnY = alignmentPatternCenters[i];
if (agnX === 6 && (agnY === 6 || agnY === cornerAlignmentCenter)) {
continue;
}
else if (agnY === 6 && (agnX === 6 || agnX === cornerAlignmentCenter)) {
continue;
}
else if (agnX === cornerAlignmentCenter && agnY === cornerAlignmentCenter) {
continue;
}
else {
AwesomeQR._drawAlignProtector(mainCanvasContext, agnX, agnY, nSize);
}
}
}
}
// - FINDER
mainCanvasContext.fillStyle = this.options.colorDark;
mainCanvasContext.fillRect(0, 0, 7 * nSize, nSize);
mainCanvasContext.fillRect((nCount - 7) * nSize, 0, 7 * nSize, nSize);
mainCanvasContext.fillRect(0, 6 * nSize, 7 * nSize, nSize);
mainCanvasContext.fillRect((nCount - 7) * nSize, 6 * nSize, 7 * nSize, nSize);
mainCanvasContext.fillRect(0, (nCount - 7) * nSize, 7 * nSize, nSize);
mainCanvasContext.fillRect(0, (nCount - 7 + 6) * nSize, 7 * nSize, nSize);
mainCanvasContext.fillRect(0, 0, nSize, 7 * nSize);
mainCanvasContext.fillRect(6 * nSize, 0, nSize, 7 * nSize);
mainCanvasContext.fillRect((nCount - 7) * nSize, 0, nSize, 7 * nSize);
mainCanvasContext.fillRect((nCount - 7 + 6) * nSize, 0, nSize, 7 * nSize);
mainCanvasContext.fillRect(0, (nCount - 7) * nSize, nSize, 7 * nSize);
mainCanvasContext.fillRect(6 * nSize, (nCount - 7) * nSize, nSize, 7 * nSize);
mainCanvasContext.fillRect(2 * nSize, 2 * nSize, 3 * nSize, 3 * nSize);
mainCanvasContext.fillRect((nCount - 7 + 2) * nSize, 2 * nSize, 3 * nSize, 3 * nSize);
mainCanvasContext.fillRect(2 * nSize, (nCount - 7 + 2) * nSize, 3 * nSize, 3 * nSize);
// - TIMING
const timingScale = ((_l = (_k = this.options.components) === null || _k === void 0 ? void 0 : _k.timing) === null || _l === void 0 ? void 0 : _l.scale) || defaultScale;
const timingXyOffset = (1 - timingScale) * 0.5;
for (let i = 0; i < nCount - 8; i += 2) {
AwesomeQR._drawDot(mainCanvasContext, 8 + i, 6, nSize, timingXyOffset, timingScale);
AwesomeQR._drawDot(mainCanvasContext, 6, 8 + i, nSize, timingXyOffset, timingScale);
}
// - CORNER ALIGNMENT PROTECTORS
const cornerAlignmentScale = ((_o = (_m = this.options.components) === null || _m === void 0 ? void 0 : _m.cornerAlignment) === null || _o === void 0 ? void 0 : _o.scale) || defaultScale;
const cornerAlignmentXyOffset = (1 - cornerAlignmentScale) * 0.5;
AwesomeQR._drawAlign(mainCanvasContext, cornerAlignmentCenter, cornerAlignmentCenter, nSize, cornerAlignmentXyOffset, cornerAlignmentScale, this.options.colorDark, ((_q = (_p = this.options.components) === null || _p === void 0 ? void 0 : _p.cornerAlignment) === null || _q === void 0 ? void 0 : _q.protectors) || false);
// - ALIGNEMNT
const alignmentScale = ((_s = (_r = this.options.components) === null || _r === void 0 ? void 0 : _r.alignment) === null || _s === void 0 ? void 0 : _s.scale) || defaultScale;
const alignmentXyOffset = (1 - alignmentScale) * 0.5;
for (let i = 0; i < alignmentPatternCenters.length; i++) {
for (let j = 0; j < alignmentPatternCenters.length; j++) {
const agnX = alignmentPatternCenters[j];
const agnY = alignmentPatternCenters[i];
if (agnX === 6 && (agnY === 6 || agnY === cornerAlignmentCenter)) {
continue;
}
else if (agnY === 6 && (agnX === 6 || agnX === cornerAlignmentCenter)) {
continue;
}
else if (agnX === cornerAlignmentCenter && agnY === cornerAlignmentCenter) {
continue;
}
else {
AwesomeQR._drawAlign(mainCanvasContext, agnX, agnY, nSize, alignmentXyOffset, alignmentScale, this.options.colorDark, ((_u = (_t = this.options.components) === null || _t === void 0 ? void 0 : _t.alignment) === null || _u === void 0 ? void 0 : _u.protectors) || false);
}
}
}
// Fill the margin
if (whiteMargin) {
mainCanvasContext.fillStyle = this.options.backgroundColor;
mainCanvasContext.fillRect(-margin, -margin, size, margin);
mainCanvasContext.fillRect(-margin, viewportSize, size, margin);
mainCanvasContext.fillRect(viewportSize, -margin, margin, size);
mainCanvasContext.fillRect(-margin, -margin, margin, size);
}
if (!!this.options.logoImage) {
const logoImage = yield loadImage(this.options.logoImage);
let logoScale = this.options.logoScale;
let logoMargin = this.options.logoMargin;
let logoCornerRadius = this.options.logoCornerRadius;
if (logoScale <= 0 || logoScale >= 1.0) {
logoScale = 0.2;
}
if (logoMargin < 0) {
logoMargin = 0;
}
if (logoCornerRadius < 0) {
logoCornerRadius = 0;
}
const logoSize = viewportSize * logoScale;
const x = 0.5 * (size - logoSize);
const y = x;
// Restore the canvas
// After restoring, the top and left margins should be taken into account
mainCanvasContext.restore();
// Clean the area that the logo covers (including margins)
mainCanvasContext.fillStyle = this.options.logoBackgroundColor;
mainCanvasContext.save();
AwesomeQR._prepareRoundedCornerClip(mainCanvasContext, x - logoMargin, y - logoMargin, logoSize + 2 * logoMargin, logoSize + 2 * logoMargin, logoCornerRadius + logoMargin);
mainCanvasContext.clip();
const oldGlobalCompositeOperation = mainCanvasContext.globalCompositeOperation;
mainCanvasContext.globalCompositeOperation = "destination-out";
mainCanvasContext.fill();
mainCanvasContext.globalCompositeOperation = oldGlobalCompositeOperation;
mainCanvasContext.restore();
// Draw logo image
mainCanvasContext.save();
AwesomeQR._prepareRoundedCornerClip(mainCanvasContext, x, y, logoSize, logoSize, logoCornerRadius);
mainCanvasContext.clip();
mainCanvasContext.drawImage(logoImage, x, y, logoSize, logoSize);
mainCanvasContext.restore();
// Re-translate the canvas to translate the top and left margins into invisible area
mainCanvasContext.save();
mainCanvasContext.translate(margin, margin);
}
if (!!parsedGIFBackground) {
let gifOutput;
// Reuse in order to apply the patch
let backgroundCanvas;
let backgroundCanvasContext;
let patchCanvas;
let patchCanvasContext;
let patchData;
gifFrames.forEach(function (frame) {
if (!gifOutput) {
gifOutput = new GIFEncoder(rawSize, rawSize);
gifOutput.setDelay(frame.delay);
gifOutput.setRepeat(0);
}
const { width, height } = frame.dims;
if (!backgroundCanvas) {
backgroundCanvas = new Canvas(width, height);
backgroundCanvasContext = backgroundCanvas.getContext("2d");
backgroundCanvasContext.rect(0, 0, backgroundCanvas.width, backgroundCanvas.height);
backgroundCanvasContext.fillStyle = "#ffffff";
backgroundCanvasContext.fill();
}
if (!patchCanvas || !patchData || width !== patchCanvas.width || height !== patchCanvas.height) {
patchCanvas = new Canvas(width, height);
patchCanvasContext = patchCanvas.getContext("2d");
patchData = patchCanvasContext.createImageData(width, height);
}
patchData.data.set(frame.patch);
patchCanvasContext.putImageData(patchData, 0, 0);
backgroundCanvasContext.drawImage(patchCanvas.getContext('2d').canvas, frame.dims.left, frame.dims.top);
const unscaledCanvas = new Canvas(size, size);
const unscaledCanvasContext = unscaledCanvas.getContext("2d");
unscaledCanvasContext.drawImage(backgroundCanvas.getContext('2d').canvas, 0, 0, size, size);
unscaledCanvasContext.rect(0, 0, size, size);
unscaledCanvasContext.fillStyle = backgroundDimming;
unscaledCanvasContext.fill();
unscaledCanvasContext.drawImage(mainCanvas.getContext('2d').canvas, 0, 0, size, size);
// Scale the final image
const outCanvas = new Canvas(rawSize, rawSize);
const outCanvasContext = outCanvas.getContext("2d");
outCanvasContext.drawImage(unscaledCanvas.getContext('2d').canvas, 0, 0, rawSize, rawSize);
gifOutput.addFrame(outCanvasContext.getImageData(0, 0, outCanvas.width, outCanvas.height).data);
});
if (!gifOutput) {
throw new Error("No frames.");
}
gifOutput.finish();
if (isElement(this.canvas)) {
const u8array = gifOutput.stream().toFlattenUint8Array();
const binary = u8array.reduce((bin, u8) => bin + String.fromCharCode(u8), "");
return Promise.resolve(`data:image/gif;base64,${window.btoa(binary)}`);
}
return Promise.resolve(Buffer.from(gifOutput.stream().toFlattenUint8Array()));
}
else {
// Swap and merge the foreground and the background
backgroundCanvasContext.drawImage(mainCanvas.getContext('2d').canvas, 0, 0, size, size);
mainCanvasContext.drawImage(backgroundCanvas.getContext('2d').canvas, -margin, -margin, size, size);
// Scale the final image
const outCanvas = new Canvas(rawSize, rawSize); //document.createElement("canvas");
const outCanvasContext = outCanvas.getContext("2d");
outCanvasContext.drawImage(mainCanvas.getContext('2d').canvas, 0, 0, rawSize, rawSize);
this.canvas = outCanvas;
const format = this.options.gifBackground ? "gif" : "png";
if (isElement(this.canvas)) {
return Promise.resolve(this.canvas.toDataURL(format));
}
return Promise.resolve(this.canvas.toBuffer(format));
}
});
}
}
AwesomeQR.CorrectLevel = QRErrorCorrectLevel;
AwesomeQR.defaultComponentOptions = {
data: {
scale: 0.4,
},
timing: {
scale: 0.5,
protectors: false,
},
alignment: {
scale: 0.5,
protectors: false,
},
cornerAlignment: {
scale: 0.5,
protectors: true,
},
};
AwesomeQR.defaultOptions = {
text: "",
size: 400,
margin: 20,
colorDark: "#000000",
colorLight: "rgba(255, 255, 255, 0.6)",
correctLevel: QRErrorCorrectLevel.M,
backgroundImage: undefined,
backgroundDimming: "rgba(0,0,0,0)",
logoImage: undefined,
logoScale: 0.2,
logoMargin: 4,
logoCornerRadius: 8,
whiteMargin: true,
components: AwesomeQR.defaultComponentOptions,
autoColor: true,
logoBackgroundColor: '#ffffff',
backgroundColor: '#ffffff',
};
function isElement(obj) {
try {
//Using W3 DOM2 (works for FF, Opera and Chrome)
return obj instanceof HTMLElement;
}
catch (e) {
//Browsers not supporting W3 DOM2 don't have HTMLElement and
//an exception is thrown and we end up here. Testing some
//properties that all elements have (works on IE7)
return (typeof obj === "object" &&
obj.nodeType === 1 &&
typeof obj.style === "object" &&
typeof obj.ownerDocument === "object");
}
}
export default GIFEncoder;
declare function GIFEncoder(width: any, height: any): void;
declare class GIFEncoder {
constructor(width: any, height: any);
width: number;
height: number;
transparent: any;
transIndex: number;
repeat: number;
delay: number;
image: any;
pixels: Uint8Array | null;
indexedPixels: Uint8Array | null;
colorDepth: number | null;
colorTab: any;
neuQuant: NeuQuant | null;
usedEntry: any[];
palSize: number;
dispose: number;
firstFrame: boolean;
sample: number;
dither: boolean;
globalPalette: any;
out: ByteArray;
setDelay(milliseconds: any): void;
setFrameRate(fps: any): void;
setDispose(disposalCode: any): void;
setRepeat(repeat: any): void;
setTransparent(color: any): void;
addFrame(imageData: any): void;
finish(): void;
setQuality(quality: any): void;
setDither(dither: any): void;
setGlobalPalette(palette: any): void;
getGlobalPalette(): any;
writeHeader(): void;
analyzePixels(): void;
indexPixels(imgq: any): void;
ditherPixels(kernel: any, serpentine: any): void;
findClosest(c: any, used: any): number;
findClosestRGB(r: any, g: any, b: any, used: any): number;
getImagePixels(): void;
writeGraphicCtrlExt(): void;
writeImageDesc(): void;
writeLSD(): void;
writeNetscapeExt(): void;
writePalette(): void;
writeShort(pValue: any): void;
writePixels(): void;
stream(): ByteArray;
}
import NeuQuant from "./TypedNeuQuant.js";
declare function ByteArray(): void;
declare class ByteArray {
page: number;
pages: any[];
newPage(): void;
cursor: number | undefined;
getData(): string;
toFlattenUint8Array(): Uint8Array;
writeByte(val: any): void;
writeUTFBytes(string: any): void;
writeBytes(array: any, offset: any, length: any): void;
}
declare namespace ByteArray {
export const pageSize: number;
export const charMap: {};
}
/*
GIFEncoder.js
Authors
Kevin Weiner (original Java version - kweiner@fmsware.com)
Thibault Imbert (AS3 version - bytearray.org)
Johan Nordberg (JS version - code@johan-nordberg.com)
Makito (Optimized for AwesomeQR - sumimakito@hotmail,com)
*/
// var NeuQuant = require("./TypedNeuQuant.js");
import NeuQuant from "./TypedNeuQuant.js";
// var LZWEncoder = require("./LZWEncoder.js");
import LZWEncoder from "./LZWEncoder.js";
function ByteArray() {
this.page = -1;
this.pages = [];
this.newPage();
}
ByteArray.pageSize = 4096;
ByteArray.charMap = {};
for (var i = 0; i < 256; i++)
ByteArray.charMap[i] = String.fromCharCode(i);
ByteArray.prototype.newPage = function () {
this.pages[++this.page] = new Uint8Array(ByteArray.pageSize);
this.cursor = 0;
};
ByteArray.prototype.getData = function () {
var rv = "";
for (var p = 0; p < this.pages.length; p++) {
for (var i = 0; i < ByteArray.pageSize; i++) {
rv += ByteArray.charMap[this.pages[p][i]];
}
}
return rv;
};
ByteArray.prototype.toFlattenUint8Array = function () {
const chunks = [];
for (var p = 0; p < this.pages.length; p++) {
if (p === this.pages.length - 1) {
const chunk = Uint8Array.from(this.pages[p].slice(0, this.cursor));
chunks.push(chunk);
}
else {
chunks.push(this.pages[p]);
}
}
const flatten = new Uint8Array(chunks.reduce((acc, chunk) => acc + chunk.length, 0));
chunks.reduce((lastLength, chunk) => {
flatten.set(chunk, lastLength);
return lastLength + chunk.length;
}, 0);
return flatten;
};
ByteArray.prototype.writeByte = function (val) {
if (this.cursor >= ByteArray.pageSize)
this.newPage();
this.pages[this.page][this.cursor++] = val;
};
ByteArray.prototype.writeUTFBytes = function (string) {
for (var l = string.length, i = 0; i < l; i++)
this.writeByte(string.charCodeAt(i));
};
ByteArray.prototype.writeBytes = function (array, offset, length) {
for (var l = length || array.length, i = offset || 0; i < l; i++)
this.writeByte(array[i]);
};
function GIFEncoder(width, height) {
// image size
this.width = ~~width;
this.height = ~~height;
// transparent color if given
this.transparent = null;
// transparent index in color table
this.transIndex = 0;
// -1 = no repeat, 0 = forever. anything else is repeat count
this.repeat = -1;
// frame delay (hundredths)
this.delay = 0;
this.image = null; // current frame
this.pixels = null; // BGR byte array from frame
this.indexedPixels = null; // converted frame indexed to palette
this.colorDepth = null; // number of bit planes
this.colorTab = null; // RGB palette
this.neuQuant = null; // NeuQuant instance that was used to generate this.colorTab.
this.usedEntry = new Array(); // active palette entries
this.palSize = 7; // color table size (bits-1)
this.dispose = -1; // disposal code (-1 = use default)
this.firstFrame = true;
this.sample = 10; // default sample interval for quantizer
this.dither = false; // default dithering
this.globalPalette = false;
this.out = new ByteArray();
}
/*
Sets the delay time between each frame, or changes it for subsequent frames
(applies to last frame added)
*/
GIFEncoder.prototype.setDelay = function (milliseconds) {
this.delay = Math.round(milliseconds / 10);
};
/*
Sets frame rate in frames per second.
*/
GIFEncoder.prototype.setFrameRate = function (fps) {
this.delay = Math.round(100 / fps);
};
/*
Sets the GIF frame disposal code for the last added frame and any
subsequent frames.
Default is 0 if no transparent color has been set, otherwise 2.
*/
GIFEncoder.prototype.setDispose = function (disposalCode) {
if (disposalCode >= 0)
this.dispose = disposalCode;
};
/*
Sets the number of times the set of GIF frames should be played.
-1 = play once
0 = repeat indefinitely
Default is -1
Must be invoked before the first image is added
*/
GIFEncoder.prototype.setRepeat = function (repeat) {
this.repeat = repeat;
};
/*
Sets the transparent color for the last added frame and any subsequent
frames. Since all colors are subject to modification in the quantization
process, the color in the final palette for each frame closest to the given
color becomes the transparent color for that frame. May be set to null to
indicate no transparent color.
*/
GIFEncoder.prototype.setTransparent = function (color) {
this.transparent = color;
};
/*
Adds next GIF frame. The frame is not written immediately, but is
actually deferred until the next frame is received so that timing
data can be inserted. Invoking finish() flushes all frames.
*/
GIFEncoder.prototype.addFrame = function (imageData) {
this.image = imageData;
this.colorTab = this.globalPalette && this.globalPalette.slice ? this.globalPalette : null;
this.getImagePixels(); // convert to correct format if necessary
this.analyzePixels(); // build color table & map pixels
if (this.globalPalette === true)
this.globalPalette = this.colorTab;
if (this.firstFrame) {
this.writeHeader();
this.writeLSD(); // logical screen descriptior
this.writePalette(); // global color table
if (this.repeat >= 0) {
// use NS app extension to indicate reps
this.writeNetscapeExt();
}
}
this.writeGraphicCtrlExt(); // write graphic control extension
this.writeImageDesc(); // image descriptor
if (!this.firstFrame && !this.globalPalette)
this.writePalette(); // local color table
this.writePixels(); // encode and write pixel data
this.firstFrame = false;
};
/*
Adds final trailer to the GIF stream, if you don't call the finish method
the GIF stream will not be valid.
*/
GIFEncoder.prototype.finish = function () {
this.out.writeByte(0x3b); // gif trailer
};
/*
Sets quality of color quantization (conversion of images to the maximum 256
colors allowed by the GIF specification). Lower values (minimum = 1)
produce better colors, but slow processing significantly. 10 is the
default, and produces good color mapping at reasonable speeds. Values
greater than 20 do not yield significant improvements in speed.
*/
GIFEncoder.prototype.setQuality = function (quality) {
if (quality < 1)
quality = 1;
this.sample = quality;
};
/*
Sets dithering method. Available are:
- FALSE no dithering
- TRUE or FloydSteinberg
- FalseFloydSteinberg
- Stucki
- Atkinson
You can add '-serpentine' to use serpentine scanning
*/
GIFEncoder.prototype.setDither = function (dither) {
if (dither === true)
dither = "FloydSteinberg";
this.dither = dither;
};
/*
Sets global palette for all frames.
You can provide TRUE to create global palette from first picture.
Or an array of r,g,b,r,g,b,...
*/
GIFEncoder.prototype.setGlobalPalette = function (palette) {
this.globalPalette = palette;
};
/*
Returns global palette used for all frames.
If setGlobalPalette(true) was used, then this function will return
calculated palette after the first frame is added.
*/
GIFEncoder.prototype.getGlobalPalette = function () {
return (this.globalPalette && this.globalPalette.slice && this.globalPalette.slice(0)) || this.globalPalette;
};
/*
Writes GIF file header
*/
GIFEncoder.prototype.writeHeader = function () {
this.out.writeUTFBytes("GIF89a");
};
/*
Analyzes current frame colors and creates color map.
*/
GIFEncoder.prototype.analyzePixels = function () {
if (!this.colorTab) {
this.neuQuant = new NeuQuant(this.pixels, this.sample);
this.neuQuant.buildColormap(); // create reduced palette
this.colorTab = this.neuQuant.getColormap();
}
// map image pixels to new palette
if (this.dither) {
this.ditherPixels(this.dither.replace("-serpentine", ""), this.dither.match(/-serpentine/) !== null);
}
else {
this.indexPixels();
}
this.pixels = null;
this.colorDepth = 8;
this.palSize = 7;
// get closest match to transparent color if specified
if (this.transparent !== null) {
this.transIndex = this.findClosest(this.transparent, true);
}
};
/*
Index pixels, without dithering
*/
GIFEncoder.prototype.indexPixels = function (imgq) {
var nPix = this.pixels.length / 3;
this.indexedPixels = new Uint8Array(nPix);
var k = 0;
for (var j = 0; j < nPix; j++) {
var index = this.findClosestRGB(this.pixels[k++] & 0xff, this.pixels[k++] & 0xff, this.pixels[k++] & 0xff);
this.usedEntry[index] = true;
this.indexedPixels[j] = index;
}
};
/*
Taken from http://jsbin.com/iXofIji/2/edit by PAEz
*/
GIFEncoder.prototype.ditherPixels = function (kernel, serpentine) {
var kernels = {
FalseFloydSteinberg: [
[3 / 8, 1, 0],
[3 / 8, 0, 1],
[2 / 8, 1, 1],
],
FloydSteinberg: [
[7 / 16, 1, 0],
[3 / 16, -1, 1],
[5 / 16, 0, 1],
[1 / 16, 1, 1],
],
Stucki: [
[8 / 42, 1, 0],
[4 / 42, 2, 0],
[2 / 42, -2, 1],
[4 / 42, -1, 1],
[8 / 42, 0, 1],
[4 / 42, 1, 1],
[2 / 42, 2, 1],
[1 / 42, -2, 2],
[2 / 42, -1, 2],
[4 / 42, 0, 2],
[2 / 42, 1, 2],
[1 / 42, 2, 2],
],
Atkinson: [
[1 / 8, 1, 0],
[1 / 8, 2, 0],
[1 / 8, -1, 1],
[1 / 8, 0, 1],
[1 / 8, 1, 1],
[1 / 8, 0, 2],
],
};
if (!kernel || !kernels[kernel]) {
throw "Unknown dithering kernel: " + kernel;
}
var ds = kernels[kernel];
var index = 0, height = this.height, width = this.width, data = this.pixels;
var direction = serpentine ? -1 : 1;
this.indexedPixels = new Uint8Array(this.pixels.length / 3);
for (var y = 0; y < height; y++) {
if (serpentine)
direction = direction * -1;
for (var x = direction == 1 ? 0 : width - 1, xend = direction == 1 ? width : 0; x !== xend; x += direction) {
index = y * width + x;
// Get original colour
var idx = index * 3;
var r1 = data[idx];
var g1 = data[idx + 1];
var b1 = data[idx + 2];
// Get converted colour
idx = this.findClosestRGB(r1, g1, b1);
this.usedEntry[idx] = true;
this.indexedPixels[index] = idx;
idx *= 3;
var r2 = this.colorTab[idx];
var g2 = this.colorTab[idx + 1];
var b2 = this.colorTab[idx + 2];
var er = r1 - r2;
var eg = g1 - g2;
var eb = b1 - b2;
for (var i = direction == 1 ? 0 : ds.length - 1, end = direction == 1 ? ds.length : 0; i !== end; i += direction) {
var x1 = ds[i][1]; // *direction; // Should this by timesd by direction?..to make the kernel go in the opposite direction....got no idea....
var y1 = ds[i][2];
if (x1 + x >= 0 && x1 + x < width && y1 + y >= 0 && y1 + y < height) {
var d = ds[i][0];
idx = index + x1 + y1 * width;
idx *= 3;
data[idx] = Math.max(0, Math.min(255, data[idx] + er * d));
data[idx + 1] = Math.max(0, Math.min(255, data[idx + 1] + eg * d));
data[idx + 2] = Math.max(0, Math.min(255, data[idx + 2] + eb * d));
}
}
}
}
};
/*
Returns index of palette color closest to c
*/
GIFEncoder.prototype.findClosest = function (c, used) {
return this.findClosestRGB((c & 0xff0000) >> 16, (c & 0x00ff00) >> 8, c & 0x0000ff, used);
};
GIFEncoder.prototype.findClosestRGB = function (r, g, b, used) {
if (this.colorTab === null)
return -1;
if (this.neuQuant && !used) {
return this.neuQuant.lookupRGB(r, g, b);
}
var c = b | (g << 8) | (r << 16);
var minpos = 0;
var dmin = 256 * 256 * 256;
var len = this.colorTab.length;
for (var i = 0, index = 0; i < len; index++) {
var dr = r - (this.colorTab[i++] & 0xff);
var dg = g - (this.colorTab[i++] & 0xff);
var db = b - (this.colorTab[i++] & 0xff);
var d = dr * dr + dg * dg + db * db;
if ((!used || this.usedEntry[index]) && d < dmin) {
dmin = d;
minpos = index;
}
}
return minpos;
};
/*
Extracts image pixels into byte array pixels
(removes alphachannel from canvas imagedata)
*/
GIFEncoder.prototype.getImagePixels = function () {
var w = this.width;
var h = this.height;
this.pixels = new Uint8Array(w * h * 3);
var data = this.image;
var srcPos = 0;
var count = 0;
for (var i = 0; i < h; i++) {
for (var j = 0; j < w; j++) {
this.pixels[count++] = data[srcPos++];
this.pixels[count++] = data[srcPos++];
this.pixels[count++] = data[srcPos++];
srcPos++;
}
}
};
/*
Writes Graphic Control Extension
*/
GIFEncoder.prototype.writeGraphicCtrlExt = function () {
this.out.writeByte(0x21); // extension introducer
this.out.writeByte(0xf9); // GCE label
this.out.writeByte(4); // data block size
var transp, disp;
if (this.transparent === null) {
transp = 0;
disp = 0; // dispose = no action
}
else {
transp = 1;
disp = 2; // force clear if using transparent color
}
if (this.dispose >= 0) {
disp = this.dispose & 7; // user override
}
disp <<= 2;
// packed fields
this.out.writeByte(0 | // 1:3 reserved
disp | // 4:6 disposal
0 | // 7 user input - 0 = none
transp // 8 transparency flag
);
this.writeShort(this.delay); // delay x 1/100 sec
this.out.writeByte(this.transIndex); // transparent color index
this.out.writeByte(0); // block terminator
};
/*
Writes Image Descriptor
*/
GIFEncoder.prototype.writeImageDesc = function () {
this.out.writeByte(0x2c); // image separator
this.writeShort(0); // image position x,y = 0,0
this.writeShort(0);
this.writeShort(this.width); // image size
this.writeShort(this.height);
// packed fields
if (this.firstFrame || this.globalPalette) {
// no LCT - GCT is used for first (or only) frame
this.out.writeByte(0);
}
else {
// specify normal LCT
this.out.writeByte(0x80 | // 1 local color table 1=yes
0 | // 2 interlace - 0=no
0 | // 3 sorted - 0=no
0 | // 4-5 reserved
this.palSize // 6-8 size of color table
);
}
};
/*
Writes Logical Screen Descriptor
*/
GIFEncoder.prototype.writeLSD = function () {
// logical screen size
this.writeShort(this.width);
this.writeShort(this.height);
// packed fields
this.out.writeByte(0x80 | // 1 : global color table flag = 1 (gct used)
0x70 | // 2-4 : color resolution = 7
0x00 | // 5 : gct sort flag = 0
this.palSize // 6-8 : gct size
);
this.out.writeByte(0); // background color index
this.out.writeByte(0); // pixel aspect ratio - assume 1:1
};
/*
Writes Netscape application extension to define repeat count.
*/
GIFEncoder.prototype.writeNetscapeExt = function () {
this.out.writeByte(0x21); // extension introducer
this.out.writeByte(0xff); // app extension label
this.out.writeByte(11); // block size
this.out.writeUTFBytes("NETSCAPE2.0"); // app id + auth code
this.out.writeByte(3); // sub-block size
this.out.writeByte(1); // loop sub-block id
this.writeShort(this.repeat); // loop count (extra iterations, 0=repeat forever)
this.out.writeByte(0); // block terminator
};
/*
Writes color table
*/
GIFEncoder.prototype.writePalette = function () {
this.out.writeBytes(this.colorTab);
var n = 3 * 256 - this.colorTab.length;
for (var i = 0; i < n; i++)
this.out.writeByte(0);
};
GIFEncoder.prototype.writeShort = function (pValue) {
this.out.writeByte(pValue & 0xff);
this.out.writeByte((pValue >> 8) & 0xff);
};
/*
Encodes and writes pixel data
*/
GIFEncoder.prototype.writePixels = function () {
var enc = new LZWEncoder(this.width, this.height, this.indexedPixels, this.colorDepth);
enc.encode(this.out);
};
/*
Retrieves the GIF stream
*/
GIFEncoder.prototype.stream = function () {
return this.out;
};
// module.exports = GIFEncoder;
export default GIFEncoder;
export default LZWEncoder;
declare function LZWEncoder(width: any, height: any, pixels: any, colorDepth: any): void;
declare class LZWEncoder {
constructor(width: any, height: any, pixels: any, colorDepth: any);
encode: (outs: any) => void;
}
/*
LZWEncoder.js
Authors
Kevin Weiner (original Java version - kweiner@fmsware.com)
Thibault Imbert (AS3 version - bytearray.org)
Johan Nordberg (JS version - code@johan-nordberg.com)
Acknowledgements
GIFCOMPR.C - GIF Image compression routines
Lempel-Ziv compression based on 'compress'. GIF modifications by
David Rowley (mgardi@watdcsu.waterloo.edu)
GIF Image compression - modified 'compress'
Based on: compress.c - File compression ala IEEE Computer, June 1984.
By Authors: Spencer W. Thomas (decvax!harpo!utah-cs!utah-gr!thomas)
Jim McKie (decvax!mcvax!jim)
Steve Davies (decvax!vax135!petsd!peora!srd)
Ken Turkowski (decvax!decwrl!turtlevax!ken)
James A. Woods (decvax!ihnp4!ames!jaw)
Joe Orost (decvax!vax135!petsd!joe)
*/
var EOF = -1;
var BITS = 12;
var HSIZE = 5003; // 80% occupancy
var masks = [0x0000, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F,
0x003F, 0x007F, 0x00FF, 0x01FF, 0x03FF, 0x07FF,
0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF];
function LZWEncoder(width, height, pixels, colorDepth) {
var initCodeSize = Math.max(2, colorDepth);
var accum = new Uint8Array(256);
var htab = new Int32Array(HSIZE);
var codetab = new Int32Array(HSIZE);
var cur_accum, cur_bits = 0;
var a_count;
var free_ent = 0; // first unused entry
var maxcode;
// block compression parameters -- after all codes are used up,
// and compression rate changes, start over.
var clear_flg = false;
// Algorithm: use open addressing double hashing (no chaining) on the
// prefix code / next character combination. We do a variant of Knuth's
// algorithm D (vol. 3, sec. 6.4) along with G. Knott's relatively-prime
// secondary probe. Here, the modular division first probe is gives way
// to a faster exclusive-or manipulation. Also do block compression with
// an adaptive reset, whereby the code table is cleared when the compression
// ratio decreases, but after the table fills. The variable-length output
// codes are re-sized at this point, and a special CLEAR code is generated
// for the decompressor. Late addition: construct the table according to
// file size for noticeable speed improvement on small files. Please direct
// questions about this implementation to ames!jaw.
var g_init_bits, ClearCode, EOFCode;
var remaining, curPixel, n_bits;
// Add a character to the end of the current packet, and if it is 254
// characters, flush the packet to disk.
function char_out(c, outs) {
accum[a_count++] = c;
if (a_count >= 254)
flush_char(outs);
}
// Clear out the hash table
// table clear for block compress
function cl_block(outs) {
cl_hash(HSIZE);
free_ent = ClearCode + 2;
clear_flg = true;
output(ClearCode, outs);
}
// Reset code table
function cl_hash(hsize) {
for (var i = 0; i < hsize; ++i)
htab[i] = -1;
}
function compress(init_bits, outs) {
var fcode, c, i, ent, disp, hsize_reg, hshift;
// Set up the globals: g_init_bits - initial number of bits
g_init_bits = init_bits;
// Set up the necessary values
clear_flg = false;
n_bits = g_init_bits;
maxcode = MAXCODE(n_bits);
ClearCode = 1 << (init_bits - 1);
EOFCode = ClearCode + 1;
free_ent = ClearCode + 2;
a_count = 0; // clear packet
ent = nextPixel();
hshift = 0;
for (fcode = HSIZE; fcode < 65536; fcode *= 2)
++hshift;
hshift = 8 - hshift; // set hash code range bound
hsize_reg = HSIZE;
cl_hash(hsize_reg); // clear hash table
output(ClearCode, outs);
outer_loop: while ((c = nextPixel()) != EOF) {
fcode = (c << BITS) + ent;
i = (c << hshift) ^ ent; // xor hashing
if (htab[i] === fcode) {
ent = codetab[i];
continue;
}
else if (htab[i] >= 0) { // non-empty slot
disp = hsize_reg - i; // secondary hash (after G. Knott)
if (i === 0)
disp = 1;
do {
if ((i -= disp) < 0)
i += hsize_reg;
if (htab[i] === fcode) {
ent = codetab[i];
continue outer_loop;
}
} while (htab[i] >= 0);
}
output(ent, outs);
ent = c;
if (free_ent < 1 << BITS) {
codetab[i] = free_ent++; // code -> hashtable
htab[i] = fcode;
}
else {
cl_block(outs);
}
}
// Put out the final code.
output(ent, outs);
output(EOFCode, outs);
}
function encode(outs) {
outs.writeByte(initCodeSize); // write "initial code size" byte
remaining = width * height; // reset navigation variables
curPixel = 0;
compress(initCodeSize + 1, outs); // compress and write the pixel data
outs.writeByte(0); // write block terminator
}
// Flush the packet to disk, and reset the accumulator
function flush_char(outs) {
if (a_count > 0) {
outs.writeByte(a_count);
outs.writeBytes(accum, 0, a_count);
a_count = 0;
}
}
function MAXCODE(n_bits) {
return (1 << n_bits) - 1;
}
// Return the next pixel from the image
function nextPixel() {
if (remaining === 0)
return EOF;
--remaining;
var pix = pixels[curPixel++];
return pix & 0xff;
}
function output(code, outs) {
cur_accum &= masks[cur_bits];
if (cur_bits > 0)
cur_accum |= (code << cur_bits);
else
cur_accum = code;
cur_bits += n_bits;
while (cur_bits >= 8) {
char_out((cur_accum & 0xff), outs);
cur_accum >>= 8;
cur_bits -= 8;
}
// If the next entry is going to be too big for the code size,
// then increase it, if possible.
if (free_ent > maxcode || clear_flg) {
if (clear_flg) {
maxcode = MAXCODE(n_bits = g_init_bits);
clear_flg = false;
}
else {
++n_bits;
if (n_bits == BITS)
maxcode = 1 << BITS;
else
maxcode = MAXCODE(n_bits);
}
}
if (code == EOFCode) {
// At EOF, write the rest of the buffer.
while (cur_bits > 0) {
char_out((cur_accum & 0xff), outs);
cur_accum >>= 8;
cur_bits -= 8;
}
flush_char(outs);
}
}
this.encode = encode;
}
// module.exports = LZWEncoder;
export default LZWEncoder;
export default NeuQuant;
declare function NeuQuant(pixels: any, samplefac: any): void;
declare class NeuQuant {
constructor(pixels: any, samplefac: any);
buildColormap: () => void;
getColormap: () => any[];
lookupRGB: (b: any, g: any, r: any) => number;
}
/* NeuQuant Neural-Net Quantization Algorithm
* ------------------------------------------
*
* Copyright (c) 1994 Anthony Dekker
*
* NEUQUANT Neural-Net quantization algorithm by Anthony Dekker, 1994.
* See "Kohonen neural networks for optimal colour quantization"
* in "Network: Computation in Neural Systems" Vol. 5 (1994) pp 351-367.
* for a discussion of the algorithm.
* See also http://members.ozemail.com.au/~dekker/NEUQUANT.HTML
*
* Any party obtaining a copy of these files from the author, directly or
* indirectly, is granted, free of charge, a full and unrestricted irrevocable,
* world-wide, paid up, royalty-free, nonexclusive right and license to deal
* in this software and documentation files (the "Software"), including without
* limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons who receive
* copies from any such party to do so, with the only requirement being
* that this copyright notice remain intact.
*
* (JavaScript port 2012 by Johan Nordberg)
*/
function toInt(v) {
return ~~v;
}
var ncycles = 100; // number of learning cycles
var netsize = 256; // number of colors used
var maxnetpos = netsize - 1;
// defs for freq and bias
var netbiasshift = 4; // bias for colour values
var intbiasshift = 16; // bias for fractions
var intbias = (1 << intbiasshift);
var gammashift = 10;
var gamma = (1 << gammashift);
var betashift = 10;
var beta = (intbias >> betashift); /* beta = 1/1024 */
var betagamma = (intbias << (gammashift - betashift));
// defs for decreasing radius factor
var initrad = (netsize >> 3); // for 256 cols, radius starts
var radiusbiasshift = 6; // at 32.0 biased by 6 bits
var radiusbias = (1 << radiusbiasshift);
var initradius = (initrad * radiusbias); //and decreases by a
var radiusdec = 30; // factor of 1/30 each cycle
// defs for decreasing alpha factor
var alphabiasshift = 10; // alpha starts at 1.0
var initalpha = (1 << alphabiasshift);
var alphadec; // biased by 10 bits
/* radbias and alpharadbias used for radpower calculation */
var radbiasshift = 8;
var radbias = (1 << radbiasshift);
var alpharadbshift = (alphabiasshift + radbiasshift);
var alpharadbias = (1 << alpharadbshift);
// four primes near 500 - assume no image has a length so large that it is
// divisible by all four primes
var prime1 = 499;
var prime2 = 491;
var prime3 = 487;
var prime4 = 503;
var minpicturebytes = (3 * prime4);
/*
Constructor: NeuQuant
Arguments:
pixels - array of pixels in RGB format
samplefac - sampling factor 1 to 30 where lower is better quality
>
> pixels = [r, g, b, r, g, b, r, g, b, ..]
>
*/
function NeuQuant(pixels, samplefac) {
var network; // int[netsize][4]
var netindex; // for network lookup - really 256
// bias and freq arrays for learning
var bias;
var freq;
var radpower;
/*
Private Method: init
sets up arrays
*/
function init() {
network = [];
netindex = [];
bias = [];
freq = [];
radpower = [];
var i, v;
for (i = 0; i < netsize; i++) {
v = (i << (netbiasshift + 8)) / netsize;
network[i] = [v, v, v];
freq[i] = intbias / netsize;
bias[i] = 0;
}
}
/*
Private Method: unbiasnet
unbiases network to give byte values 0..255 and record position i to prepare for sort
*/
function unbiasnet() {
for (var i = 0; i < netsize; i++) {
network[i][0] >>= netbiasshift;
network[i][1] >>= netbiasshift;
network[i][2] >>= netbiasshift;
network[i][3] = i; // record color number
}
}
/*
Private Method: altersingle
moves neuron *i* towards biased (b,g,r) by factor *alpha*
*/
function altersingle(alpha, i, b, g, r) {
network[i][0] -= (alpha * (network[i][0] - b)) / initalpha;
network[i][1] -= (alpha * (network[i][1] - g)) / initalpha;
network[i][2] -= (alpha * (network[i][2] - r)) / initalpha;
}
/*
Private Method: alterneigh
moves neurons in *radius* around index *i* towards biased (b,g,r) by factor *alpha*
*/
function alterneigh(radius, i, b, g, r) {
var lo = Math.abs(i - radius);
var hi = Math.min(i + radius, netsize);
var j = i + 1;
var k = i - 1;
var m = 1;
var p, a;
while ((j < hi) || (k > lo)) {
a = radpower[m++];
if (j < hi) {
p = network[j++];
p[0] -= (a * (p[0] - b)) / alpharadbias;
p[1] -= (a * (p[1] - g)) / alpharadbias;
p[2] -= (a * (p[2] - r)) / alpharadbias;
}
if (k > lo) {
p = network[k--];
p[0] -= (a * (p[0] - b)) / alpharadbias;
p[1] -= (a * (p[1] - g)) / alpharadbias;
p[2] -= (a * (p[2] - r)) / alpharadbias;
}
}
}
/*
Private Method: contest
searches for biased BGR values
*/
function contest(b, g, r) {
/*
finds closest neuron (min dist) and updates freq
finds best neuron (min dist-bias) and returns position
for frequently chosen neurons, freq[i] is high and bias[i] is negative
bias[i] = gamma * ((1 / netsize) - freq[i])
*/
var bestd = ~(1 << 31);
var bestbiasd = bestd;
var bestpos = -1;
var bestbiaspos = bestpos;
var i, n, dist, biasdist, betafreq;
for (i = 0; i < netsize; i++) {
n = network[i];
dist = Math.abs(n[0] - b) + Math.abs(n[1] - g) + Math.abs(n[2] - r);
if (dist < bestd) {
bestd = dist;
bestpos = i;
}
biasdist = dist - ((bias[i]) >> (intbiasshift - netbiasshift));
if (biasdist < bestbiasd) {
bestbiasd = biasdist;
bestbiaspos = i;
}
betafreq = (freq[i] >> betashift);
freq[i] -= betafreq;
bias[i] += (betafreq << gammashift);
}
freq[bestpos] += beta;
bias[bestpos] -= betagamma;
return bestbiaspos;
}
/*
Private Method: inxbuild
sorts network and builds netindex[0..255]
*/
function inxbuild() {
var i, j, p, q, smallpos, smallval, previouscol = 0, startpos = 0;
for (i = 0; i < netsize; i++) {
p = network[i];
smallpos = i;
smallval = p[1]; // index on g
// find smallest in i..netsize-1
for (j = i + 1; j < netsize; j++) {
q = network[j];
if (q[1] < smallval) { // index on g
smallpos = j;
smallval = q[1]; // index on g
}
}
q = network[smallpos];
// swap p (i) and q (smallpos) entries
if (i != smallpos) {
j = q[0];
q[0] = p[0];
p[0] = j;
j = q[1];
q[1] = p[1];
p[1] = j;
j = q[2];
q[2] = p[2];
p[2] = j;
j = q[3];
q[3] = p[3];
p[3] = j;
}
// smallval entry is now in position i
if (smallval != previouscol) {
netindex[previouscol] = (startpos + i) >> 1;
for (j = previouscol + 1; j < smallval; j++)
netindex[j] = i;
previouscol = smallval;
startpos = i;
}
}
netindex[previouscol] = (startpos + maxnetpos) >> 1;
for (j = previouscol + 1; j < 256; j++)
netindex[j] = maxnetpos; // really 256
}
/*
Private Method: inxsearch
searches for BGR values 0..255 and returns a color index
*/
function inxsearch(b, g, r) {
var a, p, dist;
var bestd = 1000; // biggest possible dist is 256*3
var best = -1;
var i = netindex[g]; // index on g
var j = i - 1; // start at netindex[g] and work outwards
while ((i < netsize) || (j >= 0)) {
if (i < netsize) {
p = network[i];
dist = p[1] - g; // inx key
if (dist >= bestd)
i = netsize; // stop iter
else {
i++;
if (dist < 0)
dist = -dist;
a = p[0] - b;
if (a < 0)
a = -a;
dist += a;
if (dist < bestd) {
a = p[2] - r;
if (a < 0)
a = -a;
dist += a;
if (dist < bestd) {
bestd = dist;
best = p[3];
}
}
}
}
if (j >= 0) {
p = network[j];
dist = g - p[1]; // inx key - reverse dif
if (dist >= bestd)
j = -1; // stop iter
else {
j--;
if (dist < 0)
dist = -dist;
a = p[0] - b;
if (a < 0)
a = -a;
dist += a;
if (dist < bestd) {
a = p[2] - r;
if (a < 0)
a = -a;
dist += a;
if (dist < bestd) {
bestd = dist;
best = p[3];
}
}
}
}
}
return best;
}
/*
Private Method: learn
"Main Learning Loop"
*/
function learn() {
var i;
var lengthcount = pixels.length;
var alphadec = toInt(30 + ((samplefac - 1) / 3));
var samplepixels = toInt(lengthcount / (3 * samplefac));
var delta = toInt(samplepixels / ncycles);
var alpha = initalpha;
var radius = initradius;
var rad = radius >> radiusbiasshift;
if (rad <= 1)
rad = 0;
for (i = 0; i < rad; i++)
radpower[i] = toInt(alpha * (((rad * rad - i * i) * radbias) / (rad * rad)));
var step;
if (lengthcount < minpicturebytes) {
samplefac = 1;
step = 3;
}
else if ((lengthcount % prime1) !== 0) {
step = 3 * prime1;
}
else if ((lengthcount % prime2) !== 0) {
step = 3 * prime2;
}
else if ((lengthcount % prime3) !== 0) {
step = 3 * prime3;
}
else {
step = 3 * prime4;
}
var b, g, r, j;
var pix = 0; // current pixel
i = 0;
while (i < samplepixels) {
b = (pixels[pix] & 0xff) << netbiasshift;
g = (pixels[pix + 1] & 0xff) << netbiasshift;
r = (pixels[pix + 2] & 0xff) << netbiasshift;
j = contest(b, g, r);
altersingle(alpha, j, b, g, r);
if (rad !== 0)
alterneigh(rad, j, b, g, r); // alter neighbours
pix += step;
if (pix >= lengthcount)
pix -= lengthcount;
i++;
if (delta === 0)
delta = 1;
if (i % delta === 0) {
alpha -= alpha / alphadec;
radius -= radius / radiusdec;
rad = radius >> radiusbiasshift;
if (rad <= 1)
rad = 0;
for (j = 0; j < rad; j++)
radpower[j] = toInt(alpha * (((rad * rad - j * j) * radbias) / (rad * rad)));
}
}
}
/*
Method: buildColormap
1. initializes network
2. trains it
3. removes misconceptions
4. builds colorindex
*/
function buildColormap() {
init();
learn();
unbiasnet();
inxbuild();
}
this.buildColormap = buildColormap;
/*
Method: getColormap
builds colormap from the index
returns array in the format:
>
> [r, g, b, r, g, b, r, g, b, ..]
>
*/
function getColormap() {
var map = [];
var index = [];
for (var i = 0; i < netsize; i++)
index[network[i][3]] = i;
var k = 0;
for (var l = 0; l < netsize; l++) {
var j = index[l];
map[k++] = (network[j][0]);
map[k++] = (network[j][1]);
map[k++] = (network[j][2]);
}
return map;
}
this.getColormap = getColormap;
/*
Method: lookupRGB
looks for the closest *r*, *g*, *b* color in the map and
returns its index
*/
this.lookupRGB = inxsearch;
}
// module.exports = NeuQuant;
export default NeuQuant;
export default NeuQuant;
declare function NeuQuant(pixels: any, samplefac: any): void;
declare class NeuQuant {
constructor(pixels: any, samplefac: any);
buildColormap: () => void;
getColormap: () => any[];
lookupRGB: (b: any, g: any, r: any) => number;
}
/* NeuQuant Neural-Net Quantization Algorithm
* ------------------------------------------
*
* Copyright (c) 1994 Anthony Dekker
*
* NEUQUANT Neural-Net quantization algorithm by Anthony Dekker, 1994.
* See "Kohonen neural networks for optimal colour quantization"
* in "Network: Computation in Neural Systems" Vol. 5 (1994) pp 351-367.
* for a discussion of the algorithm.
* See also http://members.ozemail.com.au/~dekker/NEUQUANT.HTML
*
* Any party obtaining a copy of these files from the author, directly or
* indirectly, is granted, free of charge, a full and unrestricted irrevocable,
* world-wide, paid up, royalty-free, nonexclusive right and license to deal
* in this software and documentation files (the "Software"), including without
* limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons who receive
* copies from any such party to do so, with the only requirement being
* that this copyright notice remain intact.
*
* (JavaScript port 2012 by Johan Nordberg)
*/
var ncycles = 100; // number of learning cycles
var netsize = 256; // number of colors used
var maxnetpos = netsize - 1;
// defs for freq and bias
var netbiasshift = 4; // bias for colour values
var intbiasshift = 16; // bias for fractions
var intbias = (1 << intbiasshift);
var gammashift = 10;
var gamma = (1 << gammashift);
var betashift = 10;
var beta = (intbias >> betashift); /* beta = 1/1024 */
var betagamma = (intbias << (gammashift - betashift));
// defs for decreasing radius factor
var initrad = (netsize >> 3); // for 256 cols, radius starts
var radiusbiasshift = 6; // at 32.0 biased by 6 bits
var radiusbias = (1 << radiusbiasshift);
var initradius = (initrad * radiusbias); //and decreases by a
var radiusdec = 30; // factor of 1/30 each cycle
// defs for decreasing alpha factor
var alphabiasshift = 10; // alpha starts at 1.0
var initalpha = (1 << alphabiasshift);
var alphadec; // biased by 10 bits
/* radbias and alpharadbias used for radpower calculation */
var radbiasshift = 8;
var radbias = (1 << radbiasshift);
var alpharadbshift = (alphabiasshift + radbiasshift);
var alpharadbias = (1 << alpharadbshift);
// four primes near 500 - assume no image has a length so large that it is
// divisible by all four primes
var prime1 = 499;
var prime2 = 491;
var prime3 = 487;
var prime4 = 503;
var minpicturebytes = (3 * prime4);
/*
Constructor: NeuQuant
Arguments:
pixels - array of pixels in RGB format
samplefac - sampling factor 1 to 30 where lower is better quality
>
> pixels = [r, g, b, r, g, b, r, g, b, ..]
>
*/
function NeuQuant(pixels, samplefac) {
var network; // int[netsize][4]
var netindex; // for network lookup - really 256
// bias and freq arrays for learning
var bias;
var freq;
var radpower;
/*
Private Method: init
sets up arrays
*/
function init() {
network = [];
netindex = new Int32Array(256);
bias = new Int32Array(netsize);
freq = new Int32Array(netsize);
radpower = new Int32Array(netsize >> 3);
var i, v;
for (i = 0; i < netsize; i++) {
v = (i << (netbiasshift + 8)) / netsize;
network[i] = new Float64Array([v, v, v, 0]);
//network[i] = [v, v, v, 0]
freq[i] = intbias / netsize;
bias[i] = 0;
}
}
/*
Private Method: unbiasnet
unbiases network to give byte values 0..255 and record position i to prepare for sort
*/
function unbiasnet() {
for (var i = 0; i < netsize; i++) {
network[i][0] >>= netbiasshift;
network[i][1] >>= netbiasshift;
network[i][2] >>= netbiasshift;
network[i][3] = i; // record color number
}
}
/*
Private Method: altersingle
moves neuron *i* towards biased (b,g,r) by factor *alpha*
*/
function altersingle(alpha, i, b, g, r) {
network[i][0] -= (alpha * (network[i][0] - b)) / initalpha;
network[i][1] -= (alpha * (network[i][1] - g)) / initalpha;
network[i][2] -= (alpha * (network[i][2] - r)) / initalpha;
}
/*
Private Method: alterneigh
moves neurons in *radius* around index *i* towards biased (b,g,r) by factor *alpha*
*/
function alterneigh(radius, i, b, g, r) {
var lo = Math.abs(i - radius);
var hi = Math.min(i + radius, netsize);
var j = i + 1;
var k = i - 1;
var m = 1;
var p, a;
while ((j < hi) || (k > lo)) {
a = radpower[m++];
if (j < hi) {
p = network[j++];
p[0] -= (a * (p[0] - b)) / alpharadbias;
p[1] -= (a * (p[1] - g)) / alpharadbias;
p[2] -= (a * (p[2] - r)) / alpharadbias;
}
if (k > lo) {
p = network[k--];
p[0] -= (a * (p[0] - b)) / alpharadbias;
p[1] -= (a * (p[1] - g)) / alpharadbias;
p[2] -= (a * (p[2] - r)) / alpharadbias;
}
}
}
/*
Private Method: contest
searches for biased BGR values
*/
function contest(b, g, r) {
/*
finds closest neuron (min dist) and updates freq
finds best neuron (min dist-bias) and returns position
for frequently chosen neurons, freq[i] is high and bias[i] is negative
bias[i] = gamma * ((1 / netsize) - freq[i])
*/
var bestd = ~(1 << 31);
var bestbiasd = bestd;
var bestpos = -1;
var bestbiaspos = bestpos;
var i, n, dist, biasdist, betafreq;
for (i = 0; i < netsize; i++) {
n = network[i];
dist = Math.abs(n[0] - b) + Math.abs(n[1] - g) + Math.abs(n[2] - r);
if (dist < bestd) {
bestd = dist;
bestpos = i;
}
biasdist = dist - ((bias[i]) >> (intbiasshift - netbiasshift));
if (biasdist < bestbiasd) {
bestbiasd = biasdist;
bestbiaspos = i;
}
betafreq = (freq[i] >> betashift);
freq[i] -= betafreq;
bias[i] += (betafreq << gammashift);
}
freq[bestpos] += beta;
bias[bestpos] -= betagamma;
return bestbiaspos;
}
/*
Private Method: inxbuild
sorts network and builds netindex[0..255]
*/
function inxbuild() {
var i, j, p, q, smallpos, smallval, previouscol = 0, startpos = 0;
for (i = 0; i < netsize; i++) {
p = network[i];
smallpos = i;
smallval = p[1]; // index on g
// find smallest in i..netsize-1
for (j = i + 1; j < netsize; j++) {
q = network[j];
if (q[1] < smallval) { // index on g
smallpos = j;
smallval = q[1]; // index on g
}
}
q = network[smallpos];
// swap p (i) and q (smallpos) entries
if (i != smallpos) {
j = q[0];
q[0] = p[0];
p[0] = j;
j = q[1];
q[1] = p[1];
p[1] = j;
j = q[2];
q[2] = p[2];
p[2] = j;
j = q[3];
q[3] = p[3];
p[3] = j;
}
// smallval entry is now in position i
if (smallval != previouscol) {
netindex[previouscol] = (startpos + i) >> 1;
for (j = previouscol + 1; j < smallval; j++)
netindex[j] = i;
previouscol = smallval;
startpos = i;
}
}
netindex[previouscol] = (startpos + maxnetpos) >> 1;
for (j = previouscol + 1; j < 256; j++)
netindex[j] = maxnetpos; // really 256
}
/*
Private Method: inxsearch
searches for BGR values 0..255 and returns a color index
*/
function inxsearch(b, g, r) {
var a, p, dist;
var bestd = 1000; // biggest possible dist is 256*3
var best = -1;
var i = netindex[g]; // index on g
var j = i - 1; // start at netindex[g] and work outwards
while ((i < netsize) || (j >= 0)) {
if (i < netsize) {
p = network[i];
dist = p[1] - g; // inx key
if (dist >= bestd)
i = netsize; // stop iter
else {
i++;
if (dist < 0)
dist = -dist;
a = p[0] - b;
if (a < 0)
a = -a;
dist += a;
if (dist < bestd) {
a = p[2] - r;
if (a < 0)
a = -a;
dist += a;
if (dist < bestd) {
bestd = dist;
best = p[3];
}
}
}
}
if (j >= 0) {
p = network[j];
dist = g - p[1]; // inx key - reverse dif
if (dist >= bestd)
j = -1; // stop iter
else {
j--;
if (dist < 0)
dist = -dist;
a = p[0] - b;
if (a < 0)
a = -a;
dist += a;
if (dist < bestd) {
a = p[2] - r;
if (a < 0)
a = -a;
dist += a;
if (dist < bestd) {
bestd = dist;
best = p[3];
}
}
}
}
}
return best;
}
/*
Private Method: learn
"Main Learning Loop"
*/
function learn() {
var i;
var lengthcount = pixels.length;
var alphadec = 30 + ((samplefac - 1) / 3);
var samplepixels = lengthcount / (3 * samplefac);
var delta = ~~(samplepixels / ncycles);
var alpha = initalpha;
var radius = initradius;
var rad = radius >> radiusbiasshift;
if (rad <= 1)
rad = 0;
for (i = 0; i < rad; i++)
radpower[i] = alpha * (((rad * rad - i * i) * radbias) / (rad * rad));
var step;
if (lengthcount < minpicturebytes) {
samplefac = 1;
step = 3;
}
else if ((lengthcount % prime1) !== 0) {
step = 3 * prime1;
}
else if ((lengthcount % prime2) !== 0) {
step = 3 * prime2;
}
else if ((lengthcount % prime3) !== 0) {
step = 3 * prime3;
}
else {
step = 3 * prime4;
}
var b, g, r, j;
var pix = 0; // current pixel
i = 0;
while (i < samplepixels) {
b = (pixels[pix] & 0xff) << netbiasshift;
g = (pixels[pix + 1] & 0xff) << netbiasshift;
r = (pixels[pix + 2] & 0xff) << netbiasshift;
j = contest(b, g, r);
altersingle(alpha, j, b, g, r);
if (rad !== 0)
alterneigh(rad, j, b, g, r); // alter neighbours
pix += step;
if (pix >= lengthcount)
pix -= lengthcount;
i++;
if (delta === 0)
delta = 1;
if (i % delta === 0) {
alpha -= alpha / alphadec;
radius -= radius / radiusdec;
rad = radius >> radiusbiasshift;
if (rad <= 1)
rad = 0;
for (j = 0; j < rad; j++)
radpower[j] = alpha * (((rad * rad - j * j) * radbias) / (rad * rad));
}
}
}
/*
Method: buildColormap
1. initializes network
2. trains it
3. removes misconceptions
4. builds colorindex
*/
function buildColormap() {
init();
learn();
unbiasnet();
inxbuild();
}
this.buildColormap = buildColormap;
/*
Method: getColormap
builds colormap from the index
returns array in the format:
>
> [r, g, b, r, g, b, r, g, b, ..]
>
*/
function getColormap() {
var map = [];
var index = [];
for (var i = 0; i < netsize; i++)
index[network[i][3]] = i;
var k = 0;
for (var l = 0; l < netsize; l++) {
var j = index[l];
map[k++] = (network[j][0]);
map[k++] = (network[j][1]);
map[k++] = (network[j][2]);
}
return map;
}
this.getColormap = getColormap;
/*
Method: lookupRGB
looks for the closest *r*, *g*, *b* color in the map and
returns its index
*/
this.lookupRGB = inxsearch;
}
// module.exports = NeuQuant;
export default NeuQuant;
export function deinterlace(pixels: any, width: any): any[];
/**
* Deinterlace function from https://github.com/shachaf/jsgif
*/
export const deinterlace = (pixels, width) => {
const newPixels = new Array(pixels.length);
const rows = pixels.length / width;
const cpRow = function (toRow, fromRow) {
const fromPixels = pixels.slice(fromRow * width, (fromRow + 1) * width);
newPixels.splice.apply(newPixels, [toRow * width, width].concat(fromPixels));
};
// See appendix E.
const offsets = [0, 4, 2, 1];
const steps = [8, 8, 4, 2];
var fromRow = 0;
for (var pass = 0; pass < 4; pass++) {
for (var toRow = offsets[pass]; toRow < rows; toRow += steps[pass]) {
cpRow(toRow, fromRow);
fromRow++;
}
}
return newPixels;
};
export function parseGIF(arrayBuffer: any): any;
export function decompressFrame(frame: any, gct: any, buildImagePatch: any): {
pixels: any[];
dims: {
top: any;
left: any;
width: any;
height: any;
};
} | undefined;
export function decompressFrames(parsedGif: any, buildImagePatches: any): any;
import GIF from 'js-binary-schema-parser/src/schemas/gif';
import { parse } from 'js-binary-schema-parser/src/index';
import { buildStream } from 'js-binary-schema-parser/src/parsers/uint8';
import { deinterlace } from './deinterlace';
import { lzw } from './lzw';
export const parseGIF = arrayBuffer => {
const byteData = new Uint8Array(arrayBuffer);
return parse(buildStream(byteData), GIF);
};
const generatePatch = image => {
const totalPixels = image.pixels.length;
const patchData = new Uint8ClampedArray(totalPixels * 4);
for (var i = 0; i < totalPixels; i++) {
const pos = i * 4;
const colorIndex = image.pixels[i];
const color = image.colorTable[colorIndex];
patchData[pos] = color[0];
patchData[pos + 1] = color[1];
patchData[pos + 2] = color[2];
patchData[pos + 3] = colorIndex !== image.transparentIndex ? 255 : 0;
}
return patchData;
};
export const decompressFrame = (frame, gct, buildImagePatch) => {
if (!frame.image) {
console.warn('gif frame does not have associated image.');
return;
}
const { image } = frame;
// get the number of pixels
const totalPixels = image.descriptor.width * image.descriptor.height;
// do lzw decompression
var pixels = lzw(image.data.minCodeSize, image.data.blocks, totalPixels);
// deal with interlacing if necessary
if (image.descriptor.lct.interlaced) {
pixels = deinterlace(pixels, image.descriptor.width);
}
const resultImage = {
pixels: pixels,
dims: {
top: frame.image.descriptor.top,
left: frame.image.descriptor.left,
width: frame.image.descriptor.width,
height: frame.image.descriptor.height
}
};
// color table
if (image.descriptor.lct && image.descriptor.lct.exists) {
resultImage.colorTable = image.lct;
}
else {
resultImage.colorTable = gct;
}
// add per frame relevant gce information
if (frame.gce) {
resultImage.delay = (frame.gce.delay || 10) * 10; // convert to ms
resultImage.disposalType = frame.gce.extras.disposal;
// transparency
if (frame.gce.extras.transparentColorGiven) {
resultImage.transparentIndex = frame.gce.transparentColorIndex;
}
}
// create canvas usable imagedata if desired
if (buildImagePatch) {
resultImage.patch = generatePatch(resultImage);
}
return resultImage;
};
export const decompressFrames = (parsedGif, buildImagePatches) => {
return parsedGif.frames
.filter(f => f.image)
.map(f => decompressFrame(f, parsedGif.gct, buildImagePatches));
};
export function lzw(minCodeSize: any, data: any, pixelCount: any): any[];
/**
* javascript port of java LZW decompression
* Original java author url: https://gist.github.com/devunwired/4479231
*/
export const lzw = (minCodeSize, data, pixelCount) => {
const MAX_STACK_SIZE = 4096;
const nullCode = -1;
const npix = pixelCount;
var available, clear, code_mask, code_size, end_of_information, in_code, old_code, bits, code, i, datum, data_size, first, top, bi, pi;
const dstPixels = new Array(pixelCount);
const prefix = new Array(MAX_STACK_SIZE);
const suffix = new Array(MAX_STACK_SIZE);
const pixelStack = new Array(MAX_STACK_SIZE + 1);
// Initialize GIF data stream decoder.
data_size = minCodeSize;
clear = 1 << data_size;
end_of_information = clear + 1;
available = clear + 2;
old_code = nullCode;
code_size = data_size + 1;
code_mask = (1 << code_size) - 1;
for (code = 0; code < clear; code++) {
prefix[code] = 0;
suffix[code] = code;
}
// Decode GIF pixel stream.
var datum, bits, count, first, top, pi, bi;
datum = bits = count = first = top = pi = bi = 0;
for (i = 0; i < npix;) {
if (top === 0) {
if (bits < code_size) {
// get the next byte
datum += data[bi] << bits;
bits += 8;
bi++;
continue;
}
// Get the next code.
code = datum & code_mask;
datum >>= code_size;
bits -= code_size;
// Interpret the code
if (code > available || code == end_of_information) {
break;
}
if (code == clear) {
// Reset decoder.
code_size = data_size + 1;
code_mask = (1 << code_size) - 1;
available = clear + 2;
old_code = nullCode;
continue;
}
if (old_code == nullCode) {
pixelStack[top++] = suffix[code];
old_code = code;
first = code;
continue;
}
in_code = code;
if (code == available) {
pixelStack[top++] = first;
code = old_code;
}
while (code > clear) {
pixelStack[top++] = suffix[code];
code = prefix[code];
}
first = suffix[code] & 0xff;
pixelStack[top++] = first;
// add a new string to the table, but only if space is available
// if not, just continue with current table until a clear code is found
// (deferred clear code implementation as per GIF spec)
if (available < MAX_STACK_SIZE) {
prefix[available] = old_code;
suffix[available] = first;
available++;
if ((available & code_mask) === 0 && available < MAX_STACK_SIZE) {
code_size++;
code_mask += available;
}
}
old_code = in_code;
}
// Pop a pixel off the pixel stack.
top--;
dstPixels[pi++] = pixelStack[top];
i++;
}
for (i = pi; i < npix; i++) {
dstPixels[i] = 0; // clear missing pixels
}
return dstPixels;
};
export * from "./qrcode";
export { AwesomeQR, Options } from "./awesome-qr";
export * from "./qrcode";
export { AwesomeQR } from "./awesome-qr";
declare class QR8bitByte {
mode: number;
data: string;
parsedData: number[];
constructor(data: string);
getLength(): number;
write(buffer: QRBitBuffer): void;
}
export declare class QRCodeModel {
typeNumber: number;
errorCorrectLevel: number;
modules?: (boolean | null)[][];
moduleCount: number;
dataCache?: number[];
dataList: QR8bitByte[];
maskPattern?: number;
constructor(typeNumber?: number, errorCorrectLevel?: number);
addData(data: string): void;
isDark(row: number, col: number): boolean | null;
getModuleCount(): number;
make(): void;
makeImpl(test: boolean, maskPattern: number): void;
setupPositionProbePattern(row: number, col: number): void;
getBestMaskPattern(): number;
setupTimingPattern(): void;
setupPositionAdjustPattern(): void;
setupTypeNumber(test: boolean): void;
setupTypeInfo(test: boolean, maskPattern: number): void;
mapData(data: number[], maskPattern: number): void;
static PAD0: number;
static PAD1: number;
static createData(typeNumber: number, errorCorrectLevel: number, dataList: QR8bitByte[]): number[];
static createBytes(buffer: QRBitBuffer, rsBlocks: QRRSBlock[]): number[];
}
export declare const QRErrorCorrectLevel: {
L: number;
M: number;
Q: number;
H: number;
};
export declare const QRMaskPattern: {
PATTERN000: number;
PATTERN001: number;
PATTERN010: number;
PATTERN011: number;
PATTERN100: number;
PATTERN101: number;
PATTERN110: number;
PATTERN111: number;
};
export declare class QRUtil {
static PATTERN_POSITION_TABLE: number[][];
static G15: number;
static G18: number;
static G15_MASK: number;
static getBCHTypeInfo(data: number): number;
static getBCHTypeNumber(data: number): number;
static getBCHDigit(data: number): number;
static getPatternPosition(typeNumber: number): number[];
static getMask(maskPattern: number, i: number, j: number): boolean;
static getErrorCorrectPolynomial(errorCorrectLength: number): QRPolynomial;
static getLengthInBits(mode: number, type: number): 14 | 11 | 12 | 8 | 10 | 9 | 16 | 13;
static getLostPoint(qrCode: QRCodeModel): number;
}
export declare class QRMath {
static glog(n: number): any;
static gexp(n: number): any;
static EXP_TABLE: any[];
static LOG_TABLE: any[];
static _constructor: void;
}
declare class QRPolynomial {
num: number[];
constructor(num: number[], shift: number);
get(index: number): number;
getLength(): number;
multiply(e: QRPolynomial): QRPolynomial;
mod(e: QRPolynomial): QRPolynomial;
}
declare class QRRSBlock {
totalCount: number;
dataCount: number;
constructor(totalCount: number, dataCount: number);
static RS_BLOCK_TABLE: number[][];
static getRSBlocks(typeNumber: number, errorCorrectLevel: number): QRRSBlock[];
static getRsBlockTable(typeNumber: number, errorCorrectLevel: number): number[] | undefined;
}
declare class QRBitBuffer {
buffer: number[];
length: number;
constructor();
get(index: number): boolean;
put(num: number, length: number): void;
getLengthInBits(): number;
putBit(bit: boolean): void;
}
export {};
//---------------------------------------------------------------------
// QRCode for JavaScript
//
// Copyright (c) 2009 Kazuhiko Arase
// Re-written in TypeScript by Makito <sumimakito@hotmail.com>
//
// URL: http://www.d-project.com/
//
// Licensed under the MIT license:
// http://www.opensource.org/licenses/mit-license.php
//
// The word "QR Code" is registered trademark of
// DENSO WAVE INCORPORATED
// http://www.denso-wave.com/qrcode/faqpatent-e.html
//
//---------------------------------------------------------------------
function checkQRVersion(version, sText, nCorrectLevel) {
const length = _getUTF8Length(sText);
const i = version - 1;
let nLimit = 0;
switch (nCorrectLevel) {
case QRErrorCorrectLevel.L:
nLimit = QRCodeLimitLength[i][0];
break;
case QRErrorCorrectLevel.M:
nLimit = QRCodeLimitLength[i][1];
break;
case QRErrorCorrectLevel.Q:
nLimit = QRCodeLimitLength[i][2];
break;
case QRErrorCorrectLevel.H:
nLimit = QRCodeLimitLength[i][3];
break;
}
return length <= nLimit;
}
function _getTypeNumber(sText, nCorrectLevel) {
var nType = 1;
var length = _getUTF8Length(sText);
for (var i = 0, len = QRCodeLimitLength.length; i < len; i++) {
var nLimit = 0;
switch (nCorrectLevel) {
case QRErrorCorrectLevel.L:
nLimit = QRCodeLimitLength[i][0];
break;
case QRErrorCorrectLevel.M:
nLimit = QRCodeLimitLength[i][1];
break;
case QRErrorCorrectLevel.Q:
nLimit = QRCodeLimitLength[i][2];
break;
case QRErrorCorrectLevel.H:
nLimit = QRCodeLimitLength[i][3];
break;
}
if (length <= nLimit) {
break;
}
else {
nType++;
}
}
if (nType > QRCodeLimitLength.length) {
throw new Error("Too long data");
}
return nType;
}
function _getUTF8Length(sText) {
var replacedText = encodeURI(sText)
.toString()
.replace(/\%[0-9a-fA-F]{2}/g, "a");
return replacedText.length + (replacedText.length != Number(sText) ? 3 : 0);
}
class QR8bitByte {
constructor(data) {
this.mode = QRMode.MODE_8BIT_BYTE;
this.parsedData = [];
this.data = data;
const byteArrays = [];
// Added to support UTF-8 Characters
for (let i = 0, l = this.data.length; i < l; i++) {
const byteArray = [];
const code = this.data.charCodeAt(i);
if (code > 0x10000) {
byteArray[0] = 0xf0 | ((code & 0x1c0000) >>> 18);
byteArray[1] = 0x80 | ((code & 0x3f000) >>> 12);
byteArray[2] = 0x80 | ((code & 0xfc0) >>> 6);
byteArray[3] = 0x80 | (code & 0x3f);
}
else if (code > 0x800) {
byteArray[0] = 0xe0 | ((code & 0xf000) >>> 12);
byteArray[1] = 0x80 | ((code & 0xfc0) >>> 6);
byteArray[2] = 0x80 | (code & 0x3f);
}
else if (code > 0x80) {
byteArray[0] = 0xc0 | ((code & 0x7c0) >>> 6);
byteArray[1] = 0x80 | (code & 0x3f);
}
else {
byteArray[0] = code;
}
byteArrays.push(byteArray);
}
this.parsedData = Array.prototype.concat.apply([], byteArrays);
if (this.parsedData.length != this.data.length) {
this.parsedData.unshift(191);
this.parsedData.unshift(187);
this.parsedData.unshift(239);
}
}
getLength() {
return this.parsedData.length;
}
write(buffer) {
for (let i = 0, l = this.parsedData.length; i < l; i++) {
buffer.put(this.parsedData[i], 8);
}
}
}
export class QRCodeModel {
constructor(typeNumber = -1, errorCorrectLevel = QRErrorCorrectLevel.L) {
this.moduleCount = 0;
this.dataList = [];
this.typeNumber = typeNumber;
this.errorCorrectLevel = errorCorrectLevel;
this.moduleCount = 0;
this.dataList = [];
}
addData(data) {
if (this.typeNumber <= 0) {
this.typeNumber = _getTypeNumber(data, this.errorCorrectLevel);
}
else if (this.typeNumber > 40) {
throw new Error(`Invalid QR version: ${this.typeNumber}`);
}
else {
if (!checkQRVersion(this.typeNumber, data, this.errorCorrectLevel)) {
throw new Error(`Data is too long for QR version: ${this.typeNumber}`);
}
}
const newData = new QR8bitByte(data);
this.dataList.push(newData);
this.dataCache = undefined;
}
isDark(row, col) {
if (row < 0 || this.moduleCount <= row || col < 0 || this.moduleCount <= col) {
throw new Error(`${row},${col}`);
}
return this.modules[row][col];
}
getModuleCount() {
return this.moduleCount;
}
make() {
this.makeImpl(false, this.getBestMaskPattern());
}
makeImpl(test, maskPattern) {
this.moduleCount = this.typeNumber * 4 + 17;
this.modules = new Array(this.moduleCount);
for (let row = 0; row < this.moduleCount; row++) {
this.modules[row] = new Array(this.moduleCount);
for (let col = 0; col < this.moduleCount; col++) {
this.modules[row][col] = null;
}
}
this.setupPositionProbePattern(0, 0);
this.setupPositionProbePattern(this.moduleCount - 7, 0);
this.setupPositionProbePattern(0, this.moduleCount - 7);
this.setupPositionAdjustPattern();
this.setupTimingPattern();
this.setupTypeInfo(test, maskPattern);
if (this.typeNumber >= 7) {
this.setupTypeNumber(test);
}
if (this.dataCache == null) {
this.dataCache = QRCodeModel.createData(this.typeNumber, this.errorCorrectLevel, this.dataList);
}
this.mapData(this.dataCache, maskPattern);
}
setupPositionProbePattern(row, col) {
for (let r = -1; r <= 7; r++) {
if (row + r <= -1 || this.moduleCount <= row + r)
continue;
for (let c = -1; c <= 7; c++) {
if (col + c <= -1 || this.moduleCount <= col + c)
continue;
if ((0 <= r && r <= 6 && (c == 0 || c == 6)) ||
(0 <= c && c <= 6 && (r == 0 || r == 6)) ||
(2 <= r && r <= 4 && 2 <= c && c <= 4)) {
this.modules[row + r][col + c] = true;
}
else {
this.modules[row + r][col + c] = false;
}
}
}
}
getBestMaskPattern() {
if (Number.isInteger(this.maskPattern) && Object.values(QRMaskPattern).includes(this.maskPattern)) {
return this.maskPattern;
}
let minLostPoint = 0;
let pattern = 0;
for (let i = 0; i < 8; i++) {
this.makeImpl(true, i);
const lostPoint = QRUtil.getLostPoint(this);
if (i == 0 || minLostPoint > lostPoint) {
minLostPoint = lostPoint;
pattern = i;
}
}
return pattern;
}
setupTimingPattern() {
for (let r = 8; r < this.moduleCount - 8; r++) {
if (this.modules[r][6] != null) {
continue;
}
this.modules[r][6] = r % 2 == 0;
}
for (let c = 8; c < this.moduleCount - 8; c++) {
if (this.modules[6][c] != null) {
continue;
}
this.modules[6][c] = c % 2 == 0;
}
}
setupPositionAdjustPattern() {
const pos = QRUtil.getPatternPosition(this.typeNumber);
for (let i = 0; i < pos.length; i++) {
for (let j = 0; j < pos.length; j++) {
const row = pos[i];
const col = pos[j];
if (this.modules[row][col] != null) {
continue;
}
for (let r = -2; r <= 2; r++) {
for (let c = -2; c <= 2; c++) {
if (r == -2 || r == 2 || c == -2 || c == 2 || (r == 0 && c == 0)) {
this.modules[row + r][col + c] = true;
}
else {
this.modules[row + r][col + c] = false;
}
}
}
}
}
}
setupTypeNumber(test) {
const bits = QRUtil.getBCHTypeNumber(this.typeNumber);
for (var i = 0; i < 18; i++) {
var mod = !test && ((bits >> i) & 1) == 1;
this.modules[Math.floor(i / 3)][(i % 3) + this.moduleCount - 8 - 3] = mod;
}
for (var i = 0; i < 18; i++) {
var mod = !test && ((bits >> i) & 1) == 1;
this.modules[(i % 3) + this.moduleCount - 8 - 3][Math.floor(i / 3)] = mod;
}
}
setupTypeInfo(test, maskPattern) {
const data = (this.errorCorrectLevel << 3) | maskPattern;
const bits = QRUtil.getBCHTypeInfo(data);
for (var i = 0; i < 15; i++) {
var mod = !test && ((bits >> i) & 1) == 1;
if (i < 6) {
this.modules[i][8] = mod;
}
else if (i < 8) {
this.modules[i + 1][8] = mod;
}
else {
this.modules[this.moduleCount - 15 + i][8] = mod;
}
}
for (var i = 0; i < 15; i++) {
var mod = !test && ((bits >> i) & 1) == 1;
if (i < 8) {
this.modules[8][this.moduleCount - i - 1] = mod;
}
else if (i < 9) {
this.modules[8][15 - i - 1 + 1] = mod;
}
else {
this.modules[8][15 - i - 1] = mod;
}
}
this.modules[this.moduleCount - 8][8] = !test;
}
mapData(data, maskPattern) {
let inc = -1;
let row = this.moduleCount - 1;
let bitIndex = 7;
let byteIndex = 0;
for (let col = this.moduleCount - 1; col > 0; col -= 2) {
if (col == 6)
col--;
while (true) {
for (let c = 0; c < 2; c++) {
if (this.modules[row][col - c] == null) {
let dark = false;
if (byteIndex < data.length) {
dark = ((data[byteIndex] >>> bitIndex) & 1) == 1;
}
const mask = QRUtil.getMask(maskPattern, row, col - c);
if (mask) {
dark = !dark;
}
this.modules[row][col - c] = dark;
bitIndex--;
if (bitIndex == -1) {
byteIndex++;
bitIndex = 7;
}
}
}
row += inc;
if (row < 0 || this.moduleCount <= row) {
row -= inc;
inc = -inc;
break;
}
}
}
}
static createData(typeNumber, errorCorrectLevel, dataList) {
const rsBlocks = QRRSBlock.getRSBlocks(typeNumber, errorCorrectLevel);
const buffer = new QRBitBuffer();
for (var i = 0; i < dataList.length; i++) {
const data = dataList[i];
buffer.put(data.mode, 4);
buffer.put(data.getLength(), QRUtil.getLengthInBits(data.mode, typeNumber));
data.write(buffer);
}
let totalDataCount = 0;
for (var i = 0; i < rsBlocks.length; i++) {
totalDataCount += rsBlocks[i].dataCount;
}
if (buffer.getLengthInBits() > totalDataCount * 8) {
throw new Error(`code length overflow. (${buffer.getLengthInBits()}>${totalDataCount * 8})`);
}
if (buffer.getLengthInBits() + 4 <= totalDataCount * 8) {
buffer.put(0, 4);
}
while (buffer.getLengthInBits() % 8 != 0) {
buffer.putBit(false);
}
while (true) {
if (buffer.getLengthInBits() >= totalDataCount * 8) {
break;
}
buffer.put(QRCodeModel.PAD0, 8);
if (buffer.getLengthInBits() >= totalDataCount * 8) {
break;
}
buffer.put(QRCodeModel.PAD1, 8);
}
return QRCodeModel.createBytes(buffer, rsBlocks);
}
static createBytes(buffer, rsBlocks) {
let offset = 0;
let maxDcCount = 0;
let maxEcCount = 0;
const dcdata = new Array(rsBlocks.length);
const ecdata = new Array(rsBlocks.length);
for (var r = 0; r < rsBlocks.length; r++) {
const dcCount = rsBlocks[r].dataCount;
const ecCount = rsBlocks[r].totalCount - dcCount;
maxDcCount = Math.max(maxDcCount, dcCount);
maxEcCount = Math.max(maxEcCount, ecCount);
dcdata[r] = new Array(dcCount);
for (var i = 0; i < dcdata[r].length; i++) {
dcdata[r][i] = 0xff & buffer.buffer[i + offset];
}
offset += dcCount;
const rsPoly = QRUtil.getErrorCorrectPolynomial(ecCount);
const rawPoly = new QRPolynomial(dcdata[r], rsPoly.getLength() - 1);
const modPoly = rawPoly.mod(rsPoly);
ecdata[r] = new Array(rsPoly.getLength() - 1);
for (var i = 0; i < ecdata[r].length; i++) {
const modIndex = i + modPoly.getLength() - ecdata[r].length;
ecdata[r][i] = modIndex >= 0 ? modPoly.get(modIndex) : 0;
}
}
let totalCodeCount = 0;
for (var i = 0; i < rsBlocks.length; i++) {
totalCodeCount += rsBlocks[i].totalCount;
}
const data = new Array(totalCodeCount);
let index = 0;
for (var i = 0; i < maxDcCount; i++) {
for (var r = 0; r < rsBlocks.length; r++) {
if (i < dcdata[r].length) {
data[index++] = dcdata[r][i];
}
}
}
for (var i = 0; i < maxEcCount; i++) {
for (var r = 0; r < rsBlocks.length; r++) {
if (i < ecdata[r].length) {
data[index++] = ecdata[r][i];
}
}
}
return data;
}
}
QRCodeModel.PAD0 = 0xec;
QRCodeModel.PAD1 = 0x11;
export const QRErrorCorrectLevel = { L: 1, M: 0, Q: 3, H: 2 };
const QRMode = { MODE_NUMBER: 1 << 0, MODE_ALPHA_NUM: 1 << 1, MODE_8BIT_BYTE: 1 << 2, MODE_KANJI: 1 << 3 };
export const QRMaskPattern = {
PATTERN000: 0,
PATTERN001: 1,
PATTERN010: 2,
PATTERN011: 3,
PATTERN100: 4,
PATTERN101: 5,
PATTERN110: 6,
PATTERN111: 7,
};
export class QRUtil {
static getBCHTypeInfo(data) {
let d = data << 10;
while (QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G15) >= 0) {
d ^= QRUtil.G15 << (QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G15));
}
return ((data << 10) | d) ^ QRUtil.G15_MASK;
}
static getBCHTypeNumber(data) {
let d = data << 12;
while (QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G18) >= 0) {
d ^= QRUtil.G18 << (QRUtil.getBCHDigit(d) - QRUtil.getBCHDigit(QRUtil.G18));
}
return (data << 12) | d;
}
static getBCHDigit(data) {
let digit = 0;
while (data != 0) {
digit++;
data >>>= 1;
}
return digit;
}
static getPatternPosition(typeNumber) {
return QRUtil.PATTERN_POSITION_TABLE[typeNumber - 1];
}
static getMask(maskPattern, i, j) {
switch (maskPattern) {
case QRMaskPattern.PATTERN000:
return (i + j) % 2 == 0;
case QRMaskPattern.PATTERN001:
return i % 2 == 0;
case QRMaskPattern.PATTERN010:
return j % 3 == 0;
case QRMaskPattern.PATTERN011:
return (i + j) % 3 == 0;
case QRMaskPattern.PATTERN100:
return (Math.floor(i / 2) + Math.floor(j / 3)) % 2 == 0;
case QRMaskPattern.PATTERN101:
return ((i * j) % 2) + ((i * j) % 3) == 0;
case QRMaskPattern.PATTERN110:
return (((i * j) % 2) + ((i * j) % 3)) % 2 == 0;
case QRMaskPattern.PATTERN111:
return (((i * j) % 3) + ((i + j) % 2)) % 2 == 0;
default:
throw new Error(`bad maskPattern:${maskPattern}`);
}
}
static getErrorCorrectPolynomial(errorCorrectLength) {
let a = new QRPolynomial([1], 0);
for (let i = 0; i < errorCorrectLength; i++) {
a = a.multiply(new QRPolynomial([1, QRMath.gexp(i)], 0));
}
return a;
}
static getLengthInBits(mode, type) {
if (1 <= type && type < 10) {
switch (mode) {
case QRMode.MODE_NUMBER:
return 10;
case QRMode.MODE_ALPHA_NUM:
return 9;
case QRMode.MODE_8BIT_BYTE:
return 8;
case QRMode.MODE_KANJI:
return 8;
default:
throw new Error(`mode:${mode}`);
}
}
else if (type < 27) {
switch (mode) {
case QRMode.MODE_NUMBER:
return 12;
case QRMode.MODE_ALPHA_NUM:
return 11;
case QRMode.MODE_8BIT_BYTE:
return 16;
case QRMode.MODE_KANJI:
return 10;
default:
throw new Error(`mode:${mode}`);
}
}
else if (type < 41) {
switch (mode) {
case QRMode.MODE_NUMBER:
return 14;
case QRMode.MODE_ALPHA_NUM:
return 13;
case QRMode.MODE_8BIT_BYTE:
return 16;
case QRMode.MODE_KANJI:
return 12;
default:
throw new Error(`mode:${mode}`);
}
}
else {
throw new Error(`type:${type}`);
}
}
static getLostPoint(qrCode) {
const moduleCount = qrCode.getModuleCount();
let lostPoint = 0;
for (var row = 0; row < moduleCount; row++) {
for (var col = 0; col < moduleCount; col++) {
let sameCount = 0;
const dark = qrCode.isDark(row, col);
for (let r = -1; r <= 1; r++) {
if (row + r < 0 || moduleCount <= row + r) {
continue;
}
for (let c = -1; c <= 1; c++) {
if (col + c < 0 || moduleCount <= col + c) {
continue;
}
if (r == 0 && c == 0) {
continue;
}
if (dark == qrCode.isDark(row + r, col + c)) {
sameCount++;
}
}
}
if (sameCount > 5) {
lostPoint += 3 + sameCount - 5;
}
}
}
for (var row = 0; row < moduleCount - 1; row++) {
for (var col = 0; col < moduleCount - 1; col++) {
let count = 0;
if (qrCode.isDark(row, col))
count++;
if (qrCode.isDark(row + 1, col))
count++;
if (qrCode.isDark(row, col + 1))
count++;
if (qrCode.isDark(row + 1, col + 1))
count++;
if (count == 0 || count == 4) {
lostPoint += 3;
}
}
}
for (var row = 0; row < moduleCount; row++) {
for (var col = 0; col < moduleCount - 6; col++) {
if (qrCode.isDark(row, col) &&
!qrCode.isDark(row, col + 1) &&
qrCode.isDark(row, col + 2) &&
qrCode.isDark(row, col + 3) &&
qrCode.isDark(row, col + 4) &&
!qrCode.isDark(row, col + 5) &&
qrCode.isDark(row, col + 6)) {
lostPoint += 40;
}
}
}
for (var col = 0; col < moduleCount; col++) {
for (var row = 0; row < moduleCount - 6; row++) {
if (qrCode.isDark(row, col) &&
!qrCode.isDark(row + 1, col) &&
qrCode.isDark(row + 2, col) &&
qrCode.isDark(row + 3, col) &&
qrCode.isDark(row + 4, col) &&
!qrCode.isDark(row + 5, col) &&
qrCode.isDark(row + 6, col)) {
lostPoint += 40;
}
}
}
let darkCount = 0;
for (var col = 0; col < moduleCount; col++) {
for (var row = 0; row < moduleCount; row++) {
if (qrCode.isDark(row, col)) {
darkCount++;
}
}
}
const ratio = Math.abs((100 * darkCount) / moduleCount / moduleCount - 50) / 5;
lostPoint += ratio * 10;
return lostPoint;
}
}
QRUtil.PATTERN_POSITION_TABLE = [
[],
[6, 18],
[6, 22],
[6, 26],
[6, 30],
[6, 34],
[6, 22, 38],
[6, 24, 42],
[6, 26, 46],
[6, 28, 50],
[6, 30, 54],
[6, 32, 58],
[6, 34, 62],
[6, 26, 46, 66],
[6, 26, 48, 70],
[6, 26, 50, 74],
[6, 30, 54, 78],
[6, 30, 56, 82],
[6, 30, 58, 86],
[6, 34, 62, 90],
[6, 28, 50, 72, 94],
[6, 26, 50, 74, 98],
[6, 30, 54, 78, 102],
[6, 28, 54, 80, 106],
[6, 32, 58, 84, 110],
[6, 30, 58, 86, 114],
[6, 34, 62, 90, 118],
[6, 26, 50, 74, 98, 122],
[6, 30, 54, 78, 102, 126],
[6, 26, 52, 78, 104, 130],
[6, 30, 56, 82, 108, 134],
[6, 34, 60, 86, 112, 138],
[6, 30, 58, 86, 114, 142],
[6, 34, 62, 90, 118, 146],
[6, 30, 54, 78, 102, 126, 150],
[6, 24, 50, 76, 102, 128, 154],
[6, 28, 54, 80, 106, 132, 158],
[6, 32, 58, 84, 110, 136, 162],
[6, 26, 54, 82, 110, 138, 166],
[6, 30, 58, 86, 114, 142, 170],
];
QRUtil.G15 = (1 << 10) | (1 << 8) | (1 << 5) | (1 << 4) | (1 << 2) | (1 << 1) | (1 << 0);
QRUtil.G18 = (1 << 12) | (1 << 11) | (1 << 10) | (1 << 9) | (1 << 8) | (1 << 5) | (1 << 2) | (1 << 0);
QRUtil.G15_MASK = (1 << 14) | (1 << 12) | (1 << 10) | (1 << 4) | (1 << 1);
export class QRMath {
static glog(n) {
if (n < 1) {
throw new Error(`glog(${n})`);
}
return QRMath.LOG_TABLE[n];
}
static gexp(n) {
while (n < 0) {
n += 255;
}
while (n >= 256) {
n -= 255;
}
return QRMath.EXP_TABLE[n];
}
}
QRMath.EXP_TABLE = new Array(256);
QRMath.LOG_TABLE = new Array(256);
QRMath._constructor = (function () {
for (var i = 0; i < 8; i++) {
QRMath.EXP_TABLE[i] = 1 << i;
}
for (var i = 8; i < 256; i++) {
QRMath.EXP_TABLE[i] =
QRMath.EXP_TABLE[i - 4] ^ QRMath.EXP_TABLE[i - 5] ^ QRMath.EXP_TABLE[i - 6] ^ QRMath.EXP_TABLE[i - 8];
}
for (var i = 0; i < 255; i++) {
QRMath.LOG_TABLE[QRMath.EXP_TABLE[i]] = i;
}
})();
class QRPolynomial {
constructor(num, shift) {
if (num.length == undefined) {
throw new Error(`${num.length}/${shift}`);
}
let offset = 0;
while (offset < num.length && num[offset] == 0) {
offset++;
}
this.num = new Array(num.length - offset + shift);
for (let i = 0; i < num.length - offset; i++) {
this.num[i] = num[i + offset];
}
}
get(index) {
return this.num[index];
}
getLength() {
return this.num.length;
}
multiply(e) {
const num = new Array(this.getLength() + e.getLength() - 1);
for (let i = 0; i < this.getLength(); i++) {
for (let j = 0; j < e.getLength(); j++) {
num[i + j] ^= QRMath.gexp(QRMath.glog(this.get(i)) + QRMath.glog(e.get(j)));
}
}
return new QRPolynomial(num, 0);
}
mod(e) {
if (this.getLength() - e.getLength() < 0) {
return this;
}
const ratio = QRMath.glog(this.get(0)) - QRMath.glog(e.get(0));
const num = new Array(this.getLength());
for (var i = 0; i < this.getLength(); i++) {
num[i] = this.get(i);
}
for (var i = 0; i < e.getLength(); i++) {
num[i] ^= QRMath.gexp(QRMath.glog(e.get(i)) + ratio);
}
return new QRPolynomial(num, 0).mod(e);
}
}
class QRRSBlock {
constructor(totalCount, dataCount) {
this.totalCount = totalCount;
this.dataCount = dataCount;
}
static getRSBlocks(typeNumber, errorCorrectLevel) {
const rsBlock = QRRSBlock.getRsBlockTable(typeNumber, errorCorrectLevel);
if (rsBlock == undefined) {
throw new Error(`bad rs block @ typeNumber:${typeNumber}/errorCorrectLevel:${errorCorrectLevel}`);
}
const length = rsBlock.length / 3;
const list = [];
for (let i = 0; i < length; i++) {
const count = rsBlock[i * 3 + 0];
const totalCount = rsBlock[i * 3 + 1];
const dataCount = rsBlock[i * 3 + 2];
for (let j = 0; j < count; j++) {
list.push(new QRRSBlock(totalCount, dataCount));
}
}
return list;
}
static getRsBlockTable(typeNumber, errorCorrectLevel) {
switch (errorCorrectLevel) {
case QRErrorCorrectLevel.L:
return QRRSBlock.RS_BLOCK_TABLE[(typeNumber - 1) * 4 + 0];
case QRErrorCorrectLevel.M:
return QRRSBlock.RS_BLOCK_TABLE[(typeNumber - 1) * 4 + 1];
case QRErrorCorrectLevel.Q:
return QRRSBlock.RS_BLOCK_TABLE[(typeNumber - 1) * 4 + 2];
case QRErrorCorrectLevel.H:
return QRRSBlock.RS_BLOCK_TABLE[(typeNumber - 1) * 4 + 3];
default:
return undefined;
}
}
}
QRRSBlock.RS_BLOCK_TABLE = [
[1, 26, 19],
[1, 26, 16],
[1, 26, 13],
[1, 26, 9],
[1, 44, 34],
[1, 44, 28],
[1, 44, 22],
[1, 44, 16],
[1, 70, 55],
[1, 70, 44],
[2, 35, 17],
[2, 35, 13],
[1, 100, 80],
[2, 50, 32],
[2, 50, 24],
[4, 25, 9],
[1, 134, 108],
[2, 67, 43],
[2, 33, 15, 2, 34, 16],
[2, 33, 11, 2, 34, 12],
[2, 86, 68],
[4, 43, 27],
[4, 43, 19],
[4, 43, 15],
[2, 98, 78],
[4, 49, 31],
[2, 32, 14, 4, 33, 15],
[4, 39, 13, 1, 40, 14],
[2, 121, 97],
[2, 60, 38, 2, 61, 39],
[4, 40, 18, 2, 41, 19],
[4, 40, 14, 2, 41, 15],
[2, 146, 116],
[3, 58, 36, 2, 59, 37],
[4, 36, 16, 4, 37, 17],
[4, 36, 12, 4, 37, 13],
[2, 86, 68, 2, 87, 69],
[4, 69, 43, 1, 70, 44],
[6, 43, 19, 2, 44, 20],
[6, 43, 15, 2, 44, 16],
[4, 101, 81],
[1, 80, 50, 4, 81, 51],
[4, 50, 22, 4, 51, 23],
[3, 36, 12, 8, 37, 13],
[2, 116, 92, 2, 117, 93],
[6, 58, 36, 2, 59, 37],
[4, 46, 20, 6, 47, 21],
[7, 42, 14, 4, 43, 15],
[4, 133, 107],
[8, 59, 37, 1, 60, 38],
[8, 44, 20, 4, 45, 21],
[12, 33, 11, 4, 34, 12],
[3, 145, 115, 1, 146, 116],
[4, 64, 40, 5, 65, 41],
[11, 36, 16, 5, 37, 17],
[11, 36, 12, 5, 37, 13],
[5, 109, 87, 1, 110, 88],
[5, 65, 41, 5, 66, 42],
[5, 54, 24, 7, 55, 25],
[11, 36, 12],
[5, 122, 98, 1, 123, 99],
[7, 73, 45, 3, 74, 46],
[15, 43, 19, 2, 44, 20],
[3, 45, 15, 13, 46, 16],
[1, 135, 107, 5, 136, 108],
[10, 74, 46, 1, 75, 47],
[1, 50, 22, 15, 51, 23],
[2, 42, 14, 17, 43, 15],
[5, 150, 120, 1, 151, 121],
[9, 69, 43, 4, 70, 44],
[17, 50, 22, 1, 51, 23],
[2, 42, 14, 19, 43, 15],
[3, 141, 113, 4, 142, 114],
[3, 70, 44, 11, 71, 45],
[17, 47, 21, 4, 48, 22],
[9, 39, 13, 16, 40, 14],
[3, 135, 107, 5, 136, 108],
[3, 67, 41, 13, 68, 42],
[15, 54, 24, 5, 55, 25],
[15, 43, 15, 10, 44, 16],
[4, 144, 116, 4, 145, 117],
[17, 68, 42],
[17, 50, 22, 6, 51, 23],
[19, 46, 16, 6, 47, 17],
[2, 139, 111, 7, 140, 112],
[17, 74, 46],
[7, 54, 24, 16, 55, 25],
[34, 37, 13],
[4, 151, 121, 5, 152, 122],
[4, 75, 47, 14, 76, 48],
[11, 54, 24, 14, 55, 25],
[16, 45, 15, 14, 46, 16],
[6, 147, 117, 4, 148, 118],
[6, 73, 45, 14, 74, 46],
[11, 54, 24, 16, 55, 25],
[30, 46, 16, 2, 47, 17],
[8, 132, 106, 4, 133, 107],
[8, 75, 47, 13, 76, 48],
[7, 54, 24, 22, 55, 25],
[22, 45, 15, 13, 46, 16],
[10, 142, 114, 2, 143, 115],
[19, 74, 46, 4, 75, 47],
[28, 50, 22, 6, 51, 23],
[33, 46, 16, 4, 47, 17],
[8, 152, 122, 4, 153, 123],
[22, 73, 45, 3, 74, 46],
[8, 53, 23, 26, 54, 24],
[12, 45, 15, 28, 46, 16],
[3, 147, 117, 10, 148, 118],
[3, 73, 45, 23, 74, 46],
[4, 54, 24, 31, 55, 25],
[11, 45, 15, 31, 46, 16],
[7, 146, 116, 7, 147, 117],
[21, 73, 45, 7, 74, 46],
[1, 53, 23, 37, 54, 24],
[19, 45, 15, 26, 46, 16],
[5, 145, 115, 10, 146, 116],
[19, 75, 47, 10, 76, 48],
[15, 54, 24, 25, 55, 25],
[23, 45, 15, 25, 46, 16],
[13, 145, 115, 3, 146, 116],
[2, 74, 46, 29, 75, 47],
[42, 54, 24, 1, 55, 25],
[23, 45, 15, 28, 46, 16],
[17, 145, 115],
[10, 74, 46, 23, 75, 47],
[10, 54, 24, 35, 55, 25],
[19, 45, 15, 35, 46, 16],
[17, 145, 115, 1, 146, 116],
[14, 74, 46, 21, 75, 47],
[29, 54, 24, 19, 55, 25],
[11, 45, 15, 46, 46, 16],
[13, 145, 115, 6, 146, 116],
[14, 74, 46, 23, 75, 47],
[44, 54, 24, 7, 55, 25],
[59, 46, 16, 1, 47, 17],
[12, 151, 121, 7, 152, 122],
[12, 75, 47, 26, 76, 48],
[39, 54, 24, 14, 55, 25],
[22, 45, 15, 41, 46, 16],
[6, 151, 121, 14, 152, 122],
[6, 75, 47, 34, 76, 48],
[46, 54, 24, 10, 55, 25],
[2, 45, 15, 64, 46, 16],
[17, 152, 122, 4, 153, 123],
[29, 74, 46, 14, 75, 47],
[49, 54, 24, 10, 55, 25],
[24, 45, 15, 46, 46, 16],
[4, 152, 122, 18, 153, 123],
[13, 74, 46, 32, 75, 47],
[48, 54, 24, 14, 55, 25],
[42, 45, 15, 32, 46, 16],
[20, 147, 117, 4, 148, 118],
[40, 75, 47, 7, 76, 48],
[43, 54, 24, 22, 55, 25],
[10, 45, 15, 67, 46, 16],
[19, 148, 118, 6, 149, 119],
[18, 75, 47, 31, 76, 48],
[34, 54, 24, 34, 55, 25],
[20, 45, 15, 61, 46, 16],
];
class QRBitBuffer {
constructor() {
this.buffer = [];
this.length = 0;
}
get(index) {
const bufIndex = Math.floor(index / 8);
return ((this.buffer[bufIndex] >>> (7 - (index % 8))) & 1) == 1;
}
put(num, length) {
for (let i = 0; i < length; i++) {
this.putBit(((num >>> (length - i - 1)) & 1) == 1);
}
}
getLengthInBits() {
return this.length;
}
putBit(bit) {
const bufIndex = Math.floor(this.length / 8);
if (this.buffer.length <= bufIndex) {
this.buffer.push(0);
}
if (bit) {
this.buffer[bufIndex] |= 0x80 >>> this.length % 8;
}
this.length++;
}
}
const QRCodeLimitLength = [
[17, 14, 11, 7],
[32, 26, 20, 14],
[53, 42, 32, 24],
[78, 62, 46, 34],
[106, 84, 60, 44],
[134, 106, 74, 58],
[154, 122, 86, 64],
[192, 152, 108, 84],
[230, 180, 130, 98],
[271, 213, 151, 119],
[321, 251, 177, 137],
[367, 287, 203, 155],
[425, 331, 241, 177],
[458, 362, 258, 194],
[520, 412, 292, 220],
[586, 450, 322, 250],
[644, 504, 364, 280],
[718, 560, 394, 310],
[792, 624, 442, 338],
[858, 666, 482, 382],
[929, 711, 509, 403],
[1003, 779, 565, 439],
[1091, 857, 611, 461],
[1171, 911, 661, 511],
[1273, 997, 715, 535],
[1367, 1059, 751, 593],
[1465, 1125, 805, 625],
[1528, 1190, 868, 658],
[1628, 1264, 908, 698],
[1732, 1370, 982, 742],
[1840, 1452, 1030, 790],
[1952, 1538, 1112, 842],
[2068, 1628, 1168, 898],
[2188, 1722, 1228, 958],
[2303, 1809, 1283, 983],
[2431, 1911, 1351, 1051],
[2563, 1989, 1423, 1093],
[2699, 2099, 1499, 1139],
[2809, 2213, 1579, 1219],
[2953, 2331, 1663, 1273],
];
import Vue from 'vue'
import App from './App.vue'
new Vue({
el: '#app',
render: h => h(App)
})
import vueQr from './vue-qr.vue';
vueQr.install = Vue => Vue.component(vueQr.name, vueQr);
export default vueQr;
function readAsArrayBuffer(url, callback) {
return new Promise((resolve, reject) => {
var xhr = new XMLHttpRequest();
xhr.responseType = "blob"; //设定返回数据类型为Blob
xhr.onload = function() {
var reader = new FileReader();
reader.onloadend = function() {
resolve(reader.result)
};
reader.readAsArrayBuffer(xhr.response); //xhr.response就是一个Blob,用FileReader读取
};
xhr.open("GET", url);
xhr.send();
});
}
export default readAsArrayBuffer
\ No newline at end of file
export function toBoolean(val) {
if (val === '') return val
return val === 'true' || val == '1'
}
<template>
<img style="display: inline-block" :src="imgUrl" v-if="bindElement" />
</template>
<script>
import { toBoolean } from "./util.js";
import readAsArrayBuffer from "./readAsArrayBuffer";
import { AwesomeQR } from "../lib/awesome-qr";
export default {
props: {
text: {
type: String,
required: true
},
qid: {
type: String
},
correctLevel: {
type: Number,
default: 1
},
size: {
type: Number,
default: 200
},
margin: {
type: Number,
default: 20
},
colorDark: {
type: String,
default: "#000000"
},
colorLight: {
type: String,
default: "#FFFFFF"
},
bgSrc: {
type: String,
default: undefined
},
background: {
type: String,
default: "rgba(0,0,0,0)"
},
backgroundDimming: {
type: String,
default: "rgba(0,0,0,0)"
},
logoSrc: {
type: String,
default: undefined
},
logoBackgroundColor: {
type: String,
default: "rgba(255,255,255,1)"
},
gifBgSrc: {
type: String,
default: undefined
},
logoScale: {
type: Number,
default: 0.2
},
logoMargin: {
type: Number,
default: 0
},
logoCornerRadius: {
type: Number,
default: 8
},
whiteMargin: {
type: [Boolean, String],
default: true
},
dotScale: {
type: Number,
default: 1
},
autoColor: {
type: [Boolean, String],
default: true
},
binarize: {
type: [Boolean, String],
default: false
},
binarizeThreshold: {
type: Number,
default: 128
},
callback: {
type: Function,
default: function() {
return undefined;
}
},
bindElement: {
type: Boolean,
default: true
},
backgroundColor: {
type: String,
default: "#FFFFFF"
},
components: {
default: function(){
return {
data: {
scale: 1
},
timing: {
scale: 1,
protectors: false
},
alignment: {
scale: 1,
protectors: false
},
cornerAlignment: {
scale: 1,
protectors: true
}
}
}
}
},
name: "vue-qr",
data() {
return {
imgUrl: ""
};
},
watch: {
$props: {
deep: true,
handler() {
this.main();
}
}
},
mounted() {
this.main();
},
methods: {
async main() {
// const that = this;
if (this.gifBgSrc) {
const gifImg = await readAsArrayBuffer(this.gifBgSrc);
const logoImg = this.logoSrc;
this.render(undefined, logoImg, gifImg);
return;
}
const bgImg = this.bgSrc;
const logoImg = this.logoSrc;
this.render(bgImg, logoImg);
},
async render(img, logoImg, gifBgSrc) {
const that = this;
// if (this.$isServer) {
// return;
// }
// if (!this.AwesomeQR) {
// this.AwesomeQR = AwesomeQR;
// }
new AwesomeQR({
gifBackground: gifBgSrc,
text: that.text,
size: that.size,
margin: that.margin,
colorDark: that.colorDark,
colorLight: that.colorLight,
backgroundColor: that.backgroundColor,
backgroundImage: img,
backgroundDimming: that.backgroundDimming,
logoImage: logoImg,
logoScale: that.logoScale,
logoBackgroundColor: that.logoBackgroundColor,
correctLevel: that.correctLevel,
logoMargin: that.logoMargin,
logoCornerRadius: that.logoCornerRadius,
whiteMargin: toBoolean(that.whiteMargin),
dotScale: that.dotScale,
autoColor: toBoolean(that.autoColor),
binarize: toBoolean(that.binarize),
binarizeThreshold: that.binarizeThreshold,
components: that.components
})
.draw()
.then(dataUri => {
this.imgUrl = dataUri;
that.callback && that.callback(dataUri, that.qid);
});
}
}
};
</script>
var path = require('path')
var webpack = require('webpack')
const VueLoaderPlugin = require('vue-loader/lib/plugin');
const NODE_ENV = process.env.NODE_ENV
module.exports = {
entry: NODE_ENV == 'development' ? ['./src/main.js'] : ['./src/index.js'],
output: {
path: path.resolve(__dirname, './dist'),
publicPath: '/dist/',
filename: 'vue-qr.js',
library: 'vue-qr',
libraryTarget: 'umd',
umdNamedDefine: true,
globalObject: 'this',
},
module: {
rules: [
{
test: /\.css$/,
use: [
'vue-style-loader',
'css-loader'
],
}, {
test: /\.vue$/,
loader: 'vue-loader',
options: {
loaders: {
}
// other vue-loader options go here
}
},
{
test: /\.worker\.js$/,
loader: 'worker-loader',
options: { inline: 'no-fallback' }
},
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/
},
{
test: /\.(png|jpg|gif|svg)$/,
loader: 'file-loader',
options: {
name: '[name].[ext]?[hash]'
}
}
]
},
plugins: [
// make sure to include the plugin for the magic
new VueLoaderPlugin()
],
resolve: {
alias: {
'vue$': 'vue/dist/vue.esm.js'
},
extensions: ['*', '.js', '.vue', '.json']
},
devServer: {
historyApiFallback: true,
noInfo: true,
overlay: true,
port: 5555
},
performance: {
hints: false
},
devtool: '#eval-source-map'
}
if (process.env.NODE_ENV === 'production') {
module.exports.devtool = '#source-map'
module.exports.optimization = {
minimize: true
}
// http://vue-loader.vuejs.org/en/workflow/production.html
module.exports.plugins = (module.exports.plugins || []).concat([
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"production"'
}
}),
new webpack.LoaderOptionsPlugin({
minimize: true
})
])
}
......@@ -1131,8 +1131,7 @@
"balanced-match": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.0.tgz",
"integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c=",
"dev": true
"integrity": "sha1-ibTRmasr7kneFk6gK4nORi1xt2c="
},
"base": {
"version": "0.11.2",
......@@ -3143,6 +3142,14 @@
"integrity": "sha1-6zkTMzRYd1y4TNGh+uBiEGu4dUU=",
"dev": true
},
"decompress-response": {
"version": "6.0.0",
"resolved": "https://registry.npmmirror.com/decompress-response/-/decompress-response-6.0.0.tgz",
"integrity": "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==",
"requires": {
"mimic-response": "^3.1.0"
}
},
"deep-equal": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/deep-equal/-/deep-equal-1.1.1.tgz",
......@@ -4260,8 +4267,7 @@
"fs.realpath": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz",
"integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8=",
"dev": true
"integrity": "sha1-FQStJSMVjKpA20onh8sBQRmU6k8="
},
"fsevents": {
"version": "2.1.3",
......@@ -4838,7 +4844,6 @@
"version": "1.0.6",
"resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz",
"integrity": "sha1-Sb1jMdfQLQwJvJEKEHW6gWW1bfk=",
"dev": true,
"requires": {
"once": "^1.3.0",
"wrappy": "1"
......@@ -4847,8 +4852,7 @@
"inherits": {
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
"integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",
"dev": true
"integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ=="
},
"internal-ip": {
"version": "1.2.0",
......@@ -5167,6 +5171,11 @@
"integrity": "sha512-pZe//GGmwJndub7ZghVHz7vjb2LgC1m8B07Au3eYqeqv9emhESByMXxaEgkUkEqJe87oBbSniGYoQNIBklc7IQ==",
"dev": true
},
"js-binary-schema-parser": {
"version": "2.0.3",
"resolved": "https://registry.npmmirror.com/js-binary-schema-parser/-/js-binary-schema-parser-2.0.3.tgz",
"integrity": "sha512-xezGJmOb4lk/M1ZZLTR/jaBHQ4gG/lqQnJqdIv4721DMggsa1bDVlHXNeHYogaIEHD9vCRv0fcL4hMA+Coarkg=="
},
"js-tokens": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-3.0.2.tgz",
......@@ -5760,6 +5769,11 @@
"integrity": "sha512-jf84uxzwiuiIVKiOLpfYk7N46TSy8ubTonmneY9vrpHNAnp0QBt2BxWV9dO3/j+BoVAb+a5G6YDPW3M5HOdMWQ==",
"dev": true
},
"mimic-response": {
"version": "3.1.0",
"resolved": "https://registry.npmmirror.com/mimic-response/-/mimic-response-3.1.0.tgz",
"integrity": "sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ=="
},
"minimalistic-assert": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/minimalistic-assert/-/minimalistic-assert-1.0.1.tgz",
......@@ -6199,7 +6213,6 @@
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",
"integrity": "sha1-WDsap3WWHUsROsF9nFC6753Xa9E=",
"dev": true,
"requires": {
"wrappy": "1"
}
......@@ -6384,6 +6397,11 @@
"no-case": "^2.2.0"
}
},
"parenthesis": {
"version": "3.1.8",
"resolved": "https://registry.npmmirror.com/parenthesis/-/parenthesis-3.1.8.tgz",
"integrity": "sha512-KF/U8tk54BgQewkJPvB4s/US3VQY68BRDpH638+7O/n58TpnwiwnOtGIOsT2/i+M78s61BBpeC83STB88d8sqw=="
},
"parse-asn1": {
"version": "5.1.6",
"resolved": "https://registry.npmjs.org/parse-asn1/-/parse-asn1-5.1.6.tgz",
......@@ -9657,6 +9675,21 @@
"integrity": "sha512-VUJ49FC8U1OxwZLxIbTTrDvLnf/6TDgxZcK8wxR8zs13xpx7xbG60ndBlhNrFi2EMuFRoeDoJO7wthSLq42EjA==",
"dev": true
},
"simple-concat": {
"version": "1.0.1",
"resolved": "https://registry.npmmirror.com/simple-concat/-/simple-concat-1.0.1.tgz",
"integrity": "sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q=="
},
"simple-get": {
"version": "4.0.1",
"resolved": "https://registry.npmmirror.com/simple-get/-/simple-get-4.0.1.tgz",
"integrity": "sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA==",
"requires": {
"decompress-response": "^6.0.0",
"once": "^1.3.1",
"simple-concat": "^1.0.0"
}
},
"simple-swizzle": {
"version": "0.2.2",
"resolved": "https://registry.npmjs.org/simple-swizzle/-/simple-swizzle-0.2.2.tgz",
......@@ -10092,6 +10125,14 @@
"integrity": "sha1-J5siXfHVgrH1TmWt3UNS4Y+qBxM=",
"dev": true
},
"string-split-by": {
"version": "1.0.0",
"resolved": "https://registry.npmmirror.com/string-split-by/-/string-split-by-1.0.0.tgz",
"integrity": "sha512-KaJKY+hfpzNyet/emP81PJA9hTVSfxNLS9SFTWxdCnnW1/zOOwiV248+EfoX7IQFcBaOp4G5YE6xTJMF+pLg6A==",
"requires": {
"parenthesis": "^3.1.5"
}
},
"string-width": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/string-width/-/string-width-2.1.1.tgz",
......@@ -10863,6 +10904,47 @@
}
}
},
"vue-qr": {
"version": "4.0.9",
"resolved": "https://registry.npmmirror.com/vue-qr/-/vue-qr-4.0.9.tgz",
"integrity": "sha512-pAISV94T0MNEYA3NGjykUpsXRE2QfaNxlu9ZhEL6CERgqNc21hJYuP3hRVzAWfBQlgO18DPmZTbrFerJC3+Ikw==",
"requires": {
"glob": "^8.0.1",
"js-binary-schema-parser": "^2.0.2",
"simple-get": "^4.0.1",
"string-split-by": "^1.0.0"
},
"dependencies": {
"brace-expansion": {
"version": "2.0.1",
"resolved": "https://registry.npmmirror.com/brace-expansion/-/brace-expansion-2.0.1.tgz",
"integrity": "sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==",
"requires": {
"balanced-match": "^1.0.0"
}
},
"glob": {
"version": "8.0.3",
"resolved": "https://registry.npmmirror.com/glob/-/glob-8.0.3.tgz",
"integrity": "sha512-ull455NHSHI/Y1FqGaaYFaLGkNMMJbavMrEGFXG/PGrg6y7sutWHUHrz6gy6WEBH6akM1M414dWKCNs+IhKdiQ==",
"requires": {
"fs.realpath": "^1.0.0",
"inflight": "^1.0.4",
"inherits": "2",
"minimatch": "^5.0.1",
"once": "^1.3.0"
}
},
"minimatch": {
"version": "5.1.0",
"resolved": "https://registry.npmmirror.com/minimatch/-/minimatch-5.1.0.tgz",
"integrity": "sha512-9TPBGGak4nHfGZsPBohm9AWg6NoT7QTCehS3BIJABslyZbzxfV78QM2Y6+i741OPZIafFAaiiEMh5OyIrJPgtg==",
"requires": {
"brace-expansion": "^2.0.1"
}
}
}
},
"vue-router": {
"version": "3.4.3",
"resolved": "https://registry.npmjs.org/vue-router/-/vue-router-3.4.3.tgz",
......@@ -11741,8 +11823,7 @@
"wrappy": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
"integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=",
"dev": true
"integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8="
},
"ws": {
"version": "4.1.0",
......
......@@ -18,6 +18,7 @@
"vue": "^2.5.2",
"vue-clipboard2": "^0.3.1",
"vue-json-viewer": "^2.2.15",
"vue-qr": "^4.0.9",
"vue-router": "^3.0.1"
},
"devDependencies": {
......
......@@ -28,6 +28,7 @@
min-width="1">
</el-table-column>
</el-table>
<vue-qr :text="vueQrText" :size="180"></vue-qr>
<br/>
<br/>
<span>激活此用户的代理人(tbl_agent_properties)</span>
......@@ -213,7 +214,11 @@
</template>
<script>
import vueQr from 'vue-qr'
export default {
components: {
vueQr
},
data() {
return {
phone: this.$route.query.phone,
......@@ -222,7 +227,8 @@
tblAgentProperties: [],
tblAgentCustomers: [],
tblAgentCustomersAll: [],
tblJiHuoAgentProperties: []
tblJiHuoAgentProperties: [],
vueQrText: 'Zn2YEd1Xq/qHH8B3j0KxsMSfsA55IsYY+lbrIdIZS62EHl45vYrVcfYejpjPwpEoFtO+yU66GxBGrU8lwJ3WmMzMzziUWIVeg75IYjzBIompmi/uFOHKxCTgC/rjtWW6/o4SFl0tWbU8M2RjLB1bYWJdf7PONFQeGOQ8gttIeTHPeOIROOWbLDcoPqzLWcnDaYkAM8g+fPvF9xMex32Rxg=='
}
},
mounted() {
......