@duke-dsh-plugins/dsh-remote-control 0.0.0-stage → 1.1.3
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.
- package/LICENSE +21 -0
- package/README.md +88 -3
- package/client.js +747 -0
- package/cordis.patch.yml +12 -0
- package/icon.svg +20 -0
- package/index.js +731 -0
- package/lib/config.mjs +270 -0
- package/lib/host-bridge.mjs +2848 -0
- package/lib/images.mjs +458 -0
- package/lib/pairing.mjs +266 -0
- package/lib/protocol.mjs +390 -0
- package/lib/push.mjs +229 -0
- package/lib/qr.mjs +439 -0
- package/lib/relay-client.mjs +741 -0
- package/lib/relay-supervisor.mjs +798 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +75 -6
- package/typert.host.js +243 -0
- package/vendor/relay/server.js +777 -0
package/lib/push.mjs
ADDED
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
// lib/push.mjs — 华为 Push Kit REST 旁路(契约 §6)。
|
|
2
|
+
//
|
|
3
|
+
// 纯 REST、无 SDK:
|
|
4
|
+
// 1. POST https://oauth2.cloud.huawei.com/oauth2/v1/token
|
|
5
|
+
// (grant_type=client_credentials&client_id&client_secret)
|
|
6
|
+
// → access_token,缓存至过期前 60s。
|
|
7
|
+
// 2. POST https://push-api.cloud.huawei.com/v1/{appId}/messages:send
|
|
8
|
+
// Authorization: Bearer <token>;push_type:"notify",
|
|
9
|
+
// target 用手机上报的 push_token;harmonyOS 载荷带标题/正文/intent
|
|
10
|
+
// (extra:sessionId、askId、kind,点击拉起 App 直达对应会话)。
|
|
11
|
+
//
|
|
12
|
+
// 契约硬性要求:任何异常不得打断主流程——本模块**所有**公开方法都不抛出,
|
|
13
|
+
// 失败静默重试一次后返回 {ok:false}。未配置(enabled=false 或字段缺失)
|
|
14
|
+
// 时直接返回 {ok:false, reason:"not-configured"},由上层在 push.state 事件
|
|
15
|
+
// 里说明(契约 §6)。
|
|
16
|
+
const TOKEN_URL = "https://oauth2.cloud.huawei.com/oauth2/v1/token";
|
|
17
|
+
const SEND_URL_BASE = "https://push-api.cloud.huawei.com/v1";
|
|
18
|
+
const TOKEN_REFRESH_MARGIN_MS = 60_000; // 过期前 60s 刷新(契约 §6)
|
|
19
|
+
const REQUEST_TIMEOUT_MS = 10_000;
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* @typedef {{
|
|
23
|
+
* enabled: boolean, appId: string, clientId: string, clientSecret: string,
|
|
24
|
+
* channelId: string, topic?: string, notifyTurnEnd?: boolean,
|
|
25
|
+
* }} PushConfig
|
|
26
|
+
* @typedef {{ok: boolean, reason?: string, status?: number}} PushResult
|
|
27
|
+
*/
|
|
28
|
+
|
|
29
|
+
/** 配置是否足以发送(enabled + 三个凭证 + appId + channelId)。 */
|
|
30
|
+
export function pushConfigured(cfg) {
|
|
31
|
+
if (!cfg || cfg.enabled !== true) return false;
|
|
32
|
+
return (
|
|
33
|
+
typeof cfg.appId === "string" && cfg.appId !== "" &&
|
|
34
|
+
typeof cfg.clientId === "string" && cfg.clientId !== "" &&
|
|
35
|
+
typeof cfg.clientSecret === "string" && cfg.clientSecret !== "" &&
|
|
36
|
+
typeof cfg.channelId === "string" && cfg.channelId !== ""
|
|
37
|
+
);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** 配置不可用的统一原因(进 push.state.reason)。 */
|
|
41
|
+
export function pushUnavailableReason(cfg) {
|
|
42
|
+
if (!cfg || cfg.enabled !== true) return "push disabled";
|
|
43
|
+
if (!cfg.appId) return "push.appId missing";
|
|
44
|
+
if (!cfg.clientId) return "push.clientId missing";
|
|
45
|
+
if (!cfg.clientSecret) return "push.clientSecret missing";
|
|
46
|
+
if (!cfg.channelId) return "push.channelId missing";
|
|
47
|
+
return "not configured";
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** 带超时的 fetch(AbortController);网络层异常原样抛出,由调用方归一。 */
|
|
51
|
+
async function fetchWithTimeout(url, init) {
|
|
52
|
+
const ac = new AbortController();
|
|
53
|
+
const timer = setTimeout(() => ac.abort(), REQUEST_TIMEOUT_MS);
|
|
54
|
+
try {
|
|
55
|
+
return await fetch(url, { ...init, signal: ac.signal });
|
|
56
|
+
} finally {
|
|
57
|
+
clearTimeout(timer);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export class PushSender {
|
|
62
|
+
#cfg;
|
|
63
|
+
#token = null;
|
|
64
|
+
#tokenExpiresAt = 0;
|
|
65
|
+
#inFlight = null;
|
|
66
|
+
#log;
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* @param {PushConfig} cfg
|
|
70
|
+
* @param {(level:"info"|"warn"|"error", message:string, extra?:object)=>void} [log]
|
|
71
|
+
*/
|
|
72
|
+
constructor(cfg, log) {
|
|
73
|
+
this.#cfg = cfg;
|
|
74
|
+
this.#log = log;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** 配置热更新(上层重载 config 后调用;换凭证则丢弃缓存 token)。 */
|
|
78
|
+
updateConfig(cfg) {
|
|
79
|
+
const old = this.#cfg;
|
|
80
|
+
if (old && cfg && (old.clientId !== cfg.clientId || old.clientSecret !== cfg.clientSecret || old.clientId !== cfg.clientId)) {
|
|
81
|
+
this.#token = null;
|
|
82
|
+
this.#tokenExpiresAt = 0;
|
|
83
|
+
}
|
|
84
|
+
this.#cfg = cfg;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
get configured() {
|
|
88
|
+
return pushConfigured(this.#cfg);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* 获取 access_token(内存缓存至过期前 60s;并发合并为单次请求)。
|
|
93
|
+
* @returns {Promise<string|null>} 失败返回 null(不抛)
|
|
94
|
+
*/
|
|
95
|
+
async accessToken() {
|
|
96
|
+
if (!this.configured) return null;
|
|
97
|
+
if (this.#token !== null && Date.now() < this.#tokenExpiresAt - TOKEN_REFRESH_MARGIN_MS) {
|
|
98
|
+
return this.#token;
|
|
99
|
+
}
|
|
100
|
+
if (this.#inFlight !== null) return this.#inFlight;
|
|
101
|
+
const cfg = this.#cfg;
|
|
102
|
+
this.#inFlight = (async () => {
|
|
103
|
+
try {
|
|
104
|
+
const body = new URLSearchParams({
|
|
105
|
+
grant_type: "client_credentials",
|
|
106
|
+
client_id: cfg.clientId,
|
|
107
|
+
client_secret: cfg.clientSecret,
|
|
108
|
+
});
|
|
109
|
+
const res = await fetchWithTimeout(TOKEN_URL, {
|
|
110
|
+
method: "POST",
|
|
111
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
|
112
|
+
body: String(body),
|
|
113
|
+
});
|
|
114
|
+
if (!res.ok) {
|
|
115
|
+
this.#log?.("warn", "push token request failed", { status: res.status });
|
|
116
|
+
return null;
|
|
117
|
+
}
|
|
118
|
+
const data = await res.json();
|
|
119
|
+
const token = data && typeof data.access_token === "string" ? data.access_token : null;
|
|
120
|
+
if (token === null) {
|
|
121
|
+
this.#log?.("warn", "push token response missing access_token");
|
|
122
|
+
return null;
|
|
123
|
+
}
|
|
124
|
+
const expiresIn = Number(data.expires_in);
|
|
125
|
+
this.#tokenExpiresAt = Date.now() + (Number.isFinite(expiresIn) && expiresIn > 0 ? expiresIn * 1000 : 3600_000);
|
|
126
|
+
this.#token = token;
|
|
127
|
+
return token;
|
|
128
|
+
} catch (e) {
|
|
129
|
+
this.#log?.("warn", "push token request error", { error: String(e && e.message) });
|
|
130
|
+
return null;
|
|
131
|
+
} finally {
|
|
132
|
+
this.#inFlight = null;
|
|
133
|
+
}
|
|
134
|
+
})();
|
|
135
|
+
return this.#inFlight;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* 发送一条通知(失败静默重试一次;绝不抛出)。
|
|
140
|
+
* @param {{
|
|
141
|
+
* pushToken: string, title: string, body: string,
|
|
142
|
+
* kind: "approval"|"question"|"turn-end",
|
|
143
|
+
* sessionId?: string, askId?: string,
|
|
144
|
+
* }} req
|
|
145
|
+
* @returns {Promise<PushResult>}
|
|
146
|
+
*/
|
|
147
|
+
async notify(req) {
|
|
148
|
+
try {
|
|
149
|
+
if (!this.configured) return { ok: false, reason: pushUnavailableReason(this.#cfg) };
|
|
150
|
+
if (typeof req?.pushToken !== "string" || req.pushToken === "") {
|
|
151
|
+
return { ok: false, reason: "no push token registered" };
|
|
152
|
+
}
|
|
153
|
+
const first = await this.#attempt(req);
|
|
154
|
+
if (first.ok) return first;
|
|
155
|
+
// 静默重试一次(契约 §6:失败静默重试一次)
|
|
156
|
+
const second = await this.#attempt(req);
|
|
157
|
+
return second;
|
|
158
|
+
} catch (e) {
|
|
159
|
+
this.#log?.("warn", "push notify error", { error: String(e && e.message) });
|
|
160
|
+
return { ok: false, reason: "error" };
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** 单次发送尝试。 */
|
|
165
|
+
async #attempt(req) {
|
|
166
|
+
const cfg = this.#cfg;
|
|
167
|
+
const token = await this.accessToken();
|
|
168
|
+
if (token === null) return { ok: false, reason: "token unavailable" };
|
|
169
|
+
|
|
170
|
+
// harmonyOS 载荷:标题 / 正文 / intent(点击拉起 App 直达会话,契约 §6)
|
|
171
|
+
const extras = [];
|
|
172
|
+
if (req.sessionId) extras.push({ key: "sessionId", value: String(req.sessionId) });
|
|
173
|
+
if (req.askId) extras.push({ key: "askId", value: String(req.askId) });
|
|
174
|
+
extras.push({ key: "kind", value: String(req.kind) });
|
|
175
|
+
|
|
176
|
+
// Push 是独立 REST 协议(非本插件的 E2E 信封),直接构造华为请求体
|
|
177
|
+
const payload = {
|
|
178
|
+
push_type: "notify",
|
|
179
|
+
token: req.pushToken,
|
|
180
|
+
message: {
|
|
181
|
+
notification: {
|
|
182
|
+
title: String(req.title).slice(0, 256),
|
|
183
|
+
body: String(req.body).slice(0, 1024),
|
|
184
|
+
},
|
|
185
|
+
android: {
|
|
186
|
+
channel_id: cfg.channelId,
|
|
187
|
+
...(cfg.topic ? { topic: cfg.topic } : {}),
|
|
188
|
+
click_action: {
|
|
189
|
+
// 拉起 App 并携带直达参数(App 侧 intent 解析同名 extra)
|
|
190
|
+
url: "dshremote://open?" + new URLSearchParams(
|
|
191
|
+
Object.fromEntries(extras.map((e) => [e.key, e.value])),
|
|
192
|
+
).toString(),
|
|
193
|
+
},
|
|
194
|
+
},
|
|
195
|
+
},
|
|
196
|
+
};
|
|
197
|
+
|
|
198
|
+
try {
|
|
199
|
+
const res = await fetchWithTimeout(`${SEND_URL_BASE}/${encodeURIComponent(cfg.appId)}/messages:send`, {
|
|
200
|
+
method: "POST",
|
|
201
|
+
headers: {
|
|
202
|
+
"Content-Type": "application/json;charset=UTF-8",
|
|
203
|
+
Authorization: "Bearer " + token,
|
|
204
|
+
},
|
|
205
|
+
body: JSON.stringify(payload),
|
|
206
|
+
});
|
|
207
|
+
if (res.ok) {
|
|
208
|
+
const data = await res.json().catch(() => ({}));
|
|
209
|
+
const code = data && data.code;
|
|
210
|
+
// 华为侧业务错误码非 "80000000" 也算失败
|
|
211
|
+
if (typeof code === "string" && code !== "80000000") {
|
|
212
|
+
this.#log?.("warn", "push send business error", { code, msg: data.msg });
|
|
213
|
+
return { ok: false, reason: String(code), status: res.status };
|
|
214
|
+
}
|
|
215
|
+
return { ok: true, status: res.status };
|
|
216
|
+
}
|
|
217
|
+
if (res.status === 401) {
|
|
218
|
+
// token 失效:丢弃缓存,重试时会重新取
|
|
219
|
+
this.#token = null;
|
|
220
|
+
this.#tokenExpiresAt = 0;
|
|
221
|
+
}
|
|
222
|
+
this.#log?.("warn", "push send failed", { status: res.status });
|
|
223
|
+
return { ok: false, status: res.status };
|
|
224
|
+
} catch (e) {
|
|
225
|
+
this.#log?.("warn", "push send error", { error: String(e && e.message) });
|
|
226
|
+
return { ok: false, reason: "network" };
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
}
|
package/lib/qr.mjs
ADDED
|
@@ -0,0 +1,439 @@
|
|
|
1
|
+
// lib/qr.mjs —— 极小 QR 码编码器(运行时零依赖;byte 模式、ECC-M、版本自适应 1–10)。
|
|
2
|
+
//
|
|
3
|
+
// 实现移植/精简自 Project Nayuki 的 “QR Code generator library”
|
|
4
|
+
// (MIT License,Copyright (c) Project Nayuki,https://www.nayuki.io/page/qr-code-generator-library)。
|
|
5
|
+
// 本文件按本插件需要重写为紧凑 ESM:仅保留 byte 模式 + ECC-M + 版本 1–10,
|
|
6
|
+
// 去掉了原库的多模式编码与版本 11–40。QR 码格式本身是 ISO/IEC 18004 开放标准。
|
|
7
|
+
// 原作授权见上;本精简版随本插件以 MIT 发布(见 ../../LICENSE)。
|
|
8
|
+
//
|
|
9
|
+
// 对外 API:
|
|
10
|
+
// encodeToMatrix(text) -> { size, version, mask, modules }(modules[y][x] 为 true=黑)
|
|
11
|
+
// toSvg(matrix, opts) -> SVG 字符串(含 4 模块静区)
|
|
12
|
+
// toAscii(matrix, opts) -> 终端可直接扫的 ASCII 二维码字符串
|
|
13
|
+
|
|
14
|
+
// ---------------------------------------------------------------------------
|
|
15
|
+
// 版本参数表(仅 ECC-M 级、版本 1–10)。两张表均来自 ISO/IEC 18004 的标准
|
|
16
|
+
// RS 分块参数(已对照独立实现 jsqr 的 VERSIONS 表逐项核对:ecc/块数
|
|
17
|
+
// 10,16,26,18,24,16,18,22,22,26 与 1,1,1,2,2,4,4,4,5,5)。
|
|
18
|
+
// 注意:同一版本内各块数据长度可不同(短/长块由 (total, blocks) 推导,
|
|
19
|
+
// addEccAndInterleave 里 numShortBlocks/shortBlockLen 的算式即为此设计),
|
|
20
|
+
// 所以此表只需「每块 ecc 数」与「块数」两个维度。
|
|
21
|
+
// ---------------------------------------------------------------------------
|
|
22
|
+
const ECC_PER_BLOCK_M = [10, 16, 26, 18, 24, 16, 18, 22, 22, 26]; // 版本 1..10
|
|
23
|
+
const NUM_BLOCKS_M = [1, 1, 1, 2, 2, 4, 4, 4, 5, 5]; // 版本 1..10(v9=3×36+2×37,v10=4×43+1×44)
|
|
24
|
+
const MIN_VERSION = 1;
|
|
25
|
+
const MAX_VERSION = 10;
|
|
26
|
+
const ECC_FORMAT_BITS_M = 0; // 格式信息里的纠错级别位:L=1 M=0 Q=3 H=2
|
|
27
|
+
|
|
28
|
+
/** 版本 v 的原始数据模块数(去掉功能图形后的总容量,单位 bit)。 */
|
|
29
|
+
function getNumRawDataModules(ver) {
|
|
30
|
+
let result = (16 * ver + 128) * ver + 64;
|
|
31
|
+
if (ver >= 2) {
|
|
32
|
+
const numAlign = Math.floor(ver / 7) + 2;
|
|
33
|
+
result -= (25 * numAlign - 10) * numAlign - 55;
|
|
34
|
+
if (ver >= 7) result -= 36;
|
|
35
|
+
}
|
|
36
|
+
return result;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** 版本 v(ECC-M)可用的数据码字数。 */
|
|
40
|
+
function getNumDataCodewords(ver) {
|
|
41
|
+
return Math.floor(getNumRawDataModules(ver) / 8) - ECC_PER_BLOCK_M[ver - 1] * NUM_BLOCKS_M[ver - 1];
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// ---------------------------------------------------------------------------
|
|
45
|
+
// GF(256) Reed-Solomon(本原多项式 0x11D,与 QR 码标准一致)
|
|
46
|
+
// ---------------------------------------------------------------------------
|
|
47
|
+
function gfMul(x, y) {
|
|
48
|
+
let z = 0;
|
|
49
|
+
for (let i = 7; i >= 0; i--) {
|
|
50
|
+
z = (z << 1) ^ ((z >>> 7) * 0x11d);
|
|
51
|
+
z ^= ((y >>> i) & 1) * x;
|
|
52
|
+
}
|
|
53
|
+
return z & 0xff;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function rsDivisor(degree) {
|
|
57
|
+
const result = new Uint8Array(degree);
|
|
58
|
+
result[degree - 1] = 1;
|
|
59
|
+
let root = 1;
|
|
60
|
+
for (let i = 0; i < degree; i++) {
|
|
61
|
+
for (let j = 0; j < degree; j++) {
|
|
62
|
+
result[j] = gfMul(result[j], root);
|
|
63
|
+
if (j + 1 < degree) result[j] ^= result[j + 1];
|
|
64
|
+
}
|
|
65
|
+
root = gfMul(root, 0x02);
|
|
66
|
+
}
|
|
67
|
+
return result;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function rsRemainder(data, divisor) {
|
|
71
|
+
const result = new Uint8Array(divisor.length);
|
|
72
|
+
for (const b of data) {
|
|
73
|
+
const factor = b ^ result[0];
|
|
74
|
+
result.copyWithin(0, 1);
|
|
75
|
+
result[result.length - 1] = 0;
|
|
76
|
+
for (let i = 0; i < result.length; i++) result[i] ^= gfMul(divisor[i], factor);
|
|
77
|
+
}
|
|
78
|
+
return result;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// ---------------------------------------------------------------------------
|
|
82
|
+
// 数据编码:分块 + RS 纠错 + 交织
|
|
83
|
+
// ---------------------------------------------------------------------------
|
|
84
|
+
function addEccAndInterleave(data, ver) {
|
|
85
|
+
const numBlocks = NUM_BLOCKS_M[ver - 1];
|
|
86
|
+
const blockEccLen = ECC_PER_BLOCK_M[ver - 1];
|
|
87
|
+
const rawCodewords = Math.floor(getNumRawDataModules(ver) / 8);
|
|
88
|
+
const numShortBlocks = numBlocks - (rawCodewords % numBlocks);
|
|
89
|
+
const shortBlockLen = Math.floor(rawCodewords / numBlocks);
|
|
90
|
+
|
|
91
|
+
const blocks = [];
|
|
92
|
+
const divisor = rsDivisor(blockEccLen);
|
|
93
|
+
for (let i = 0, k = 0; i < numBlocks; i++) {
|
|
94
|
+
const datLen = shortBlockLen - blockEccLen + (i < numShortBlocks ? 0 : 1);
|
|
95
|
+
const dat = data.slice(k, k + datLen);
|
|
96
|
+
k += datLen;
|
|
97
|
+
const ecc = rsRemainder(dat, divisor);
|
|
98
|
+
if (i < numShortBlocks) dat.push(0); // 占位,使各块等长以便交织;交织时跳过
|
|
99
|
+
blocks.push(dat.concat(Array.from(ecc)));
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const result = [];
|
|
103
|
+
for (let i = 0; i < blocks[0].length; i++) {
|
|
104
|
+
for (let j = 0; j < blocks.length; j++) {
|
|
105
|
+
// 短块的占位字节在 data 段末尾(i == shortBlockLen - blockEccLen)被跳过
|
|
106
|
+
if (i !== shortBlockLen - blockEccLen || j >= numShortBlocks) result.push(blocks[j][i]);
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
return result;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** 把 UTF-8 文本编成数据码字序列(byte 模式 + 终止符 + 0xEC/0x11 填充)。 */
|
|
113
|
+
function buildDataCodewords(bytes, ver) {
|
|
114
|
+
const capacityBits = getNumDataCodewords(ver) * 8;
|
|
115
|
+
const bits = [];
|
|
116
|
+
const push = (val, len) => {
|
|
117
|
+
for (let i = len - 1; i >= 0; i--) bits.push((val >>> i) & 1);
|
|
118
|
+
};
|
|
119
|
+
push(0b0100, 4); // byte 模式指示符
|
|
120
|
+
push(bytes.length, ver <= 9 ? 8 : 16); // 字符计数(版本 1–9 为 8 位,10+ 为 16 位)
|
|
121
|
+
for (const b of bytes) push(b, 8);
|
|
122
|
+
if (bits.length > capacityBits) throw new Error("QR: data too long for version " + ver);
|
|
123
|
+
|
|
124
|
+
// 终止符(至多 4 个 0)→ 补齐到字节边界 → 0xEC/0x11 交替填充
|
|
125
|
+
push(0, Math.min(4, capacityBits - bits.length));
|
|
126
|
+
while (bits.length % 8 !== 0) bits.push(0);
|
|
127
|
+
for (let pad = 0xec; bits.length < capacityBits; pad ^= 0xec ^ 0x11) push(pad, 8);
|
|
128
|
+
|
|
129
|
+
const out = [];
|
|
130
|
+
for (let i = 0; i < bits.length; i += 8) {
|
|
131
|
+
let byte = 0;
|
|
132
|
+
for (let j = 0; j < 8; j++) byte = (byte << 1) | bits[i + j];
|
|
133
|
+
out.push(byte);
|
|
134
|
+
}
|
|
135
|
+
return out;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
// ---------------------------------------------------------------------------
|
|
139
|
+
// 矩阵:功能图形 / 数据布局 / 掩模 / 格式与版本信息
|
|
140
|
+
// ---------------------------------------------------------------------------
|
|
141
|
+
function getBit(x, i) {
|
|
142
|
+
return ((x >>> i) & 1) !== 0;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** 对齐图形中心坐标(版本 1 无对齐图形)。 */
|
|
146
|
+
function getAlignmentPatternPositions(ver) {
|
|
147
|
+
if (ver === 1) return [];
|
|
148
|
+
const numAlign = Math.floor(ver / 7) + 2;
|
|
149
|
+
const size = ver * 4 + 17;
|
|
150
|
+
const step = ver === 32 ? 26 : Math.ceil((ver * 4 + 4) / (numAlign * 2 - 2)) * 2;
|
|
151
|
+
const result = [6];
|
|
152
|
+
for (let pos = size - 7; result.length < numAlign; pos -= step) result.splice(1, 0, pos);
|
|
153
|
+
return result;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function makeQrModules(ver, codewords) {
|
|
157
|
+
const size = ver * 4 + 17;
|
|
158
|
+
const modules = Array.from({ length: size }, () => new Array(size).fill(false));
|
|
159
|
+
const isFunction = Array.from({ length: size }, () => new Array(size).fill(false));
|
|
160
|
+
|
|
161
|
+
const setFunc = (x, y, dark) => {
|
|
162
|
+
modules[y][x] = dark;
|
|
163
|
+
isFunction[y][x] = true;
|
|
164
|
+
};
|
|
165
|
+
|
|
166
|
+
const drawFinder = (x, y) => {
|
|
167
|
+
for (let dy = -4; dy <= 4; dy++) {
|
|
168
|
+
for (let dx = -4; dx <= 4; dx++) {
|
|
169
|
+
const dist = Math.max(Math.abs(dx), Math.abs(dy));
|
|
170
|
+
const xx = x + dx;
|
|
171
|
+
const yy = y + dy;
|
|
172
|
+
if (xx >= 0 && xx < size && yy >= 0 && yy < size) setFunc(xx, yy, dist !== 2 && dist !== 4);
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
};
|
|
176
|
+
|
|
177
|
+
const drawAlignment = (x, y) => {
|
|
178
|
+
for (let dy = -2; dy <= 2; dy++) {
|
|
179
|
+
for (let dx = -2; dx <= 2; dx++) {
|
|
180
|
+
setFunc(x + dx, y + dy, Math.max(Math.abs(dx), Math.abs(dy)) !== 1);
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
};
|
|
184
|
+
|
|
185
|
+
const drawFormatBits = (mask) => {
|
|
186
|
+
const data = (ECC_FORMAT_BITS_M << 3) | mask;
|
|
187
|
+
let rem = data;
|
|
188
|
+
for (let i = 0; i < 10; i++) rem = (rem << 1) ^ ((rem >>> 9) * 0x537);
|
|
189
|
+
const bits = ((data << 10) | rem) ^ 0x5412;
|
|
190
|
+
// 第一份拷贝(左上角定位图形周围)
|
|
191
|
+
for (let i = 0; i <= 5; i++) setFunc(8, i, getBit(bits, i));
|
|
192
|
+
setFunc(8, 7, getBit(bits, 6));
|
|
193
|
+
setFunc(8, 8, getBit(bits, 7));
|
|
194
|
+
setFunc(7, 8, getBit(bits, 8));
|
|
195
|
+
for (let i = 9; i < 15; i++) setFunc(14 - i, 8, getBit(bits, i));
|
|
196
|
+
// 第二份拷贝(右上/左下)
|
|
197
|
+
for (let i = 0; i < 8; i++) setFunc(size - 1 - i, 8, getBit(bits, i));
|
|
198
|
+
for (let i = 8; i < 15; i++) setFunc(8, size - 15 + i, getBit(bits, i));
|
|
199
|
+
setFunc(8, size - 8, true); // 固定的黑模块
|
|
200
|
+
};
|
|
201
|
+
|
|
202
|
+
// 定时图形
|
|
203
|
+
for (let i = 0; i < size; i++) {
|
|
204
|
+
setFunc(6, i, i % 2 === 0);
|
|
205
|
+
setFunc(i, 6, i % 2 === 0);
|
|
206
|
+
}
|
|
207
|
+
// 三个定位图形(含分隔带)
|
|
208
|
+
drawFinder(3, 3);
|
|
209
|
+
drawFinder(size - 4, 3);
|
|
210
|
+
drawFinder(3, size - 4);
|
|
211
|
+
// 对齐图形(避开与定位图形重叠的三个角)
|
|
212
|
+
const alignPos = getAlignmentPatternPositions(ver);
|
|
213
|
+
const n = alignPos.length;
|
|
214
|
+
for (let i = 0; i < n; i++) {
|
|
215
|
+
for (let j = 0; j < n; j++) {
|
|
216
|
+
if ((i === 0 && j === 0) || (i === 0 && j === n - 1) || (i === n - 1 && j === 0)) continue;
|
|
217
|
+
drawAlignment(alignPos[i], alignPos[j]);
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
// 版本信息(版本 ≥7)
|
|
221
|
+
if (ver >= 7) {
|
|
222
|
+
let rem = ver;
|
|
223
|
+
for (let i = 0; i < 12; i++) rem = (rem << 1) ^ ((rem >>> 11) * 0x1f25);
|
|
224
|
+
const bits = (ver << 12) | rem;
|
|
225
|
+
for (let i = 0; i < 18; i++) {
|
|
226
|
+
const bit = getBit(bits, i);
|
|
227
|
+
const a = size - 11 + (i % 3);
|
|
228
|
+
const b = Math.floor(i / 3);
|
|
229
|
+
setFunc(a, b, bit);
|
|
230
|
+
setFunc(b, a, bit);
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
drawFormatBits(0); // 占位;选定掩模后重画
|
|
234
|
+
|
|
235
|
+
// 数据布局:右下起蛇形上行/下行,每两列一组,跳过第 6 列
|
|
236
|
+
let i = 0;
|
|
237
|
+
for (let right = size - 1; right >= 1; right -= 2) {
|
|
238
|
+
if (right === 6) right = 5;
|
|
239
|
+
for (let vert = 0; vert < size; vert++) {
|
|
240
|
+
for (let j = 0; j < 2; j++) {
|
|
241
|
+
const x = right - j;
|
|
242
|
+
const upward = ((right + 1) & 2) === 0;
|
|
243
|
+
const y = upward ? size - 1 - vert : vert;
|
|
244
|
+
if (!isFunction[y][x] && i < codewords.length * 8) {
|
|
245
|
+
modules[y][x] = getBit(codewords[i >>> 3], 7 - (i & 7));
|
|
246
|
+
i++;
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
const maskFn = (mask, x, y) => {
|
|
253
|
+
switch (mask) {
|
|
254
|
+
case 0: return (x + y) % 2 === 0;
|
|
255
|
+
case 1: return y % 2 === 0;
|
|
256
|
+
case 2: return x % 3 === 0;
|
|
257
|
+
case 3: return (x + y) % 3 === 0;
|
|
258
|
+
case 4: return (Math.floor(x / 3) + Math.floor(y / 2)) % 2 === 0;
|
|
259
|
+
case 5: return ((x * y) % 2) + ((x * y) % 3) === 0;
|
|
260
|
+
case 6: return (((x * y) % 2) + ((x * y) % 3)) % 2 === 0;
|
|
261
|
+
case 7: return (((x + y) % 2) + ((x * y) % 3)) % 2 === 0;
|
|
262
|
+
default: throw new Error("QR: bad mask " + mask);
|
|
263
|
+
}
|
|
264
|
+
};
|
|
265
|
+
|
|
266
|
+
const applyMask = (mask) => {
|
|
267
|
+
for (let y = 0; y < size; y++) {
|
|
268
|
+
for (let x = 0; x < size; x++) {
|
|
269
|
+
if (!isFunction[y][x] && maskFn(mask, x, y)) modules[y][x] = !modules[y][x];
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
};
|
|
273
|
+
|
|
274
|
+
// 掩模罚分(N1/N2/N3/N4,ISO/IEC 18000 定义)
|
|
275
|
+
const finderPenaltyCountPatterns = (runHistory) => {
|
|
276
|
+
const n = runHistory[1];
|
|
277
|
+
const core = n > 0 && runHistory[2] === n && runHistory[3] === n * 3 && runHistory[4] === n && runHistory[5] === n;
|
|
278
|
+
return (
|
|
279
|
+
(core && runHistory[0] >= n * 4 && runHistory[6] >= n ? 1 : 0) +
|
|
280
|
+
(core && runHistory[6] >= n * 4 && runHistory[0] >= n ? 1 : 0)
|
|
281
|
+
);
|
|
282
|
+
};
|
|
283
|
+
const finderPenaltyAddHistory = (currentRunLength, runHistory) => {
|
|
284
|
+
if (runHistory[0] === 0) currentRunLength += size; // 初始亮边
|
|
285
|
+
runHistory.pop();
|
|
286
|
+
runHistory.unshift(currentRunLength);
|
|
287
|
+
};
|
|
288
|
+
const finderPenaltyTerminateAndCount = (currentRunColor, currentRunLength, runHistory) => {
|
|
289
|
+
if (currentRunColor) {
|
|
290
|
+
finderPenaltyAddHistory(currentRunLength, runHistory);
|
|
291
|
+
currentRunLength = 0;
|
|
292
|
+
}
|
|
293
|
+
currentRunLength += size; // 末尾亮边
|
|
294
|
+
finderPenaltyAddHistory(currentRunLength, runHistory);
|
|
295
|
+
return finderPenaltyCountPatterns(runHistory);
|
|
296
|
+
};
|
|
297
|
+
const getPenaltyScore = () => {
|
|
298
|
+
let result = 0;
|
|
299
|
+
for (let y = 0; y < size; y++) {
|
|
300
|
+
let runColor = false;
|
|
301
|
+
let runX = 0;
|
|
302
|
+
const runHistory = [0, 0, 0, 0, 0, 0, 0];
|
|
303
|
+
for (let x = 0; x < size; x++) {
|
|
304
|
+
if (modules[y][x] === runColor) {
|
|
305
|
+
runX++;
|
|
306
|
+
if (runX === 5) result += 3;
|
|
307
|
+
else if (runX > 5) result++;
|
|
308
|
+
} else {
|
|
309
|
+
finderPenaltyAddHistory(runX, runHistory);
|
|
310
|
+
if (!runColor) result += finderPenaltyCountPatterns(runHistory) * 40;
|
|
311
|
+
runColor = modules[y][x];
|
|
312
|
+
runX = 1;
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
result += finderPenaltyTerminateAndCount(runColor, runX, runHistory) * 40;
|
|
316
|
+
}
|
|
317
|
+
for (let x = 0; x < size; x++) {
|
|
318
|
+
let runColor = false;
|
|
319
|
+
let runY = 0;
|
|
320
|
+
const runHistory = [0, 0, 0, 0, 0, 0, 0];
|
|
321
|
+
for (let y = 0; y < size; y++) {
|
|
322
|
+
if (modules[y][x] === runColor) {
|
|
323
|
+
runY++;
|
|
324
|
+
if (runY === 5) result += 3;
|
|
325
|
+
else if (runY > 5) result++;
|
|
326
|
+
} else {
|
|
327
|
+
finderPenaltyAddHistory(runY, runHistory);
|
|
328
|
+
if (!runColor) result += finderPenaltyCountPatterns(runHistory) * 40;
|
|
329
|
+
runColor = modules[y][x];
|
|
330
|
+
runY = 1;
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
result += finderPenaltyTerminateAndCount(runColor, runY, runHistory) * 40;
|
|
334
|
+
}
|
|
335
|
+
for (let y = 0; y < size - 1; y++) {
|
|
336
|
+
for (let x = 0; x < size - 1; x++) {
|
|
337
|
+
const c = modules[y][x];
|
|
338
|
+
if (c === modules[y][x + 1] && c === modules[y + 1][x] && c === modules[y + 1][x + 1]) result += 3;
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
let dark = 0;
|
|
342
|
+
for (const row of modules) for (const c of row) dark += c ? 1 : 0;
|
|
343
|
+
const total = size * size;
|
|
344
|
+
const k = Math.ceil(Math.abs(dark * 20 - total * 10) / total) - 1;
|
|
345
|
+
result += k * 10;
|
|
346
|
+
return result;
|
|
347
|
+
};
|
|
348
|
+
|
|
349
|
+
// 选掩模:罚分最小者
|
|
350
|
+
let bestMask = 0;
|
|
351
|
+
let minPenalty = Infinity;
|
|
352
|
+
for (let mask = 0; mask < 8; mask++) {
|
|
353
|
+
applyMask(mask);
|
|
354
|
+
drawFormatBits(mask);
|
|
355
|
+
const penalty = getPenaltyScore();
|
|
356
|
+
if (penalty < minPenalty) {
|
|
357
|
+
minPenalty = penalty;
|
|
358
|
+
bestMask = mask;
|
|
359
|
+
}
|
|
360
|
+
applyMask(mask); // XOR 恢复
|
|
361
|
+
}
|
|
362
|
+
applyMask(bestMask);
|
|
363
|
+
drawFormatBits(bestMask);
|
|
364
|
+
|
|
365
|
+
return { size, modules, mask: bestMask };
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
/**
|
|
369
|
+
* 把文本编码为 QR 矩阵(byte 模式,UTF-8,ECC-M,版本自适应 1–10)。
|
|
370
|
+
* @param {string} text
|
|
371
|
+
* @returns {{size:number, version:number, mask:number, modules:boolean[][]}}
|
|
372
|
+
*/
|
|
373
|
+
export function encodeToMatrix(text) {
|
|
374
|
+
const bytes = Array.from(new TextEncoder().encode(String(text)));
|
|
375
|
+
let version = -1;
|
|
376
|
+
for (let v = MIN_VERSION; v <= MAX_VERSION; v++) {
|
|
377
|
+
const ccBits = v <= 9 ? 8 : 16;
|
|
378
|
+
if (getNumDataCodewords(v) * 8 >= 4 + ccBits + bytes.length * 8) {
|
|
379
|
+
version = v;
|
|
380
|
+
break;
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
if (version < 0) {
|
|
384
|
+
throw new Error("QR: payload too long for version ≤ " + MAX_VERSION + " (" + bytes.length + " bytes)");
|
|
385
|
+
}
|
|
386
|
+
const data = buildDataCodewords(bytes, version);
|
|
387
|
+
const codewords = addEccAndInterleave(data, version);
|
|
388
|
+
const { size, modules, mask } = makeQrModules(version, codewords);
|
|
389
|
+
return { size, version, mask, modules };
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
/**
|
|
393
|
+
* 渲染 SVG(默认 8px/模块 + 4 模块静区,黑底白底对比)。
|
|
394
|
+
* @param {{size:number, modules:boolean[][]}} qr
|
|
395
|
+
* @param {{scale?:number, quiet?:number, dark?:string, light?:string}} [opts]
|
|
396
|
+
*/
|
|
397
|
+
export function toSvg(qr, opts = {}) {
|
|
398
|
+
const scale = Number.isInteger(opts.scale) && opts.scale > 0 ? opts.scale : 8;
|
|
399
|
+
const quiet = Number.isInteger(opts.quiet) && opts.quiet >= 0 ? opts.quiet : 4;
|
|
400
|
+
const dark = typeof opts.dark === "string" ? opts.dark : "#000000";
|
|
401
|
+
const light = typeof opts.light === "string" ? opts.light : "#ffffff";
|
|
402
|
+
const n = qr.size;
|
|
403
|
+
const dim = (n + quiet * 2) * scale;
|
|
404
|
+
let path = "";
|
|
405
|
+
for (let y = 0; y < n; y++) {
|
|
406
|
+
for (let x = 0; x < n; x++) {
|
|
407
|
+
if (qr.modules[y][x]) path += `M${x + quiet} ${y + quiet}h1v1h-1z`;
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
return (
|
|
411
|
+
`<svg xmlns="http://www.w3.org/2000/svg" width="${dim}" height="${dim}" ` +
|
|
412
|
+
`viewBox="0 0 ${n + quiet * 2} ${n + quiet * 2}" shape-rendering="crispEdges">` +
|
|
413
|
+
`<rect width="100%" height="100%" fill="${light}"/>` +
|
|
414
|
+
`<path d="${path}" fill="${dark}"/>` +
|
|
415
|
+
`</svg>\n`
|
|
416
|
+
);
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
/**
|
|
420
|
+
* 渲染 ASCII 二维码(每模块两字符宽以保持方形比例;含静区,可直接扫屏)。
|
|
421
|
+
* @param {{size:number, modules:boolean[][]}} qr
|
|
422
|
+
* @param {{quiet?:number}} [opts]
|
|
423
|
+
*/
|
|
424
|
+
export function toAscii(qr, opts = {}) {
|
|
425
|
+
const quiet = Number.isInteger(opts.quiet) && opts.quiet >= 0 ? opts.quiet : 2;
|
|
426
|
+
const on = "██";
|
|
427
|
+
const off = " ";
|
|
428
|
+
const lines = [];
|
|
429
|
+
const n = qr.size;
|
|
430
|
+
const blank = off.repeat(n + quiet * 2);
|
|
431
|
+
for (let i = 0; i < quiet; i++) lines.push(blank);
|
|
432
|
+
for (let y = 0; y < n; y++) {
|
|
433
|
+
let row = off.repeat(quiet);
|
|
434
|
+
for (let x = 0; x < n; x++) row += qr.modules[y][x] ? on : off;
|
|
435
|
+
lines.push(row + off.repeat(quiet));
|
|
436
|
+
}
|
|
437
|
+
for (let i = 0; i < quiet; i++) lines.push(blank);
|
|
438
|
+
return lines.join("\n");
|
|
439
|
+
}
|