dsh-plugin-console-oh 0.0.0-stage → 0.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/README.md +86 -2
  2. package/cordis.patch.yml +16 -0
  3. package/lib/client.js +451 -0
  4. package/lib/index.js +1414 -0
  5. package/lib/server.mjs +718 -0
  6. package/lib/tunnel.mjs +238 -0
  7. package/lib/vendor/README.md +11 -0
  8. package/lib/vendor/dijkstrajs/LICENSE.md +19 -0
  9. package/lib/vendor/dijkstrajs/index.js +165 -0
  10. package/lib/vendor/dijkstrajs/package.json +5 -0
  11. package/lib/vendor/qrcode/LICENSE +10 -0
  12. package/lib/vendor/qrcode/core/alignment-pattern.js +83 -0
  13. package/lib/vendor/qrcode/core/alphanumeric-data.js +59 -0
  14. package/lib/vendor/qrcode/core/bit-buffer.js +37 -0
  15. package/lib/vendor/qrcode/core/bit-matrix.js +65 -0
  16. package/lib/vendor/qrcode/core/byte-data.js +30 -0
  17. package/lib/vendor/qrcode/core/error-correction-code.js +135 -0
  18. package/lib/vendor/qrcode/core/error-correction-level.js +50 -0
  19. package/lib/vendor/qrcode/core/finder-pattern.js +22 -0
  20. package/lib/vendor/qrcode/core/format-info.js +29 -0
  21. package/lib/vendor/qrcode/core/galois-field.js +69 -0
  22. package/lib/vendor/qrcode/core/kanji-data.js +54 -0
  23. package/lib/vendor/qrcode/core/mask-pattern.js +234 -0
  24. package/lib/vendor/qrcode/core/mode.js +167 -0
  25. package/lib/vendor/qrcode/core/numeric-data.js +43 -0
  26. package/lib/vendor/qrcode/core/polynomial.js +62 -0
  27. package/lib/vendor/qrcode/core/qrcode.js +495 -0
  28. package/lib/vendor/qrcode/core/reed-solomon-encoder.js +56 -0
  29. package/lib/vendor/qrcode/core/regex.js +31 -0
  30. package/lib/vendor/qrcode/core/segments.js +330 -0
  31. package/lib/vendor/qrcode/core/utils.js +63 -0
  32. package/lib/vendor/qrcode/core/version-check.js +9 -0
  33. package/lib/vendor/qrcode/core/version.js +163 -0
  34. package/lib/vendor/qrcode/index.js +20 -0
  35. package/lib/vendor/qrcode/package.json +5 -0
  36. package/lib/vendor/qrcode/renderer/svg-tag.js +81 -0
  37. package/lib/vendor/qrcode/renderer/utils.js +99 -0
  38. package/package.json +64 -4
