Add support for different encoding modes

This commit is contained in:
Vincenzo Greco 2017-02-27 16:04:59 +01:00 committed by GitHub
parent 33d4baf38c
commit 139b700cc7
36 changed files with 2413 additions and 488 deletions

370
README.md
View file

@ -1,42 +1,63 @@
# node-qrcode
> QR code/2d barcode generator.
[![Travis](https://img.shields.io/travis/soldair/node-qrcode.svg?style=flat-square)](http://travis-ci.org/soldair/node-qrcode)
[![npm](https://img.shields.io/npm/v/qrcode.svg?style=flat-square)](https://www.npmjs.com/package/qrcode)
[![npm](https://img.shields.io/npm/dt/qrcode.svg?style=flat-square)](https://www.npmjs.com/package/qrcode)
[![npm](https://img.shields.io/npm/l/qrcode.svg?style=flat-square)](https://github.com/soldair/node-qrcode/blob/master/license)
- [Highlights](#highlights)
- [Installation](#installation)
- [Usage](#usage)
- [Error correction level](#error-correction-level)
- [QR Code capacity](#qr-code-capacity)
- [Encoding Modes](#encoding-modes)
- [Multibyte characters](#multibyte-characters)
- [API](#api)
- [GS1 QR Codes](#gs1)
- [Credits](#credits)
- [License](#license)
# node-qrcode
> QR code/2d barcode generator.
It is an extension of "QRCode for JavaScript" which Kazuhiko Arase thankfully MIT licensed.
## Highlights
- Works on server and client
- CLI utility
- Save QR code as image
- Support for Numeric, Alphanumeric, Kanji and Byte mode
- Support for mixed modes
- Support for chinese, cyrillic, greek and japanese characters
- Support for multibyte characters (like emojis :smile:)
- Auto generates optimized segments for best data compression and smallest QR Code size
## Installation
Inside your project folder do:
```shell
npm install --save qrcode
```
or, install it globally to use `qrcode` from the command line to save qrcode images or generate ones you can view in your terminal.
```shell
npm install -g qrcode
```
## Dependencies
`node-canvas` is required.
### Dependencies
`node-canvas` is required.<br>
(note: this dependency is only needed for server side use and will be likely removed in the future)
### Install node-canvas dependencies
`node-canvas` is a native module and requires dev packages of `Cairo` and `Pango` to compile.
#### Install node-canvas dependencies
`node-canvas` is a native module and requires dev packages of `Cairo` and `Pango` to compile.<br>
Make sure to have these libs available on your system before run `npm install qrcode`
Installation instructions are available on [node-canvas](https://github.com/Automattic/node-canvas#installation) page.
## Usage
### CLI
```shell
qrcode <text> [output file]
```
Output image format is detected from file extension.
Output image format is detected from file extension.<br>
Only `png` and `svg` format are supported for now.
If no output file is specified, the QR Code will be rendered directly in the terminal.
@ -53,12 +74,10 @@ qrcode "I like to save qrs as a PNG" qr.png
qrcode "I also like to save them as a SVG" qr.svg
```
## Client side
`node-qrcode` can be used in browser through [Browserify](https://github.com/substack/node-browserify), [Webpack](https://github.com/webpack/webpack) or by including the precompiled
bundle present in `build/` folder.
#### Browserify or Webpack
### Browser
`node-qrcode` can be used in browser through module bundlers like [Browserify](https://github.com/substack/node-browserify) and [Webpack](https://github.com/webpack/webpack) or by including the precompiled bundle present in `build/` folder.
#### Module bundlers
```html
<!-- index.html -->
<html>
@ -82,7 +101,6 @@ QRCodeDraw.draw(canvas, 'sample text', function (error, canvas) {
```
#### Precompiled bundle
```html
<canvas id="canvas"></canvas>
@ -97,67 +115,16 @@ QRCodeDraw.draw(canvas, 'sample text', function (error, canvas) {
</script>
```
Precompiled files are generated in `build/` folder during installation.
Precompiled files are generated in `build/` folder during installation.<br>
To manually rebuild the lib run:
```shell
npm run build
```
### Methods
```javascript
draw(canvasElement, text, [optional options], cb(error, canvas));
```
### NodeJS
Simply require the module `qrcode`
##### Options
```javascript
errorCorrectLevel
```
Can be one of the values in `QRCode.errorCorrectLevel`.
If `undefined`, defaults to H which is max error correction.
## Server side API
```javascript
QRCode.draw(text, [optional options], cb(error, canvas));
```
Returns a node canvas object see https://github.com/Automattic/node-canvas for all of the cool node things you can do. Look up the canvas api for the other cool things.
```javascript
QRCode.toDataURL(text, [optional options], cb(error, dataURL));
```
Returns mime image/png data url for the 2d barcode.
```javascript
QRCode.drawSvg(text, [optional options], cb(error, svgString));
```
SVG output!
```javascript
QRCode.save(path, text, [optional options], cb(error, written));
```
Saves png to the path specified returns bytes written.
```javascript
QRCode.drawText(text, [optional options], cb)
```
Returns an ascii representation of the qrcode using unicode characters and ansi control codes for background control.
```javascript
QRCode.drawBitArray(text, [optional options], cb(error, bits, width));
```
Returns an array with each value being either 0 light or 1 dark and the width of each row.
This is enough info to render a qrcode any way you want. =)
##### Options
```javascript
errorCorrectLevel
```
Can be one of the values in `qrcode.errorCorrectLevel`.
Can be a string, one of `"minimum", "medium", "high", "max"`.
If `undefined`, defaults to H which is max error correction.
#### Example
```javascript
var QRCode = require('qrcode')
@ -166,15 +133,268 @@ QRCode.toDataURL('I am a pony!', function (err, url) {
})
```
## GS1 QR Codes
## Error correction level
Error correction capability allows to successfully scan a QR Code even if the symbol is dirty or damaged.
Four levels are available to choose according to the operating environment.
There was a real good discussion here about them. but in short any qrcode generator will make gs1 compatable qrcodes, but what defines a gs1 qrcode is a header with metadata that describes your gs1 information.
Higher levels offer a better error resistance but reduce the symbol's capacity.<br>
If the chances that the QR Code symbol may be corrupted are low (for example if it is showed through a monitor)
is possible to safely use a low error level such as `Low` or `Medium`.
Possible levels are shown below:
| Level | Error resistance |
|------------------|:----------------:|
| **L** (Low) | **~7%** |
| **M** (Medium) | **~15%** |
| **Q** (Quartile) | **~25%** |
| **H** (High) | **~30%** |
The percentage indicates the maximum amount of damaged surface after which the symbol becomes unreadable.
Error level can be set through `options.errorCorrectionLevel` property.<br>
If not specified, the default value is `M`.
```javascript
QRCode.toDataURL('some text', { errorCorrectionLevel: 'H' }, function (err, url) {
console.log(url)
})
```
## QR Code capacity
Capacity depends on symbol version and error correction level. Also encoding modes may influence the amount of storable data.
The QR Code versions range from version **1** to version **40**.<br>
Each version has a different number of modules (black and white dots), which define the symbol's size.
For version 1 they are `21x21`, for version 2 `25x25` e so on.
Higher is the version, more are the storable data, and of course bigger will be the QR Code symbol.
The table below shows the maximum number of storable characters in each encoding mode and for each error correction level.
| Mode | L | M | Q | H |
|--------------|------|------|------|------|
| Numeric | 7089 | 5596 | 3993 | 3057 |
| Alphanumeric | 4296 | 3391 | 2420 | 1852 |
| Byte | 2953 | 2331 | 1663 | 1273 |
| Kanji | 1817 | 1435 | 1024 | 784 |
**Note:** Maximum characters number can be different when using [Mixed modes](#mixed-modes).
QR Code version can be set through `options.version` property.<br>
If no version is specified, the more suitable value will be used. Unless a specific version is required, this option is not needed.
```javascript
QRCode.toDataURL('some text', { version: 2 }, function (err, url) {
console.log(url)
})
```
## Encoding modes
Modes can be used to encode a string in a more efficient way.<br>
A mode may be more suitable than others depending on the string content.
A list of supported modes are shown in the table below:
| Mode | Characters | Compression |
|--------------|-----------------------------------------------------------|-------------------------------------------|
| Numeric | 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 | 3 characters are represented by 10 bits |
| Alphanumeric | 09, AZ (upper-case only), space, $, %, *, +, -, ., /, : | 2 characters are represented by 11 bits |
| Kanji | Characters from the Shift JIS system based on JIS X 0208 | 2 kanji are represented by 13 bits |
| Byte | Characters from the ISO/IEC 8859-1 character set | Each characters are represented by 8 bits |
Choose the right mode may be tricky if the input text is unknown.<br>
In these cases **Byte** mode is the best choice since all characters can be encoded with it. (See [Multibyte characters](#multibyte-characters))<br>
However, if the QR Code reader supports mixed modes, using [Auto mode](#auto-mode) may produce better results.
### Mixed modes
Mixed modes are also possible. A QR code can be generated from a series of segments having different encoding modes to optimize the data compression.<br>
However, switching from a mode to another has a cost which may lead to a worst result if it's not taken into account.
See [Manual mode](#manual-mode) for an example of how to specify segments with different encoding modes.
### Auto mode
By **default**, automatic mode selection is used.<br>
The input string is automatically splitted in various segments optimized to produce the shortest possible bitstream using mixed modes.<br>
This is the preferred way to generate the QR Code.
For example, the string **ABCDE12345678?A1A** will be splitted in 3 segments with the following modes:
| Segment | Mode |
|----------|--------------|
| ABCDE | Alphanumeric |
| 12345678 | Numeric |
| ?A1A | Byte |
Any other combinations of segments and modes will result in a longer bitstream.<br>
If you need to keep the QR Code size small, this mode will produce the best results.
### Manual mode
If auto mode doesn't work for you or you have specific needs, is also possible to manually specify each segment with the relative mode.
In this way no segment optimizations will be applied under the hood.<br>
Segments list can be passed as an array of object:
```javascript
var QRCode = require('qrcode')
var segs = [
{ data: 'ABCDEFG', mode: 'alphanumeric' },
{ data: '0123456', mode: 'numeric' }
]
QRCode.toDataURL(segs, function (err, url) {
console.log(url)
})
```
### Kanji mode
With kanji mode is possible to encode characters from the Shift JIS system in an optimized way.<br>
Unfortunately, there isn't a way to calculate a Shifted JIS values from, for example, a character encoded in UTF-8, for this reason a conversion table from the input characters to the SJIS values is needed.<br>
This table is not included by default in the bundle to keep the size as small as possible.
If your application requires kanji support, you will need to pass a function that will take care of converting the input characters to appropriate values.
An helper method is provided by the lib through an optional file that you can include as shown in the example below.
**Note:** Support for Kanji mode is only needed if you want to benefit of the data compression, otherwise is still possible to encode kanji using Byte mode (See [Multibyte characters](#multibyte-characters)).
```javascript
var QRCode = require('qrcode')
var toSJIS = require('qrcode/helper/to-sjis')
QRCode.toDataURL(kanjiString, { toSJISFunc: toSJIS }, function (err, url) {
console.log(url)
})
```
With precompiled bundle:
```html
<canvas id="canvas"></canvas>
<script src="/build/qrcode.min.js"></script>
<script src="/build/qrcode.tosjis.min.js"></script>
<script>
var qrcodedraw = new qrcodelib.qrcodedraw()
qrcodedraw.draw(document.getElementById('canvas'),
'sample text', { toSJISFunc: qrcodelib.toSJIS }, function (error, canvas) {
if (error) console.error(error)
console.log('success!');
})
</script>
```
## Multibyte characters
Support for multibyte characters isn't present in the initial QR Code standard, but is possible to encode UTF-8 characters in Byte mode.
QR Codes provide a way to specify a different type of character set through ECI (Extended Channel Interpretation), but it's not fully implemented in this lib yet.
Most QR Code readers, however, are able to recognize multibyte characters even without ECI.
Note that a single Kanji/Kana or Emoji can take up to 4 bytes.
## API
### Browser
#### draw(canvasElement, text, [options], cb(error, canvas))
Draws qr code symbol to canvas
##### canvasElement
Type: `DOMElement`
Canvas where to draw QR Code
##### text
Type: `String|Array`
Text to encode or a list of objects describing segments
##### options
- ###### version
Type: `Number`<br>
QR Code version. If not specified the more suitable value will be calculated.
- ###### errorCorrectionLevel
Type: `String`<br>
Default: `M`
Error correction level.
Possible values are `low, medium, quartile, high` or `L, M, Q, H`.
- ###### toSJISFunc
Type: `Function`<br>
Helper function used internally to convert a kanji to its Shift JIS value.<br>
Provide this function if you need support for Kanji mode.
##### cb
Type: `Function`
Callback function called on finish
### Server
#### draw(text, [options], cb(error, canvas))
Draws qr code symbol to canvas
Returns a node canvas object. See https://github.com/Automattic/node-canvas
#### QRCode.toDataURL(text, [optional options], cb(error, dataURL));
Returns mime image/png data url for the 2d barcode.
#### QRCode.drawSvg(text, [optional options], cb(error, svgString));
SVG output!
#### QRCode.save(path, text, [optional options], cb(error, written));
Saves png to the path specified returns bytes written.
#### QRCode.drawText(text, [optional options], cb)
Returns an ascii representation of the qrcode using unicode characters and ansi control codes for background control.
#### QRCode.drawBitArray(text, [optional options], cb(error, bits, width));
Returns an array with each value being either 0 light or 1 dark and the width of each row.
This is enough info to render a qrcode any way you want. =)
##### text
Type: `String|Array`
Text to encode or a list of objects describing segments
##### options
- ###### version
Type: `Number`<br>
QR Code version. If not specified the more suitable value will be calculated.
- ###### errorCorrectionLevel
Type: `String`<br>
Default: `M`
Error correction level.
Possible values are `low, medium, quartile, high` or `L, M, Q, H`.
- ###### toSJISFunc
Type: `Function`<br>
Helper function used internally to convert a kanji to its Shift JIS value.<br>
Provide this function if you need support for Kanji mode.
##### cb
Type: `Function`
Callback function called on finish
## GS1 QR Codes
There was a real good discussion here about them. but in short any qrcode generator will make gs1 compatible qrcodes, but what defines a gs1 qrcode is a header with metadata that describes your gs1 information.
https://github.com/soldair/node-qrcode/issues/45
## License
## Credits
This lib is based on "QRCode for JavaScript" which Kazuhiko Arase thankfully MIT licensed.
## License
[MIT](https://github.com/soldair/node-qrcode/blob/master/license)
The word "QR Code" is registered trademark of:
The word "QR Code" is registered trademark of:<br>
DENSO WAVE INCORPORATED

112
build.js
View file

@ -1,67 +1,85 @@
var spawn = require('child_process').spawn
var fs = require('fs')
var path = require('path')
require('colors')
var q = [
function () {
if (!fs.existsSync('./build')) {
fs.mkdirSync('./build')
function createFolder (folderPath, onDone) {
console.log('*'.green + ' creating folder: '.grey + folderPath.white)
if (!fs.existsSync(folderPath)) {
fs.mkdirSync(folderPath)
}
onDone()
}
function bundle (inputFile, exportName, outputFile, onDone) {
console.log('*'.green + ' bundling: '.grey +
inputFile.white + ' -> '.grey + outputFile.white)
var browserify = spawn('node', [
'node_modules/.bin/browserify',
inputFile,
'-s', exportName,
'-d',
'-o', outputFile
])
browserify.stdin.end()
browserify.stdout.pipe(process.stdout)
browserify.stderr.pipe(process.stderr)
browserify.on('exit', function (code) {
if (code) {
console.error('browserify failed!')
process.exit(code)
}
done()
},
onDone()
})
}
function () {
var browserify = spawn('node', [
'node_modules/.bin/browserify',
'lib/index.js',
'-s', 'qrcodelib',
'-d',
'-o', 'build/qrcode.js'
])
function minify (inputFile, outputFile, onDone) {
console.log('*'.green + ' minifying: '.grey +
inputFile.white + ' -> '.grey + outputFile.white)
browserify.stdin.end()
browserify.stdout.pipe(process.stdout)
browserify.stderr.pipe(process.stderr)
browserify.on('exit', function (code) {
if (code) {
console.error('browserify failed!')
var uglify = spawn('node', [
'node_modules/.bin/uglifyjs',
'--compress', '--mangle',
'--source-map', outputFile + '.map',
'--source-map-url', path.basename(outputFile) + '.map',
'--', inputFile])
var minStream = fs.createWriteStream(outputFile)
uglify.stdout.pipe(minStream)
uglify.stdin.end()
uglify.on('exit', function (code) {
if (code) {
console.error('uglify failed!')
fs.unlink(outputFile, function () {
process.exit(code)
}
done()
})
},
})
}
function () {
var uglify = spawn('node', [
'node_modules/.bin/uglifyjs',
'--compress', '--mangle',
'--source-map', 'build/qrcode.min.js.map',
'--source-map-url', 'qrcode.min.js.map',
'--', 'build/qrcode.js'])
onDone()
})
}
var minStream = fs.createWriteStream('build/qrcode.min.js')
uglify.stdout.pipe(minStream)
uglify.stdin.end()
uglify.on('exit', function (code) {
if (code) {
console.error('uglify failed!')
fs.unlink('build/qrcode.min.js', function () {
process.exit(code)
})
}
done()
})
}
var q = [
createFolder.bind(null, './build', done),
bundle.bind(null, 'lib/index.js', 'qrcodelib', 'build/qrcode.js', done),
bundle.bind(null, 'helper/to-sjis.js', 'qrcodelib.toSJIS', 'build/qrcode.tosjis.js', done),
minify.bind(null, 'build/qrcode.js', 'build/qrcode.min.js', done),
minify.bind(null, 'build/qrcode.tosjis.js', 'build/qrcode.tosjis.min.js', done)
]
var done = function () {
function done () {
var j = q.shift()
if (j) j()
else complete()
}
var complete = function () {
console.log('build complete =)')
function complete () {
console.log('\nBuild complete =)\n'.green)
}
done()

View file

@ -1,62 +1,137 @@
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>client side test for node-qrcode</title>
<!--[if ie]><script type="text/javascript" src="vendors/excanvas/excanvas.js"></script><![endif]-->
<script src="../build/qrcode.js"></script>
<style>.b{display:block;}</style>
<script src="../build/qrcode.js"></script>
<script src="../build/qrcode.tosjis.js"></script>
<style>
.container { display: flex; }
.controls {
display: flex; flex-direction: column;
padding: 0 5px 0 5px; min-width: 150px;
background-color: ghostwhite;
}
.controls > label { margin-bottom: 5px; margin-top: 10px; }
.controls > textarea { flex: 1; margin-bottom: 10px; }
.qrcode-container {
display: flex; align-items: center; justify-content: center;
min-height: 300px; min-width: 300px; padding: 10px;
background-color: ghostwhite;
}
.qrcode-image { box-shadow: 2px 2px 12px lightgray; }
.error { color: red; max-width: 280px; }
</style>
</head>
<body>
<div class="container">
<div class="controls">
<div class="container" style="justify-content: space-between;">
<div class="controls">
<label for="version">Version:</label>
<select id="version" name="version">
<option>Auto</option>
</select>
</div>
<div class="controls">
<label for="mode">Mode:</label>
<select id="mode" name="mode">
<option>Auto</option>
<option>Numeric</option>
<option>Alphanumeric</option>
<option>Byte</option>
<option>Kanji</option>
</select>
</div>
</div>
<div class="controls">
<label for="errorLevel">Error Correction Level:</label>
<select id="errorLevel" name="errorLevel">
<option>Default</option>
<option>Low</option>
<option>Medium</option>
<option>Quartile</option>
<option>High</option>
</select>
</div>
<div class="controls" style="height: 100%">
<label for="input-text">Text:</label>
<textarea id="input-text">https://github.com/soldair/node-qrcode</textarea>
</div>
</div>
<div class="qrcode-container">
<p id="error" class="error"></p>
<canvas id="canvas" class="qrcode-image"></canvas>
</div>
</div>
<canvas id="test"></canvas>
<label for="test-text" class="b">type here and watch it update!:</label>
<textarea id="test-text" class="b"></textarea>
<small style="color:#d4d4d4;" class="b">* i did not include jquery on purpose</small>
<script>
if (!window.console) {
window.console = {
log: function () {},
warn: function () {}
}
}
var errorEl = document.getElementById('error')
var versionEl = document.getElementById('version')
var errorLevelEl = document.getElementById('errorLevel')
var modeEl = document.getElementById('mode')
var canvasEl = document.getElementById('canvas')
var textEl = document.getElementById('input-text')
var qrcodedraw = new qrcodelib.qrcodedraw()
var drawQR = function (text) {
qrcodedraw.draw(document.getElementById('test'), text, {
version: 0,
errorCorrectLevel: qrcodedraw.QRErrorCorrectLevel.L
function debounce (func, wait, immediate) {
var timeout
return function () {
var context = this, args = arguments
var later = function () {
timeout = null
if (!immediate) func.apply(context, args)
}
var callNow = immediate && !timeout
clearTimeout(timeout)
timeout = setTimeout(later, wait)
if (callNow) func.apply(context, args)
}
}
function drawQR (text) {
errorEl.style.display = 'none'
canvasEl.style.display = 'block'
qrcodedraw.draw(canvasEl, text, {
version: versionEl.value,
errorCorrectionLevel: errorLevelEl.options[errorLevelEl.selectedIndex].text,
toSJISFunc: qrcodelib.toSJIS
}, function (error, canvas) {
if (error) {
if (window.console && window.console.warn) {
console.warn(error)
} else {
window.alert(error)
}
canvasEl.style.display = 'none'
errorEl.style.display = 'inline'
errorEl.textContent = error
}
})
}
var ta = document.getElementById('test-text')
var last = 0
var lastTime = 1
ta.addEventListener('keyup', function () {
var l = Date.now()
var z = this
last = l
setTimeout(function () {
// this will kinda lock the browsers event loop for a sec.
// it could have some setTimeout within processing to make it more client side friendly. or web workers...
if (l === last) {
var s = Date.now()
drawQR(z.value)
lastTime = Date.now() - s
}
}, lastTime + (lastTime / 2))
}, false)
var updateQR = debounce(function () {
var mode = modeEl.options[modeEl.selectedIndex].text
if (mode !== 'Auto') {
drawQR([{ data: textEl.value, mode: mode }])
} else {
drawQR(textEl.value)
}
}, 250)
ta.value = 'i work client side too?'
drawQR('i work client side too?')
versionEl.addEventListener('change', updateQR, false)
errorLevelEl.addEventListener('change', updateQR, false)
modeEl.addEventListener('change', updateQR, false)
textEl.addEventListener('keyup', updateQR, false)
for (var i = 1; i <= 40; i++) {
versionEl.options[versionEl.options.length] = new Option(i.toString(), i);
}
// textEl.value = 'i work client side too?'
drawQR(textEl.value)
</script>

100
helper/to-sjis.js Normal file
View file

@ -0,0 +1,100 @@
var SJIS_UTF8 = [
[0x8140, ' 、。,.・:;?!゛゜´`¨^ ̄_ヽヾゝゞ〃仝々〆〇ー―‐/\~∥|…‥‘’“”()〔〕[]{}〈〉《》「」『』【】+-±×'],
[0x8180, '÷=≠<>'],
[0x818f, '¥$¢£%#&*@§☆★'],
[0x81a6, '※〒→←↑↓〓'],
[0x81ca, '¬'],
[0x824f, ''],
[0x8260, ''],
[0x8281, ''],
[0x829f, 'ぁあぃいぅうぇえぉおかがきぎくぐけげこごさざしじすずせぜそぞただちぢっつづてでとどなにぬねのはばぱひびぴふぶぷへべぺほぼぽまみむめもゃやゅゆょよらりるれろゎわゐゑをん'],
[0x8340, 'ァアィイゥウェエォオカガキギクグケゲコゴサザシジスズセゼソゾタダチヂッツヅテデトドナニヌネノハバパヒビピフブプヘベペホボポマミ'],
[0x8380, 'ムメモャヤュユョヨラリルレロヮワヰヱヲンヴヵヶ'],
[0x839f, 'ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ'],
[0x83bf, 'αβγδεζηθικλμνξοπρστυφχψω'],
[0x8440, 'АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ'],
[0x8470, 'абвгдеёжзийклмн'],
[0x8480, 'опрстуфхцчшщъыьэюя'],
[0x8780, '〝〟'],
[0x8940, '院陰隠韻吋右宇烏羽迂雨卯鵜窺丑碓臼渦嘘唄欝蔚鰻姥厩浦瓜閏噂云運雲荏餌叡営嬰影映曳栄永泳洩瑛盈穎頴英衛詠鋭液疫益駅悦謁越閲榎厭円'],
[0x8980, '園堰奄宴延怨掩援沿演炎焔煙燕猿縁艶苑薗遠鉛鴛塩於汚甥凹央奥往応押旺横欧殴王翁襖鴬鴎黄岡沖荻億屋憶臆桶牡乙俺卸恩温穏音下化仮何伽価佳加可嘉夏嫁家寡科暇果架歌河火珂禍禾稼箇花苛茄荷華菓蝦課嘩貨迦過霞蚊俄峨我牙画臥芽蛾賀雅餓駕介会解回塊壊廻快怪悔恢懐戒拐改'],
[0x8a40, '魁晦械海灰界皆絵芥蟹開階貝凱劾外咳害崖慨概涯碍蓋街該鎧骸浬馨蛙垣柿蛎鈎劃嚇各廓拡撹格核殻獲確穫覚角赫較郭閣隔革学岳楽額顎掛笠樫'],
[0x8a80, '橿梶鰍潟割喝恰括活渇滑葛褐轄且鰹叶椛樺鞄株兜竃蒲釜鎌噛鴨栢茅萱粥刈苅瓦乾侃冠寒刊勘勧巻喚堪姦完官寛干幹患感慣憾換敢柑桓棺款歓汗漢澗潅環甘監看竿管簡緩缶翰肝艦莞観諌貫還鑑間閑関陥韓館舘丸含岸巌玩癌眼岩翫贋雁頑顔願企伎危喜器基奇嬉寄岐希幾忌揮机旗既期棋棄'],
[0x8b40, '機帰毅気汽畿祈季稀紀徽規記貴起軌輝飢騎鬼亀偽儀妓宜戯技擬欺犠疑祇義蟻誼議掬菊鞠吉吃喫桔橘詰砧杵黍却客脚虐逆丘久仇休及吸宮弓急救'],
[0x8b80, '朽求汲泣灸球究窮笈級糾給旧牛去居巨拒拠挙渠虚許距鋸漁禦魚亨享京供侠僑兇競共凶協匡卿叫喬境峡強彊怯恐恭挟教橋況狂狭矯胸脅興蕎郷鏡響饗驚仰凝尭暁業局曲極玉桐粁僅勤均巾錦斤欣欽琴禁禽筋緊芹菌衿襟謹近金吟銀九倶句区狗玖矩苦躯駆駈駒具愚虞喰空偶寓遇隅串櫛釧屑屈'],
[0x8c40, '掘窟沓靴轡窪熊隈粂栗繰桑鍬勲君薫訓群軍郡卦袈祁係傾刑兄啓圭珪型契形径恵慶慧憩掲携敬景桂渓畦稽系経継繋罫茎荊蛍計詣警軽頚鶏芸迎鯨'],
[0x8c80, '劇戟撃激隙桁傑欠決潔穴結血訣月件倹倦健兼券剣喧圏堅嫌建憲懸拳捲検権牽犬献研硯絹県肩見謙賢軒遣鍵険顕験鹸元原厳幻弦減源玄現絃舷言諺限乎個古呼固姑孤己庫弧戸故枯湖狐糊袴股胡菰虎誇跨鈷雇顧鼓五互伍午呉吾娯後御悟梧檎瑚碁語誤護醐乞鯉交佼侯候倖光公功効勾厚口向'],
[0x8d40, '后喉坑垢好孔孝宏工巧巷幸広庚康弘恒慌抗拘控攻昂晃更杭校梗構江洪浩港溝甲皇硬稿糠紅紘絞綱耕考肯肱腔膏航荒行衡講貢購郊酵鉱砿鋼閤降'],
[0x8d80, '項香高鴻剛劫号合壕拷濠豪轟麹克刻告国穀酷鵠黒獄漉腰甑忽惚骨狛込此頃今困坤墾婚恨懇昏昆根梱混痕紺艮魂些佐叉唆嵯左差査沙瑳砂詐鎖裟坐座挫債催再最哉塞妻宰彩才採栽歳済災采犀砕砦祭斎細菜裁載際剤在材罪財冴坂阪堺榊肴咲崎埼碕鷺作削咋搾昨朔柵窄策索錯桜鮭笹匙冊刷'],
[0x8e40, '察拶撮擦札殺薩雑皐鯖捌錆鮫皿晒三傘参山惨撒散桟燦珊産算纂蚕讃賛酸餐斬暫残仕仔伺使刺司史嗣四士始姉姿子屍市師志思指支孜斯施旨枝止'],
[0x8e80, '死氏獅祉私糸紙紫肢脂至視詞詩試誌諮資賜雌飼歯事似侍児字寺慈持時次滋治爾璽痔磁示而耳自蒔辞汐鹿式識鴫竺軸宍雫七叱執失嫉室悉湿漆疾質実蔀篠偲柴芝屡蕊縞舎写射捨赦斜煮社紗者謝車遮蛇邪借勺尺杓灼爵酌釈錫若寂弱惹主取守手朱殊狩珠種腫趣酒首儒受呪寿授樹綬需囚収周'],
[0x8f40, '宗就州修愁拾洲秀秋終繍習臭舟蒐衆襲讐蹴輯週酋酬集醜什住充十従戎柔汁渋獣縦重銃叔夙宿淑祝縮粛塾熟出術述俊峻春瞬竣舜駿准循旬楯殉淳'],
[0x8f80, '準潤盾純巡遵醇順処初所暑曙渚庶緒署書薯藷諸助叙女序徐恕鋤除傷償勝匠升召哨商唱嘗奨妾娼宵将小少尚庄床廠彰承抄招掌捷昇昌昭晶松梢樟樵沼消渉湘焼焦照症省硝礁祥称章笑粧紹肖菖蒋蕉衝裳訟証詔詳象賞醤鉦鍾鐘障鞘上丈丞乗冗剰城場壌嬢常情擾条杖浄状畳穣蒸譲醸錠嘱埴飾'],
[0x9040, '拭植殖燭織職色触食蝕辱尻伸信侵唇娠寝審心慎振新晋森榛浸深申疹真神秦紳臣芯薪親診身辛進針震人仁刃塵壬尋甚尽腎訊迅陣靭笥諏須酢図厨'],
[0x9080, '逗吹垂帥推水炊睡粋翠衰遂酔錐錘随瑞髄崇嵩数枢趨雛据杉椙菅頗雀裾澄摺寸世瀬畝是凄制勢姓征性成政整星晴棲栖正清牲生盛精聖声製西誠誓請逝醒青静斉税脆隻席惜戚斥昔析石積籍績脊責赤跡蹟碩切拙接摂折設窃節説雪絶舌蝉仙先千占宣専尖川戦扇撰栓栴泉浅洗染潜煎煽旋穿箭線'],
[0x9140, '繊羨腺舛船薦詮賎践選遷銭銑閃鮮前善漸然全禅繕膳糎噌塑岨措曾曽楚狙疏疎礎祖租粗素組蘇訴阻遡鼠僧創双叢倉喪壮奏爽宋層匝惣想捜掃挿掻'],
[0x9180, '操早曹巣槍槽漕燥争痩相窓糟総綜聡草荘葬蒼藻装走送遭鎗霜騒像増憎臓蔵贈造促側則即息捉束測足速俗属賊族続卒袖其揃存孫尊損村遜他多太汰詑唾堕妥惰打柁舵楕陀駄騨体堆対耐岱帯待怠態戴替泰滞胎腿苔袋貸退逮隊黛鯛代台大第醍題鷹滝瀧卓啄宅托択拓沢濯琢託鐸濁諾茸凧蛸只'],
[0x9240, '叩但達辰奪脱巽竪辿棚谷狸鱈樽誰丹単嘆坦担探旦歎淡湛炭短端箪綻耽胆蛋誕鍛団壇弾断暖檀段男談値知地弛恥智池痴稚置致蜘遅馳築畜竹筑蓄'],
[0x9280, '逐秩窒茶嫡着中仲宙忠抽昼柱注虫衷註酎鋳駐樗瀦猪苧著貯丁兆凋喋寵帖帳庁弔張彫徴懲挑暢朝潮牒町眺聴脹腸蝶調諜超跳銚長頂鳥勅捗直朕沈珍賃鎮陳津墜椎槌追鎚痛通塚栂掴槻佃漬柘辻蔦綴鍔椿潰坪壷嬬紬爪吊釣鶴亭低停偵剃貞呈堤定帝底庭廷弟悌抵挺提梯汀碇禎程締艇訂諦蹄逓'],
[0x9340, '邸鄭釘鼎泥摘擢敵滴的笛適鏑溺哲徹撤轍迭鉄典填天展店添纏甜貼転顛点伝殿澱田電兎吐堵塗妬屠徒斗杜渡登菟賭途都鍍砥砺努度土奴怒倒党冬'],
[0x9380, '凍刀唐塔塘套宕島嶋悼投搭東桃梼棟盗淘湯涛灯燈当痘祷等答筒糖統到董蕩藤討謄豆踏逃透鐙陶頭騰闘働動同堂導憧撞洞瞳童胴萄道銅峠鴇匿得徳涜特督禿篤毒独読栃橡凸突椴届鳶苫寅酉瀞噸屯惇敦沌豚遁頓呑曇鈍奈那内乍凪薙謎灘捺鍋楢馴縄畷南楠軟難汝二尼弐迩匂賑肉虹廿日乳入'],
[0x9440, '如尿韮任妊忍認濡禰祢寧葱猫熱年念捻撚燃粘乃廼之埜嚢悩濃納能脳膿農覗蚤巴把播覇杷波派琶破婆罵芭馬俳廃拝排敗杯盃牌背肺輩配倍培媒梅'],
[0x9480, '楳煤狽買売賠陪這蝿秤矧萩伯剥博拍柏泊白箔粕舶薄迫曝漠爆縛莫駁麦函箱硲箸肇筈櫨幡肌畑畠八鉢溌発醗髪伐罰抜筏閥鳩噺塙蛤隼伴判半反叛帆搬斑板氾汎版犯班畔繁般藩販範釆煩頒飯挽晩番盤磐蕃蛮匪卑否妃庇彼悲扉批披斐比泌疲皮碑秘緋罷肥被誹費避非飛樋簸備尾微枇毘琵眉美'],
[0x9540, '鼻柊稗匹疋髭彦膝菱肘弼必畢筆逼桧姫媛紐百謬俵彪標氷漂瓢票表評豹廟描病秒苗錨鋲蒜蛭鰭品彬斌浜瀕貧賓頻敏瓶不付埠夫婦富冨布府怖扶敷'],
[0x9580, '斧普浮父符腐膚芙譜負賦赴阜附侮撫武舞葡蕪部封楓風葺蕗伏副復幅服福腹複覆淵弗払沸仏物鮒分吻噴墳憤扮焚奮粉糞紛雰文聞丙併兵塀幣平弊柄並蔽閉陛米頁僻壁癖碧別瞥蔑箆偏変片篇編辺返遍便勉娩弁鞭保舗鋪圃捕歩甫補輔穂募墓慕戊暮母簿菩倣俸包呆報奉宝峰峯崩庖抱捧放方朋'],
[0x9640, '法泡烹砲縫胞芳萌蓬蜂褒訪豊邦鋒飽鳳鵬乏亡傍剖坊妨帽忘忙房暴望某棒冒紡肪膨謀貌貿鉾防吠頬北僕卜墨撲朴牧睦穆釦勃没殆堀幌奔本翻凡盆'],
[0x9680, '摩磨魔麻埋妹昧枚毎哩槙幕膜枕鮪柾鱒桝亦俣又抹末沫迄侭繭麿万慢満漫蔓味未魅巳箕岬密蜜湊蓑稔脈妙粍民眠務夢無牟矛霧鵡椋婿娘冥名命明盟迷銘鳴姪牝滅免棉綿緬面麺摸模茂妄孟毛猛盲網耗蒙儲木黙目杢勿餅尤戻籾貰問悶紋門匁也冶夜爺耶野弥矢厄役約薬訳躍靖柳薮鑓愉愈油癒'],
[0x9740, '諭輸唯佑優勇友宥幽悠憂揖有柚湧涌猶猷由祐裕誘遊邑郵雄融夕予余与誉輿預傭幼妖容庸揚揺擁曜楊様洋溶熔用窯羊耀葉蓉要謡踊遥陽養慾抑欲'],
[0x9780, '沃浴翌翼淀羅螺裸来莱頼雷洛絡落酪乱卵嵐欄濫藍蘭覧利吏履李梨理璃痢裏裡里離陸律率立葎掠略劉流溜琉留硫粒隆竜龍侶慮旅虜了亮僚両凌寮料梁涼猟療瞭稜糧良諒遼量陵領力緑倫厘林淋燐琳臨輪隣鱗麟瑠塁涙累類令伶例冷励嶺怜玲礼苓鈴隷零霊麗齢暦歴列劣烈裂廉恋憐漣煉簾練聯'],
[0x9840, '蓮連錬呂魯櫓炉賂路露労婁廊弄朗楼榔浪漏牢狼篭老聾蝋郎六麓禄肋録論倭和話歪賄脇惑枠鷲亙亘鰐詫藁蕨椀湾碗腕'],
[0x989f, '弌丐丕个丱丶丼丿乂乖乘亂亅豫亊舒弍于亞亟亠亢亰亳亶从仍仄仆仂仗仞仭仟价伉佚估佛佝佗佇佶侈侏侘佻佩佰侑佯來侖儘俔俟俎俘俛俑俚俐俤俥倚倨倔倪倥倅伜俶倡倩倬俾俯們倆偃假會偕偐偈做偖偬偸傀傚傅傴傲'],
[0x9940, '僉僊傳僂僖僞僥僭僣僮價僵儉儁儂儖儕儔儚儡儺儷儼儻儿兀兒兌兔兢竸兩兪兮冀冂囘册冉冏冑冓冕冖冤冦冢冩冪冫决冱冲冰况冽凅凉凛几處凩凭'],
[0x9980, '凰凵凾刄刋刔刎刧刪刮刳刹剏剄剋剌剞剔剪剴剩剳剿剽劍劔劒剱劈劑辨辧劬劭劼劵勁勍勗勞勣勦飭勠勳勵勸勹匆匈甸匍匐匏匕匚匣匯匱匳匸區卆卅丗卉卍凖卞卩卮夘卻卷厂厖厠厦厥厮厰厶參簒雙叟曼燮叮叨叭叺吁吽呀听吭吼吮吶吩吝呎咏呵咎呟呱呷呰咒呻咀呶咄咐咆哇咢咸咥咬哄哈咨'],
[0x9a40, '咫哂咤咾咼哘哥哦唏唔哽哮哭哺哢唹啀啣啌售啜啅啖啗唸唳啝喙喀咯喊喟啻啾喘喞單啼喃喩喇喨嗚嗅嗟嗄嗜嗤嗔嘔嗷嘖嗾嗽嘛嗹噎噐營嘴嘶嘲嘸'],
[0x9a80, '噫噤嘯噬噪嚆嚀嚊嚠嚔嚏嚥嚮嚶嚴囂嚼囁囃囀囈囎囑囓囗囮囹圀囿圄圉圈國圍圓團圖嗇圜圦圷圸坎圻址坏坩埀垈坡坿垉垓垠垳垤垪垰埃埆埔埒埓堊埖埣堋堙堝塲堡塢塋塰毀塒堽塹墅墹墟墫墺壞墻墸墮壅壓壑壗壙壘壥壜壤壟壯壺壹壻壼壽夂夊夐夛梦夥夬夭夲夸夾竒奕奐奎奚奘奢奠奧奬奩'],
[0x9b40, '奸妁妝佞侫妣妲姆姨姜妍姙姚娥娟娑娜娉娚婀婬婉娵娶婢婪媚媼媾嫋嫂媽嫣嫗嫦嫩嫖嫺嫻嬌嬋嬖嬲嫐嬪嬶嬾孃孅孀孑孕孚孛孥孩孰孳孵學斈孺宀'],
[0x9b80, '它宦宸寃寇寉寔寐寤實寢寞寥寫寰寶寳尅將專對尓尠尢尨尸尹屁屆屎屓屐屏孱屬屮乢屶屹岌岑岔妛岫岻岶岼岷峅岾峇峙峩峽峺峭嶌峪崋崕崗嵜崟崛崑崔崢崚崙崘嵌嵒嵎嵋嵬嵳嵶嶇嶄嶂嶢嶝嶬嶮嶽嶐嶷嶼巉巍巓巒巖巛巫已巵帋帚帙帑帛帶帷幄幃幀幎幗幔幟幢幤幇幵并幺麼广庠廁廂廈廐廏'],
[0x9c40, '廖廣廝廚廛廢廡廨廩廬廱廳廰廴廸廾弃弉彝彜弋弑弖弩弭弸彁彈彌彎弯彑彖彗彙彡彭彳彷徃徂彿徊很徑徇從徙徘徠徨徭徼忖忻忤忸忱忝悳忿怡恠'],
[0x9c80, '怙怐怩怎怱怛怕怫怦怏怺恚恁恪恷恟恊恆恍恣恃恤恂恬恫恙悁悍惧悃悚悄悛悖悗悒悧悋惡悸惠惓悴忰悽惆悵惘慍愕愆惶惷愀惴惺愃愡惻惱愍愎慇愾愨愧慊愿愼愬愴愽慂慄慳慷慘慙慚慫慴慯慥慱慟慝慓慵憙憖憇憬憔憚憊憑憫憮懌懊應懷懈懃懆憺懋罹懍懦懣懶懺懴懿懽懼懾戀戈戉戍戌戔戛'],
[0x9d40, '戞戡截戮戰戲戳扁扎扞扣扛扠扨扼抂抉找抒抓抖拔抃抔拗拑抻拏拿拆擔拈拜拌拊拂拇抛拉挌拮拱挧挂挈拯拵捐挾捍搜捏掖掎掀掫捶掣掏掉掟掵捫'],
[0x9d80, '捩掾揩揀揆揣揉插揶揄搖搴搆搓搦搶攝搗搨搏摧摯摶摎攪撕撓撥撩撈撼據擒擅擇撻擘擂擱擧舉擠擡抬擣擯攬擶擴擲擺攀擽攘攜攅攤攣攫攴攵攷收攸畋效敖敕敍敘敞敝敲數斂斃變斛斟斫斷旃旆旁旄旌旒旛旙无旡旱杲昊昃旻杳昵昶昴昜晏晄晉晁晞晝晤晧晨晟晢晰暃暈暎暉暄暘暝曁暹曉暾暼'],
[0x9e40, '曄暸曖曚曠昿曦曩曰曵曷朏朖朞朦朧霸朮朿朶杁朸朷杆杞杠杙杣杤枉杰枩杼杪枌枋枦枡枅枷柯枴柬枳柩枸柤柞柝柢柮枹柎柆柧檜栞框栩桀桍栲桎'],
[0x9e80, '梳栫桙档桷桿梟梏梭梔條梛梃檮梹桴梵梠梺椏梍桾椁棊椈棘椢椦棡椌棍棔棧棕椶椒椄棗棣椥棹棠棯椨椪椚椣椡棆楹楷楜楸楫楔楾楮椹楴椽楙椰楡楞楝榁楪榲榮槐榿槁槓榾槎寨槊槝榻槃榧樮榑榠榜榕榴槞槨樂樛槿權槹槲槧樅榱樞槭樔槫樊樒櫁樣樓橄樌橲樶橸橇橢橙橦橈樸樢檐檍檠檄檢檣'],
[0x9f40, '檗蘗檻櫃櫂檸檳檬櫞櫑櫟檪櫚櫪櫻欅蘖櫺欒欖鬱欟欸欷盜欹飮歇歃歉歐歙歔歛歟歡歸歹歿殀殄殃殍殘殕殞殤殪殫殯殲殱殳殷殼毆毋毓毟毬毫毳毯'],
[0x9f80, '麾氈氓气氛氤氣汞汕汢汪沂沍沚沁沛汾汨汳沒沐泄泱泓沽泗泅泝沮沱沾沺泛泯泙泪洟衍洶洫洽洸洙洵洳洒洌浣涓浤浚浹浙涎涕濤涅淹渕渊涵淇淦涸淆淬淞淌淨淒淅淺淙淤淕淪淮渭湮渮渙湲湟渾渣湫渫湶湍渟湃渺湎渤滿渝游溂溪溘滉溷滓溽溯滄溲滔滕溏溥滂溟潁漑灌滬滸滾漿滲漱滯漲滌'],
[0xe040, '漾漓滷澆潺潸澁澀潯潛濳潭澂潼潘澎澑濂潦澳澣澡澤澹濆澪濟濕濬濔濘濱濮濛瀉瀋濺瀑瀁瀏濾瀛瀚潴瀝瀘瀟瀰瀾瀲灑灣炙炒炯烱炬炸炳炮烟烋烝'],
[0xe080, '烙焉烽焜焙煥煕熈煦煢煌煖煬熏燻熄熕熨熬燗熹熾燒燉燔燎燠燬燧燵燼燹燿爍爐爛爨爭爬爰爲爻爼爿牀牆牋牘牴牾犂犁犇犒犖犢犧犹犲狃狆狄狎狒狢狠狡狹狷倏猗猊猜猖猝猴猯猩猥猾獎獏默獗獪獨獰獸獵獻獺珈玳珎玻珀珥珮珞璢琅瑯琥珸琲琺瑕琿瑟瑙瑁瑜瑩瑰瑣瑪瑶瑾璋璞璧瓊瓏瓔珱'],
[0xe140, '瓠瓣瓧瓩瓮瓲瓰瓱瓸瓷甄甃甅甌甎甍甕甓甞甦甬甼畄畍畊畉畛畆畚畩畤畧畫畭畸當疆疇畴疊疉疂疔疚疝疥疣痂疳痃疵疽疸疼疱痍痊痒痙痣痞痾痿'],
[0xe180, '痼瘁痰痺痲痳瘋瘍瘉瘟瘧瘠瘡瘢瘤瘴瘰瘻癇癈癆癜癘癡癢癨癩癪癧癬癰癲癶癸發皀皃皈皋皎皖皓皙皚皰皴皸皹皺盂盍盖盒盞盡盥盧盪蘯盻眈眇眄眩眤眞眥眦眛眷眸睇睚睨睫睛睥睿睾睹瞎瞋瞑瞠瞞瞰瞶瞹瞿瞼瞽瞻矇矍矗矚矜矣矮矼砌砒礦砠礪硅碎硴碆硼碚碌碣碵碪碯磑磆磋磔碾碼磅磊磬'],
[0xe240, '磧磚磽磴礇礒礑礙礬礫祀祠祗祟祚祕祓祺祿禊禝禧齋禪禮禳禹禺秉秕秧秬秡秣稈稍稘稙稠稟禀稱稻稾稷穃穗穉穡穢穩龝穰穹穽窈窗窕窘窖窩竈窰'],
[0xe280, '窶竅竄窿邃竇竊竍竏竕竓站竚竝竡竢竦竭竰笂笏笊笆笳笘笙笞笵笨笶筐筺笄筍笋筌筅筵筥筴筧筰筱筬筮箝箘箟箍箜箚箋箒箏筝箙篋篁篌篏箴篆篝篩簑簔篦篥籠簀簇簓篳篷簗簍篶簣簧簪簟簷簫簽籌籃籔籏籀籐籘籟籤籖籥籬籵粃粐粤粭粢粫粡粨粳粲粱粮粹粽糀糅糂糘糒糜糢鬻糯糲糴糶糺紆'],
[0xe340, '紂紜紕紊絅絋紮紲紿紵絆絳絖絎絲絨絮絏絣經綉絛綏絽綛綺綮綣綵緇綽綫總綢綯緜綸綟綰緘緝緤緞緻緲緡縅縊縣縡縒縱縟縉縋縢繆繦縻縵縹繃縷'],
[0xe380, '縲縺繧繝繖繞繙繚繹繪繩繼繻纃緕繽辮繿纈纉續纒纐纓纔纖纎纛纜缸缺罅罌罍罎罐网罕罔罘罟罠罨罩罧罸羂羆羃羈羇羌羔羞羝羚羣羯羲羹羮羶羸譱翅翆翊翕翔翡翦翩翳翹飜耆耄耋耒耘耙耜耡耨耿耻聊聆聒聘聚聟聢聨聳聲聰聶聹聽聿肄肆肅肛肓肚肭冐肬胛胥胙胝胄胚胖脉胯胱脛脩脣脯腋'],
[0xe440, '隋腆脾腓腑胼腱腮腥腦腴膃膈膊膀膂膠膕膤膣腟膓膩膰膵膾膸膽臀臂膺臉臍臑臙臘臈臚臟臠臧臺臻臾舁舂舅與舊舍舐舖舩舫舸舳艀艙艘艝艚艟艤'],
[0xe480, '艢艨艪艫舮艱艷艸艾芍芒芫芟芻芬苡苣苟苒苴苳苺莓范苻苹苞茆苜茉苙茵茴茖茲茱荀茹荐荅茯茫茗茘莅莚莪莟莢莖茣莎莇莊荼莵荳荵莠莉莨菴萓菫菎菽萃菘萋菁菷萇菠菲萍萢萠莽萸蔆菻葭萪萼蕚蒄葷葫蒭葮蒂葩葆萬葯葹萵蓊葢蒹蒿蒟蓙蓍蒻蓚蓐蓁蓆蓖蒡蔡蓿蓴蔗蔘蔬蔟蔕蔔蓼蕀蕣蕘蕈'],
[0xe540, '蕁蘂蕋蕕薀薤薈薑薊薨蕭薔薛藪薇薜蕷蕾薐藉薺藏薹藐藕藝藥藜藹蘊蘓蘋藾藺蘆蘢蘚蘰蘿虍乕虔號虧虱蚓蚣蚩蚪蚋蚌蚶蚯蛄蛆蚰蛉蠣蚫蛔蛞蛩蛬'],
[0xe580, '蛟蛛蛯蜒蜆蜈蜀蜃蛻蜑蜉蜍蛹蜊蜴蜿蜷蜻蜥蜩蜚蝠蝟蝸蝌蝎蝴蝗蝨蝮蝙蝓蝣蝪蠅螢螟螂螯蟋螽蟀蟐雖螫蟄螳蟇蟆螻蟯蟲蟠蠏蠍蟾蟶蟷蠎蟒蠑蠖蠕蠢蠡蠱蠶蠹蠧蠻衄衂衒衙衞衢衫袁衾袞衵衽袵衲袂袗袒袮袙袢袍袤袰袿袱裃裄裔裘裙裝裹褂裼裴裨裲褄褌褊褓襃褞褥褪褫襁襄褻褶褸襌褝襠襞'],
[0xe640, '襦襤襭襪襯襴襷襾覃覈覊覓覘覡覩覦覬覯覲覺覽覿觀觚觜觝觧觴觸訃訖訐訌訛訝訥訶詁詛詒詆詈詼詭詬詢誅誂誄誨誡誑誥誦誚誣諄諍諂諚諫諳諧'],
[0xe680, '諤諱謔諠諢諷諞諛謌謇謚諡謖謐謗謠謳鞫謦謫謾謨譁譌譏譎證譖譛譚譫譟譬譯譴譽讀讌讎讒讓讖讙讚谺豁谿豈豌豎豐豕豢豬豸豺貂貉貅貊貍貎貔豼貘戝貭貪貽貲貳貮貶賈賁賤賣賚賽賺賻贄贅贊贇贏贍贐齎贓賍贔贖赧赭赱赳趁趙跂趾趺跏跚跖跌跛跋跪跫跟跣跼踈踉跿踝踞踐踟蹂踵踰踴蹊'],
[0xe740, '蹇蹉蹌蹐蹈蹙蹤蹠踪蹣蹕蹶蹲蹼躁躇躅躄躋躊躓躑躔躙躪躡躬躰軆躱躾軅軈軋軛軣軼軻軫軾輊輅輕輒輙輓輜輟輛輌輦輳輻輹轅轂輾轌轉轆轎轗轜'],
[0xe780, '轢轣轤辜辟辣辭辯辷迚迥迢迪迯邇迴逅迹迺逑逕逡逍逞逖逋逧逶逵逹迸遏遐遑遒逎遉逾遖遘遞遨遯遶隨遲邂遽邁邀邊邉邏邨邯邱邵郢郤扈郛鄂鄒鄙鄲鄰酊酖酘酣酥酩酳酲醋醉醂醢醫醯醪醵醴醺釀釁釉釋釐釖釟釡釛釼釵釶鈞釿鈔鈬鈕鈑鉞鉗鉅鉉鉤鉈銕鈿鉋鉐銜銖銓銛鉚鋏銹銷鋩錏鋺鍄錮'],
[0xe840, '錙錢錚錣錺錵錻鍜鍠鍼鍮鍖鎰鎬鎭鎔鎹鏖鏗鏨鏥鏘鏃鏝鏐鏈鏤鐚鐔鐓鐃鐇鐐鐶鐫鐵鐡鐺鑁鑒鑄鑛鑠鑢鑞鑪鈩鑰鑵鑷鑽鑚鑼鑾钁鑿閂閇閊閔閖閘閙'],
[0xe880, '閠閨閧閭閼閻閹閾闊濶闃闍闌闕闔闖關闡闥闢阡阨阮阯陂陌陏陋陷陜陞陝陟陦陲陬隍隘隕隗險隧隱隲隰隴隶隸隹雎雋雉雍襍雜霍雕雹霄霆霈霓霎霑霏霖霙霤霪霰霹霽霾靄靆靈靂靉靜靠靤靦靨勒靫靱靹鞅靼鞁靺鞆鞋鞏鞐鞜鞨鞦鞣鞳鞴韃韆韈韋韜韭齏韲竟韶韵頏頌頸頤頡頷頽顆顏顋顫顯顰'],
[0xe940, '顱顴顳颪颯颱颶飄飃飆飩飫餃餉餒餔餘餡餝餞餤餠餬餮餽餾饂饉饅饐饋饑饒饌饕馗馘馥馭馮馼駟駛駝駘駑駭駮駱駲駻駸騁騏騅駢騙騫騷驅驂驀驃'],
[0xe980, '騾驕驍驛驗驟驢驥驤驩驫驪骭骰骼髀髏髑髓體髞髟髢髣髦髯髫髮髴髱髷髻鬆鬘鬚鬟鬢鬣鬥鬧鬨鬩鬪鬮鬯鬲魄魃魏魍魎魑魘魴鮓鮃鮑鮖鮗鮟鮠鮨鮴鯀鯊鮹鯆鯏鯑鯒鯣鯢鯤鯔鯡鰺鯲鯱鯰鰕鰔鰉鰓鰌鰆鰈鰒鰊鰄鰮鰛鰥鰤鰡鰰鱇鰲鱆鰾鱚鱠鱧鱶鱸鳧鳬鳰鴉鴈鳫鴃鴆鴪鴦鶯鴣鴟鵄鴕鴒鵁鴿鴾鵆鵈'],
[0xea40, '鵝鵞鵤鵑鵐鵙鵲鶉鶇鶫鵯鵺鶚鶤鶩鶲鷄鷁鶻鶸鶺鷆鷏鷂鷙鷓鷸鷦鷭鷯鷽鸚鸛鸞鹵鹹鹽麁麈麋麌麒麕麑麝麥麩麸麪麭靡黌黎黏黐黔黜點黝黠黥黨黯'],
[0xea80, '黴黶黷黹黻黼黽鼇鼈皷鼕鼡鼬鼾齊齒齔齣齟齠齡齦齧齬齪齷齲齶龕龜龠堯槇遙瑤凜熙']
]
module.exports = function toSJIS (utf8Char) {
if (!utf8Char || utf8Char === '') return
for (var i = 0; i < SJIS_UTF8.length; i++) {
var kanji = SJIS_UTF8[i][1]
var posIndex = kanji.indexOf(utf8Char)
if (posIndex >= 0) {
return SJIS_UTF8[i][0] + posIndex
}
}
}

View file

@ -0,0 +1,60 @@
var Mode = require('./mode')
/**
* Array of characters available in alphanumeric mode
*
* As per QR Code specification, to each character
* is assigned a value from 0 to 44 which in this case coincides
* with the array index
*
* @type {Array}
*/
var ALPHA_NUM_CHARS = [
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
' ', '$', '%', '*', '+', '-', '.', '/', ':'
]
function AlphanumericData (data) {
this.mode = Mode.ALPHANUMERIC
this.data = data
}
AlphanumericData.getBitsLength = function getBitsLength (length) {
return 11 * Math.floor(length / 2) + 6 * (length % 2)
}
AlphanumericData.prototype.getLength = function getLength () {
return this.data.length
}
AlphanumericData.prototype.getBitsLength = function getBitsLength () {
return AlphanumericData.getBitsLength(this.data.length)
}
AlphanumericData.prototype.write = function write (bitBuffer) {
var i
// Input data characters are divided into groups of two characters
// and encoded as 11-bit binary codes.
for (i = 0; i + 2 <= this.data.length; i += 2) {
// The character value of the first character is multiplied by 45
var value = ALPHA_NUM_CHARS.indexOf(this.data[i]) * 45
// The character value of the second digit is added to the product
value += ALPHA_NUM_CHARS.indexOf(this.data[i + 1])
// The sum is then stored as 11-bit binary number
bitBuffer.put(value, 11)
}
// If the number of input data characters is not a multiple of two,
// the character value of the final character is encoded as a 6-bit binary number.
if (this.data.length % 2) {
bitBuffer.put(ALPHA_NUM_CHARS.indexOf(this.data[i]), 6)
}
}
module.exports = AlphanumericData

View file

@ -6,35 +6,23 @@ function ByteData (data) {
this.data = new Buffer(data)
}
ByteData.getCharCountIndicator = function getCharCountIndicator (version) {
if (version >= 1 && version < 10) {
// 1 - 9
return 8
} else if (version >= 10 && version < 41) {
// 10 - 40
return 16
} else {
throw new Error('version: ' + version)
ByteData.getBitsLength = function getBitsLength (length) {
return length * 8
}
ByteData.prototype.getLength = function getLength () {
return this.data.length
}
ByteData.prototype.getBitsLength = function getBitsLength () {
return ByteData.getBitsLength(this.data.length)
}
ByteData.prototype.write = function (bitBuffer) {
for (var i = 0, l = this.data.length; i < l; i++) {
bitBuffer.put(this.data[i], 8)
}
}
ByteData.prototype = {
getLength: function (buffer) {
return this.data.length
},
append: function (data) {
this.data = Buffer.concat([this.data, new Buffer(data)])
return this
},
write: function (buffer) {
for (var i = 0, l = this.data.length; i < l; i++) {
buffer.put(this.data[i], 8)
}
},
getCharCountIndicator: ByteData.getCharCountIndicator
}
module.exports = ByteData

View file

@ -1,6 +1,50 @@
module.exports = {
L: 1,
M: 0,
Q: 3,
H: 2
exports.L = { bit: 1 }
exports.M = { bit: 0 }
exports.Q = { bit: 3 }
exports.H = { bit: 2 }
function fromString (string) {
if (typeof string !== 'string') {
throw new Error('Param is not a string')
}
var lcStr = string.toLowerCase()
switch (lcStr) {
case 'l':
case 'low':
return exports.L
case 'm':
case 'medium':
return exports.M
case 'q':
case 'quartile':
return exports.Q
case 'h':
case 'high':
return exports.H
default:
throw new Error('Unknown EC Level: ' + string)
}
}
exports.isValid = function isValid (level) {
return level && typeof level.bit !== 'undefined' &&
level.bit >= 0 && level.bit < 4
}
exports.from = function from (value, defaultValue) {
if (exports.isValid(value)) {
return value
}
try {
return fromString(value)
} catch (e) {
return defaultValue
}
}

View file

@ -15,7 +15,7 @@ var G15_BCH = Utils.getBCHDigit(G15)
* @return {Number} Encoded format information bits
*/
exports.getEncodedBits = function getEncodedBits (errorCorrectionLevel, mask) {
var data = ((errorCorrectionLevel << 3) | mask)
var data = ((errorCorrectionLevel.bit << 3) | mask)
var d = data << 10
while (Utils.getBCHDigit(d) - G15_BCH >= 0) {

54
lib/core/kanji-data.js Normal file
View file

@ -0,0 +1,54 @@
var Mode = require('./mode')
var Utils = require('./utils')
function KanjiData (data) {
this.mode = Mode.KANJI
this.data = data
}
KanjiData.getBitsLength = function getBitsLength (length) {
return length * 13
}
KanjiData.prototype.getLength = function getLength () {
return this.data.length
}
KanjiData.prototype.getBitsLength = function getBitsLength () {
return KanjiData.getBitsLength(this.data.length)
}
KanjiData.prototype.write = function (bitBuffer) {
var i
// In the Shift JIS system, Kanji characters are represented by a two byte combination.
// These byte values are shifted from the JIS X 0208 values.
// JIS X 0208 gives details of the shift coded representation.
for (i = 0; i < this.data.length; i++) {
var value = Utils.toSJIS(this.data[i])
// For characters with Shift JIS values from 0x8140 to 0x9FFC:
if (value >= 0x8140 && value <= 0x9FFC) {
// Subtract 0x8140 from Shift JIS value
value -= 0x8140
// For characters with Shift JIS values from 0xE040 to 0xEBBF
} else if (value >= 0xE040 && value <= 0xEBBF) {
// Subtract 0xC140 from Shift JIS value
value -= 0xC140
} else {
throw new Error(
'Invalid SJIS character: ' + this.data[i] + '\n' +
'Make sure your charset is UTF-8')
}
// Multiply most significant byte of result by 0xC0
// and add least significant byte to product
value = (((value >>> 8) & 0xff) * 0xC0) + (value & 0xff)
// Convert result to a 13-bit binary string
bitBuffer.put(value, 13)
}
}
module.exports = KanjiData

View file

@ -1,34 +1,167 @@
var Version = require('./version')
var Regex = require('./regex')
/**
* Data modes
* Numeric mode encodes data from the decimal digit set (0 - 9)
* (byte values 30HEX to 39HEX).
* Normally, 3 data characters are represented by 10 bits.
*
* @type {Object}
*/
module.exports = {
/**
* Numeric mode encodes data from the decimal digit set (0 - 9) (byte values 30HEX to 39HEX).
* Normally, 3 data characters are represented by 10 bits.
*/
NUMERIC: 1 << 0,
/**
* Alphanumeric mode encodes data from a set of 45 characters,
* i.e. 10 numeric digits (0 - 9),
* 26 alphabetic characters (A - Z),
* and 9 symbols (SP, $, %, *, +, -, ., /, :).
* Normally, two input characters are represented by 11 bits.
*/
ALPHA_NUM: 1 << 1,
/**
* In byte mode, data is encoded at 8 bits per character.
*/
BYTE: 1 << 2,
/**
* The Kanji mode efficiently encodes Kanji characters in accordance with the Shift JIS system
* based on JIS X 0208. The Shift JIS values are shifted from the JIS X 0208 values.
* JIS X 0208 gives details of the shift coded representation.
* Each two-byte character value is compacted to a 13-bit binary codeword.
*/
KANJI: 1 << 3
exports.NUMERIC = {
id: 'Numeric',
bit: 1 << 0,
ccBits: [10, 12, 14]
}
/**
* Alphanumeric mode encodes data from a set of 45 characters,
* i.e. 10 numeric digits (0 - 9),
* 26 alphabetic characters (A - Z),
* and 9 symbols (SP, $, %, *, +, -, ., /, :).
* Normally, two input characters are represented by 11 bits.
*
* @type {Object}
*/
exports.ALPHANUMERIC = {
id: 'Alphanumeric',
bit: 1 << 1,
ccBits: [9, 11, 13]
}
/**
* In byte mode, data is encoded at 8 bits per character.
*
* @type {Object}
*/
exports.BYTE = {
id: 'Byte',
bit: 1 << 2,
ccBits: [8, 16, 16]
}
/**
* The Kanji mode efficiently encodes Kanji characters in accordance with
* the Shift JIS system based on JIS X 0208.
* The Shift JIS values are shifted from the JIS X 0208 values.
* JIS X 0208 gives details of the shift coded representation.
* Each two-byte character value is compacted to a 13-bit binary codeword.
*
* @type {Object}
*/
exports.KANJI = {
id: 'Kanji',
bit: 1 << 3,
ccBits: [8, 10, 12]
}
/**
* Mixed mode will contain a sequences of data in a combination of any of
* the modes described above
*
* @type {Object}
*/
exports.MIXED = {
bit: -1
}
/**
* Returns the number of bits needed to store the data length
* according to QR Code specifications.
*
* @param {Mode} mode Data mode
* @param {Number} version QR Code version
* @return {Number} Number of bits
*/
exports.getCharCountIndicator = function getCharCountIndicator (mode, version) {
if (!mode.ccBits) throw new Error('Invalid mode: ' + mode)
if (!Version.isValid(version)) {
throw new Error('Invalid version: ' + version)
}
if (version >= 1 && version < 10) return mode.ccBits[0]
else if (version < 27) return mode.ccBits[1]
return mode.ccBits[2]
}
/**
* Returns the most efficient mode to store the specified data
*
* @param {String} dataStr Input data string
* @return {Mode} Best mode
*/
exports.getBestModeForData = function getBestModeForData (dataStr) {
if (Regex.testNumeric(dataStr)) return exports.NUMERIC
else if (Regex.testAlphanumeric(dataStr)) return exports.ALPHANUMERIC
else if (Regex.testKanji(dataStr)) return exports.KANJI
else return exports.BYTE
}
/**
* Return mode name as string
*
* @param {Mode} mode Mode object
* @returns {String} Mode name
*/
exports.toString = function toString (mode) {
if (mode && mode.id) return mode.id
throw new Error('Invalid mode')
}
/**
* Check if input param is a valid mode object
*
* @param {Mode} mode Mode object
* @returns {Boolean} True if valid mode, false otherwise
*/
exports.isValid = function isValid (mode) {
return mode && mode.bit && mode.ccBits
}
/**
* Get mode object from its name
*
* @param {String} string Mode name
* @returns {Mode} Mode object
*/
function fromString (string) {
if (typeof string !== 'string') {
throw new Error('Param is not a string')
}
var lcStr = string.toLowerCase()
switch (lcStr) {
case 'numeric':
return exports.NUMERIC
case 'alphanumeric':
return exports.ALPHANUMERIC
case 'kanji':
return exports.KANJI
case 'byte':
return exports.BYTE
default:
throw new Error('Unknown mode: ' + string)
}
}
/**
* Returns mode from a value.
* If value is not a valid mode, returns defaultValue
*
* @param {Mode|String} value Encoding mode
* @param {Mode} defaultValue Fallback value
* @return {Mode} Encoding mode
*/
exports.from = function from (value, defaultValue) {
if (exports.isValid(value)) {
return value
}
try {
return fromString(value)
} catch (e) {
return defaultValue
}
}

43
lib/core/numeric-data.js Normal file
View file

@ -0,0 +1,43 @@
var Mode = require('./mode')
function NumericData (data) {
this.mode = Mode.NUMERIC
this.data = data.toString()
}
NumericData.getBitsLength = function getBitsLength (length) {
return 10 * Math.floor(length / 3) + ((length % 3) ? ((length % 3) * 3 + 1) : 0)
}
NumericData.prototype.getLength = function getLength () {
return this.data.length
}
NumericData.prototype.getBitsLength = function getBitsLength () {
return NumericData.getBitsLength(this.data.length)
}
NumericData.prototype.write = function write (bitBuffer) {
var i, group, value
// The input data string is divided into groups of three digits,
// and each group is converted to its 10-bit binary equivalent.
for (i = 0; i + 3 <= this.data.length; i += 3) {
group = this.data.substr(i, 3)
value = parseInt(group, 10)
bitBuffer.put(value, 10)
}
// If the number of input digits is not an exact multiple of three,
// the final one or two digits are converted to 4 or 7 bits respectively.
var remainingNum = this.data.length - i
if (remainingNum > 0) {
group = this.data.substr(i)
value = parseInt(group, 10)
bitBuffer.put(value, remainingNum * 3 + 1)
}
}
module.exports = NumericData

View file

@ -1,7 +1,6 @@
var Buffer = require('../utils/buffer')
var Utils = require('./utils')
var ECLevel = require('./error-correction-level')
var ByteData = require('./byte-data')
var BitBuffer = require('./bit-buffer')
var BitMatrix = require('./bit-matrix')
var AlignmentPattern = require('./alignment-pattern')
@ -11,6 +10,9 @@ var ECCode = require('./error-correction-code')
var ReedSolomonEncoder = require('./reed-solomon-encoder')
var Version = require('./version')
var FormatInfo = require('./format-info')
var Mode = require('./mode')
var Segments = require('./segments')
var isArray = require('../utils/is-array')
/**
* QRCode for JavaScript
@ -148,7 +150,7 @@ function setupVersionInfo (matrix, version, reserve) {
* Add format info bits to matrix
*
* @param {BitMatrix} matrix Modules matrix
* @param {Number} errorCorrectionLevel Error correction level
* @param {ErrorCorrectionLevel} errorCorrectionLevel Error correction level
* @param {Number} maskPattern Mask pattern reference value
* @param {Boolean} reserve If true, marks bits as reserved and set their values to 0
*/
@ -233,26 +235,30 @@ function setupData (matrix, data) {
* Create encoded codewords from data input
*
* @param {Number} version QR Code version
* @param {Number} errorCorrectionLevel Error correction level
* @param {ErrorCorrectionLevel} errorCorrectionLevel Error correction level
* @param {ByteData} data Data input
* @return {Buffer} Buffer containing encoded codewords
*/
function createData (version, errorCorrectionLevel, data) {
function createData (version, errorCorrectionLevel, segments) {
// Prepare data buffer
var buffer = new BitBuffer()
// prefix data with mode indicator (4 bits in byte mode)
buffer.put(data.mode, 4)
segments.forEach(function (data) {
// prefix data with mode indicator (4 bits)
buffer.put(data.mode.bit, 4)
// Prefix data with character count indicator.
// The character count indicator is a string of bits that represents the number of characters
// that are being encoded. The character count indicator must be placed after the mode indicator
// and must be a certain number of bits long, depending on the QR version and data mode
// @see {@link ByteData.getCharCountIndicator}.
buffer.put(data.getLength(), data.getCharCountIndicator(version))
// Prefix data with character count indicator.
// The character count indicator is a string of bits that represents the
// number of characters that are being encoded.
// The character count indicator must be placed after the mode indicator
// and must be a certain number of bits long, depending on the QR version
// and data mode
// @see {@link Mode.getCharCountIndicator}.
buffer.put(data.getLength(), Mode.getCharCountIndicator(data.mode, version))
// add binary data sequence to buffer
data.write(buffer)
// add binary data sequence to buffer
data.write(buffer)
})
// Calculate required number of bits
var totalCodewords = Utils.getSymbolTotalCodewords(version)
@ -295,7 +301,7 @@ function createData (version, errorCorrectionLevel, data) {
*
* @param {BitBuffer} bitBuffer Data to encode
* @param {Number} version QR Code version
* @param {Number} errorCorrectionLevel Error correction level
* @param {ErrorCorrectionLevel} errorCorrectionLevel Error correction level
* @return {Buffer} Buffer containing encoded codewords
*/
function createCodewords (bitBuffer, version, errorCorrectionLevel) {
@ -374,30 +380,132 @@ function createCodewords (bitBuffer, version, errorCorrectionLevel) {
}
/**
* QR Code
* Build QR Code symbol
*
* @param {Number} version QR Code version
* @param {Number} errorCorrectionLevel Error correction level
* @param {String} data Input string
* @param {Number} version QR Code version
* @param {ErrorCorretionLevel} errorCorrectionLevel Error level
* @return {Object} Object containing symbol data
*/
function QRCode (version, errorCorrectionLevel) {
this.version = version
this.errorCorrectionLevel = errorCorrectionLevel
this.modules = null
this.moduleCount = 0
this.dataCache = null
this.data = null
function createSymbol (data, version, errorCorrectionLevel) {
var segments
if (isArray(data)) {
segments = Segments.fromArray(data)
} else if (typeof data === 'string') {
var estimatedVersion = version
if (!estimatedVersion) {
var rawSegments = Segments.rawSplit(data)
// Estimate best version that can contain raw splitted segments
estimatedVersion = Version.getBestVersionForData(rawSegments,
errorCorrectionLevel)
}
// Build optimized segments
// If estimated version is undefined, try with the highest version
segments = Segments.fromString(data, estimatedVersion)
} else {
throw new Error('Invalid data')
}
// Get the min version that can contain data
var bestVersion = Version.getBestVersionForData(segments,
errorCorrectionLevel)
// If no version is found, data cannot be stored
if (!bestVersion) {
throw new Error('The amount of data is too big to be stored in a QR Code')
}
// If not specified, use min version as default
if (!version) {
version = bestVersion
// Check if the specified version can contain the data
} else if (version < bestVersion) {
throw new Error('\n' +
'The chosen QR Code version cannot contain this amount of data.\n' +
'Minimum version required to store current data is: ' + bestVersion + '.\n'
)
}
var dataBits = createData(version, errorCorrectionLevel, segments)
// Allocate matrix buffer
var moduleCount = Utils.getSymbolSize(version)
var modules = new BitMatrix(moduleCount)
// Add function modules
setupFinderPattern(modules, version)
setupTimingPattern(modules)
setupAlignmentPattern(modules, version)
// Add temporary blank bits for format info and version info just to set them as reserved.
// This is needed to prevent these bits from being masked by {@link MaskPattern.applyMask}
// since the masking operation must be performed only on the encoding region.
// These blocks will be replaced with correct values later in code.
setupFormatInfo(modules, errorCorrectionLevel, 0, true)
if (version >= 7) {
setupVersionInfo(modules, version, true)
}
// Add data codewords
setupData(modules, dataBits)
// Find best mask pattern
var maskPattern = MaskPattern.getBestMask(modules)
// Apply mask pattern
MaskPattern.applyMask(maskPattern, modules)
// Replace format info bits with correct values
setupFormatInfo(modules, errorCorrectionLevel, maskPattern)
// Replace version info bits with correct values
if (version >= 7) {
setupVersionInfo(modules, version)
}
return {
data: modules,
version: version,
errorCorrectionLevel: errorCorrectionLevel,
maskPattern: maskPattern
}
}
/**
* Add datas to store
* QR Code
*
* @param {String, Number, Array, Buffer} data
* @param {String | Array} data Input data
* @param {Object} options Optional configurations
* @param {Number} options.version QR Code version
* @param {String} options.errorCorrectionLevel Error correction level
* @param {Function} options.toSJISFunc Helper func to convert utf8 to sjis
*/
QRCode.prototype.addData = function addData (data) {
if (this.data) this.data.append(data)
else this.data = new ByteData(data)
function QRCode (data, options) {
if (typeof data === 'undefined' || data === '') {
throw new Error('No input text')
}
this.dataCache = null
this.errorCorrectionLevel = ECLevel.M
this.version = undefined
if (typeof options !== 'undefined') {
// Use higher error correction level as default
this.errorCorrectionLevel = ECLevel.from(options.errorCorrectionLevel, ECLevel.M)
this.version = Version.from(options.version)
if (options.toSJISFunc) {
Utils.setToSJISFunction(options.toSJISFunc)
}
}
var qr = createSymbol(data, this.version, this.errorCorrectionLevel)
this.version = qr.version
this.modules = qr.data
}
/**
@ -408,7 +516,8 @@ QRCode.prototype.addData = function addData (data) {
* @return {Boolean} Module value (black/white)
*/
QRCode.prototype.isDark = function isDark (row, col) {
if (row < 0 || this.moduleCount <= row || col < 0 || this.moduleCount <= col) {
var size = this.modules.size
if (row < 0 || size <= row || col < 0 || size <= col) {
throw new Error(row + ',' + col)
}
@ -421,74 +530,5 @@ QRCode.prototype.isDark = function isDark (row, col) {
* @return {Number} size
*/
QRCode.prototype.getModuleCount = function getModuleCount () {
return this.moduleCount
}
/**
* Build QR Code symbol
*/
QRCode.prototype.make = function make () {
if (this.dataCache === null) {
// Use higher error correction level as default
if (typeof this.errorCorrectionLevel === 'undefined') this.errorCorrectionLevel = ECLevel.H
// Get the min version that can contain data
var bestVersion = Version.getBestVersionForData(this.data, this.errorCorrectionLevel)
// If no version is found, data cannot be stored
if (!bestVersion) {
throw new Error('The amount of data is too big to be stored in a QR Code')
}
// If not specified, use min version as default
if (!this.version) {
this.version = bestVersion
// Check if the specified version can contain the data
} else if (this.version < bestVersion) {
throw new Error('\n' +
'The chosen QR Code version cannot contain this amount of data.\n' +
'Max characters allowed with current config: ' +
Version.getCapacity(this.version, this.errorCorrectionLevel) + '\n' +
'Minimum version required to store current data: ' + bestVersion + '\n'
)
}
this.dataCache = createData(this.version, this.errorCorrectionLevel, this.data)
}
// Allocate matrix buffer
this.moduleCount = Utils.getSymbolSize(this.version)
this.modules = new BitMatrix(this.moduleCount)
// Add function modules
setupFinderPattern(this.modules, this.version)
setupTimingPattern(this.modules)
setupAlignmentPattern(this.modules, this.version)
// Add temporary blank bits for format info and version info just to set them as reserved.
// This is needed to prevent these bits from being masked by {@link MaskPattern.applyMask}
// since the masking operation must be performed only on the encoding region.
// These blocks will be replaced with correct values later in code.
setupFormatInfo(this.modules, this.errorCorrectionLevel, 0, true)
if (this.version >= 7) {
setupVersionInfo(this.modules, this.version, true)
}
// Add data codewords
setupData(this.modules, this.dataCache)
// Find best mask pattern
var maskPattern = MaskPattern.getBestMask(this.modules)
// Apply mask pattern
MaskPattern.applyMask(maskPattern, this.modules)
// Replace format info bits with correct values
setupFormatInfo(this.modules, this.errorCorrectionLevel, maskPattern)
// Replace version info bits with correct values
if (this.version >= 7) {
setupVersionInfo(this.modules, this.version)
}
return this.modules.size
}

28
lib/core/regex.js Normal file
View file

@ -0,0 +1,28 @@
var numeric = '[0-9]+'
var alphanumeric = '[A-Z $%*+-./:]+'
var kanji = '(?:[\u3000-\u303F]|[\u3040-\u309F]|[\u30A0-\u30FF]|' +
'[\uFF00-\uFFEF]|[\u4E00-\u9FAF]|[\u2605-\u2606]|[\u2190-\u2195]|\u203B|' +
'[―‐∥…‥‘’“”≠]|[Α-ё]|[§¨±´×÷])+'
var byte = '(?:(?![A-Z0-9 $%*+-./:]|' + kanji + ').)+'
exports.KANJI = new RegExp(kanji, 'g')
exports.BYTE_KANJI = new RegExp('[^A-Z0-9 $%*+-./:]+', 'g')
exports.BYTE = new RegExp(byte, 'g')
exports.NUMERIC = new RegExp(numeric, 'g')
exports.ALPHANUMERIC = new RegExp(alphanumeric, 'g')
var TEST_KANJI = new RegExp('^' + kanji + '$')
var TEST_NUMERIC = new RegExp('^' + numeric + '$')
var TEST_ALPHANUMERIC = new RegExp('^[A-Z0-9 $%*+-./:]+$')
exports.testKanji = function testKanji (str) {
return TEST_KANJI.test(str)
}
exports.testNumeric = function testNumeric (str) {
return TEST_NUMERIC.test(str)
}
exports.testAlphanumeric = function testAlphanumeric (str) {
return TEST_ALPHANUMERIC.test(str)
}

331
lib/core/segments.js Normal file
View file

@ -0,0 +1,331 @@
var Mode = require('./mode')
var NumericData = require('./numeric-data')
var AlphanumericData = require('./alphanumeric-data')
var ByteData = require('./byte-data')
var KanjiData = require('./kanji-data')
var Regex = require('./regex')
var Utils = require('./utils')
var dijkstra = require('dijkstrajs')
/**
* Returns UTF8 byte length
*
* @param {String} str Input string
* @return {Number} Number of byte
*/
function getStringByteLength (str) {
return unescape(encodeURIComponent(str)).length
}
/**
* Get a list of segments of the specified mode
* from a string
*
* @param {Mode} mode Segment mode
* @param {String} str String to process
* @return {Array} Array of object with segments data
*/
function getSegments (regex, mode, str) {
var segments = []
var result
while ((result = regex.exec(str)) !== null) {
segments.push({
data: result[0],
index: result.index,
mode: mode,
length: result[0].length
})
}
return segments
}
/**
* Extracts a series of segments with the appropriate
* modes from a string
*
* @param {String} dataStr Input string
* @return {Array} Array of object with segments data
*/
function getSegmentsFromString (dataStr) {
var numSegs = getSegments(Regex.NUMERIC, Mode.NUMERIC, dataStr)
var alphaNumSegs = getSegments(Regex.ALPHANUMERIC, Mode.ALPHANUMERIC, dataStr)
var byteSegs
var kanjiSegs
if (Utils.isKanjiModeEnabled()) {
byteSegs = getSegments(Regex.BYTE, Mode.BYTE, dataStr)
kanjiSegs = getSegments(Regex.KANJI, Mode.KANJI, dataStr)
} else {
byteSegs = getSegments(Regex.BYTE_KANJI, Mode.BYTE, dataStr)
kanjiSegs = []
}
var segs = numSegs.concat(alphaNumSegs, byteSegs, kanjiSegs)
return segs
.sort(function (s1, s2) {
return s1.index - s2.index
})
.map(function (obj) {
return {
data: obj.data,
mode: obj.mode,
length: obj.length
}
})
}
/**
* Returns how many bits are needed to encode a string of
* specified length with the specified mode
*
* @param {Number} length String length
* @param {Mode} mode Segment mode
* @return {Number} Bit length
*/
function getSegmentBitsLength (length, mode) {
switch (mode) {
case Mode.NUMERIC:
return NumericData.getBitsLength(length)
case Mode.ALPHANUMERIC:
return AlphanumericData.getBitsLength(length)
case Mode.KANJI:
return KanjiData.getBitsLength(length)
case Mode.BYTE:
return ByteData.getBitsLength(length)
}
}
/**
* Merges adjacent segments which have the same mode
*
* @param {Array} segs Array of object with segments data
* @return {Array} Array of object with segments data
*/
function mergeSegments (segs) {
return segs.reduce(function (acc, curr) {
var prevSeg = acc.length - 1 >= 0 ? acc[acc.length - 1] : null
if (prevSeg && prevSeg.mode === curr.mode) {
acc[acc.length - 1].data += curr.data
return acc
}
acc.push(curr)
return acc
}, [])
}
/**
* Generates a list of all possible nodes combination which
* will be used to build a segments graph.
*
* Nodes are divided by groups. Each group will contain a list of all the modes
* in which is possible to encode the given text.
*
* For example the text '12345' can be encoded as Numeric, Alphanumeric or Byte.
* The group for '12345' will contain then 3 objects, one for each
* possible encoding mode.
*
* Each node represents a possible segment.
*
* @param {Array} segs Array of object with segments data
* @return {Array} Array of object with segments data
*/
function buildNodes (segs) {
var nodes = []
for (var i = 0; i < segs.length; i++) {
var seg = segs[i]
switch (seg.mode) {
case Mode.NUMERIC:
nodes.push([seg,
{ data: seg.data, mode: Mode.ALPHANUMERIC, length: seg.length },
{ data: seg.data, mode: Mode.BYTE, length: seg.length }
])
break
case Mode.ALPHANUMERIC:
nodes.push([seg,
{ data: seg.data, mode: Mode.BYTE, length: seg.length }
])
break
case Mode.KANJI:
nodes.push([seg,
{ data: seg.data, mode: Mode.BYTE, length: getStringByteLength(seg.data) }
])
break
case Mode.BYTE:
nodes.push([
{ data: seg.data, mode: Mode.BYTE, length: getStringByteLength(seg.data) }
])
}
}
return nodes
}
/**
* Builds a graph from a list of nodes.
* All segments in each node group will be connected with all the segments of
* the next group and so on.
*
* At each connection will be assigned a weight depending on the
* segment's byte length.
*
* @param {Array} nodes Array of object with segments data
* @param {Number} version QR Code version
* @return {Object} Graph of all possible segments
*/
function buildGraph (nodes, version) {
var table = {}
var graph = {'start': {}}
var prevNodeIds = ['start']
for (var i = 0; i < nodes.length; i++) {
var nodeGroup = nodes[i]
var currentNodeIds = []
for (var j = 0; j < nodeGroup.length; j++) {
var node = nodeGroup[j]
var key = '' + i + j
currentNodeIds.push(key)
table[key] = { node: node, lastCount: 0 }
graph[key] = {}
for (var n = 0; n < prevNodeIds.length; n++) {
var prevNodeId = prevNodeIds[n]
if (table[prevNodeId] && table[prevNodeId].node.mode === node.mode) {
graph[prevNodeId][key] =
getSegmentBitsLength(table[prevNodeId].lastCount + node.length, node.mode) -
getSegmentBitsLength(table[prevNodeId].lastCount, node.mode)
table[prevNodeId].lastCount += node.length
} else {
if (table[prevNodeId]) table[prevNodeId].lastCount = node.length
graph[prevNodeId][key] = getSegmentBitsLength(node.length, node.mode) +
4 + Mode.getCharCountIndicator(node.mode, version) // switch cost
}
}
}
prevNodeIds = currentNodeIds
}
for (n = 0; n < prevNodeIds.length; n++) {
graph[prevNodeIds[n]]['end'] = 0
}
return { map: graph, table: table }
}
/**
* Builds a segment from a specified data and mode.
* If a mode is not specified, the more suitable will be used.
*
* @param {String} data Input data
* @param {Mode | String} modesHint Data mode
* @return {Segment} Segment
*/
function buildSingleSegment (data, modesHint) {
var mode
var bestMode = Mode.getBestModeForData(data)
mode = Mode.from(modesHint, bestMode)
// Make sure data can be encoded
if (mode !== Mode.BYTE && mode.bit < bestMode.bit) {
throw new Error('"' + data + '"' +
' cannot be encoded with mode ' + Mode.toString(mode) +
'.\n Suggested mode is: ' + Mode.toString(bestMode))
}
// Use Mode.BYTE if Kanji support is disabled
if (mode === Mode.KANJI && !Utils.isKanjiModeEnabled()) {
mode = Mode.BYTE
}
switch (mode) {
case Mode.NUMERIC:
return new NumericData(data)
case Mode.ALPHANUMERIC:
return new AlphanumericData(data)
case Mode.KANJI:
return new KanjiData(data)
case Mode.BYTE:
return new ByteData(data)
}
}
/**
* Builds a list of segments from an array.
* Array can contain Strings or Objects with segment's info.
*
* For each item which is a string, will be generated a segment with the given
* string and the more appropriate encoding mode.
*
* For each item which is an object, will be generated a segment with the given
* data and mode.
* Objects must contain at least the property "data".
* If property "mode" is not present, the more suitable mode will be used.
*
* @param {Array} array Array of objects with segments data
* @return {Array} Array of Segments
*/
exports.fromArray = function fromArray (array) {
return array.reduce(function (acc, seg) {
if (typeof seg === 'string') {
acc.push(buildSingleSegment(seg, null))
} else if (seg.data) {
acc.push(buildSingleSegment(seg.data, seg.mode))
}
return acc
}, [])
}
/**
* Builds an optimized sequence of segments from a string,
* which will produce the shortest possible bitstream.
*
* @param {String} data Input string
* @param {Number} version QR Code version
* @return {Array} Array of segments
*/
exports.fromString = function fromString (data, version) {
var segs = getSegmentsFromString(data, Utils.isKanjiModeEnabled())
var nodes = buildNodes(segs)
var graph = buildGraph(nodes, version)
var path = dijkstra.find_path(graph.map, 'start', 'end')
var optimizedSegs = []
for (var i = 1; i < path.length - 1; i++) {
optimizedSegs.push(graph.table[path[i]].node)
}
return exports.fromArray(mergeSegments(optimizedSegs))
}
/**
* Splits a string in various segments with the modes which
* best represent their content.
* The produced segments are far from being optimized.
* The output of this function is only used to estimate a QR Code version
* which may contain the data.
*
* @param {string} data Input string
* @return {Array} Array of segments
*/
exports.rawSplit = function rawSplit (data) {
return exports.fromArray(
getSegmentsFromString(data, Utils.isKanjiModeEnabled())
)
}

View file

@ -1,3 +1,4 @@
var toSJISFunction
var CODEWORDS_COUNT = [
0, // Not used
26, 44, 70, 100, 134, 172, 196, 242, 292, 346,
@ -44,3 +45,19 @@ exports.getBCHDigit = function (data) {
return digit
}
exports.setToSJISFunction = function setToSJISFunction (f) {
if (typeof f !== 'function') {
throw new Error('"toSJISFunc" is not a valid function.')
}
toSJISFunction = f
}
exports.isKanjiModeEnabled = function () {
return typeof toSJISFunction !== 'undefined'
}
exports.toSJIS = function toSJIS (kanji) {
return toSJISFunction(kanji)
}

View file

@ -1,16 +1,45 @@
var Buffer = require('../utils/buffer')
var Utils = require('./utils')
var ECCode = require('./error-correction-code')
var ECLevel = require('./error-correction-level')
var ByteData = require('./byte-data')
var Mode = require('./mode')
var isArray = require('../utils/is-array')
// Generator polynomial used to encode version information
var G18 = (1 << 12) | (1 << 11) | (1 << 10) | (1 << 9) | (1 << 8) | (1 << 5) | (1 << 2) | (1 << 0)
var G18_BCH = Utils.getBCHDigit(G18)
var getBestVersionForDataLength = function getBestVersionForDataLength (length, errorCorrectionLevel) {
function getBestVersionForDataLength (mode, length, errorCorrectionLevel) {
for (var currentVersion = 1; currentVersion <= 40; currentVersion++) {
if (length <= exports.getCapacity(currentVersion, errorCorrectionLevel)) return currentVersion
if (length <= exports.getCapacity(currentVersion, errorCorrectionLevel, mode)) {
return currentVersion
}
}
return undefined
}
function getReservedBitsCount (mode, version) {
// Character count indicator + mode indicator bits
return Mode.getCharCountIndicator(mode, version) + 4
}
function getTotalBitsFromDataArray (segments, version) {
var totalBits = 0
segments.forEach(function (data) {
var reservedBits = getReservedBitsCount(data.mode, version)
totalBits += reservedBits + data.getBitsLength()
})
return totalBits
}
function getBestVersionForMixedData (segments, errorCorrectionLevel) {
for (var currentVersion = 1; currentVersion <= 40; currentVersion++) {
var length = getTotalBitsFromDataArray(segments, currentVersion)
if (length <= exports.getCapacity(currentVersion, errorCorrectionLevel, Mode.MIXED)) {
return currentVersion
}
}
return undefined
@ -22,23 +51,43 @@ var getBestVersionForDataLength = function getBestVersionForDataLength (length,
* @param {Number} version QR Code version
* @return {Boolean} true if valid version, false otherwise
*/
exports.isValidVersion = function isValidVersion (version) {
exports.isValid = function isValid (version) {
return !isNaN(version) && version >= 1 && version <= 40
}
/**
* Returns version number from a value.
* If value is not a valid version, returns defaultValue
*
* @param {Number|String} value QR Code version
* @param {Number} defaultValue Fallback value
* @return {Number} QR Code version number
*/
exports.from = function from (value, defaultValue) {
if (exports.isValid(value)) {
return parseInt(value, 10)
}
return defaultValue
}
/**
* Returns how much data can be stored with the specified QR code version
* and error correction level
*
* @param {Number} version QR Code version (1-40)
* @param {Number} errorCorrectionLevel Error correction level
* @param {Mode} mode Data mode
* @return {Number} Quantity of storable data
*/
exports.getCapacity = function getCapacity (version, errorCorrectionLevel) {
if (!exports.isValidVersion(version)) {
exports.getCapacity = function getCapacity (version, errorCorrectionLevel, mode) {
if (!exports.isValid(version)) {
throw new Error('Invalid QR Code version')
}
// Use Byte mode as default
if (typeof mode === 'undefined') mode = Mode.BYTE
// Total codewords for this QR code version (Data + Error correction)
var totalCodewords = Utils.getSymbolTotalCodewords(version)
@ -48,32 +97,55 @@ exports.getCapacity = function getCapacity (version, errorCorrectionLevel) {
// Total number of data codewords
var dataTotalCodewordsBits = (totalCodewords - ecTotalCodewords) * 8
// Character count indicator + mode indicator bits
var reservedBits = ByteData.getCharCountIndicator(version) + 4
if (mode === Mode.MIXED) return dataTotalCodewordsBits
var usableBits = dataTotalCodewordsBits - getReservedBitsCount(mode, version)
// Return max number of storable codewords
return Math.floor((dataTotalCodewordsBits - reservedBits) / 8)
switch (mode) {
case Mode.NUMERIC:
return Math.floor((usableBits / 10) * 3)
case Mode.ALPHANUMERIC:
return Math.floor((usableBits / 11) * 2)
case Mode.KANJI:
return Math.floor(usableBits / 13)
case Mode.BYTE:
default:
return Math.floor(usableBits / 8)
}
}
/**
* Returns the minimum version needed to contain the amount of data
*
* @param {Buffer, Array, ByteData} data Data buffer
* @param {Segment} data Segment of data
* @param {Number} [errorCorrectionLevel=H] Error correction level
* @param {Mode} mode Data mode
* @return {Number} QR Code version
*/
exports.getBestVersionForData = function getBestVersionForData (data, errorCorrectionLevel) {
var dataLength
var seg
if (data instanceof ByteData) dataLength = data.getLength()
else if (Buffer.isBuffer(data)) dataLength = data.length
else dataLength = new Buffer(data).length
var ecl = ECLevel.from(errorCorrectionLevel, ECLevel.M)
var ecl = errorCorrectionLevel
if (isArray(data)) {
if (data.length > 1) {
return getBestVersionForMixedData(data, ecl)
}
if (typeof ecl === 'undefined') ecl = ECLevel.H
if (data.length === 0) {
return 1
}
return getBestVersionForDataLength(dataLength, ecl)
seg = data[0]
} else {
seg = data
}
return getBestVersionForDataLength(seg.mode, seg.getLength(), ecl)
}
/**
@ -87,7 +159,7 @@ exports.getBestVersionForData = function getBestVersionForData (data, errorCorre
* @return {Number} Encoded version info bits
*/
exports.getEncodedBits = function getEncodedBits (version) {
if (!exports.isValidVersion(version) || version < 7) {
if (!exports.isValid(version) || version < 7) {
throw new Error('Invalid QR Code version')
}

View file

@ -54,7 +54,7 @@ var parseOptions = function (options) {
if (options.errorCorrectLevel) {
var ec = options.errorCorrectLevel
if (textKeys[ec]) {
options.errorCorrectLevel = textKeys[ec]
options.errorCorrectionLevel = textKeys[ec]
}
}
return options
@ -212,7 +212,7 @@ exports.drawText = function (text, options, cb) {
}
var drawInstance = new QRCodeDraw()
drawInstance.drawBitArray(text, function (error, bits, width) {
drawInstance.drawBitArray(text, options, function (error, bits, width) {
if (!error) {
var code = terminalRender.renderBits(bits, width)
cb(error, code)
@ -229,7 +229,7 @@ exports.drawSvg = function (text, options, cb) {
}
var drawInstance = new QRCodeDraw()
drawInstance.drawBitArray(text, function (error, bits, width) {
drawInstance.drawBitArray(text, options, function (error, bits, width) {
if (!error) {
var code = svgRender.renderBits(bits, width, options)
cb(error, code)

View file

@ -50,7 +50,7 @@ QRCodeDraw.prototype = {
}
if (typeof options !== 'object') {
options.errorCorrectLevel = options
options.errorCorrectionLevel = options
}
this.scale = options.scale || this.scale
@ -58,14 +58,11 @@ QRCodeDraw.prototype = {
// create qrcode!
try {
var qr = new QRCodeLib(options.version, options.errorCorrectLevel)
var qr = new QRCodeLib(text, options)
var scale = this.scale || 4
var ctx = canvas.getContext('2d')
var width = 0
qr.addData(text)
qr.make()
var margin = this.marginWidth()
var currenty = margin
width = this.dataWidth(qr) + margin * 2
@ -110,14 +107,11 @@ QRCodeDraw.prototype = {
// create qrcode!
try {
var qr = new QRCodeLib(options.version, options.errorCorrectLevel)
var qr = new QRCodeLib(text, options)
var width = 0
var bits
var bitc = 0
qr.addData(text)
qr.make()
width = this.dataWidth(qr, 1)
bits = new Array(width * width)

View file

@ -19,7 +19,8 @@
"files": [
"bin",
"build",
"lib"
"lib",
"helper"
],
"homepage": "http://github.com/soldair/node-qrcode",
"license": "MIT",
@ -35,16 +36,17 @@
},
"dependencies": {
"canvas": "~1.3.4",
"colors": "*"
"colors": "*",
"dijkstrajs": "^1.0.1"
},
"devDependencies": {
"browserify": "^13.1.1",
"browserify": "^14.1.0",
"canvasutil": "*",
"express": "2.5.x",
"libxmljs": "^0.18.0",
"standard": "*",
"tap": "*",
"uglify-js": "^2.7.4"
"uglify-js": "^2.7.5"
},
"repository": {
"type": "git",

View file

@ -1,9 +1,10 @@
var spawn = require('child_process').spawn
var path = require('path')
var opt = {
cwd: __dirname,
env: (function () {
process.env.NODE_PATH = './lib'
process.env.NODE_PATH = './' + path.delimiter + './lib'
return process.env
}()),
stdio: [process.stdin, process.stdout, process.stderr]
@ -12,5 +13,5 @@ var opt = {
spawn('node', [
'node_modules/.bin/tap',
'--cov',
'test/**/*.test.js'
process.argv[2] || 'test/**/*.test.js'
], opt)

View file

@ -6,7 +6,7 @@ var QRCode = require('../../')
test('drawSvg', function (t) {
var expectedSvg = fs.readFileSync(path.join(__dirname, '/fixtures/expected-output.svg'), 'UTF-8')
QRCode.drawSvg('http://www.google.com', function (err, code) {
QRCode.drawSvg('http://www.google.com', { errorCorrectionLevel: 'H' }, function (err, code) {
t.ok(!err, 'there should be no error')
t.equal(code, expectedSvg, 'should output a valid svg')

View file

@ -7,7 +7,7 @@ var shouldBe =
var lShouldBe = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHwAAAB8CAYAAACrHtS+AAAABmJLR0QA/wD/AP+gvaeTAAACVUlEQVR4nO3dy27rMAwA0bro//+yu/cihEBSVDxztr15YSDw2rKT677v+0cYv9NvQHsZHMbgMAaHMTiMwWEMDmNwGIPDGBzG4DAGhzE4jMFhDA5jcBiDwxgcxuAwf9VPeF1X9VN+tHpJ3vP9PR+/+vdu1ZccusJhDA5jcJjyGf5UPYOyM7T6/Zz2+SKucBiDwxgcpn2GP63OqN3H2dmZ3P35slzhMAaHMTjM9hneLZqJ0d+jGf/tXOEwBocxOMzrZvjTafvb01zhMAaHMTjM9hk+fVwbzezs+5v+fBFXOIzBYQwO0z7Ddx/nVl93vnru/XSucBiDwxgcpnyGn34cGsnup5/OFQ5jcBiDw4zfH37a/vT0dfPdXOEwBocxOEz7cXj3ue3szN99bn31/fsdL0oxOIzBYY67Lr17pmZnaPV5ht3nIVzhMAaHMTjM+He8TB+XPq1+B8zq/ymm99td4TAGhzE4zPH3lmWPk1dfL/vvp/e7I65wGIPDGBzmuk8bMknd36de/fzuh6uVwWEMDjN+XXpW9bnp7EyNHj993b0rHMbgMAaHef3vlq3O5N3f07b73LsrHMbgMAaHGb+mLbL7t0KzM9X9cB3F4DAGhznu3rKsaL+5+n7y3Y/PcoXDGBzG4DCvm+Hd+9mr16Ttvq4+4gqHMTiMwWGOv7es+vVW7//ufj33w9XK4DAGh3nd75ZFqve3q2eyx+EqZXAYg8O87v5wfeYKhzE4jMFhDA5jcBiDwxgcxuAwBocxOIzBYQwOY3AYg8MYHMbgMAaHMTiMwWH+AWVFEfpSXe+vAAAAAElFTkSuQmCC'
test('qrcode to data uri should be correct.', function (t) {
QRCode.toDataURL('i am a pony!', function (err, url) {
QRCode.toDataURL('i am a pony!', { errorCorrectionLevel: 'H' }, function (err, url) {
if (err) console.log(err)
t.ok(!err, 'there should be no error ' + err)
t.equals(url, shouldBe, 'url generated should match expected value')
@ -16,7 +16,7 @@ test('qrcode to data uri should be correct.', function (t) {
})
test('qrcode generated with changed error correction should be expected value', function (t) {
QRCode.toDataURL('i am a pony!', {errorCorrectLevel: 'minimum'}, function (err, url) {
QRCode.toDataURL('i am a pony!', { errorCorrectLevel: 'minimum' }, function (err, url) {
t.ok(!err, 'there should be no error ' + err)
t.equals(url, lShouldBe, 'url should match expected value for error correction L')
t.end()

View file

@ -0,0 +1,41 @@
var test = require('tap').test
var BitBuffer = require('core/bit-buffer')
var AlphanumericData = require('core/alphanumeric-data')
var Mode = require('core/mode')
var testData = [
{
data: 'A',
length: 1,
bitLength: 6,
dataBit: [40]
},
{
data: 'AB',
length: 2,
bitLength: 11,
dataBit: [57, 160]
},
{
data: 'ABC12',
length: 5,
bitLength: 28,
dataBit: [57, 168, 116, 32]
}
]
test('Alphanumeric Data', function (t) {
testData.forEach(function (data) {
var alphanumericData = new AlphanumericData(data.data)
t.equal(alphanumericData.mode, Mode.ALPHANUMERIC, 'Mode should be ALPHANUMERIC')
t.equal(alphanumericData.getLength(), data.length, 'Should return correct length')
t.equal(alphanumericData.getBitsLength(), data.bitLength, 'Should return correct bit length')
var bitBuffer = new BitBuffer()
alphanumericData.write(bitBuffer)
t.deepEqual(bitBuffer.buffer, data.dataBit, 'Should write correct data to buffer')
})
t.end()
})

View file

@ -5,6 +5,7 @@ var Mode = require('core/mode')
test('Byte Data', function (t) {
var text = '1234'
var textBitLength = 32
var textByte = [49, 50, 51, 52] // 1, 2, 3, 4
var utf8Text = '\u00bd + \u00bc = \u00be' // 9 char, 12 byte
@ -12,23 +13,12 @@ test('Byte Data', function (t) {
t.equal(byteData.mode, Mode.BYTE, 'Mode should be BYTE')
t.equal(byteData.getLength(), text.length, 'Should return correct length')
t.ok(ByteData.getCharCountIndicator, 'getCharCountIndicator should be defined')
for (var v = 1; v <= 40; v++) {
t.ok(byteData.getCharCountIndicator(v), 'Should return a positive number')
}
t.throw(function () { byteData.getCharCountIndicator(0) }, 'Should throw if invalid version')
t.equal(byteData.getBitsLength(), textBitLength, 'Should return correct bit length')
var bitBuffer = new BitBuffer()
byteData.write(bitBuffer)
t.deepEqual(bitBuffer.buffer, textByte, 'Should write correct data to buffer')
byteData.append(text)
t.equal(byteData.getLength(), text.length * 2, 'Should return correct length')
t.deepEqual(byteData.data, new Buffer(textByte.concat(textByte)), 'Should correctly append data')
var byteDataUtf8 = new ByteData(utf8Text)
t.equal(byteDataUtf8.getLength(), 12, 'Should return correct length for utf8 chars')

View file

@ -3,17 +3,17 @@ var Utils = require('core/utils')
var Version = require('core/version')
var ECLevel = require('core/error-correction-level')
var ECCode = require('core/error-correction-code')
var ByteData = require('core/byte-data')
var Mode = require('core/mode')
test('Error correction codewords', function (t) {
var levels = [ECLevel.L, ECLevel.M, ECLevel.Q, ECLevel.H]
for (var v = 1; v <= 40; v++) {
var totalCodewords = Utils.getSymbolTotalCodewords(v)
var reservedByte = Math.ceil((ByteData.getCharCountIndicator(v) + 4) / 8)
var reservedByte = Math.ceil((Mode.getCharCountIndicator(Mode.BYTE, v) + 4) / 8)
for (var l = 0; l < levels.length; l++) {
var dataCodewords = Version.getCapacity(v, levels[l]) + reservedByte
var dataCodewords = Version.getCapacity(v, levels[l], Mode.BYTE) + reservedByte
var expectedCodewords = totalCodewords - dataCodewords

View file

@ -0,0 +1,34 @@
var test = require('tap').test
var ECLevel = require('core/error-correction-level')
var EC_LEVELS = [ECLevel.L, ECLevel.M, ECLevel.Q, ECLevel.H]
test('Error level from input value', function (t) {
var values = [['l', 'low'], ['m', 'medium'], ['q', 'quartile'], ['h', 'high']]
for (var l = 0; l < values.length; l++) {
for (var i = 0; i < values[l].length; i++) {
t.equal(ECLevel.from(values[l][i]), EC_LEVELS[l])
t.equal(ECLevel.from(values[l][i].toUpperCase()), EC_LEVELS[l])
}
}
t.equal(ECLevel.from(ECLevel.L), ECLevel.L, 'Should return passed level if value is valid')
t.equal(ECLevel.from(undefined, ECLevel.M), ECLevel.M, 'Should return default level if value is undefined')
t.equal(ECLevel.from('', ECLevel.Q), ECLevel.Q, 'Should return default level if value is invalid')
t.end()
})
test('Error level validity', function (t) {
for (var l = 0; l < EC_LEVELS.length; l++) {
t.ok(ECLevel.isValid(EC_LEVELS[l]), 'Should return true if error level is valid')
}
t.notOk(ECLevel.isValid(undefined), 'Should return false if level is undefined')
t.notOk(ECLevel.isValid({}), 'Should return false if bit property is undefined')
t.notOk(ECLevel.isValid({ bit: -1 }), 'Should return false if bit property value is < 0')
t.notOk(ECLevel.isValid({ bit: 4 }), 'Should return false if bit property value is > 3')
t.end()
})

View file

@ -0,0 +1,30 @@
var test = require('tap').test
var BitBuffer = require('core/bit-buffer')
var KanjiData = require('core/kanji-data')
var Mode = require('core/mode')
var toSJIS = require('helper/to-sjis')
require('core/utils').setToSJISFunction(toSJIS)
test('Kanji Data', function (t) {
var data = '漢字漾癶'
var length = 4
var bitLength = 52 // length * 13
var dataBit = [57, 250, 134, 174, 129, 134, 0]
var kanjiData = new KanjiData(data)
t.equal(kanjiData.mode, Mode.KANJI, 'Mode should be KANJI')
t.equal(kanjiData.getLength(), length, 'Should return correct length')
t.equal(kanjiData.getBitsLength(), bitLength, 'Should return correct bit length')
var bitBuffer = new BitBuffer()
kanjiData.write(bitBuffer)
t.deepEqual(bitBuffer.buffer, dataBit, 'Should write correct data to buffer')
kanjiData = new KanjiData('abc')
bitBuffer = new BitBuffer()
t.throw(function () { kanjiData.write(bitBuffer) }, 'Should throw if data is invalid')
t.end()
})

128
test/unit/core/mode.test.js Normal file
View file

@ -0,0 +1,128 @@
var test = require('tap').test
var Mode = require('core/mode')
test('Mode bits', function (t) {
var EXPECTED_BITS = {
numeric: 1,
alphanumeric: 2,
byte: 4,
kanji: 8,
mixed: -1
}
t.equal(Mode.NUMERIC.bit, EXPECTED_BITS.numeric)
t.equal(Mode.ALPHANUMERIC.bit, EXPECTED_BITS.alphanumeric)
t.equal(Mode.BYTE.bit, EXPECTED_BITS.byte)
t.equal(Mode.KANJI.bit, EXPECTED_BITS.kanji)
t.equal(Mode.MIXED.bit, EXPECTED_BITS.mixed)
t.end()
})
test('Char count bits', function (t) {
var EXPECTED_BITS = {
numeric: [10, 12, 14],
alphanumeric: [9, 11, 13],
byte: [8, 16, 16],
kanji: [8, 10, 12]
}
var v
for (v = 1; v < 10; v++) {
t.equal(Mode.getCharCountIndicator(Mode.NUMERIC, v), EXPECTED_BITS.numeric[0])
t.equal(Mode.getCharCountIndicator(Mode.ALPHANUMERIC, v), EXPECTED_BITS.alphanumeric[0])
t.equal(Mode.getCharCountIndicator(Mode.BYTE, v), EXPECTED_BITS.byte[0])
t.equal(Mode.getCharCountIndicator(Mode.KANJI, v), EXPECTED_BITS.kanji[0])
}
for (v = 10; v < 27; v++) {
t.equal(Mode.getCharCountIndicator(Mode.NUMERIC, v), EXPECTED_BITS.numeric[1])
t.equal(Mode.getCharCountIndicator(Mode.ALPHANUMERIC, v), EXPECTED_BITS.alphanumeric[1])
t.equal(Mode.getCharCountIndicator(Mode.BYTE, v), EXPECTED_BITS.byte[1])
t.equal(Mode.getCharCountIndicator(Mode.KANJI, v), EXPECTED_BITS.kanji[1])
}
for (v = 27; v <= 40; v++) {
t.equal(Mode.getCharCountIndicator(Mode.NUMERIC, v), EXPECTED_BITS.numeric[2])
t.equal(Mode.getCharCountIndicator(Mode.ALPHANUMERIC, v), EXPECTED_BITS.alphanumeric[2])
t.equal(Mode.getCharCountIndicator(Mode.BYTE, v), EXPECTED_BITS.byte[2])
t.equal(Mode.getCharCountIndicator(Mode.KANJI, v), EXPECTED_BITS.kanji[2])
}
t.throw(function () { Mode.getCharCountIndicator({}, 1) },
'Should throw if mode is invalid')
t.throw(function () { Mode.getCharCountIndicator(Mode.BYTE, 0) },
'Should throw if version is invalid')
t.end()
})
test('Best mode', function (t) {
var EXPECTED_MODE = {
'12345': Mode.NUMERIC,
'abcde': Mode.BYTE,
'1234a': Mode.BYTE,
'ABCDa': Mode.BYTE,
'ABCDE': Mode.ALPHANUMERIC,
'12ABC': Mode.ALPHANUMERIC,
'乂ЁЖぞβ': Mode.KANJI,
'ΑΒΓψωЮЯабв': Mode.KANJI,
'皿a晒三': Mode.BYTE
}
Object.keys(EXPECTED_MODE).forEach(function (data) {
t.equal(Mode.getBestModeForData(data), EXPECTED_MODE[data],
'Should return mode ' + Mode.toString(EXPECTED_MODE[data]) + ' for data: ' + data)
})
t.end()
})
test('Is valid', function (t) {
t.ok(Mode.isValid(Mode.NUMERIC))
t.ok(Mode.isValid(Mode.ALPHANUMERIC))
t.ok(Mode.isValid(Mode.BYTE))
t.ok(Mode.isValid(Mode.KANJI))
t.notOk(Mode.isValid(undefined))
t.notOk(Mode.isValid({ bit: 1 }))
t.notOk(Mode.isValid({ ccBits: [] }))
t.end()
})
test('From value', function (t) {
var modes = [
{ name: 'numeric', mode: Mode.NUMERIC },
{ name: 'alphanumeric', mode: Mode.ALPHANUMERIC },
{ name: 'kanji', mode: Mode.KANJI },
{ name: 'byte', mode: Mode.BYTE }
]
for (var m = 0; m < modes.length; m++) {
t.equal(Mode.from(modes[m].name), modes[m].mode)
t.equal(Mode.from(modes[m].name.toUpperCase()), modes[m].mode)
t.equal(Mode.from(modes[m].mode), modes[m].mode)
}
t.equal(Mode.from('', Mode.NUMERIC), Mode.NUMERIC,
'Should return default value if mode is invalid')
t.equal(Mode.from(null, Mode.NUMERIC), Mode.NUMERIC,
'Should return default value if mode undefined')
t.end()
})
test('To string', function (t) {
t.equal(Mode.toString(Mode.NUMERIC), 'Numeric')
t.equal(Mode.toString(Mode.ALPHANUMERIC), 'Alphanumeric')
t.equal(Mode.toString(Mode.BYTE), 'Byte')
t.equal(Mode.toString(Mode.KANJI), 'Kanji')
t.throw(function () { Mode.toString({}) }, 'Should throw if mode is invalid')
t.end()
})

View file

@ -0,0 +1,54 @@
var test = require('tap').test
var BitBuffer = require('core/bit-buffer')
var NumericData = require('core/numeric-data')
var Mode = require('core/mode')
var testData = [
{
data: 8,
length: 1,
bitLength: 4,
dataBit: [128]
},
{
data: 16,
length: 2,
bitLength: 7,
dataBit: [32]
},
{
data: 128,
length: 3,
bitLength: 10,
dataBit: [32, 0]
},
{
data: 12345,
length: 5,
bitLength: 17,
// (123)d -> (0001111011)b 10bit
// (45)d -> (0101101)b 7bit
//
// (00011110)b -> (30)d
// (11010110)b -> (214)d
// (10000000)b -> (128)d
dataBit: [30, 214, 128]
}
]
test('Numeric Data', function (t) {
testData.forEach(function (data) {
var numericData = new NumericData(data.data)
t.equal(numericData.mode, Mode.NUMERIC, 'Mode should be NUMERIC')
t.equal(numericData.getLength(), data.length, 'Should return correct length')
t.equal(numericData.getBitsLength(), data.bitLength, 'Should return correct bit length')
var bitBuffer = new BitBuffer()
numericData.write(bitBuffer)
t.deepEqual(bitBuffer.buffer, data.dataBit, 'Should write correct data to buffer')
})
t.end()
})

View file

@ -1,20 +1,15 @@
var test = require('tap').test
var ByteData = require('core/byte-data')
var ECLevel = require('core/error-correction-level')
var Version = require('core/version')
var QRCode = require('core/qrcode')
var toSJIS = require('helper/to-sjis')
test('QRCode interface', function (t) {
var qr
t.notThrow(function () { qr = new QRCode() }, 'Should not throw')
t.throw(function () { QRCode() }, 'Should throw if no data is provided')
t.notThrow(function () { QRCode('1234567') }, 'Should not throw')
qr.addData('1234567')
t.ok(qr.data instanceof ByteData, 'Should add data in correct mode')
qr.make()
t.equal(qr.version, 1, 'Should create qrcode with correct version')
var qr = new QRCode('a123456A', { version: 1, errorCorrectionLevel: 'H' })
t.equal(qr.getModuleCount(), 21, 'Should return correct modules count')
t.equal(qr.errorCorrectionLevel, ECLevel.H, 'Should set default EC level to H')
var outOfBoundCoords = [
[0, 22], [22, 0], [22, 22], [-1, 0], [0, -1]
@ -27,23 +22,103 @@ test('QRCode interface', function (t) {
var darkModule = qr.isDark(qr.getModuleCount() - 8, 8)
t.ok(darkModule, 'Should have a dark module at coords [size-8][8]')
t.throw(function () {
qr = new QRCode({})
}, 'Should throw if invalid data is passed')
t.notThrow(function () {
qr = new QRCode('AAAAA00000', { version: 5 })
}, 'Should accept data as string')
t.notThrow(function () {
qr = new QRCode([
{ data: 'ABCDEFG', mode: 'alphanumeric' },
{ data: 'abcdefg' },
{ data: '晒三', mode: 'kanji' },
{ data: '0123456', mode: 'numeric' }
], { toSJISFunc: toSJIS })
}, 'Should accept data as array of objects')
t.notThrow(function () {
qr = new QRCode('AAAAA00000', { errorCorrectionLevel: 'quartile' })
qr = new QRCode('AAAAA00000', { errorCorrectionLevel: 'q' })
}, 'Should accept errorCorrectionLevel as string')
t.end()
})
test('QRCode error correction', function (t) {
var qr
var ecValues = [
{ name: ['l', 'low'], level: ECLevel.L },
{ name: ['m', 'medium'], level: ECLevel.M },
{ name: ['q', 'quartile'], level: ECLevel.Q },
{ name: ['h', 'high'], level: ECLevel.H }
]
for (var l = 0; l < ecValues.length; l++) {
for (var i = 0; i < ecValues[l].name.length; i++) {
t.notThrow(function () {
qr = new QRCode('ABCDEFG', { errorCorrectionLevel: ecValues[l].name[i] })
}, 'Should accept errorCorrectionLevel value: ' + ecValues[l].name[i])
t.deepEqual(qr.errorCorrectionLevel, ecValues[l].level,
'Should have correct errorCorrectionLevel value')
t.notThrow(function () {
qr = new QRCode('ABCDEFG', { errorCorrectionLevel: ecValues[l].name[i].toUpperCase() })
}, 'Should accept errorCorrectionLevel value: ' + ecValues[l].name[i].toUpperCase())
t.deepEqual(qr.errorCorrectionLevel, ecValues[l].level,
'Should have correct errorCorrectionLevel value')
}
}
qr = new QRCode('ABCDEFG')
t.equal(qr.errorCorrectionLevel, ECLevel.M, 'Should set default EC level to M')
t.end()
})
test('QRCode version', function (t) {
var qr = new QRCode(7, ECLevel.L)
qr.addData('data')
qr.make()
t.equal(qr.version, 7, 'Should create qrcode with correct version')
t.equal(qr.errorCorrectionLevel, ECLevel.L, 'Should set correct EC level')
var qr = new QRCode('data', { version: 9, errorCorrectionLevel: ECLevel.M })
qr = new QRCode(1, ECLevel.H)
qr.addData(new Array(Version.getCapacity(2, ECLevel.H)).join('-'))
t.throw(function () { qr.make() }, 'Should throw if data cannot be contained with chosen version')
t.equal(qr.version, 9, 'Should create qrcode with correct version')
t.equal(qr.errorCorrectionLevel, ECLevel.M, 'Should set correct EC level')
qr = new QRCode(40, ECLevel.H)
qr.addData(new Array(Version.getCapacity(40, ECLevel.H) + 2).join('-'))
t.throw(function () { qr.make() }, 'Should throw if data cannot be contained in a qr code')
t.throw(function () {
qr = new QRCode(new Array(Version.getCapacity(2, ECLevel.H)).join('a'),
{ version: 1, errorCorrectionLevel: ECLevel.H })
}, 'Should throw if data cannot be contained with chosen version')
t.throw(function () {
qr = new QRCode(new Array(Version.getCapacity(40, ECLevel.H) + 2).join('a'),
{ version: 40, errorCorrectionLevel: ECLevel.H })
}, 'Should throw if data cannot be contained in a qr code')
t.notThrow(function () {
qr = new QRCode('abcdefg', { version: 'invalid' })
}, 'Should use best version if the one provided is invalid')
t.end()
})
test('QRCode capacity', function (t) {
var qr
qr = new QRCode([{ data: 'abcdefg', mode: 'byte' }])
t.equal(qr.version, 1, 'Should contain 7 byte characters')
qr = new QRCode([{ data: '12345678901234567', mode: 'numeric' }])
t.equal(qr.version, 1, 'Should contain 17 numeric characters')
qr = new QRCode([{ data: 'ABCDEFGHIL', mode: 'alphanumeric' }])
t.equal(qr.version, 1, 'Should contain 10 alphanumeric characters')
qr = new QRCode([{ data: 'AIぐサ', mode: 'kanji' }],
{ toSJISFunc: toSJIS })
t.equal(qr.version, 1, 'Should contain 4 kanji characters')
t.end()
})

View file

@ -25,5 +25,9 @@ test('Reed-Solomon encoder', function (t) {
enc = new RS(0)
t.notOk(enc.genPoly, 'Should not create a generator polynomial if degree is 0')
enc = new RS(1)
t.deepEqual(enc.encode(new Buffer([0])), new Buffer([0]),
'Should return correct buffer')
t.end()
})

View file

@ -0,0 +1,39 @@
var test = require('tap').test
var Regex = require('core/regex')
test('Regex', function (t) {
t.ok(Regex.NUMERIC instanceof RegExp,
'Should export a regex for NUMERIC')
t.ok(Regex.ALPHANUMERIC instanceof RegExp,
'Should export a regex for ALPHANUMERIC')
t.ok(Regex.BYTE instanceof RegExp,
'Should export a regex for BYTE')
t.ok(Regex.KANJI instanceof RegExp,
'Should export a regex for KANJI')
t.ok(Regex.BYTE_KANJI instanceof RegExp,
'Should export a regex for BYTE_KANJI')
t.end()
})
test('Regex test', function (t) {
t.ok(Regex.testNumeric('123456'), 'Should return true if is a number')
t.notOk(Regex.testNumeric('a12345'), 'Should return false if is not a number')
t.notOk(Regex.testNumeric('ABC123'), 'Should return false if is not a number')
t.ok(Regex.testAlphanumeric('123ABC'), 'Should return true if is alphanumeric')
t.ok(Regex.testAlphanumeric('123456'), 'Should return true if is alphanumeric')
t.notOk(Regex.testAlphanumeric('ABCabc'), 'Should return false if is not alphanumeric')
t.ok(Regex.testKanji('乂ЁЖぞβ'), 'Should return true if is a kanji')
t.notOk(Regex.testKanji('皿a晒三A'), 'Should return false if is not a kanji')
t.notOk(Regex.testKanji('123456'), 'Should return false if is not a kanji')
t.notOk(Regex.testKanji('ABC123'), 'Should return false if is not a kanji')
t.notOk(Regex.testKanji('abcdef'), 'Should return false if is not a kanji')
t.end()
})

View file

@ -0,0 +1,207 @@
var test = require('tap').test
var Mode = require('core/mode')
var Segments = require('core/segments')
var NumericData = require('core/numeric-data')
var AlphanumericData = require('core/alphanumeric-data')
var ByteData = require('core/byte-data')
var toSJIS = require('helper/to-sjis')
var Utils = require('core/utils')
var testData = [
{
input: '1A1',
result: [{data: '1A1', mode: Mode.ALPHANUMERIC}]
},
{
input: 'a-1-b-2?',
result: [{data: 'a-1-b-2?', mode: Mode.BYTE}]
},
{
input: 'AB123456CDF',
result: [{data: 'AB123456CDF', mode: Mode.ALPHANUMERIC}]
},
{
input: 'aABC000000-?-----a',
result: [
{data: 'aABC', mode: Mode.BYTE},
{data: '000000', mode: Mode.NUMERIC},
{data: '-?-----a', mode: Mode.BYTE}
]
},
{
input: 'aABC000000A?',
result: [
{data: 'aABC', mode: Mode.BYTE},
{data: '000000', mode: Mode.NUMERIC},
{data: 'A?', mode: Mode.BYTE}
]
},
{
input: 'a1234ABCDEF?',
result: [
{data: 'a', mode: Mode.BYTE},
{data: '1234ABCDEF', mode: Mode.ALPHANUMERIC},
{data: '?', mode: Mode.BYTE}
]
},
{
input: '12345A12345',
result: [
{data: '12345A12345', mode: Mode.ALPHANUMERIC}
]
},
{
input: 'aABCDEFGHILMNa',
result: [
{data: 'a', mode: Mode.BYTE},
{data: 'ABCDEFGHILMN', mode: Mode.ALPHANUMERIC},
{data: 'a', mode: Mode.BYTE}
]
},
{
input: 'Aa12345',
result: [
{data: 'Aa', mode: Mode.BYTE},
{data: '12345', mode: Mode.NUMERIC}
]
},
{
input: 'a1A2B3C4D5E6F4G7',
result: [
{data: 'a', mode: Mode.BYTE},
{data: '1A2B3C4D5E6F4G7', mode: Mode.ALPHANUMERIC}
]
},
{
input: '123456789QWERTYUIOPASD',
result: [
{data: '123456789', mode: Mode.NUMERIC},
{data: 'QWERTYUIOPASD', mode: Mode.ALPHANUMERIC}
]
},
{
input: 'QWERTYUIOPASD123456789',
result: [
{data: 'QWERTYUIOPASD', mode: Mode.ALPHANUMERIC},
{data: '123456789', mode: Mode.NUMERIC}
]
},
{
input: 'ABCDEF123456a',
result: [
{data: 'ABCDEF123456', mode: Mode.ALPHANUMERIC},
{data: 'a', mode: Mode.BYTE}
]
},
{
input: 'abcdefABCDEF',
result: [
{data: 'abcdef', mode: Mode.BYTE},
{data: 'ABCDEF', mode: Mode.ALPHANUMERIC}
]
},
{
input: 'a123456ABCDEa',
result: [
{data: 'a', mode: Mode.BYTE},
{data: '123456ABCDE', mode: Mode.ALPHANUMERIC},
{data: 'a', mode: Mode.BYTE}
]
},
{
input: 'AAAAA12345678?A1A',
result: [
{data: 'AAAAA', mode: Mode.ALPHANUMERIC},
{data: '12345678', mode: Mode.NUMERIC},
{data: '?A1A', mode: Mode.BYTE}
]
},
{
input: 'Aaa',
result: [{data: 'Aaa', mode: Mode.BYTE}]
},
{
input: 'Aa12345A',
result: [
{data: 'Aa', mode: Mode.BYTE},
{data: '12345A', mode: Mode.ALPHANUMERIC}
]
}
]
var kanjiTestData = [
{
input: '乂ЁЖぞβ',
result: [{data: '乂ЁЖぞβ', mode: Mode.KANJI}]
},
{
input: 'ΑΒΓψωЮЯабв',
result: [{data: 'ΑΒΓψωЮЯабв', mode: Mode.KANJI}]
},
{
input: '皿a晒三',
result: [
{data: '皿a', mode: Mode.BYTE},
{data: '晒三', mode: Mode.KANJI}
]
}
]
testData = testData.concat(kanjiTestData)
test('Segments from array', function (t) {
t.deepEqual(Segments.fromArray(['abcdef', '12345']),
[new ByteData('abcdef'), new NumericData('12345')],
'Should return correct segment from array of string')
t.deepEqual(Segments.fromArray(
[{ data: 'abcdef', mode: Mode.BYTE }, { data: '12345', mode: Mode.NUMERIC }]),
[new ByteData('abcdef'), new NumericData('12345')],
'Should return correct segment from array of objects')
t.deepEqual(Segments.fromArray(
[{ data: 'abcdef', mode: 'byte' }, { data: '12345', mode: 'numeric' }]),
[new ByteData('abcdef'), new NumericData('12345')],
'Should return correct segment from array of objects if mode is specified as string')
t.deepEqual(Segments.fromArray(
[{ data: 'abcdef' }, { data: '12345' }]),
[new ByteData('abcdef'), new NumericData('12345')],
'Should return correct segment from array of objects if mode is not specified')
t.deepEqual(Segments.fromArray([{}]), [],
'Should return an empty array')
t.throw(function () { Segments.fromArray([{ data: 'ABCDE', mode: 'numeric' }]) },
'Should throw if segment cannot be encoded with specified mode')
t.deepEqual(Segments.fromArray(
[{ data: '', mode: Mode.KANJI }]), [new ByteData('')],
'Should use Byte mode if kanji support is disabled')
t.end()
})
test('Segments optimization', function (t) {
t.deepEqual(Segments.fromString('乂ЁЖ', 1), Segments.fromArray([{ data: '乂ЁЖ', mode: 'byte' }]),
'Should use Byte mode if Kanji support is disabled')
Utils.setToSJISFunction(toSJIS)
testData.forEach(function (data) {
t.deepEqual(Segments.fromString(data.input, 1), Segments.fromArray(data.result))
})
t.end()
})
test('Segments raw split', function (t) {
var splitted = [
new ByteData('abc'),
new AlphanumericData('DEF'),
new NumericData('123')
]
t.deepEqual(Segments.rawSplit('abcDEF123'), splitted)
t.end()
})

View file

@ -1,5 +1,5 @@
var test = require('tap').test
var utils = require('core/utils')
var Utils = require('core/utils')
/**
* QR Code sizes. Each element refers to a version
@ -14,12 +14,12 @@ var EXPECTED_SYMBOL_SIZES = [
153, 157, 161, 165, 169, 173, 177]
test('Symbol size', function (t) {
t.throws(function () { utils.getSymbolSize() }, 'Should throw if version is undefined')
t.throws(function () { utils.getSymbolSize(0) }, 'Should throw if version is not in range')
t.throws(function () { utils.getSymbolSize(41) }, 'Should throw if version is not in range')
t.throws(function () { Utils.getSymbolSize() }, 'Should throw if version is undefined')
t.throws(function () { Utils.getSymbolSize(0) }, 'Should throw if version is not in range')
t.throws(function () { Utils.getSymbolSize(41) }, 'Should throw if version is not in range')
for (var i = 1; i <= 40; i++) {
t.equal(utils.getSymbolSize(i), EXPECTED_SYMBOL_SIZES[i - 1], 'Should return correct symbol size')
t.equal(Utils.getSymbolSize(i), EXPECTED_SYMBOL_SIZES[i - 1], 'Should return correct symbol size')
}
t.end()
@ -27,8 +27,47 @@ test('Symbol size', function (t) {
test('Symbol codewords', function (t) {
for (var i = 1; i <= 40; i++) {
t.ok(utils.getSymbolTotalCodewords(i), 'Should return positive number')
t.ok(Utils.getSymbolTotalCodewords(i), 'Should return positive number')
}
t.end()
})
test('BCH Digit', function (t) {
var testData = [
{ data: 0, bch: 0 },
{ data: 1, bch: 1 },
{ data: 2, bch: 2 },
{ data: 4, bch: 3 },
{ data: 8, bch: 4 }
]
testData.forEach(function (d) {
t.equal(Utils.getBCHDigit(d.data), d.bch,
'Should return correct BCH for value: ' + d.data)
})
t.end()
})
test('Set/Get SJIS function', function (t) {
t.throw(function () { Utils.setToSJISFunction() },
'Should throw if param is not a function')
t.notOk(Utils.isKanjiModeEnabled(),
'Kanji mode should be disabled if "toSJIS" function is not set')
var testFunc = function testFunc (c) {
return 'test_' + c
}
Utils.setToSJISFunction(testFunc)
t.ok(Utils.isKanjiModeEnabled(),
'Kanji mode should be enabled if "toSJIS" function is set')
t.equal(Utils.toSJIS('a'), 'test_a',
'Should correctly call "toSJIS" function')
t.end()
})

View file

@ -1,49 +1,64 @@
var test = require('tap').test
var Version = require('core/version')
var ECLevel = require('core/error-correction-level')
var Mode = require('core/mode')
var NumericData = require('core/numeric-data')
var AlphanumericData = require('core/alphanumeric-data')
var KanjiData = require('core/kanji-data')
var ByteData = require('core/byte-data')
var EXPECTED_CAPACITY = [
[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]
var EC_LEVELS = [ECLevel.L, ECLevel.M, ECLevel.Q, ECLevel.H]
var EXPECTED_NUMERIC_CAPACITY = [
[41, 34, 27, 17], [77, 63, 48, 34], [127, 101, 77, 58], [187, 149, 111, 82],
[255, 202, 144, 106], [322, 255, 178, 139], [370, 293, 207, 154], [461, 365, 259, 202],
[552, 432, 312, 235], [652, 513, 364, 288], [772, 604, 427, 331], [883, 691, 489, 374],
[1022, 796, 580, 427], [1101, 871, 621, 468], [1250, 991, 703, 530], [1408, 1082, 775, 602],
[1548, 1212, 876, 674], [1725, 1346, 948, 746], [1903, 1500, 1063, 813], [2061, 1600, 1159, 919],
[2232, 1708, 1224, 969], [2409, 1872, 1358, 1056], [2620, 2059, 1468, 1108], [2812, 2188, 1588, 1228],
[3057, 2395, 1718, 1286], [3283, 2544, 1804, 1425], [3517, 2701, 1933, 1501], [3669, 2857, 2085, 1581],
[3909, 3035, 2181, 1677], [4158, 3289, 2358, 1782], [4417, 3486, 2473, 1897], [4686, 3693, 2670, 2022],
[4965, 3909, 2805, 2157], [5253, 4134, 2949, 2301], [5529, 4343, 3081, 2361], [5836, 4588, 3244, 2524],
[6153, 4775, 3417, 2625], [6479, 5039, 3599, 2735], [6743, 5313, 3791, 2927], [7089, 5596, 3993, 3057]
]
var EXPECTED_ALPHANUMERIC_CAPACITY = [
[25, 20, 16, 10], [47, 38, 29, 20], [77, 61, 47, 35], [114, 90, 67, 50],
[154, 122, 87, 64], [195, 154, 108, 84], [224, 178, 125, 93], [279, 221, 157, 122],
[335, 262, 189, 143], [395, 311, 221, 174], [468, 366, 259, 200], [535, 419, 296, 227],
[619, 483, 352, 259], [667, 528, 376, 283], [758, 600, 426, 321], [854, 656, 470, 365],
[938, 734, 531, 408], [1046, 816, 574, 452], [1153, 909, 644, 493], [1249, 970, 702, 557],
[1352, 1035, 742, 587], [1460, 1134, 823, 640], [1588, 1248, 890, 672], [1704, 1326, 963, 744],
[1853, 1451, 1041, 779], [1990, 1542, 1094, 864], [2132, 1637, 1172, 910], [2223, 1732, 1263, 958],
[2369, 1839, 1322, 1016], [2520, 1994, 1429, 1080], [2677, 2113, 1499, 1150], [2840, 2238, 1618, 1226],
[3009, 2369, 1700, 1307], [3183, 2506, 1787, 1394], [3351, 2632, 1867, 1431], [3537, 2780, 1966, 1530],
[3729, 2894, 2071, 1591], [3927, 3054, 2181, 1658], [4087, 3220, 2298, 1774], [4296, 3391, 2420, 1852]
]
var EXPECTED_KANJI_CAPACITY = [
[10, 8, 7, 4], [20, 16, 12, 8], [32, 26, 20, 15], [48, 38, 28, 21],
[65, 52, 37, 27], [82, 65, 45, 36], [95, 75, 53, 39], [118, 93, 66, 52],
[141, 111, 80, 60], [167, 131, 93, 74], [198, 155, 109, 85], [226, 177, 125, 96],
[262, 204, 149, 109], [282, 223, 159, 120], [320, 254, 180, 136], [361, 277, 198, 154],
[397, 310, 224, 173], [442, 345, 243, 191], [488, 384, 272, 208], [528, 410, 297, 235],
[572, 438, 314, 248], [618, 480, 348, 270], [672, 528, 376, 284], [721, 561, 407, 315],
[784, 614, 440, 330], [842, 652, 462, 365], [902, 692, 496, 385], [940, 732, 534, 405],
[1002, 778, 559, 430], [1066, 843, 604, 457], [1132, 894, 634, 486], [1201, 947, 684, 518],
[1273, 1002, 719, 553], [1347, 1060, 756, 590], [1417, 1113, 790, 605], [1496, 1176, 832, 647],
[1577, 1224, 876, 673], [1661, 1292, 923, 701], [1729, 1362, 972, 750], [1817, 1435, 1024, 784]
]
var EXPECTED_BYTE_CAPACITY = [
[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]
]
var EXPECTED_VERSION_BITS = [
@ -55,10 +70,19 @@ var EXPECTED_VERSION_BITS = [
]
test('Version validity', function (t) {
t.notOk(Version.isValidVersion(), 'Should return false if no input')
t.notOk(Version.isValidVersion(''), 'Should return false if version is not a number')
t.notOk(Version.isValidVersion(0), 'Should return false if version is not in range')
t.notOk(Version.isValidVersion(41), 'Should return false if version is not in range')
t.notOk(Version.isValid(), 'Should return false if no input')
t.notOk(Version.isValid(''), 'Should return false if version is not a number')
t.notOk(Version.isValid(0), 'Should return false if version is not in range')
t.notOk(Version.isValid(41), 'Should return false if version is not in range')
t.end()
})
test('Version from value', function (t) {
t.equal(Version.from(5), 5, 'Should return correct version from a number')
t.equal(Version.from('5'), 5, 'Should return correct version from a string')
t.equal(Version.from(0, 1), 1, 'Should return default value if version is invalid')
t.equal(Version.from(null, 1), 1, 'Should return default value if version is undefined')
t.end()
})
@ -69,53 +93,74 @@ test('Version capacity', function (t) {
t.throws(function () { Version.getCapacity(0) }, 'Should throw if version is not in range')
t.throws(function () { Version.getCapacity(41) }, 'Should throw if version is not in range')
for (var i = 1; i <= 40; i++) {
t.equal(Version.getCapacity(i, ECLevel.L), EXPECTED_CAPACITY[i - 1][0], 'Should return correct capacity')
t.equal(Version.getCapacity(i, ECLevel.M), EXPECTED_CAPACITY[i - 1][1], 'Should return correct capacity')
t.equal(Version.getCapacity(i, ECLevel.Q), EXPECTED_CAPACITY[i - 1][2], 'Should return correct capacity')
t.equal(Version.getCapacity(i, ECLevel.H), EXPECTED_CAPACITY[i - 1][3], 'Should return correct capacity')
for (var l = 0; l < EC_LEVELS.length; l++) {
for (var i = 1; i <= 40; i++) {
t.equal(Version.getCapacity(i, EC_LEVELS[l], Mode.NUMERIC),
EXPECTED_NUMERIC_CAPACITY[i - 1][l], 'Should return correct numeric mode capacity')
t.equal(Version.getCapacity(i, EC_LEVELS[l], Mode.ALPHANUMERIC),
EXPECTED_ALPHANUMERIC_CAPACITY[i - 1][l], 'Should return correct alphanumeric mode capacity')
t.equal(Version.getCapacity(i, EC_LEVELS[l], Mode.KANJI),
EXPECTED_KANJI_CAPACITY[i - 1][l], 'Should return correct kanji mode capacity')
t.equal(Version.getCapacity(i, EC_LEVELS[l], Mode.BYTE),
EXPECTED_BYTE_CAPACITY[i - 1][l], 'Should return correct byte mode capacity')
t.equal(Version.getCapacity(i, EC_LEVELS[l]),
EXPECTED_BYTE_CAPACITY[i - 1][l], 'Should return correct byte mode capacity')
}
}
t.end()
})
test('Version best match', function (t) {
var levels = [ECLevel.L, ECLevel.M, ECLevel.Q, ECLevel.H]
function testBestVersionForCapacity (expectedCapacity, DataCtor) {
for (var v = 0; v < 40; v++) {
for (var l = 0; l < EC_LEVELS.length; l++) {
var capacity = expectedCapacity[v][l]
var data = new DataCtor(new Array(capacity + 1).join('-'))
for (var v = 0; v < 40; v++) {
for (var l = 0; l < levels.length; l++) {
var capacity = EXPECTED_CAPACITY[v][l]
var dataArray = new Array(capacity)
var dataString = new Array(capacity + 1).join(' ')
var dataBuffer = new Buffer(capacity)
var byteData = new ByteData(new Array(capacity))
t.equal(Version.getBestVersionForData(data, EC_LEVELS[l]), v + 1, 'Should return best version')
t.equal(Version.getBestVersionForData([data], EC_LEVELS[l]), v + 1, 'Should return best version')
t.equal(Version.getBestVersionForData(dataArray, levels[l]), v + 1, 'Should return best version')
t.equal(Version.getBestVersionForData(dataString, levels[l]), v + 1, 'Should return best version')
t.equal(Version.getBestVersionForData(dataBuffer, levels[l]), v + 1, 'Should return best version')
t.equal(Version.getBestVersionForData(byteData, levels[l]), v + 1, 'Should return best version')
if (l === 3) {
t.deepEqual(Version.getBestVersionForData(dataArray), v + 1, 'Should return best version for ECLevel.H if error level is undefined')
t.deepEqual(Version.getBestVersionForData(dataString), v + 1, 'Should return best version for ECLevel.H if error level is undefined')
t.deepEqual(Version.getBestVersionForData(dataBuffer), v + 1, 'Should return best version for ECLevel.H if error level is undefined')
t.deepEqual(Version.getBestVersionForData(byteData), v + 1, 'Should return best version for ECLevel.H if error level is undefined')
if (l === 1) {
t.equal(Version.getBestVersionForData(data, null), v + 1,
'Should return best version for ECLevel.M if error level is undefined')
t.equal(Version.getBestVersionForData([data], null), v + 1,
'Should return best version for ECLevel.M if error level is undefined')
}
}
}
for (var i = 0; i < EC_LEVELS.length; i++) {
var exceededCapacity = expectedCapacity[39][i] + 1
var tooBigData = new DataCtor(new Array(exceededCapacity + 1).join('-'))
var tooBigDataArray = [
new DataCtor(new Array(Math.floor(exceededCapacity / 2)).join('-')),
new DataCtor(new Array(Math.floor(exceededCapacity / 2) + 1).join('-'))
]
t.notOk(Version.getBestVersionForData(tooBigData, EC_LEVELS[i]),
'Should return undefined if data is too big')
t.notOk(Version.getBestVersionForData([tooBigData], EC_LEVELS[i]),
'Should return undefined if data is too big')
t.notOk(Version.getBestVersionForData(tooBigDataArray, EC_LEVELS[i]),
'Should return undefined if data is too big')
}
}
for (var i = 0; i < levels.length; i++) {
var exceededCapacity = EXPECTED_CAPACITY[39][i] + 1
var tooBigDataArray = new Array(exceededCapacity)
var tooBigDataString = new Array(exceededCapacity + 1).join('-')
var tooBigDataBuffer = new Buffer(exceededCapacity)
var tooBigByteData = new ByteData(new Array(exceededCapacity))
testBestVersionForCapacity(EXPECTED_NUMERIC_CAPACITY, NumericData)
testBestVersionForCapacity(EXPECTED_ALPHANUMERIC_CAPACITY, AlphanumericData)
testBestVersionForCapacity(EXPECTED_KANJI_CAPACITY, KanjiData)
testBestVersionForCapacity(EXPECTED_BYTE_CAPACITY, ByteData)
t.notOk(Version.getBestVersionForData(tooBigDataArray, levels[i]), 'Should return undefined if data is too big')
t.notOk(Version.getBestVersionForData(tooBigDataString, levels[i]), 'Should return undefined if data is too big')
t.notOk(Version.getBestVersionForData(tooBigDataBuffer, levels[i]), 'Should return undefined if data is too big')
t.notOk(Version.getBestVersionForData(tooBigByteData, levels[i]), 'Should return undefined if data is too big')
}
t.ok(Version.getBestVersionForData([new ByteData('abc'), new NumericData('1234')]),
'Should return a version number if input array is valid')
t.equal(Version.getBestVersionForData([]), 1,
'Should return 1 if array is empty')
t.end()
})
@ -124,7 +169,8 @@ test('Version encoded info', function (t) {
var v
for (v = 0; v < 7; v++) {
t.throws(function () { Version.getEncodedBits(v) }, 'Should throw if version is invalid or less than 7')
t.throws(function () { Version.getEncodedBits(v) },
'Should throw if version is invalid or less than 7')
}
for (v = 7; v <= 40; v++) {

View file

@ -0,0 +1,18 @@
var test = require('tap').test
var toSJIS = require('helper/to-sjis')
test('SJIS from char', function (t) {
t.notOk(toSJIS(''),
'Should return undefined if character is invalid')
t.notOk(toSJIS('A'),
'Should return undefined if character is not a kanji')
t.equal(toSJIS('襦'), 0xe640,
'Should return correct SJIS value')
t.equal(toSJIS('¬'), 0x81ca,
'Should return correct SJIS value')
t.end()
})