package/lib/tunnel.mjs ADDED
@@ -0,0 +1,238 @@
1
+ // cloudflared 隧道管理:缺失时自动下载,跑起来后从日志里抠公网地址。
2
+ // 不依赖 cloudflared 的配置文件,用官方 quick tunnel(trycloudflare.com)。
3
+ import { spawn, spawnSync } from 'node:child_process'
4
+ import fs from 'node:fs'
5
+ import path from 'node:path'
6
+
7
+ const UPSTREAM = 'https://github.com/cloudflare/cloudflared/releases/latest/download/'
8
+ // 校园网/国内网络经常直连不通 GitHub,按顺序换镜像试
9
+ const MIRRORS = [
10
+ '',
11
+ 'https://gh-proxy.com/',
12
+ 'https://ghfast.top/'
13
+ ]
14
+ const MIN_BYTES = 8 * 1024 * 1024
15
+
16
+ // 各平台校验:Windows 验 Authenticode(签名者 Cloudflare, Inc.),
17
+ // macOS 验 Apple Developer ID 签名(codesign,同样认 Cloudflare),
18
+ // Linux 没有统一签名机制,只靠 HTTPS 直连官方 release(走镜像时无本地校验,README 有说明)。
19
+ // 这是唯一从外部取可执行文件的地方,验不过就删掉、拒绝启动。
20
+ export function verifyBin(bin) {
21
+ if (process.platform === 'win32') {
22
+ const script = [
23
+ '$s = Get-AuthenticodeSignature -LiteralPath $env:DCO_BIN',
24
+ "if ($s.Status -eq 'Valid' -and $s.SignerCertificate.Subject -match 'Cloudflare') { 'OK' }",
25
+ "else { 'BAD ' + $s.Status + ' | ' + $s.SignerCertificate.Subject }"
26
+ ].join('; ')
27
+ let r
28
+ try {
29
+ r = spawnSync('powershell', ['-NoProfile', '-NonInteractive', '-Command', script], {
30
+ env: Object.assign({}, process.env, { DCO_BIN: bin }),
31
+ encoding: 'utf8',
32
+ timeout: 20000,
33
+ windowsHide: true
34
+ })
35
+ } catch (e) {
36
+ return { ok: false, reason: '签名校验没跑起来:' + ((e && e.message) || e) }
37
+ }
38
+ const out = String((r && r.stdout) || '').trim()
39
+ if (out === 'OK') return { ok: true, reason: '' }
40
+ return { ok: false, reason: out || ('校验无输出,退出码 ' + (r && r.status)) }
41
+ }
42
+ if (process.platform === 'darwin') {
43
+ let r
44
+ try {
45
+ r = spawnSync('codesign', ['--verify', '--strict', bin], { timeout: 20000 })
46
+ } catch (e) {
47
+ return { ok: false, reason: 'codesign 没跑起来:' + ((e && e.message) || e) }
48
+ }
49
+ if ((r.status || 0) !== 0) {
50
+ return { ok: false, reason: (r.stderr && String(r.stderr).trim()) || 'codesign 校验失败(exit ' + r.status + ')' }
51
+ }
52
+ const d = spawnSync('codesign', ['--display', '--verbose=2', bin], { timeout: 20000 })
53
+ const info = String((d.stderr || d.stdout) || '')
54
+ if (/Cloudflare/i.test(info)) return { ok: true, reason: '' }
55
+ return { ok: false, reason: '签名授权方不是 Cloudflare' }
56
+ }
57
+ return { ok: true, reason: '' }
58
+ }
59
+
60
+ // 非 Windows 统一叫 cloudflared:与官方 tgz 内文件名、brew/系统安装名一致,PATH 查找也能命中
61
+ const BIN_NAME = process.platform === 'win32' ? 'cloudflared.exe' : 'cloudflared'
62
+
63
+ export function assetName() {
64
+ // Windows 恒用 amd64(ARM Windows 可跑 x64 模拟);darwin/linux 按机器架构取官方资产
65
+ if (process.platform === 'win32') return 'cloudflared-windows-amd64.exe'
66
+ const arm = process.arch === 'arm64'
67
+ if (process.platform === 'darwin') return arm ? 'cloudflared-darwin-arm64.tgz' : 'cloudflared-darwin-amd64.tgz'
68
+ return arm ? 'cloudflared-linux-arm64' : 'cloudflared-linux-amd64'
69
+ }
70
+
71
+ // darwin 官方资产是 .tgz(内含单个文件 cloudflared);三大平台都有 tar(macOS/Linux 原生,Windows 10+ 内置)
72
+ function extractTgz(tgzPath, destDir) {
73
+ const r = spawnSync('tar', ['-xzf', tgzPath, '-C', destDir], { timeout: 60000, windowsHide: true })
74
+ if (r.error || (r.status !== 0 && r.status !== null)) {
75
+ const detail = (r.stderr && String(r.stderr).trim()) || (r.error && r.error.message) || 'exit ' + r.status
76
+ throw new Error('tgz 解包失败:' + detail)
77
+ }
78
+ const out = path.join(destDir, 'cloudflared')
79
+ if (!fs.existsSync(out)) throw new Error('tgz 解包后没找到 cloudflared')
80
+ return out
81
+ }
82
+
83
+ export class CloudflaredTunnel {
84
+ constructor(opts) {
85
+ this.dir = opts.dir
86
+ this.port = () => opts.port()
87
+ this.log = opts.log || (() => {})
88
+ this.state = 'idle'
89
+ this.url = ''
90
+ this.error = ''
91
+ this.child = null
92
+ this.since = 0
93
+ this.manualBin = opts.binPath ? String(opts.binPath) : ''
94
+ this.verified = false
95
+ this.downloadBase = opts.downloadBase ? String(opts.downloadBase) : ''
96
+ }
97
+
98
+ binPath() {
99
+ if (this.manualBin && fs.existsSync(this.manualBin)) return this.manualBin
100
+ const local = path.join(this.dir, BIN_NAME)
101
+ if (fs.existsSync(local)) return local
102
+ // PATH 里已有的直接用
103
+ const dirs = String(process.env.PATH || '').split(path.delimiter)
104
+ for (const d of dirs) {
105
+ if (!d) continue
106
+ const p = path.join(d, BIN_NAME)
107
+ try { if (fs.existsSync(p)) return p } catch (_) { }
108
+ }
109
+ return ''
110
+ }
111
+
112
+ status() {
113
+ return {
114
+ state: this.state,
115
+ url: this.url,
116
+ error: this.error,
117
+ since: this.since,
118
+ bin: this.binPath() ? 'ok' : 'missing',
119
+ provider: 'cloudflared'
120
+ }
121
+ }
122
+
123
+ async ensureBinary() {
124
+ const have = this.binPath()
125
+ if (have) return have
126
+ fs.mkdirSync(this.dir, { recursive: true })
127
+ const asset = assetName()
128
+ const tgz = asset.endsWith('.tgz')
129
+ const dest = path.join(this.dir, tgz ? BIN_NAME + '.tgz' : BIN_NAME)
130
+ this.state = 'downloading'
131
+ this.error = ''
132
+
133
+ const bases = this.downloadBase !== '' ? [this.downloadBase] : MIRRORS
134
+ const errors = []
135
+ for (const base of bases) {
136
+ const url = base === '' ? UPSTREAM + asset : base + UPSTREAM + asset
137
+ try {
138
+ this.log('[tunnel] 下载 cloudflared:' + url)
139
+ const res = await fetch(url, { redirect: 'follow' })
140
+ if (!res.ok) throw new Error('HTTP ' + res.status)
141
+ const buf = Buffer.from(await res.arrayBuffer())
142
+ if (buf.length < MIN_BYTES) throw new Error('文件不完整(' + buf.length + ' 字节)')
143
+ fs.writeFileSync(dest, buf)
144
+ let bin = dest
145
+ if (tgz) {
146
+ bin = extractTgz(dest, this.dir)
147
+ try { fs.unlinkSync(dest) } catch (_) { }
148
+ }
149
+ try { fs.chmodSync(bin, 0o755) } catch (_) { }
150
+ const sig = verifyBin(bin)
151
+ if (!sig.ok) {
152
+ try { fs.unlinkSync(bin) } catch (_) { }
153
+ throw new Error('签名校验不通过(' + sig.reason + '),已删除这个文件')
154
+ }
155
+ this.verified = true
156
+ this.log('[tunnel] cloudflared 就位(' + Math.round(buf.length / 1048576) + 'MB,签名已校验)')
157
+ return bin
158
+ } catch (e) {
159
+ const msg = String((e && e.message) || e)
160
+ errors.push((base === '' ? 'github' : base.replace(/^https?:\/\//, '').replace(/\/$/, '')) + ': ' + msg)
161
+ this.log('[tunnel] 这一路没成 —— ' + msg)
162
+ }
163
+ }
164
+ throw new Error('自动下载失败。可以手动下载 ' + asset + ' 解压放到 ' + this.dir + ',或装好后在配置里写 cloudflaredPath。(' + errors.join(';') + ')')
165
+ }
166
+
167
+ async start() {
168
+ if (this.state === 'up' || this.state === 'starting') return this.status()
169
+ this.error = ''
170
+ this.since = Date.now()
171
+ let bin = ''
172
+ try { bin = await this.ensureBinary() } catch (e) {
173
+ this.state = 'failed'
174
+ this.error = String((e && e.message) || e)
175
+ this.log('[tunnel] ' + this.error)
176
+ return this.status()
177
+ }
178
+
179
+ if (!this.verified) {
180
+ const sig = verifyBin(bin)
181
+ if (!sig.ok) {
182
+ this.state = 'failed'
183
+ this.error = '云隧道程序签名校验不通过(' + sig.reason + '),已拒绝启动。删掉 ' + bin + ' 重新下载,或自己从官网放一份。'
184
+ this.log('[tunnel] ' + this.error)
185
+ return this.status()
186
+ }
187
+ this.verified = true
188
+ }
189
+
190
+ this.state = 'starting'
191
+ const args = ['tunnel', '--url', 'http://127.0.0.1:' + this.port(), '--no-autoupdate', '--loglevel', 'info']
192
+ this.log('[tunnel] ' + bin + ' ' + args.join(' '))
193
+ let child
194
+ try {
195
+ child = spawn(bin, args, { windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] })
196
+ } catch (e) {
197
+ this.state = 'failed'
198
+ this.error = 'cloudflared 启动失败:' + ((e && e.message) || e)
199
+ return this.status()
200
+ }
201
+ this.child = child
202
+ const onData = (buf) => {
203
+ const text = String(buf)
204
+ const hit = text.match(/https:\/\/[a-z0-9][a-z0-9-]*\.trycloudflare\.com/i)
205
+ if (hit && this.url !== hit[0]) {
206
+ this.url = hit[0]
207
+ this.state = 'up'
208
+ this.error = ''
209
+ this.log('[tunnel] 公网地址就绪:' + this.url)
210
+ }
211
+ if (/ERR|error|failed/i.test(text) && this.state === 'starting') {
212
+ const line = text.split('\n').map((s) => s.trim()).filter(Boolean).pop() || ''
213
+ if (line) this.error = line.slice(0, 300)
214
+ }
215
+ }
216
+ child.stdout.on('data', onData)
217
+ child.stderr.on('data', onData)
218
+ child.on('exit', (code) => {
219
+ this.child = null
220
+ if (this.state !== 'idle') {
221
+ this.state = code === 0 ? 'idle' : 'failed'
222
+ if (code !== 0 && !this.error) this.error = 'cloudflared 退出,代码 ' + code
223
+ this.log('[tunnel] 退出 code=' + code)
224
+ }
225
+ })
226
+ return this.status()
227
+ }
228
+
229
+ stop() {
230
+ this.state = 'idle'
231
+ this.url = ''
232
+ if (this.child) {
233
+ try { this.child.kill() } catch (_) { }
234
+ this.child = null
235
+ }
236
+ return this.status()
237
+ }
238
+ }
@@ -0,0 +1,11 @@
1
+ # vendor/qrcode
2
+
3
+ 从 npm 包 `qrcode@1.5.4` 里拷出来的最小集合,只用于在插件进程内生成配对二维码 SVG。
4
+
5
+ - `qrcode/`:`lib/core/*`、`lib/renderer/svg-tag.js`、`lib/renderer/utils.js`,原样保留
6
+ - `dijkstrajs/`:QR 分段用到的单文件依赖
7
+ - 唯一改动:`core/segments.js` 里的 `require('dijkstrajs')` 改成相对路径
8
+
9
+ 没有拷 png / terminal / cli 渲染器,所以不需要 pngjs、yargs。
10
+
11
+ 许可证见 `qrcode/LICENSE` 与 `dijkstrajs/LICENSE.md`(均 MIT)。
@@ -0,0 +1,19 @@
1
+ ```
2
+ Dijkstra path-finding functions. Adapted from the Dijkstar Python project.
3
+
4
+ Copyright (C) 2008
5
+ Wyatt Baldwin <self@wyattbaldwin.com>
6
+ All rights reserved
7
+
8
+ Licensed under the MIT license.
9
+
10
+ http://www.opensource.org/licenses/mit-license.php
11
+
12
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
13
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
14
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
15
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
16
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
17
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
18
+ THE SOFTWARE.
19
+ ```
@@ -0,0 +1,165 @@
1
+ 'use strict';
2
+
3
+ /******************************************************************************
4
+ * Created 2008-08-19.
5
+ *
6
+ * Dijkstra path-finding functions. Adapted from the Dijkstar Python project.
7
+ *
8
+ * Copyright (C) 2008
9
+ * Wyatt Baldwin <self@wyattbaldwin.com>
10
+ * All rights reserved
11
+ *
12
+ * Licensed under the MIT license.
13
+ *
14
+ * http://www.opensource.org/licenses/mit-license.php
15
+ *
16
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22
+ * THE SOFTWARE.
23
+ *****************************************************************************/
24
+ var dijkstra = {
25
+ single_source_shortest_paths: function(graph, s, d) {
26
+ // Predecessor map for each node that has been encountered.
27
+ // node ID => predecessor node ID
28
+ var predecessors = {};
29
+
30
+ // Costs of shortest paths from s to all nodes encountered.
31
+ // node ID => cost
32
+ var costs = {};
33
+ costs[s] = 0;
34
+
35
+ // Costs of shortest paths from s to all nodes encountered; differs from
36
+ // `costs` in that it provides easy access to the node that currently has
37
+ // the known shortest path from s.
38
+ // XXX: Do we actually need both `costs` and `open`?
39
+ var open = dijkstra.PriorityQueue.make();
40
+ open.push(s, 0);
41
+
42
+ var closest,
43
+ u, v,
44
+ cost_of_s_to_u,
45
+ adjacent_nodes,
46
+ cost_of_e,
47
+ cost_of_s_to_u_plus_cost_of_e,
48
+ cost_of_s_to_v,
49
+ first_visit;
50
+ while (!open.empty()) {
51
+ // In the nodes remaining in graph that have a known cost from s,
52
+ // find the node, u, that currently has the shortest path from s.
53
+ closest = open.pop();
54
+ u = closest.value;
55
+ cost_of_s_to_u = closest.cost;
56
+
57
+ // Get nodes adjacent to u...
58
+ adjacent_nodes = graph[u] || {};
59
+
60
+ // ...and explore the edges that connect u to those nodes, updating
61
+ // the cost of the shortest paths to any or all of those nodes as
62
+ // necessary. v is the node across the current edge from u.
63
+ for (v in adjacent_nodes) {
64
+ if (adjacent_nodes.hasOwnProperty(v)) {
65
+ // Get the cost of the edge running from u to v.
66
+ cost_of_e = adjacent_nodes[v];
67
+
68
+ // Cost of s to u plus the cost of u to v across e--this is *a*
69
+ // cost from s to v that may or may not be less than the current
70
+ // known cost to v.
71
+ cost_of_s_to_u_plus_cost_of_e = cost_of_s_to_u + cost_of_e;
72
+
73
+ // If we haven't visited v yet OR if the current known cost from s to
74
+ // v is greater than the new cost we just found (cost of s to u plus
75
+ // cost of u to v across e), update v's cost in the cost list and
76
+ // update v's predecessor in the predecessor list (it's now u).
77
+ cost_of_s_to_v = costs[v];
78
+ first_visit = (typeof costs[v] === 'undefined');
79
+ if (first_visit || cost_of_s_to_v > cost_of_s_to_u_plus_cost_of_e) {
80
+ costs[v] = cost_of_s_to_u_plus_cost_of_e;
81
+ open.push(v, cost_of_s_to_u_plus_cost_of_e);
82
+ predecessors[v] = u;
83
+ }
84
+ }
85
+ }
86
+ }
87
+
88
+ if (typeof d !== 'undefined' && typeof costs[d] === 'undefined') {
89
+ var msg = ['Could not find a path from ', s, ' to ', d, '.'].join('');
90
+ throw new Error(msg);
91
+ }
92
+
93
+ return predecessors;
94
+ },
95
+
96
+ extract_shortest_path_from_predecessor_list: function(predecessors, d) {
97
+ var nodes = [];
98
+ var u = d;
99
+ var predecessor;
100
+ while (u) {
101
+ nodes.push(u);
102
+ predecessor = predecessors[u];
103
+ u = predecessors[u];
104
+ }
105
+ nodes.reverse();
106
+ return nodes;
107
+ },
108
+
109
+ find_path: function(graph, s, d) {
110
+ var predecessors = dijkstra.single_source_shortest_paths(graph, s, d);
111
+ return dijkstra.extract_shortest_path_from_predecessor_list(
112
+ predecessors, d);
113
+ },
114
+
115
+ /**
116
+ * A very naive priority queue implementation.
117
+ */
118
+ PriorityQueue: {
119
+ make: function (opts) {
120
+ var T = dijkstra.PriorityQueue,
121
+ t = {},
122
+ key;
123
+ opts = opts || {};
124
+ for (key in T) {
125
+ if (T.hasOwnProperty(key)) {
126
+ t[key] = T[key];
127
+ }
128
+ }
129
+ t.queue = [];
130
+ t.sorter = opts.sorter || T.default_sorter;
131
+ return t;
132
+ },
133
+
134
+ default_sorter: function (a, b) {
135
+ return a.cost - b.cost;
136
+ },
137
+
138
+ /**
139
+ * Add a new item to the queue and ensure the highest priority element
140
+ * is at the front of the queue.
141
+ */
142
+ push: function (value, cost) {
143
+ var item = {value: value, cost: cost};
144
+ this.queue.push(item);
145
+ this.queue.sort(this.sorter);
146
+ },
147
+
148
+ /**
149
+ * Return the highest priority element in the queue.
150
+ */
151
+ pop: function () {
152
+ return this.queue.shift();
153
+ },
154
+
155
+ empty: function () {
156
+ return this.queue.length === 0;
157
+ }
158
+ }
159
+ };
160
+
161
+
162
+ // node.js module exports
163
+ if (typeof module !== 'undefined') {
164
+ module.exports = dijkstra;
165
+ }
@@ -0,0 +1,5 @@
1
+ {
2
+ "name": "vendor-dijkstrajs",
3
+ "private": true,
4
+ "type": "commonjs"
5
+ }
@@ -0,0 +1,10 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2012 Ryan Day
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
10
+
@@ -0,0 +1,83 @@
1
+ /**
2
+ * Alignment pattern are fixed reference pattern in defined positions
3
+ * in a matrix symbology, which enables the decode software to re-synchronise
4
+ * the coordinate mapping of the image modules in the event of moderate amounts
5
+ * of distortion of the image.
6
+ *
7
+ * Alignment patterns are present only in QR Code symbols of version 2 or larger
8
+ * and their number depends on the symbol version.
9
+ */
10
+
11
+ const getSymbolSize = require('./utils').getSymbolSize
12
+
13
+ /**
14
+ * Calculate the row/column coordinates of the center module of each alignment pattern
15
+ * for the specified QR Code version.
16
+ *
17
+ * The alignment patterns are positioned symmetrically on either side of the diagonal
18
+ * running from the top left corner of the symbol to the bottom right corner.
19
+ *
20
+ * Since positions are simmetrical only half of the coordinates are returned.
21
+ * Each item of the array will represent in turn the x and y coordinate.
22
+ * @see {@link getPositions}
23
+ *
24
+ * @param {Number} version QR Code version
25
+ * @return {Array} Array of coordinate
26
+ */
27
+ exports.getRowColCoords = function getRowColCoords (version) {
28
+ if (version === 1) return []
29
+
30
+ const posCount = Math.floor(version / 7) + 2
31
+ const size = getSymbolSize(version)
32
+ const intervals = size === 145 ? 26 : Math.ceil((size - 13) / (2 * posCount - 2)) * 2
33
+ const positions = [size - 7] // Last coord is always (size - 7)
34
+
35
+ for (let i = 1; i < posCount - 1; i++) {
36
+ positions[i] = positions[i - 1] - intervals
37
+ }
38
+
39
+ positions.push(6) // First coord is always 6
40
+
41
+ return positions.reverse()
42
+ }
43
+
44
+ /**
45
+ * Returns an array containing the positions of each alignment pattern.
46
+ * Each array's element represent the center point of the pattern as (x, y) coordinates
47
+ *
48
+ * Coordinates are calculated expanding the row/column coordinates returned by {@link getRowColCoords}
49
+ * and filtering out the items that overlaps with finder pattern
50
+ *
51
+ * @example
52
+ * For a Version 7 symbol {@link getRowColCoords} returns values 6, 22 and 38.
53
+ * The alignment patterns, therefore, are to be centered on (row, column)
54
+ * positions (6,22), (22,6), (22,22), (22,38), (38,22), (38,38).
55
+ * Note that the coordinates (6,6), (6,38), (38,6) are occupied by finder patterns
56
+ * and are not therefore used for alignment patterns.
57
+ *
58
+ * let pos = getPositions(7)
59
+ * // [[6,22], [22,6], [22,22], [22,38], [38,22], [38,38]]
60
+ *
61
+ * @param {Number} version QR Code version
62
+ * @return {Array} Array of coordinates
63
+ */
64
+ exports.getPositions = function getPositions (version) {
65
+ const coords = []
66
+ const pos = exports.getRowColCoords(version)
67
+ const posLength = pos.length
68
+
69
+ for (let i = 0; i < posLength; i++) {
70
+ for (let j = 0; j < posLength; j++) {
71
+ // Skip if position is occupied by finder patterns
72
+ if ((i === 0 && j === 0) || // top-left
73
+ (i === 0 && j === posLength - 1) || // bottom-left
74
+ (i === posLength - 1 && j === 0)) { // top-right
75
+ continue
76
+ }
77
+
78
+ coords.push([pos[i], pos[j]])
79
+ }
80
+ }
81
+
82
+ return coords
83
+ }
@@ -0,0 +1,59 @@
1
+ const Mode = require('./mode')
2
+
3
+ /**
4
+ * Array of characters available in alphanumeric mode
5
+ *
6
+ * As per QR Code specification, to each character
7
+ * is assigned a value from 0 to 44 which in this case coincides
8
+ * with the array index
9
+ *
10
+ * @type {Array}
11
+ */
12
+ const ALPHA_NUM_CHARS = [
13
+ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
14
+ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
15
+ 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
16
+ ' ', '$', '%', '*', '+', '-', '.', '/', ':'
17
+ ]
18
+
19
+ function AlphanumericData (data) {
20
+ this.mode = Mode.ALPHANUMERIC
21
+ this.data = data
22
+ }
23
+
24
+ AlphanumericData.getBitsLength = function getBitsLength (length) {
25
+ return 11 * Math.floor(length / 2) + 6 * (length % 2)
26
+ }
27
+
28
+ AlphanumericData.prototype.getLength = function getLength () {
29
+ return this.data.length
30
+ }
31
+
32
+ AlphanumericData.prototype.getBitsLength = function getBitsLength () {
33
+ return AlphanumericData.getBitsLength(this.data.length)
34
+ }
35
+
36
+ AlphanumericData.prototype.write = function write (bitBuffer) {
37
+ let i
38
+
39
+ // Input data characters are divided into groups of two characters
40
+ // and encoded as 11-bit binary codes.
41
+ for (i = 0; i + 2 <= this.data.length; i += 2) {
42
+ // The character value of the first character is multiplied by 45
43
+ let value = ALPHA_NUM_CHARS.indexOf(this.data[i]) * 45
44
+
45
+ // The character value of the second digit is added to the product
46
+ value += ALPHA_NUM_CHARS.indexOf(this.data[i + 1])
47
+
48
+ // The sum is then stored as 11-bit binary number
49
+ bitBuffer.put(value, 11)
50
+ }
51
+
52
+ // If the number of input data characters is not a multiple of two,
53
+ // the character value of the final character is encoded as a 6-bit binary number.
54
+ if (this.data.length % 2) {
55
+ bitBuffer.put(ALPHA_NUM_CHARS.indexOf(this.data[i]), 6)
56
+ }
57
+ }
58
+
59
+ module.exports = AlphanumericData
@@ -0,0 +1,37 @@
1
+ function BitBuffer () {
2
+ this.buffer = []
3
+ this.length = 0
4
+ }
5
+
6
+ BitBuffer.prototype = {
7
+
8
+ get: function (index) {
9
+ const bufIndex = Math.floor(index / 8)
10
+ return ((this.buffer[bufIndex] >>> (7 - index % 8)) & 1) === 1
11
+ },
12
+
13
+ put: function (num, length) {
14
+ for (let i = 0; i < length; i++) {
15
+ this.putBit(((num >>> (length - i - 1)) & 1) === 1)
16
+ }
17
+ },
18
+
19
+ getLengthInBits: function () {
20
+ return this.length
21
+ },
22
+
23
+ putBit: function (bit) {
24
+ const bufIndex = Math.floor(this.length / 8)
25
+ if (this.buffer.length <= bufIndex) {
26
+ this.buffer.push(0)
27
+ }
28
+
29
+ if (bit) {
30
+ this.buffer[bufIndex] |= (0x80 >>> (this.length % 8))
31
+ }
32
+
33
+ this.length++
34
+ }
35
+ }
36
+
37
+ module.exports = BitBuffer