@kubohiroya/turbowarp-webrtc-qrcode-pairing 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/LICENSE +373 -0
  2. package/README.ja.md +122 -0
  3. package/README.md +414 -0
  4. package/dist/extension-manifest.json +318 -0
  5. package/dist/webrtc-qrcode-pairing.js +4064 -0
  6. package/docs/architecture.ja.md +57 -0
  7. package/docs/architecture.md +65 -0
  8. package/docs/design/qr-pairing/README.md +16 -0
  9. package/docs/design/qr-pairing/architecture.md +191 -0
  10. package/docs/design/qr-pairing/block-api.md +123 -0
  11. package/docs/design/qr-pairing/dataflow.md +202 -0
  12. package/docs/design/qr-pairing/extraction-plan.md +134 -0
  13. package/docs/design/qr-pairing/interfaces.ts +473 -0
  14. package/docs/design/qr-pairing/requirements.md +152 -0
  15. package/docs/design/qr-pairing/test-plan.md +126 -0
  16. package/docs/index.html +34 -0
  17. package/docs/initialization-issue.ja.md +34 -0
  18. package/docs/integration-guide.ja.md +245 -0
  19. package/docs/integration-guide.md +258 -0
  20. package/docs/migration.ja.md +110 -0
  21. package/docs/migration.md +115 -0
  22. package/package.json +90 -0
  23. package/schemas/extension-manifest.schema.json +49 -0
  24. package/src/block-definitions.json +264 -0
  25. package/src/clock.ts +18 -0
  26. package/src/config/feature-flags.ts +18 -0
  27. package/src/config/qr-config.ts +22 -0
  28. package/src/config.ts +12 -0
  29. package/src/errors.ts +51 -0
  30. package/src/extension-manifest.ts +149 -0
  31. package/src/extension.ts +281 -0
  32. package/src/globals.d.ts +54 -0
  33. package/src/index.ts +8 -0
  34. package/src/pairing/controller.ts +836 -0
  35. package/src/pairing/limits.ts +12 -0
  36. package/src/pairing/types.ts +96 -0
  37. package/src/ports/display.ts +136 -0
  38. package/src/ports/qr-scan.ts +151 -0
  39. package/src/ports/webrtc.ts +61 -0
  40. package/src/qr/courier.ts +267 -0
  41. package/src/qr/envelope.ts +0 -0
  42. package/src/qr/hash.ts +13 -0
  43. package/src/qr/limits.ts +44 -0
  44. package/src/qr/svg.ts +34 -0
  45. package/templates/README.ja.md +183 -0
  46. package/templates/README.md +198 -0
@@ -0,0 +1,4064 @@
1
+ // Name: TurboWarp-WebRTC-QRCode-Pairing
2
+ // ID: kubohiroyawebrtcqrcodepairing
3
+ // Description: Exchanges WebRTC offers and answers by carrying them optically as QR codes.
4
+ // By: Hiroya Kubo
5
+ // License: MPL-2.0
6
+
7
+ (function (Scratch) {
8
+ 'use strict';
9
+
10
+ //#region \0rolldown/runtime.js
11
+ var __create = Object.create;
12
+ var __defProp = Object.defineProperty;
13
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
14
+ var __getOwnPropNames = Object.getOwnPropertyNames;
15
+ var __getProtoOf = Object.getPrototypeOf;
16
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
17
+ var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
18
+ var __copyProps = (to, from, except, desc) => {
19
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
20
+ key = keys[i];
21
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
22
+ get: ((k) => from[k]).bind(null, key),
23
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
24
+ });
25
+ }
26
+ return to;
27
+ };
28
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
29
+ value: mod,
30
+ enumerable: true
31
+ }) : target, mod));
32
+ //#endregion
33
+ //#region src/config.ts
34
+ var extensionConfig = {
35
+ id: "kubohiroyawebrtcqrcodepairing",
36
+ slug: "webrtc-qrcode-pairing",
37
+ name: "TurboWarp-WebRTC-QRCode-Pairing",
38
+ description: "Exchanges WebRTC offers and answers by carrying them optically as QR codes.",
39
+ author: "Hiroya Kubo",
40
+ license: "MPL-2.0",
41
+ unsandboxed: true,
42
+ docsURI: "https://kubohiroya.github.io/turbowarp-webrtc-qrcode-pairing/",
43
+ blockIconURI: "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA0OCA0OCI+PHJlY3QgeD0iNCIgeT0iOCIgd2lkdGg9IjE4IiBoZWlnaHQ9IjE0IiByeD0iMyIgZmlsbD0iIzRDOTdGRiIvPjxyZWN0IHg9IjI2IiB5PSI4IiB3aWR0aD0iMTgiIGhlaWdodD0iMTQiIHJ4PSIzIiBmaWxsPSIjNTlDMDU5Ii8+PHJlY3QgeD0iMTUiIHk9IjI2IiB3aWR0aD0iMTgiIGhlaWdodD0iMTQiIHJ4PSIzIiBmaWxsPSIjRkZBQjE5Ii8+PC9zdmc+"
44
+ };
45
+ var block_definitions_default = {
46
+ extensionName: "TurboWarp-WebRTC-QRCode-Pairing",
47
+ blocks: [
48
+ {
49
+ "opcode": "startOfferPairing",
50
+ "blockType": "COMMAND",
51
+ "text": "start offer pairing [SESSION] as [LOCAL_PEER] to [REMOTE_PEER]",
52
+ "description": "Creates a WebRTC offer for the integration machine and prepares its QR parts.",
53
+ "arguments": {
54
+ "SESSION": {
55
+ "type": "STRING",
56
+ "defaultValue": "pairing-1"
57
+ },
58
+ "LOCAL_PEER": {
59
+ "type": "STRING",
60
+ "defaultValue": "hub"
61
+ },
62
+ "REMOTE_PEER": {
63
+ "type": "STRING",
64
+ "defaultValue": "camera-1"
65
+ }
66
+ }
67
+ },
68
+ {
69
+ "opcode": "startAnswerPairing",
70
+ "blockType": "COMMAND",
71
+ "text": "start answer pairing [SESSION] as [LOCAL_PEER]",
72
+ "description": "Waits for an offer on the camera machine. Leave the name empty to adopt the name the offer assigns.",
73
+ "arguments": {
74
+ "SESSION": {
75
+ "type": "STRING",
76
+ "defaultValue": "pairing-1"
77
+ },
78
+ "LOCAL_PEER": {
79
+ "type": "STRING",
80
+ "defaultValue": ""
81
+ }
82
+ }
83
+ },
84
+ {
85
+ "opcode": "ingestPairingQrText",
86
+ "blockType": "COMMAND",
87
+ "text": "receive pairing QR text [TEXT] for [SESSION]",
88
+ "description": "Accepts one decoded QR text. Repeated readings of the same part are ignored.",
89
+ "arguments": {
90
+ "TEXT": {
91
+ "type": "STRING",
92
+ "defaultValue": ""
93
+ },
94
+ "SESSION": {
95
+ "type": "STRING",
96
+ "defaultValue": "pairing-1"
97
+ }
98
+ }
99
+ },
100
+ {
101
+ "opcode": "scanPairingQrFromCamera",
102
+ "blockType": "COMMAND",
103
+ "text": "scan pairing QR for [SESSION] from camera [CAMERA_ID]",
104
+ "description": "Reads parts from the named camera until the exchange has every part it needs.",
105
+ "arguments": {
106
+ "SESSION": {
107
+ "type": "STRING",
108
+ "defaultValue": "pairing-1"
109
+ },
110
+ "CAMERA_ID": {
111
+ "type": "STRING",
112
+ "defaultValue": "default"
113
+ }
114
+ }
115
+ },
116
+ {
117
+ "opcode": "pairingReceivedParts",
118
+ "blockType": "REPORTER",
119
+ "text": "received parts of [SESSION]",
120
+ "description": "Returns how many distinct parts have been accepted.",
121
+ "arguments": { "SESSION": {
122
+ "type": "STRING",
123
+ "defaultValue": "pairing-1"
124
+ } }
125
+ },
126
+ {
127
+ "opcode": "pairingRequiredParts",
128
+ "blockType": "REPORTER",
129
+ "text": "required parts of [SESSION]",
130
+ "description": "Returns how many parts the incoming message has, or zero before the first part arrives.",
131
+ "arguments": { "SESSION": {
132
+ "type": "STRING",
133
+ "defaultValue": "pairing-1"
134
+ } }
135
+ },
136
+ {
137
+ "opcode": "pairingMissingParts",
138
+ "blockType": "REPORTER",
139
+ "text": "missing parts of [SESSION]",
140
+ "description": "Returns the one-based part numbers that have not been read yet, separated by commas.",
141
+ "arguments": { "SESSION": {
142
+ "type": "STRING",
143
+ "defaultValue": "pairing-1"
144
+ } }
145
+ },
146
+ {
147
+ "opcode": "showPairingQrPart",
148
+ "blockType": "COMMAND",
149
+ "text": "show pairing QR part [INDEX] of [SESSION] on this sprite",
150
+ "description": "Shows the selected one-based part using a temporary sprite skin.",
151
+ "arguments": {
152
+ "INDEX": {
153
+ "type": "NUMBER",
154
+ "defaultValue": 1
155
+ },
156
+ "SESSION": {
157
+ "type": "STRING",
158
+ "defaultValue": "pairing-1"
159
+ }
160
+ }
161
+ },
162
+ {
163
+ "opcode": "showNextPairingQrPart",
164
+ "blockType": "COMMAND",
165
+ "text": "show next pairing QR part of [SESSION] on this sprite",
166
+ "description": "Shows the next part and wraps from the last part back to the first.",
167
+ "arguments": { "SESSION": {
168
+ "type": "STRING",
169
+ "defaultValue": "pairing-1"
170
+ } }
171
+ },
172
+ {
173
+ "opcode": "pairingQrPartCount",
174
+ "blockType": "REPORTER",
175
+ "text": "pairing QR part count of [SESSION]",
176
+ "description": "Returns how many parts are prepared for display, or zero when none are.",
177
+ "arguments": { "SESSION": {
178
+ "type": "STRING",
179
+ "defaultValue": "pairing-1"
180
+ } }
181
+ },
182
+ {
183
+ "opcode": "pairingQrCurrentPart",
184
+ "blockType": "REPORTER",
185
+ "text": "current pairing QR part of [SESSION]",
186
+ "description": "Returns the one-based part selected for display, or zero when none is selected.",
187
+ "arguments": { "SESSION": {
188
+ "type": "STRING",
189
+ "defaultValue": "pairing-1"
190
+ } }
191
+ },
192
+ {
193
+ "opcode": "pairingQrPartSvg",
194
+ "blockType": "REPORTER",
195
+ "text": "pairing QR part [INDEX] of [SESSION] as SVG",
196
+ "description": "Returns the part as SVG markup so a project can display it its own way.",
197
+ "arguments": {
198
+ "INDEX": {
199
+ "type": "NUMBER",
200
+ "defaultValue": 1
201
+ },
202
+ "SESSION": {
203
+ "type": "STRING",
204
+ "defaultValue": "pairing-1"
205
+ }
206
+ }
207
+ },
208
+ {
209
+ "opcode": "pairingQrPartDataUri",
210
+ "blockType": "REPORTER",
211
+ "text": "pairing QR part [INDEX] of [SESSION] as data URI",
212
+ "description": "Returns the part as a base64 SVG data URI for costumes and HTML images.",
213
+ "arguments": {
214
+ "INDEX": {
215
+ "type": "NUMBER",
216
+ "defaultValue": 1
217
+ },
218
+ "SESSION": {
219
+ "type": "STRING",
220
+ "defaultValue": "pairing-1"
221
+ }
222
+ }
223
+ },
224
+ {
225
+ "opcode": "endPairingQrDisplay",
226
+ "blockType": "COMMAND",
227
+ "text": "end pairing QR display of [SESSION]",
228
+ "description": "Restores the sprites this session changed. The session itself stays open.",
229
+ "arguments": { "SESSION": {
230
+ "type": "STRING",
231
+ "defaultValue": "pairing-1"
232
+ } }
233
+ },
234
+ {
235
+ "opcode": "pairingPhase",
236
+ "blockType": "REPORTER",
237
+ "text": "pairing phase of [SESSION]",
238
+ "description": "Returns the session phase, such as offer-ready, receiving, answer-ready, connecting, or connected.",
239
+ "arguments": { "SESSION": {
240
+ "type": "STRING",
241
+ "defaultValue": "pairing-1"
242
+ } }
243
+ },
244
+ {
245
+ "opcode": "pairingConnectionState",
246
+ "blockType": "REPORTER",
247
+ "text": "pairing connection state of [SESSION]",
248
+ "description": "Returns the WebRTC connection state reported for this session's peer.",
249
+ "arguments": { "SESSION": {
250
+ "type": "STRING",
251
+ "defaultValue": "pairing-1"
252
+ } }
253
+ },
254
+ {
255
+ "opcode": "isPairingConnected",
256
+ "blockType": "BOOLEAN",
257
+ "text": "pairing [SESSION] connected?",
258
+ "description": "Reports whether WebRTC has established the connection for this session.",
259
+ "arguments": { "SESSION": {
260
+ "type": "STRING",
261
+ "defaultValue": "pairing-1"
262
+ } }
263
+ },
264
+ {
265
+ "opcode": "waitUntilPairingConnected",
266
+ "blockType": "COMMAND",
267
+ "text": "wait until pairing [SESSION] is connected",
268
+ "description": "Waits for the connection, or fails when the session is cancelled, times out, or fails.",
269
+ "arguments": { "SESSION": {
270
+ "type": "STRING",
271
+ "defaultValue": "pairing-1"
272
+ } }
273
+ },
274
+ {
275
+ "opcode": "pairingError",
276
+ "blockType": "REPORTER",
277
+ "text": "pairing error code of [SESSION]",
278
+ "description": "Returns the latest error code, such as hash-mismatch or peer-mismatch, or an empty string.",
279
+ "arguments": { "SESSION": {
280
+ "type": "STRING",
281
+ "defaultValue": "pairing-1"
282
+ } }
283
+ },
284
+ {
285
+ "opcode": "pairingErrorMessage",
286
+ "blockType": "REPORTER",
287
+ "text": "pairing error message of [SESSION]",
288
+ "description": "Returns the latest error message. Pairing codes and QR payloads are never included.",
289
+ "arguments": { "SESSION": {
290
+ "type": "STRING",
291
+ "defaultValue": "pairing-1"
292
+ } }
293
+ },
294
+ {
295
+ "opcode": "pairingLocalPeer",
296
+ "blockType": "REPORTER",
297
+ "text": "local peer of [SESSION]",
298
+ "description": "Returns the name this machine uses for itself in this exchange.",
299
+ "arguments": { "SESSION": {
300
+ "type": "STRING",
301
+ "defaultValue": "pairing-1"
302
+ } }
303
+ },
304
+ {
305
+ "opcode": "pairingRemotePeer",
306
+ "blockType": "REPORTER",
307
+ "text": "remote peer of [SESSION]",
308
+ "description": "Returns the name this machine uses for the other machine, which is also its WebRTC peer name.",
309
+ "arguments": { "SESSION": {
310
+ "type": "STRING",
311
+ "defaultValue": "pairing-1"
312
+ } }
313
+ },
314
+ {
315
+ "opcode": "pairingExchangeId",
316
+ "blockType": "REPORTER",
317
+ "text": "exchange id of [SESSION]",
318
+ "description": "Returns the identifier of the current offer and answer exchange. A retry allocates a new one.",
319
+ "arguments": { "SESSION": {
320
+ "type": "STRING",
321
+ "defaultValue": "pairing-1"
322
+ } }
323
+ },
324
+ {
325
+ "opcode": "pairingRemainingSeconds",
326
+ "blockType": "REPORTER",
327
+ "text": "remaining seconds of [SESSION]",
328
+ "description": "Returns the seconds left before the exchange times out.",
329
+ "arguments": { "SESSION": {
330
+ "type": "STRING",
331
+ "defaultValue": "pairing-1"
332
+ } }
333
+ },
334
+ {
335
+ "opcode": "pairingSessions",
336
+ "blockType": "REPORTER",
337
+ "text": "pairing sessions",
338
+ "description": "Returns the open session names, separated by commas.",
339
+ "arguments": {}
340
+ },
341
+ {
342
+ "opcode": "cancelPairing",
343
+ "blockType": "COMMAND",
344
+ "text": "cancel pairing [SESSION]",
345
+ "description": "Cancels the exchange and releases displays, buffers, and unconnected peers. Established connections stay up.",
346
+ "arguments": { "SESSION": {
347
+ "type": "STRING",
348
+ "defaultValue": "pairing-1"
349
+ } }
350
+ },
351
+ {
352
+ "opcode": "retryPairing",
353
+ "blockType": "COMMAND",
354
+ "text": "retry pairing [SESSION]",
355
+ "description": "Starts a new exchange for the same session. QR codes from the previous exchange stop being accepted.",
356
+ "arguments": { "SESSION": {
357
+ "type": "STRING",
358
+ "defaultValue": "pairing-1"
359
+ } }
360
+ },
361
+ {
362
+ "opcode": "setPairingTimeout",
363
+ "blockType": "COMMAND",
364
+ "text": "set pairing timeout of [SESSION] to [SECONDS] seconds",
365
+ "description": "Sets how long the exchange waits, measured on this machine's own clock.",
366
+ "arguments": {
367
+ "SESSION": {
368
+ "type": "STRING",
369
+ "defaultValue": "pairing-1"
370
+ },
371
+ "SECONDS": {
372
+ "type": "NUMBER",
373
+ "defaultValue": 600
374
+ }
375
+ }
376
+ }
377
+ ]
378
+ };
379
+ //#endregion
380
+ //#region src/config/feature-flags.ts
381
+ var overrides = globalThis.__TWQP_FEATURE_FLAGS__;
382
+ /**
383
+ * Startup-fixed flags, read once and frozen. The QR pairing path stays opt-in
384
+ * until it is verified on hardware; turning it off is a route switch back to
385
+ * manual offer/answer exchange, not a disconnect of established connections.
386
+ */
387
+ var featureFlags = Object.freeze({ qrCodePairing: overrides?.qrCodePairing === true });
388
+ //#endregion
389
+ //#region src/clock.ts
390
+ var systemMonotonicClock = { nowMilliseconds: () => typeof performance === "object" && typeof performance.now === "function" ? performance.now() : Date.now() };
391
+ //#endregion
392
+ //#region src/config/qr-config.ts
393
+ var configuredLevel = globalThis.__TWQP_QR_CONFIG__?.errorCorrectionLevel;
394
+ /**
395
+ * Startup-fixed QR settings. M is the software-validated default; higher levels
396
+ * survive worse optical conditions but carry fewer characters per symbol, which
397
+ * raises the part count the operator has to carry.
398
+ */
399
+ var qrConfig = Object.freeze({ errorCorrectionLevel: isLevel(configuredLevel) ? configuredLevel : "M" });
400
+ function isLevel(value) {
401
+ return value === "L" || value === "M" || value === "Q" || value === "H";
402
+ }
403
+ //#endregion
404
+ //#region src/errors.ts
405
+ var QrPairingError = class extends Error {
406
+ constructor(code, message, options) {
407
+ super(message, options);
408
+ this.name = "QrPairingError";
409
+ this.code = code;
410
+ }
411
+ };
412
+ //#endregion
413
+ //#region node_modules/.pnpm/qrcode@1.5.4/node_modules/qrcode/lib/can-promise.js
414
+ var require_can_promise = /* @__PURE__ */ __commonJSMin(((exports, module) => {
415
+ module.exports = function() {
416
+ return typeof Promise === "function" && Promise.prototype && Promise.prototype.then;
417
+ };
418
+ }));
419
+ //#endregion
420
+ //#region node_modules/.pnpm/qrcode@1.5.4/node_modules/qrcode/lib/core/utils.js
421
+ var require_utils$1 = /* @__PURE__ */ __commonJSMin(((exports) => {
422
+ var toSJISFunction;
423
+ var CODEWORDS_COUNT = [
424
+ 0,
425
+ 26,
426
+ 44,
427
+ 70,
428
+ 100,
429
+ 134,
430
+ 172,
431
+ 196,
432
+ 242,
433
+ 292,
434
+ 346,
435
+ 404,
436
+ 466,
437
+ 532,
438
+ 581,
439
+ 655,
440
+ 733,
441
+ 815,
442
+ 901,
443
+ 991,
444
+ 1085,
445
+ 1156,
446
+ 1258,
447
+ 1364,
448
+ 1474,
449
+ 1588,
450
+ 1706,
451
+ 1828,
452
+ 1921,
453
+ 2051,
454
+ 2185,
455
+ 2323,
456
+ 2465,
457
+ 2611,
458
+ 2761,
459
+ 2876,
460
+ 3034,
461
+ 3196,
462
+ 3362,
463
+ 3532,
464
+ 3706
465
+ ];
466
+ /**
467
+ * Returns the QR Code size for the specified version
468
+ *
469
+ * @param {Number} version QR Code version
470
+ * @return {Number} size of QR code
471
+ */
472
+ exports.getSymbolSize = function getSymbolSize(version) {
473
+ if (!version) throw new Error("\"version\" cannot be null or undefined");
474
+ if (version < 1 || version > 40) throw new Error("\"version\" should be in range from 1 to 40");
475
+ return version * 4 + 17;
476
+ };
477
+ /**
478
+ * Returns the total number of codewords used to store data and EC information.
479
+ *
480
+ * @param {Number} version QR Code version
481
+ * @return {Number} Data length in bits
482
+ */
483
+ exports.getSymbolTotalCodewords = function getSymbolTotalCodewords(version) {
484
+ return CODEWORDS_COUNT[version];
485
+ };
486
+ /**
487
+ * Encode data with Bose-Chaudhuri-Hocquenghem
488
+ *
489
+ * @param {Number} data Value to encode
490
+ * @return {Number} Encoded value
491
+ */
492
+ exports.getBCHDigit = function(data) {
493
+ let digit = 0;
494
+ while (data !== 0) {
495
+ digit++;
496
+ data >>>= 1;
497
+ }
498
+ return digit;
499
+ };
500
+ exports.setToSJISFunction = function setToSJISFunction(f) {
501
+ if (typeof f !== "function") throw new Error("\"toSJISFunc\" is not a valid function.");
502
+ toSJISFunction = f;
503
+ };
504
+ exports.isKanjiModeEnabled = function() {
505
+ return typeof toSJISFunction !== "undefined";
506
+ };
507
+ exports.toSJIS = function toSJIS(kanji) {
508
+ return toSJISFunction(kanji);
509
+ };
510
+ }));
511
+ //#endregion
512
+ //#region node_modules/.pnpm/qrcode@1.5.4/node_modules/qrcode/lib/core/error-correction-level.js
513
+ var require_error_correction_level = /* @__PURE__ */ __commonJSMin(((exports) => {
514
+ exports.L = { bit: 1 };
515
+ exports.M = { bit: 0 };
516
+ exports.Q = { bit: 3 };
517
+ exports.H = { bit: 2 };
518
+ function fromString(string) {
519
+ if (typeof string !== "string") throw new Error("Param is not a string");
520
+ switch (string.toLowerCase()) {
521
+ case "l":
522
+ case "low": return exports.L;
523
+ case "m":
524
+ case "medium": return exports.M;
525
+ case "q":
526
+ case "quartile": return exports.Q;
527
+ case "h":
528
+ case "high": return exports.H;
529
+ default: throw new Error("Unknown EC Level: " + string);
530
+ }
531
+ }
532
+ exports.isValid = function isValid(level) {
533
+ return level && typeof level.bit !== "undefined" && level.bit >= 0 && level.bit < 4;
534
+ };
535
+ exports.from = function from(value, defaultValue) {
536
+ if (exports.isValid(value)) return value;
537
+ try {
538
+ return fromString(value);
539
+ } catch (e) {
540
+ return defaultValue;
541
+ }
542
+ };
543
+ }));
544
+ //#endregion
545
+ //#region node_modules/.pnpm/qrcode@1.5.4/node_modules/qrcode/lib/core/bit-buffer.js
546
+ var require_bit_buffer = /* @__PURE__ */ __commonJSMin(((exports, module) => {
547
+ function BitBuffer() {
548
+ this.buffer = [];
549
+ this.length = 0;
550
+ }
551
+ BitBuffer.prototype = {
552
+ get: function(index) {
553
+ const bufIndex = Math.floor(index / 8);
554
+ return (this.buffer[bufIndex] >>> 7 - index % 8 & 1) === 1;
555
+ },
556
+ put: function(num, length) {
557
+ for (let i = 0; i < length; i++) this.putBit((num >>> length - i - 1 & 1) === 1);
558
+ },
559
+ getLengthInBits: function() {
560
+ return this.length;
561
+ },
562
+ putBit: function(bit) {
563
+ const bufIndex = Math.floor(this.length / 8);
564
+ if (this.buffer.length <= bufIndex) this.buffer.push(0);
565
+ if (bit) this.buffer[bufIndex] |= 128 >>> this.length % 8;
566
+ this.length++;
567
+ }
568
+ };
569
+ module.exports = BitBuffer;
570
+ }));
571
+ //#endregion
572
+ //#region node_modules/.pnpm/qrcode@1.5.4/node_modules/qrcode/lib/core/bit-matrix.js
573
+ var require_bit_matrix = /* @__PURE__ */ __commonJSMin(((exports, module) => {
574
+ /**
575
+ * Helper class to handle QR Code symbol modules
576
+ *
577
+ * @param {Number} size Symbol size
578
+ */
579
+ function BitMatrix(size) {
580
+ if (!size || size < 1) throw new Error("BitMatrix size must be defined and greater than 0");
581
+ this.size = size;
582
+ this.data = new Uint8Array(size * size);
583
+ this.reservedBit = new Uint8Array(size * size);
584
+ }
585
+ /**
586
+ * Set bit value at specified location
587
+ * If reserved flag is set, this bit will be ignored during masking process
588
+ *
589
+ * @param {Number} row
590
+ * @param {Number} col
591
+ * @param {Boolean} value
592
+ * @param {Boolean} reserved
593
+ */
594
+ BitMatrix.prototype.set = function(row, col, value, reserved) {
595
+ const index = row * this.size + col;
596
+ this.data[index] = value;
597
+ if (reserved) this.reservedBit[index] = true;
598
+ };
599
+ /**
600
+ * Returns bit value at specified location
601
+ *
602
+ * @param {Number} row
603
+ * @param {Number} col
604
+ * @return {Boolean}
605
+ */
606
+ BitMatrix.prototype.get = function(row, col) {
607
+ return this.data[row * this.size + col];
608
+ };
609
+ /**
610
+ * Applies xor operator at specified location
611
+ * (used during masking process)
612
+ *
613
+ * @param {Number} row
614
+ * @param {Number} col
615
+ * @param {Boolean} value
616
+ */
617
+ BitMatrix.prototype.xor = function(row, col, value) {
618
+ this.data[row * this.size + col] ^= value;
619
+ };
620
+ /**
621
+ * Check if bit at specified location is reserved
622
+ *
623
+ * @param {Number} row
624
+ * @param {Number} col
625
+ * @return {Boolean}
626
+ */
627
+ BitMatrix.prototype.isReserved = function(row, col) {
628
+ return this.reservedBit[row * this.size + col];
629
+ };
630
+ module.exports = BitMatrix;
631
+ }));
632
+ //#endregion
633
+ //#region node_modules/.pnpm/qrcode@1.5.4/node_modules/qrcode/lib/core/alignment-pattern.js
634
+ var require_alignment_pattern = /* @__PURE__ */ __commonJSMin(((exports) => {
635
+ /**
636
+ * Alignment pattern are fixed reference pattern in defined positions
637
+ * in a matrix symbology, which enables the decode software to re-synchronise
638
+ * the coordinate mapping of the image modules in the event of moderate amounts
639
+ * of distortion of the image.
640
+ *
641
+ * Alignment patterns are present only in QR Code symbols of version 2 or larger
642
+ * and their number depends on the symbol version.
643
+ */
644
+ var getSymbolSize = require_utils$1().getSymbolSize;
645
+ /**
646
+ * Calculate the row/column coordinates of the center module of each alignment pattern
647
+ * for the specified QR Code version.
648
+ *
649
+ * The alignment patterns are positioned symmetrically on either side of the diagonal
650
+ * running from the top left corner of the symbol to the bottom right corner.
651
+ *
652
+ * Since positions are simmetrical only half of the coordinates are returned.
653
+ * Each item of the array will represent in turn the x and y coordinate.
654
+ * @see {@link getPositions}
655
+ *
656
+ * @param {Number} version QR Code version
657
+ * @return {Array} Array of coordinate
658
+ */
659
+ exports.getRowColCoords = function getRowColCoords(version) {
660
+ if (version === 1) return [];
661
+ const posCount = Math.floor(version / 7) + 2;
662
+ const size = getSymbolSize(version);
663
+ const intervals = size === 145 ? 26 : Math.ceil((size - 13) / (2 * posCount - 2)) * 2;
664
+ const positions = [size - 7];
665
+ for (let i = 1; i < posCount - 1; i++) positions[i] = positions[i - 1] - intervals;
666
+ positions.push(6);
667
+ return positions.reverse();
668
+ };
669
+ /**
670
+ * Returns an array containing the positions of each alignment pattern.
671
+ * Each array's element represent the center point of the pattern as (x, y) coordinates
672
+ *
673
+ * Coordinates are calculated expanding the row/column coordinates returned by {@link getRowColCoords}
674
+ * and filtering out the items that overlaps with finder pattern
675
+ *
676
+ * @example
677
+ * For a Version 7 symbol {@link getRowColCoords} returns values 6, 22 and 38.
678
+ * The alignment patterns, therefore, are to be centered on (row, column)
679
+ * positions (6,22), (22,6), (22,22), (22,38), (38,22), (38,38).
680
+ * Note that the coordinates (6,6), (6,38), (38,6) are occupied by finder patterns
681
+ * and are not therefore used for alignment patterns.
682
+ *
683
+ * let pos = getPositions(7)
684
+ * // [[6,22], [22,6], [22,22], [22,38], [38,22], [38,38]]
685
+ *
686
+ * @param {Number} version QR Code version
687
+ * @return {Array} Array of coordinates
688
+ */
689
+ exports.getPositions = function getPositions(version) {
690
+ const coords = [];
691
+ const pos = exports.getRowColCoords(version);
692
+ const posLength = pos.length;
693
+ for (let i = 0; i < posLength; i++) for (let j = 0; j < posLength; j++) {
694
+ if (i === 0 && j === 0 || i === 0 && j === posLength - 1 || i === posLength - 1 && j === 0) continue;
695
+ coords.push([pos[i], pos[j]]);
696
+ }
697
+ return coords;
698
+ };
699
+ }));
700
+ //#endregion
701
+ //#region node_modules/.pnpm/qrcode@1.5.4/node_modules/qrcode/lib/core/finder-pattern.js
702
+ var require_finder_pattern = /* @__PURE__ */ __commonJSMin(((exports) => {
703
+ var getSymbolSize = require_utils$1().getSymbolSize;
704
+ var FINDER_PATTERN_SIZE = 7;
705
+ /**
706
+ * Returns an array containing the positions of each finder pattern.
707
+ * Each array's element represent the top-left point of the pattern as (x, y) coordinates
708
+ *
709
+ * @param {Number} version QR Code version
710
+ * @return {Array} Array of coordinates
711
+ */
712
+ exports.getPositions = function getPositions(version) {
713
+ const size = getSymbolSize(version);
714
+ return [
715
+ [0, 0],
716
+ [size - FINDER_PATTERN_SIZE, 0],
717
+ [0, size - FINDER_PATTERN_SIZE]
718
+ ];
719
+ };
720
+ }));
721
+ //#endregion
722
+ //#region node_modules/.pnpm/qrcode@1.5.4/node_modules/qrcode/lib/core/mask-pattern.js
723
+ var require_mask_pattern = /* @__PURE__ */ __commonJSMin(((exports) => {
724
+ /**
725
+ * Data mask pattern reference
726
+ * @type {Object}
727
+ */
728
+ exports.Patterns = {
729
+ PATTERN000: 0,
730
+ PATTERN001: 1,
731
+ PATTERN010: 2,
732
+ PATTERN011: 3,
733
+ PATTERN100: 4,
734
+ PATTERN101: 5,
735
+ PATTERN110: 6,
736
+ PATTERN111: 7
737
+ };
738
+ /**
739
+ * Weighted penalty scores for the undesirable features
740
+ * @type {Object}
741
+ */
742
+ var PenaltyScores = {
743
+ N1: 3,
744
+ N2: 3,
745
+ N3: 40,
746
+ N4: 10
747
+ };
748
+ /**
749
+ * Check if mask pattern value is valid
750
+ *
751
+ * @param {Number} mask Mask pattern
752
+ * @return {Boolean} true if valid, false otherwise
753
+ */
754
+ exports.isValid = function isValid(mask) {
755
+ return mask != null && mask !== "" && !isNaN(mask) && mask >= 0 && mask <= 7;
756
+ };
757
+ /**
758
+ * Returns mask pattern from a value.
759
+ * If value is not valid, returns undefined
760
+ *
761
+ * @param {Number|String} value Mask pattern value
762
+ * @return {Number} Valid mask pattern or undefined
763
+ */
764
+ exports.from = function from(value) {
765
+ return exports.isValid(value) ? parseInt(value, 10) : void 0;
766
+ };
767
+ /**
768
+ * Find adjacent modules in row/column with the same color
769
+ * and assign a penalty value.
770
+ *
771
+ * Points: N1 + i
772
+ * i is the amount by which the number of adjacent modules of the same color exceeds 5
773
+ */
774
+ exports.getPenaltyN1 = function getPenaltyN1(data) {
775
+ const size = data.size;
776
+ let points = 0;
777
+ let sameCountCol = 0;
778
+ let sameCountRow = 0;
779
+ let lastCol = null;
780
+ let lastRow = null;
781
+ for (let row = 0; row < size; row++) {
782
+ sameCountCol = sameCountRow = 0;
783
+ lastCol = lastRow = null;
784
+ for (let col = 0; col < size; col++) {
785
+ let module$1 = data.get(row, col);
786
+ if (module$1 === lastCol) sameCountCol++;
787
+ else {
788
+ if (sameCountCol >= 5) points += PenaltyScores.N1 + (sameCountCol - 5);
789
+ lastCol = module$1;
790
+ sameCountCol = 1;
791
+ }
792
+ module$1 = data.get(col, row);
793
+ if (module$1 === lastRow) sameCountRow++;
794
+ else {
795
+ if (sameCountRow >= 5) points += PenaltyScores.N1 + (sameCountRow - 5);
796
+ lastRow = module$1;
797
+ sameCountRow = 1;
798
+ }
799
+ }
800
+ if (sameCountCol >= 5) points += PenaltyScores.N1 + (sameCountCol - 5);
801
+ if (sameCountRow >= 5) points += PenaltyScores.N1 + (sameCountRow - 5);
802
+ }
803
+ return points;
804
+ };
805
+ /**
806
+ * Find 2x2 blocks with the same color and assign a penalty value
807
+ *
808
+ * Points: N2 * (m - 1) * (n - 1)
809
+ */
810
+ exports.getPenaltyN2 = function getPenaltyN2(data) {
811
+ const size = data.size;
812
+ let points = 0;
813
+ for (let row = 0; row < size - 1; row++) for (let col = 0; col < size - 1; col++) {
814
+ const last = data.get(row, col) + data.get(row, col + 1) + data.get(row + 1, col) + data.get(row + 1, col + 1);
815
+ if (last === 4 || last === 0) points++;
816
+ }
817
+ return points * PenaltyScores.N2;
818
+ };
819
+ /**
820
+ * Find 1:1:3:1:1 ratio (dark:light:dark:light:dark) pattern in row/column,
821
+ * preceded or followed by light area 4 modules wide
822
+ *
823
+ * Points: N3 * number of pattern found
824
+ */
825
+ exports.getPenaltyN3 = function getPenaltyN3(data) {
826
+ const size = data.size;
827
+ let points = 0;
828
+ let bitsCol = 0;
829
+ let bitsRow = 0;
830
+ for (let row = 0; row < size; row++) {
831
+ bitsCol = bitsRow = 0;
832
+ for (let col = 0; col < size; col++) {
833
+ bitsCol = bitsCol << 1 & 2047 | data.get(row, col);
834
+ if (col >= 10 && (bitsCol === 1488 || bitsCol === 93)) points++;
835
+ bitsRow = bitsRow << 1 & 2047 | data.get(col, row);
836
+ if (col >= 10 && (bitsRow === 1488 || bitsRow === 93)) points++;
837
+ }
838
+ }
839
+ return points * PenaltyScores.N3;
840
+ };
841
+ /**
842
+ * Calculate proportion of dark modules in entire symbol
843
+ *
844
+ * Points: N4 * k
845
+ *
846
+ * k is the rating of the deviation of the proportion of dark modules
847
+ * in the symbol from 50% in steps of 5%
848
+ */
849
+ exports.getPenaltyN4 = function getPenaltyN4(data) {
850
+ let darkCount = 0;
851
+ const modulesCount = data.data.length;
852
+ for (let i = 0; i < modulesCount; i++) darkCount += data.data[i];
853
+ return Math.abs(Math.ceil(darkCount * 100 / modulesCount / 5) - 10) * PenaltyScores.N4;
854
+ };
855
+ /**
856
+ * Return mask value at given position
857
+ *
858
+ * @param {Number} maskPattern Pattern reference value
859
+ * @param {Number} i Row
860
+ * @param {Number} j Column
861
+ * @return {Boolean} Mask value
862
+ */
863
+ function getMaskAt(maskPattern, i, j) {
864
+ switch (maskPattern) {
865
+ case exports.Patterns.PATTERN000: return (i + j) % 2 === 0;
866
+ case exports.Patterns.PATTERN001: return i % 2 === 0;
867
+ case exports.Patterns.PATTERN010: return j % 3 === 0;
868
+ case exports.Patterns.PATTERN011: return (i + j) % 3 === 0;
869
+ case exports.Patterns.PATTERN100: return (Math.floor(i / 2) + Math.floor(j / 3)) % 2 === 0;
870
+ case exports.Patterns.PATTERN101: return i * j % 2 + i * j % 3 === 0;
871
+ case exports.Patterns.PATTERN110: return (i * j % 2 + i * j % 3) % 2 === 0;
872
+ case exports.Patterns.PATTERN111: return (i * j % 3 + (i + j) % 2) % 2 === 0;
873
+ default: throw new Error("bad maskPattern:" + maskPattern);
874
+ }
875
+ }
876
+ /**
877
+ * Apply a mask pattern to a BitMatrix
878
+ *
879
+ * @param {Number} pattern Pattern reference number
880
+ * @param {BitMatrix} data BitMatrix data
881
+ */
882
+ exports.applyMask = function applyMask(pattern, data) {
883
+ const size = data.size;
884
+ for (let col = 0; col < size; col++) for (let row = 0; row < size; row++) {
885
+ if (data.isReserved(row, col)) continue;
886
+ data.xor(row, col, getMaskAt(pattern, row, col));
887
+ }
888
+ };
889
+ /**
890
+ * Returns the best mask pattern for data
891
+ *
892
+ * @param {BitMatrix} data
893
+ * @return {Number} Mask pattern reference number
894
+ */
895
+ exports.getBestMask = function getBestMask(data, setupFormatFunc) {
896
+ const numPatterns = Object.keys(exports.Patterns).length;
897
+ let bestPattern = 0;
898
+ let lowerPenalty = Infinity;
899
+ for (let p = 0; p < numPatterns; p++) {
900
+ setupFormatFunc(p);
901
+ exports.applyMask(p, data);
902
+ const penalty = exports.getPenaltyN1(data) + exports.getPenaltyN2(data) + exports.getPenaltyN3(data) + exports.getPenaltyN4(data);
903
+ exports.applyMask(p, data);
904
+ if (penalty < lowerPenalty) {
905
+ lowerPenalty = penalty;
906
+ bestPattern = p;
907
+ }
908
+ }
909
+ return bestPattern;
910
+ };
911
+ }));
912
+ //#endregion
913
+ //#region node_modules/.pnpm/qrcode@1.5.4/node_modules/qrcode/lib/core/error-correction-code.js
914
+ var require_error_correction_code = /* @__PURE__ */ __commonJSMin(((exports) => {
915
+ var ECLevel = require_error_correction_level();
916
+ var EC_BLOCKS_TABLE = [
917
+ 1,
918
+ 1,
919
+ 1,
920
+ 1,
921
+ 1,
922
+ 1,
923
+ 1,
924
+ 1,
925
+ 1,
926
+ 1,
927
+ 2,
928
+ 2,
929
+ 1,
930
+ 2,
931
+ 2,
932
+ 4,
933
+ 1,
934
+ 2,
935
+ 4,
936
+ 4,
937
+ 2,
938
+ 4,
939
+ 4,
940
+ 4,
941
+ 2,
942
+ 4,
943
+ 6,
944
+ 5,
945
+ 2,
946
+ 4,
947
+ 6,
948
+ 6,
949
+ 2,
950
+ 5,
951
+ 8,
952
+ 8,
953
+ 4,
954
+ 5,
955
+ 8,
956
+ 8,
957
+ 4,
958
+ 5,
959
+ 8,
960
+ 11,
961
+ 4,
962
+ 8,
963
+ 10,
964
+ 11,
965
+ 4,
966
+ 9,
967
+ 12,
968
+ 16,
969
+ 4,
970
+ 9,
971
+ 16,
972
+ 16,
973
+ 6,
974
+ 10,
975
+ 12,
976
+ 18,
977
+ 6,
978
+ 10,
979
+ 17,
980
+ 16,
981
+ 6,
982
+ 11,
983
+ 16,
984
+ 19,
985
+ 6,
986
+ 13,
987
+ 18,
988
+ 21,
989
+ 7,
990
+ 14,
991
+ 21,
992
+ 25,
993
+ 8,
994
+ 16,
995
+ 20,
996
+ 25,
997
+ 8,
998
+ 17,
999
+ 23,
1000
+ 25,
1001
+ 9,
1002
+ 17,
1003
+ 23,
1004
+ 34,
1005
+ 9,
1006
+ 18,
1007
+ 25,
1008
+ 30,
1009
+ 10,
1010
+ 20,
1011
+ 27,
1012
+ 32,
1013
+ 12,
1014
+ 21,
1015
+ 29,
1016
+ 35,
1017
+ 12,
1018
+ 23,
1019
+ 34,
1020
+ 37,
1021
+ 12,
1022
+ 25,
1023
+ 34,
1024
+ 40,
1025
+ 13,
1026
+ 26,
1027
+ 35,
1028
+ 42,
1029
+ 14,
1030
+ 28,
1031
+ 38,
1032
+ 45,
1033
+ 15,
1034
+ 29,
1035
+ 40,
1036
+ 48,
1037
+ 16,
1038
+ 31,
1039
+ 43,
1040
+ 51,
1041
+ 17,
1042
+ 33,
1043
+ 45,
1044
+ 54,
1045
+ 18,
1046
+ 35,
1047
+ 48,
1048
+ 57,
1049
+ 19,
1050
+ 37,
1051
+ 51,
1052
+ 60,
1053
+ 19,
1054
+ 38,
1055
+ 53,
1056
+ 63,
1057
+ 20,
1058
+ 40,
1059
+ 56,
1060
+ 66,
1061
+ 21,
1062
+ 43,
1063
+ 59,
1064
+ 70,
1065
+ 22,
1066
+ 45,
1067
+ 62,
1068
+ 74,
1069
+ 24,
1070
+ 47,
1071
+ 65,
1072
+ 77,
1073
+ 25,
1074
+ 49,
1075
+ 68,
1076
+ 81
1077
+ ];
1078
+ var EC_CODEWORDS_TABLE = [
1079
+ 7,
1080
+ 10,
1081
+ 13,
1082
+ 17,
1083
+ 10,
1084
+ 16,
1085
+ 22,
1086
+ 28,
1087
+ 15,
1088
+ 26,
1089
+ 36,
1090
+ 44,
1091
+ 20,
1092
+ 36,
1093
+ 52,
1094
+ 64,
1095
+ 26,
1096
+ 48,
1097
+ 72,
1098
+ 88,
1099
+ 36,
1100
+ 64,
1101
+ 96,
1102
+ 112,
1103
+ 40,
1104
+ 72,
1105
+ 108,
1106
+ 130,
1107
+ 48,
1108
+ 88,
1109
+ 132,
1110
+ 156,
1111
+ 60,
1112
+ 110,
1113
+ 160,
1114
+ 192,
1115
+ 72,
1116
+ 130,
1117
+ 192,
1118
+ 224,
1119
+ 80,
1120
+ 150,
1121
+ 224,
1122
+ 264,
1123
+ 96,
1124
+ 176,
1125
+ 260,
1126
+ 308,
1127
+ 104,
1128
+ 198,
1129
+ 288,
1130
+ 352,
1131
+ 120,
1132
+ 216,
1133
+ 320,
1134
+ 384,
1135
+ 132,
1136
+ 240,
1137
+ 360,
1138
+ 432,
1139
+ 144,
1140
+ 280,
1141
+ 408,
1142
+ 480,
1143
+ 168,
1144
+ 308,
1145
+ 448,
1146
+ 532,
1147
+ 180,
1148
+ 338,
1149
+ 504,
1150
+ 588,
1151
+ 196,
1152
+ 364,
1153
+ 546,
1154
+ 650,
1155
+ 224,
1156
+ 416,
1157
+ 600,
1158
+ 700,
1159
+ 224,
1160
+ 442,
1161
+ 644,
1162
+ 750,
1163
+ 252,
1164
+ 476,
1165
+ 690,
1166
+ 816,
1167
+ 270,
1168
+ 504,
1169
+ 750,
1170
+ 900,
1171
+ 300,
1172
+ 560,
1173
+ 810,
1174
+ 960,
1175
+ 312,
1176
+ 588,
1177
+ 870,
1178
+ 1050,
1179
+ 336,
1180
+ 644,
1181
+ 952,
1182
+ 1110,
1183
+ 360,
1184
+ 700,
1185
+ 1020,
1186
+ 1200,
1187
+ 390,
1188
+ 728,
1189
+ 1050,
1190
+ 1260,
1191
+ 420,
1192
+ 784,
1193
+ 1140,
1194
+ 1350,
1195
+ 450,
1196
+ 812,
1197
+ 1200,
1198
+ 1440,
1199
+ 480,
1200
+ 868,
1201
+ 1290,
1202
+ 1530,
1203
+ 510,
1204
+ 924,
1205
+ 1350,
1206
+ 1620,
1207
+ 540,
1208
+ 980,
1209
+ 1440,
1210
+ 1710,
1211
+ 570,
1212
+ 1036,
1213
+ 1530,
1214
+ 1800,
1215
+ 570,
1216
+ 1064,
1217
+ 1590,
1218
+ 1890,
1219
+ 600,
1220
+ 1120,
1221
+ 1680,
1222
+ 1980,
1223
+ 630,
1224
+ 1204,
1225
+ 1770,
1226
+ 2100,
1227
+ 660,
1228
+ 1260,
1229
+ 1860,
1230
+ 2220,
1231
+ 720,
1232
+ 1316,
1233
+ 1950,
1234
+ 2310,
1235
+ 750,
1236
+ 1372,
1237
+ 2040,
1238
+ 2430
1239
+ ];
1240
+ /**
1241
+ * Returns the number of error correction block that the QR Code should contain
1242
+ * for the specified version and error correction level.
1243
+ *
1244
+ * @param {Number} version QR Code version
1245
+ * @param {Number} errorCorrectionLevel Error correction level
1246
+ * @return {Number} Number of error correction blocks
1247
+ */
1248
+ exports.getBlocksCount = function getBlocksCount(version, errorCorrectionLevel) {
1249
+ switch (errorCorrectionLevel) {
1250
+ case ECLevel.L: return EC_BLOCKS_TABLE[(version - 1) * 4 + 0];
1251
+ case ECLevel.M: return EC_BLOCKS_TABLE[(version - 1) * 4 + 1];
1252
+ case ECLevel.Q: return EC_BLOCKS_TABLE[(version - 1) * 4 + 2];
1253
+ case ECLevel.H: return EC_BLOCKS_TABLE[(version - 1) * 4 + 3];
1254
+ default: return;
1255
+ }
1256
+ };
1257
+ /**
1258
+ * Returns the number of error correction codewords to use for the specified
1259
+ * version and error correction level.
1260
+ *
1261
+ * @param {Number} version QR Code version
1262
+ * @param {Number} errorCorrectionLevel Error correction level
1263
+ * @return {Number} Number of error correction codewords
1264
+ */
1265
+ exports.getTotalCodewordsCount = function getTotalCodewordsCount(version, errorCorrectionLevel) {
1266
+ switch (errorCorrectionLevel) {
1267
+ case ECLevel.L: return EC_CODEWORDS_TABLE[(version - 1) * 4 + 0];
1268
+ case ECLevel.M: return EC_CODEWORDS_TABLE[(version - 1) * 4 + 1];
1269
+ case ECLevel.Q: return EC_CODEWORDS_TABLE[(version - 1) * 4 + 2];
1270
+ case ECLevel.H: return EC_CODEWORDS_TABLE[(version - 1) * 4 + 3];
1271
+ default: return;
1272
+ }
1273
+ };
1274
+ }));
1275
+ //#endregion
1276
+ //#region node_modules/.pnpm/qrcode@1.5.4/node_modules/qrcode/lib/core/galois-field.js
1277
+ var require_galois_field = /* @__PURE__ */ __commonJSMin(((exports) => {
1278
+ var EXP_TABLE = /* @__PURE__ */ new Uint8Array(512);
1279
+ var LOG_TABLE = /* @__PURE__ */ new Uint8Array(256);
1280
+ (function initTables() {
1281
+ let x = 1;
1282
+ for (let i = 0; i < 255; i++) {
1283
+ EXP_TABLE[i] = x;
1284
+ LOG_TABLE[x] = i;
1285
+ x <<= 1;
1286
+ if (x & 256) x ^= 285;
1287
+ }
1288
+ for (let i = 255; i < 512; i++) EXP_TABLE[i] = EXP_TABLE[i - 255];
1289
+ })();
1290
+ /**
1291
+ * Returns log value of n inside Galois Field
1292
+ *
1293
+ * @param {Number} n
1294
+ * @return {Number}
1295
+ */
1296
+ exports.log = function log(n) {
1297
+ if (n < 1) throw new Error("log(" + n + ")");
1298
+ return LOG_TABLE[n];
1299
+ };
1300
+ /**
1301
+ * Returns anti-log value of n inside Galois Field
1302
+ *
1303
+ * @param {Number} n
1304
+ * @return {Number}
1305
+ */
1306
+ exports.exp = function exp(n) {
1307
+ return EXP_TABLE[n];
1308
+ };
1309
+ /**
1310
+ * Multiplies two number inside Galois Field
1311
+ *
1312
+ * @param {Number} x
1313
+ * @param {Number} y
1314
+ * @return {Number}
1315
+ */
1316
+ exports.mul = function mul(x, y) {
1317
+ if (x === 0 || y === 0) return 0;
1318
+ return EXP_TABLE[LOG_TABLE[x] + LOG_TABLE[y]];
1319
+ };
1320
+ }));
1321
+ //#endregion
1322
+ //#region node_modules/.pnpm/qrcode@1.5.4/node_modules/qrcode/lib/core/polynomial.js
1323
+ var require_polynomial = /* @__PURE__ */ __commonJSMin(((exports) => {
1324
+ var GF = require_galois_field();
1325
+ /**
1326
+ * Multiplies two polynomials inside Galois Field
1327
+ *
1328
+ * @param {Uint8Array} p1 Polynomial
1329
+ * @param {Uint8Array} p2 Polynomial
1330
+ * @return {Uint8Array} Product of p1 and p2
1331
+ */
1332
+ exports.mul = function mul(p1, p2) {
1333
+ const coeff = new Uint8Array(p1.length + p2.length - 1);
1334
+ for (let i = 0; i < p1.length; i++) for (let j = 0; j < p2.length; j++) coeff[i + j] ^= GF.mul(p1[i], p2[j]);
1335
+ return coeff;
1336
+ };
1337
+ /**
1338
+ * Calculate the remainder of polynomials division
1339
+ *
1340
+ * @param {Uint8Array} divident Polynomial
1341
+ * @param {Uint8Array} divisor Polynomial
1342
+ * @return {Uint8Array} Remainder
1343
+ */
1344
+ exports.mod = function mod(divident, divisor) {
1345
+ let result = new Uint8Array(divident);
1346
+ while (result.length - divisor.length >= 0) {
1347
+ const coeff = result[0];
1348
+ for (let i = 0; i < divisor.length; i++) result[i] ^= GF.mul(divisor[i], coeff);
1349
+ let offset = 0;
1350
+ while (offset < result.length && result[offset] === 0) offset++;
1351
+ result = result.slice(offset);
1352
+ }
1353
+ return result;
1354
+ };
1355
+ /**
1356
+ * Generate an irreducible generator polynomial of specified degree
1357
+ * (used by Reed-Solomon encoder)
1358
+ *
1359
+ * @param {Number} degree Degree of the generator polynomial
1360
+ * @return {Uint8Array} Buffer containing polynomial coefficients
1361
+ */
1362
+ exports.generateECPolynomial = function generateECPolynomial(degree) {
1363
+ let poly = new Uint8Array([1]);
1364
+ for (let i = 0; i < degree; i++) poly = exports.mul(poly, new Uint8Array([1, GF.exp(i)]));
1365
+ return poly;
1366
+ };
1367
+ }));
1368
+ //#endregion
1369
+ //#region node_modules/.pnpm/qrcode@1.5.4/node_modules/qrcode/lib/core/reed-solomon-encoder.js
1370
+ var require_reed_solomon_encoder = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1371
+ var Polynomial = require_polynomial();
1372
+ function ReedSolomonEncoder(degree) {
1373
+ this.genPoly = void 0;
1374
+ this.degree = degree;
1375
+ if (this.degree) this.initialize(this.degree);
1376
+ }
1377
+ /**
1378
+ * Initialize the encoder.
1379
+ * The input param should correspond to the number of error correction codewords.
1380
+ *
1381
+ * @param {Number} degree
1382
+ */
1383
+ ReedSolomonEncoder.prototype.initialize = function initialize(degree) {
1384
+ this.degree = degree;
1385
+ this.genPoly = Polynomial.generateECPolynomial(this.degree);
1386
+ };
1387
+ /**
1388
+ * Encodes a chunk of data
1389
+ *
1390
+ * @param {Uint8Array} data Buffer containing input data
1391
+ * @return {Uint8Array} Buffer containing encoded data
1392
+ */
1393
+ ReedSolomonEncoder.prototype.encode = function encode(data) {
1394
+ if (!this.genPoly) throw new Error("Encoder not initialized");
1395
+ const paddedData = new Uint8Array(data.length + this.degree);
1396
+ paddedData.set(data);
1397
+ const remainder = Polynomial.mod(paddedData, this.genPoly);
1398
+ const start = this.degree - remainder.length;
1399
+ if (start > 0) {
1400
+ const buff = new Uint8Array(this.degree);
1401
+ buff.set(remainder, start);
1402
+ return buff;
1403
+ }
1404
+ return remainder;
1405
+ };
1406
+ module.exports = ReedSolomonEncoder;
1407
+ }));
1408
+ //#endregion
1409
+ //#region node_modules/.pnpm/qrcode@1.5.4/node_modules/qrcode/lib/core/version-check.js
1410
+ var require_version_check = /* @__PURE__ */ __commonJSMin(((exports) => {
1411
+ /**
1412
+ * Check if QR Code version is valid
1413
+ *
1414
+ * @param {Number} version QR Code version
1415
+ * @return {Boolean} true if valid version, false otherwise
1416
+ */
1417
+ exports.isValid = function isValid(version) {
1418
+ return !isNaN(version) && version >= 1 && version <= 40;
1419
+ };
1420
+ }));
1421
+ //#endregion
1422
+ //#region node_modules/.pnpm/qrcode@1.5.4/node_modules/qrcode/lib/core/regex.js
1423
+ var require_regex = /* @__PURE__ */ __commonJSMin(((exports) => {
1424
+ var numeric = "[0-9]+";
1425
+ var alphanumeric = "[A-Z $%*+\\-./:]+";
1426
+ var kanji = "(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";
1427
+ kanji = kanji.replace(/u/g, "\\u");
1428
+ var byte = "(?:(?![A-Z0-9 $%*+\\-./:]|" + kanji + ")(?:.|[\r\n]))+";
1429
+ exports.KANJI = new RegExp(kanji, "g");
1430
+ exports.BYTE_KANJI = /* @__PURE__ */ new RegExp("[^A-Z0-9 $%*+\\-./:]+", "g");
1431
+ exports.BYTE = new RegExp(byte, "g");
1432
+ exports.NUMERIC = new RegExp(numeric, "g");
1433
+ exports.ALPHANUMERIC = new RegExp(alphanumeric, "g");
1434
+ var TEST_KANJI = new RegExp("^" + kanji + "$");
1435
+ var TEST_NUMERIC = /* @__PURE__ */ new RegExp("^[0-9]+$");
1436
+ var TEST_ALPHANUMERIC = /* @__PURE__ */ new RegExp("^[A-Z0-9 $%*+\\-./:]+$");
1437
+ exports.testKanji = function testKanji(str) {
1438
+ return TEST_KANJI.test(str);
1439
+ };
1440
+ exports.testNumeric = function testNumeric(str) {
1441
+ return TEST_NUMERIC.test(str);
1442
+ };
1443
+ exports.testAlphanumeric = function testAlphanumeric(str) {
1444
+ return TEST_ALPHANUMERIC.test(str);
1445
+ };
1446
+ }));
1447
+ //#endregion
1448
+ //#region node_modules/.pnpm/qrcode@1.5.4/node_modules/qrcode/lib/core/mode.js
1449
+ var require_mode = /* @__PURE__ */ __commonJSMin(((exports) => {
1450
+ var VersionCheck = require_version_check();
1451
+ var Regex = require_regex();
1452
+ /**
1453
+ * Numeric mode encodes data from the decimal digit set (0 - 9)
1454
+ * (byte values 30HEX to 39HEX).
1455
+ * Normally, 3 data characters are represented by 10 bits.
1456
+ *
1457
+ * @type {Object}
1458
+ */
1459
+ exports.NUMERIC = {
1460
+ id: "Numeric",
1461
+ bit: 1,
1462
+ ccBits: [
1463
+ 10,
1464
+ 12,
1465
+ 14
1466
+ ]
1467
+ };
1468
+ /**
1469
+ * Alphanumeric mode encodes data from a set of 45 characters,
1470
+ * i.e. 10 numeric digits (0 - 9),
1471
+ * 26 alphabetic characters (A - Z),
1472
+ * and 9 symbols (SP, $, %, *, +, -, ., /, :).
1473
+ * Normally, two input characters are represented by 11 bits.
1474
+ *
1475
+ * @type {Object}
1476
+ */
1477
+ exports.ALPHANUMERIC = {
1478
+ id: "Alphanumeric",
1479
+ bit: 2,
1480
+ ccBits: [
1481
+ 9,
1482
+ 11,
1483
+ 13
1484
+ ]
1485
+ };
1486
+ /**
1487
+ * In byte mode, data is encoded at 8 bits per character.
1488
+ *
1489
+ * @type {Object}
1490
+ */
1491
+ exports.BYTE = {
1492
+ id: "Byte",
1493
+ bit: 4,
1494
+ ccBits: [
1495
+ 8,
1496
+ 16,
1497
+ 16
1498
+ ]
1499
+ };
1500
+ /**
1501
+ * The Kanji mode efficiently encodes Kanji characters in accordance with
1502
+ * the Shift JIS system based on JIS X 0208.
1503
+ * The Shift JIS values are shifted from the JIS X 0208 values.
1504
+ * JIS X 0208 gives details of the shift coded representation.
1505
+ * Each two-byte character value is compacted to a 13-bit binary codeword.
1506
+ *
1507
+ * @type {Object}
1508
+ */
1509
+ exports.KANJI = {
1510
+ id: "Kanji",
1511
+ bit: 8,
1512
+ ccBits: [
1513
+ 8,
1514
+ 10,
1515
+ 12
1516
+ ]
1517
+ };
1518
+ /**
1519
+ * Mixed mode will contain a sequences of data in a combination of any of
1520
+ * the modes described above
1521
+ *
1522
+ * @type {Object}
1523
+ */
1524
+ exports.MIXED = { bit: -1 };
1525
+ /**
1526
+ * Returns the number of bits needed to store the data length
1527
+ * according to QR Code specifications.
1528
+ *
1529
+ * @param {Mode} mode Data mode
1530
+ * @param {Number} version QR Code version
1531
+ * @return {Number} Number of bits
1532
+ */
1533
+ exports.getCharCountIndicator = function getCharCountIndicator(mode, version) {
1534
+ if (!mode.ccBits) throw new Error("Invalid mode: " + mode);
1535
+ if (!VersionCheck.isValid(version)) throw new Error("Invalid version: " + version);
1536
+ if (version >= 1 && version < 10) return mode.ccBits[0];
1537
+ else if (version < 27) return mode.ccBits[1];
1538
+ return mode.ccBits[2];
1539
+ };
1540
+ /**
1541
+ * Returns the most efficient mode to store the specified data
1542
+ *
1543
+ * @param {String} dataStr Input data string
1544
+ * @return {Mode} Best mode
1545
+ */
1546
+ exports.getBestModeForData = function getBestModeForData(dataStr) {
1547
+ if (Regex.testNumeric(dataStr)) return exports.NUMERIC;
1548
+ else if (Regex.testAlphanumeric(dataStr)) return exports.ALPHANUMERIC;
1549
+ else if (Regex.testKanji(dataStr)) return exports.KANJI;
1550
+ else return exports.BYTE;
1551
+ };
1552
+ /**
1553
+ * Return mode name as string
1554
+ *
1555
+ * @param {Mode} mode Mode object
1556
+ * @returns {String} Mode name
1557
+ */
1558
+ exports.toString = function toString(mode) {
1559
+ if (mode && mode.id) return mode.id;
1560
+ throw new Error("Invalid mode");
1561
+ };
1562
+ /**
1563
+ * Check if input param is a valid mode object
1564
+ *
1565
+ * @param {Mode} mode Mode object
1566
+ * @returns {Boolean} True if valid mode, false otherwise
1567
+ */
1568
+ exports.isValid = function isValid(mode) {
1569
+ return mode && mode.bit && mode.ccBits;
1570
+ };
1571
+ /**
1572
+ * Get mode object from its name
1573
+ *
1574
+ * @param {String} string Mode name
1575
+ * @returns {Mode} Mode object
1576
+ */
1577
+ function fromString(string) {
1578
+ if (typeof string !== "string") throw new Error("Param is not a string");
1579
+ switch (string.toLowerCase()) {
1580
+ case "numeric": return exports.NUMERIC;
1581
+ case "alphanumeric": return exports.ALPHANUMERIC;
1582
+ case "kanji": return exports.KANJI;
1583
+ case "byte": return exports.BYTE;
1584
+ default: throw new Error("Unknown mode: " + string);
1585
+ }
1586
+ }
1587
+ /**
1588
+ * Returns mode from a value.
1589
+ * If value is not a valid mode, returns defaultValue
1590
+ *
1591
+ * @param {Mode|String} value Encoding mode
1592
+ * @param {Mode} defaultValue Fallback value
1593
+ * @return {Mode} Encoding mode
1594
+ */
1595
+ exports.from = function from(value, defaultValue) {
1596
+ if (exports.isValid(value)) return value;
1597
+ try {
1598
+ return fromString(value);
1599
+ } catch (e) {
1600
+ return defaultValue;
1601
+ }
1602
+ };
1603
+ }));
1604
+ //#endregion
1605
+ //#region node_modules/.pnpm/qrcode@1.5.4/node_modules/qrcode/lib/core/version.js
1606
+ var require_version = /* @__PURE__ */ __commonJSMin(((exports) => {
1607
+ var Utils = require_utils$1();
1608
+ var ECCode = require_error_correction_code();
1609
+ var ECLevel = require_error_correction_level();
1610
+ var Mode = require_mode();
1611
+ var VersionCheck = require_version_check();
1612
+ var G18 = 7973;
1613
+ var G18_BCH = Utils.getBCHDigit(G18);
1614
+ function getBestVersionForDataLength(mode, length, errorCorrectionLevel) {
1615
+ for (let currentVersion = 1; currentVersion <= 40; currentVersion++) if (length <= exports.getCapacity(currentVersion, errorCorrectionLevel, mode)) return currentVersion;
1616
+ }
1617
+ function getReservedBitsCount(mode, version) {
1618
+ return Mode.getCharCountIndicator(mode, version) + 4;
1619
+ }
1620
+ function getTotalBitsFromDataArray(segments, version) {
1621
+ let totalBits = 0;
1622
+ segments.forEach(function(data) {
1623
+ const reservedBits = getReservedBitsCount(data.mode, version);
1624
+ totalBits += reservedBits + data.getBitsLength();
1625
+ });
1626
+ return totalBits;
1627
+ }
1628
+ function getBestVersionForMixedData(segments, errorCorrectionLevel) {
1629
+ for (let currentVersion = 1; currentVersion <= 40; currentVersion++) if (getTotalBitsFromDataArray(segments, currentVersion) <= exports.getCapacity(currentVersion, errorCorrectionLevel, Mode.MIXED)) return currentVersion;
1630
+ }
1631
+ /**
1632
+ * Returns version number from a value.
1633
+ * If value is not a valid version, returns defaultValue
1634
+ *
1635
+ * @param {Number|String} value QR Code version
1636
+ * @param {Number} defaultValue Fallback value
1637
+ * @return {Number} QR Code version number
1638
+ */
1639
+ exports.from = function from(value, defaultValue) {
1640
+ if (VersionCheck.isValid(value)) return parseInt(value, 10);
1641
+ return defaultValue;
1642
+ };
1643
+ /**
1644
+ * Returns how much data can be stored with the specified QR code version
1645
+ * and error correction level
1646
+ *
1647
+ * @param {Number} version QR Code version (1-40)
1648
+ * @param {Number} errorCorrectionLevel Error correction level
1649
+ * @param {Mode} mode Data mode
1650
+ * @return {Number} Quantity of storable data
1651
+ */
1652
+ exports.getCapacity = function getCapacity(version, errorCorrectionLevel, mode) {
1653
+ if (!VersionCheck.isValid(version)) throw new Error("Invalid QR Code version");
1654
+ if (typeof mode === "undefined") mode = Mode.BYTE;
1655
+ const dataTotalCodewordsBits = (Utils.getSymbolTotalCodewords(version) - ECCode.getTotalCodewordsCount(version, errorCorrectionLevel)) * 8;
1656
+ if (mode === Mode.MIXED) return dataTotalCodewordsBits;
1657
+ const usableBits = dataTotalCodewordsBits - getReservedBitsCount(mode, version);
1658
+ switch (mode) {
1659
+ case Mode.NUMERIC: return Math.floor(usableBits / 10 * 3);
1660
+ case Mode.ALPHANUMERIC: return Math.floor(usableBits / 11 * 2);
1661
+ case Mode.KANJI: return Math.floor(usableBits / 13);
1662
+ case Mode.BYTE:
1663
+ default: return Math.floor(usableBits / 8);
1664
+ }
1665
+ };
1666
+ /**
1667
+ * Returns the minimum version needed to contain the amount of data
1668
+ *
1669
+ * @param {Segment} data Segment of data
1670
+ * @param {Number} [errorCorrectionLevel=H] Error correction level
1671
+ * @param {Mode} mode Data mode
1672
+ * @return {Number} QR Code version
1673
+ */
1674
+ exports.getBestVersionForData = function getBestVersionForData(data, errorCorrectionLevel) {
1675
+ let seg;
1676
+ const ecl = ECLevel.from(errorCorrectionLevel, ECLevel.M);
1677
+ if (Array.isArray(data)) {
1678
+ if (data.length > 1) return getBestVersionForMixedData(data, ecl);
1679
+ if (data.length === 0) return 1;
1680
+ seg = data[0];
1681
+ } else seg = data;
1682
+ return getBestVersionForDataLength(seg.mode, seg.getLength(), ecl);
1683
+ };
1684
+ /**
1685
+ * Returns version information with relative error correction bits
1686
+ *
1687
+ * The version information is included in QR Code symbols of version 7 or larger.
1688
+ * It consists of an 18-bit sequence containing 6 data bits,
1689
+ * with 12 error correction bits calculated using the (18, 6) Golay code.
1690
+ *
1691
+ * @param {Number} version QR Code version
1692
+ * @return {Number} Encoded version info bits
1693
+ */
1694
+ exports.getEncodedBits = function getEncodedBits(version) {
1695
+ if (!VersionCheck.isValid(version) || version < 7) throw new Error("Invalid QR Code version");
1696
+ let d = version << 12;
1697
+ while (Utils.getBCHDigit(d) - G18_BCH >= 0) d ^= G18 << Utils.getBCHDigit(d) - G18_BCH;
1698
+ return version << 12 | d;
1699
+ };
1700
+ }));
1701
+ //#endregion
1702
+ //#region node_modules/.pnpm/qrcode@1.5.4/node_modules/qrcode/lib/core/format-info.js
1703
+ var require_format_info = /* @__PURE__ */ __commonJSMin(((exports) => {
1704
+ var Utils = require_utils$1();
1705
+ var G15 = 1335;
1706
+ var G15_MASK = 21522;
1707
+ var G15_BCH = Utils.getBCHDigit(G15);
1708
+ /**
1709
+ * Returns format information with relative error correction bits
1710
+ *
1711
+ * The format information is a 15-bit sequence containing 5 data bits,
1712
+ * with 10 error correction bits calculated using the (15, 5) BCH code.
1713
+ *
1714
+ * @param {Number} errorCorrectionLevel Error correction level
1715
+ * @param {Number} mask Mask pattern
1716
+ * @return {Number} Encoded format information bits
1717
+ */
1718
+ exports.getEncodedBits = function getEncodedBits(errorCorrectionLevel, mask) {
1719
+ const data = errorCorrectionLevel.bit << 3 | mask;
1720
+ let d = data << 10;
1721
+ while (Utils.getBCHDigit(d) - G15_BCH >= 0) d ^= G15 << Utils.getBCHDigit(d) - G15_BCH;
1722
+ return (data << 10 | d) ^ G15_MASK;
1723
+ };
1724
+ }));
1725
+ //#endregion
1726
+ //#region node_modules/.pnpm/qrcode@1.5.4/node_modules/qrcode/lib/core/numeric-data.js
1727
+ var require_numeric_data = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1728
+ var Mode = require_mode();
1729
+ function NumericData(data) {
1730
+ this.mode = Mode.NUMERIC;
1731
+ this.data = data.toString();
1732
+ }
1733
+ NumericData.getBitsLength = function getBitsLength(length) {
1734
+ return 10 * Math.floor(length / 3) + (length % 3 ? length % 3 * 3 + 1 : 0);
1735
+ };
1736
+ NumericData.prototype.getLength = function getLength() {
1737
+ return this.data.length;
1738
+ };
1739
+ NumericData.prototype.getBitsLength = function getBitsLength() {
1740
+ return NumericData.getBitsLength(this.data.length);
1741
+ };
1742
+ NumericData.prototype.write = function write(bitBuffer) {
1743
+ let i, group, value;
1744
+ for (i = 0; i + 3 <= this.data.length; i += 3) {
1745
+ group = this.data.substr(i, 3);
1746
+ value = parseInt(group, 10);
1747
+ bitBuffer.put(value, 10);
1748
+ }
1749
+ const remainingNum = this.data.length - i;
1750
+ if (remainingNum > 0) {
1751
+ group = this.data.substr(i);
1752
+ value = parseInt(group, 10);
1753
+ bitBuffer.put(value, remainingNum * 3 + 1);
1754
+ }
1755
+ };
1756
+ module.exports = NumericData;
1757
+ }));
1758
+ //#endregion
1759
+ //#region node_modules/.pnpm/qrcode@1.5.4/node_modules/qrcode/lib/core/alphanumeric-data.js
1760
+ var require_alphanumeric_data = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1761
+ var Mode = require_mode();
1762
+ /**
1763
+ * Array of characters available in alphanumeric mode
1764
+ *
1765
+ * As per QR Code specification, to each character
1766
+ * is assigned a value from 0 to 44 which in this case coincides
1767
+ * with the array index
1768
+ *
1769
+ * @type {Array}
1770
+ */
1771
+ var ALPHA_NUM_CHARS = [
1772
+ "0",
1773
+ "1",
1774
+ "2",
1775
+ "3",
1776
+ "4",
1777
+ "5",
1778
+ "6",
1779
+ "7",
1780
+ "8",
1781
+ "9",
1782
+ "A",
1783
+ "B",
1784
+ "C",
1785
+ "D",
1786
+ "E",
1787
+ "F",
1788
+ "G",
1789
+ "H",
1790
+ "I",
1791
+ "J",
1792
+ "K",
1793
+ "L",
1794
+ "M",
1795
+ "N",
1796
+ "O",
1797
+ "P",
1798
+ "Q",
1799
+ "R",
1800
+ "S",
1801
+ "T",
1802
+ "U",
1803
+ "V",
1804
+ "W",
1805
+ "X",
1806
+ "Y",
1807
+ "Z",
1808
+ " ",
1809
+ "$",
1810
+ "%",
1811
+ "*",
1812
+ "+",
1813
+ "-",
1814
+ ".",
1815
+ "/",
1816
+ ":"
1817
+ ];
1818
+ function AlphanumericData(data) {
1819
+ this.mode = Mode.ALPHANUMERIC;
1820
+ this.data = data;
1821
+ }
1822
+ AlphanumericData.getBitsLength = function getBitsLength(length) {
1823
+ return 11 * Math.floor(length / 2) + 6 * (length % 2);
1824
+ };
1825
+ AlphanumericData.prototype.getLength = function getLength() {
1826
+ return this.data.length;
1827
+ };
1828
+ AlphanumericData.prototype.getBitsLength = function getBitsLength() {
1829
+ return AlphanumericData.getBitsLength(this.data.length);
1830
+ };
1831
+ AlphanumericData.prototype.write = function write(bitBuffer) {
1832
+ let i = 0;
1833
+ for (; i + 2 <= this.data.length; i += 2) {
1834
+ let value = ALPHA_NUM_CHARS.indexOf(this.data[i]) * 45;
1835
+ value += ALPHA_NUM_CHARS.indexOf(this.data[i + 1]);
1836
+ bitBuffer.put(value, 11);
1837
+ }
1838
+ if (this.data.length % 2) bitBuffer.put(ALPHA_NUM_CHARS.indexOf(this.data[i]), 6);
1839
+ };
1840
+ module.exports = AlphanumericData;
1841
+ }));
1842
+ //#endregion
1843
+ //#region node_modules/.pnpm/qrcode@1.5.4/node_modules/qrcode/lib/core/byte-data.js
1844
+ var require_byte_data = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1845
+ var Mode = require_mode();
1846
+ function ByteData(data) {
1847
+ this.mode = Mode.BYTE;
1848
+ if (typeof data === "string") this.data = new TextEncoder().encode(data);
1849
+ else this.data = new Uint8Array(data);
1850
+ }
1851
+ ByteData.getBitsLength = function getBitsLength(length) {
1852
+ return length * 8;
1853
+ };
1854
+ ByteData.prototype.getLength = function getLength() {
1855
+ return this.data.length;
1856
+ };
1857
+ ByteData.prototype.getBitsLength = function getBitsLength() {
1858
+ return ByteData.getBitsLength(this.data.length);
1859
+ };
1860
+ ByteData.prototype.write = function(bitBuffer) {
1861
+ for (let i = 0, l = this.data.length; i < l; i++) bitBuffer.put(this.data[i], 8);
1862
+ };
1863
+ module.exports = ByteData;
1864
+ }));
1865
+ //#endregion
1866
+ //#region node_modules/.pnpm/qrcode@1.5.4/node_modules/qrcode/lib/core/kanji-data.js
1867
+ var require_kanji_data = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1868
+ var Mode = require_mode();
1869
+ var Utils = require_utils$1();
1870
+ function KanjiData(data) {
1871
+ this.mode = Mode.KANJI;
1872
+ this.data = data;
1873
+ }
1874
+ KanjiData.getBitsLength = function getBitsLength(length) {
1875
+ return length * 13;
1876
+ };
1877
+ KanjiData.prototype.getLength = function getLength() {
1878
+ return this.data.length;
1879
+ };
1880
+ KanjiData.prototype.getBitsLength = function getBitsLength() {
1881
+ return KanjiData.getBitsLength(this.data.length);
1882
+ };
1883
+ KanjiData.prototype.write = function(bitBuffer) {
1884
+ let i = 0;
1885
+ for (; i < this.data.length; i++) {
1886
+ let value = Utils.toSJIS(this.data[i]);
1887
+ if (value >= 33088 && value <= 40956) value -= 33088;
1888
+ else if (value >= 57408 && value <= 60351) value -= 49472;
1889
+ else throw new Error("Invalid SJIS character: " + this.data[i] + "\nMake sure your charset is UTF-8");
1890
+ value = (value >>> 8 & 255) * 192 + (value & 255);
1891
+ bitBuffer.put(value, 13);
1892
+ }
1893
+ };
1894
+ module.exports = KanjiData;
1895
+ }));
1896
+ //#endregion
1897
+ //#region node_modules/.pnpm/dijkstrajs@1.0.3/node_modules/dijkstrajs/dijkstra.js
1898
+ var require_dijkstra = /* @__PURE__ */ __commonJSMin(((exports, module) => {
1899
+ /******************************************************************************
1900
+ * Created 2008-08-19.
1901
+ *
1902
+ * Dijkstra path-finding functions. Adapted from the Dijkstar Python project.
1903
+ *
1904
+ * Copyright (C) 2008
1905
+ * Wyatt Baldwin <self@wyattbaldwin.com>
1906
+ * All rights reserved
1907
+ *
1908
+ * Licensed under the MIT license.
1909
+ *
1910
+ * http://www.opensource.org/licenses/mit-license.php
1911
+ *
1912
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
1913
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
1914
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
1915
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
1916
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
1917
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
1918
+ * THE SOFTWARE.
1919
+ *****************************************************************************/
1920
+ var dijkstra = {
1921
+ single_source_shortest_paths: function(graph, s, d) {
1922
+ var predecessors = {};
1923
+ var costs = {};
1924
+ costs[s] = 0;
1925
+ var open = dijkstra.PriorityQueue.make();
1926
+ open.push(s, 0);
1927
+ var closest, u, v, cost_of_s_to_u, adjacent_nodes, cost_of_e, cost_of_s_to_u_plus_cost_of_e, cost_of_s_to_v, first_visit;
1928
+ while (!open.empty()) {
1929
+ closest = open.pop();
1930
+ u = closest.value;
1931
+ cost_of_s_to_u = closest.cost;
1932
+ adjacent_nodes = graph[u] || {};
1933
+ for (v in adjacent_nodes) if (adjacent_nodes.hasOwnProperty(v)) {
1934
+ cost_of_e = adjacent_nodes[v];
1935
+ cost_of_s_to_u_plus_cost_of_e = cost_of_s_to_u + cost_of_e;
1936
+ cost_of_s_to_v = costs[v];
1937
+ first_visit = typeof costs[v] === "undefined";
1938
+ if (first_visit || cost_of_s_to_v > cost_of_s_to_u_plus_cost_of_e) {
1939
+ costs[v] = cost_of_s_to_u_plus_cost_of_e;
1940
+ open.push(v, cost_of_s_to_u_plus_cost_of_e);
1941
+ predecessors[v] = u;
1942
+ }
1943
+ }
1944
+ }
1945
+ if (typeof d !== "undefined" && typeof costs[d] === "undefined") {
1946
+ var msg = [
1947
+ "Could not find a path from ",
1948
+ s,
1949
+ " to ",
1950
+ d,
1951
+ "."
1952
+ ].join("");
1953
+ throw new Error(msg);
1954
+ }
1955
+ return predecessors;
1956
+ },
1957
+ extract_shortest_path_from_predecessor_list: function(predecessors, d) {
1958
+ var nodes = [];
1959
+ var u = d;
1960
+ while (u) {
1961
+ nodes.push(u);
1962
+ predecessors[u];
1963
+ u = predecessors[u];
1964
+ }
1965
+ nodes.reverse();
1966
+ return nodes;
1967
+ },
1968
+ find_path: function(graph, s, d) {
1969
+ var predecessors = dijkstra.single_source_shortest_paths(graph, s, d);
1970
+ return dijkstra.extract_shortest_path_from_predecessor_list(predecessors, d);
1971
+ },
1972
+ /**
1973
+ * A very naive priority queue implementation.
1974
+ */
1975
+ PriorityQueue: {
1976
+ make: function(opts) {
1977
+ var T = dijkstra.PriorityQueue, t = {}, key;
1978
+ opts = opts || {};
1979
+ for (key in T) if (T.hasOwnProperty(key)) t[key] = T[key];
1980
+ t.queue = [];
1981
+ t.sorter = opts.sorter || T.default_sorter;
1982
+ return t;
1983
+ },
1984
+ default_sorter: function(a, b) {
1985
+ return a.cost - b.cost;
1986
+ },
1987
+ /**
1988
+ * Add a new item to the queue and ensure the highest priority element
1989
+ * is at the front of the queue.
1990
+ */
1991
+ push: function(value, cost) {
1992
+ var item = {
1993
+ value,
1994
+ cost
1995
+ };
1996
+ this.queue.push(item);
1997
+ this.queue.sort(this.sorter);
1998
+ },
1999
+ /**
2000
+ * Return the highest priority element in the queue.
2001
+ */
2002
+ pop: function() {
2003
+ return this.queue.shift();
2004
+ },
2005
+ empty: function() {
2006
+ return this.queue.length === 0;
2007
+ }
2008
+ }
2009
+ };
2010
+ if (typeof module !== "undefined") module.exports = dijkstra;
2011
+ }));
2012
+ //#endregion
2013
+ //#region node_modules/.pnpm/qrcode@1.5.4/node_modules/qrcode/lib/core/segments.js
2014
+ var require_segments = /* @__PURE__ */ __commonJSMin(((exports) => {
2015
+ var Mode = require_mode();
2016
+ var NumericData = require_numeric_data();
2017
+ var AlphanumericData = require_alphanumeric_data();
2018
+ var ByteData = require_byte_data();
2019
+ var KanjiData = require_kanji_data();
2020
+ var Regex = require_regex();
2021
+ var Utils = require_utils$1();
2022
+ var dijkstra = require_dijkstra();
2023
+ /**
2024
+ * Returns UTF8 byte length
2025
+ *
2026
+ * @param {String} str Input string
2027
+ * @return {Number} Number of byte
2028
+ */
2029
+ function getStringByteLength(str) {
2030
+ return unescape(encodeURIComponent(str)).length;
2031
+ }
2032
+ /**
2033
+ * Get a list of segments of the specified mode
2034
+ * from a string
2035
+ *
2036
+ * @param {Mode} mode Segment mode
2037
+ * @param {String} str String to process
2038
+ * @return {Array} Array of object with segments data
2039
+ */
2040
+ function getSegments(regex, mode, str) {
2041
+ const segments = [];
2042
+ let result;
2043
+ while ((result = regex.exec(str)) !== null) segments.push({
2044
+ data: result[0],
2045
+ index: result.index,
2046
+ mode,
2047
+ length: result[0].length
2048
+ });
2049
+ return segments;
2050
+ }
2051
+ /**
2052
+ * Extracts a series of segments with the appropriate
2053
+ * modes from a string
2054
+ *
2055
+ * @param {String} dataStr Input string
2056
+ * @return {Array} Array of object with segments data
2057
+ */
2058
+ function getSegmentsFromString(dataStr) {
2059
+ const numSegs = getSegments(Regex.NUMERIC, Mode.NUMERIC, dataStr);
2060
+ const alphaNumSegs = getSegments(Regex.ALPHANUMERIC, Mode.ALPHANUMERIC, dataStr);
2061
+ let byteSegs;
2062
+ let kanjiSegs;
2063
+ if (Utils.isKanjiModeEnabled()) {
2064
+ byteSegs = getSegments(Regex.BYTE, Mode.BYTE, dataStr);
2065
+ kanjiSegs = getSegments(Regex.KANJI, Mode.KANJI, dataStr);
2066
+ } else {
2067
+ byteSegs = getSegments(Regex.BYTE_KANJI, Mode.BYTE, dataStr);
2068
+ kanjiSegs = [];
2069
+ }
2070
+ return numSegs.concat(alphaNumSegs, byteSegs, kanjiSegs).sort(function(s1, s2) {
2071
+ return s1.index - s2.index;
2072
+ }).map(function(obj) {
2073
+ return {
2074
+ data: obj.data,
2075
+ mode: obj.mode,
2076
+ length: obj.length
2077
+ };
2078
+ });
2079
+ }
2080
+ /**
2081
+ * Returns how many bits are needed to encode a string of
2082
+ * specified length with the specified mode
2083
+ *
2084
+ * @param {Number} length String length
2085
+ * @param {Mode} mode Segment mode
2086
+ * @return {Number} Bit length
2087
+ */
2088
+ function getSegmentBitsLength(length, mode) {
2089
+ switch (mode) {
2090
+ case Mode.NUMERIC: return NumericData.getBitsLength(length);
2091
+ case Mode.ALPHANUMERIC: return AlphanumericData.getBitsLength(length);
2092
+ case Mode.KANJI: return KanjiData.getBitsLength(length);
2093
+ case Mode.BYTE: return ByteData.getBitsLength(length);
2094
+ }
2095
+ }
2096
+ /**
2097
+ * Merges adjacent segments which have the same mode
2098
+ *
2099
+ * @param {Array} segs Array of object with segments data
2100
+ * @return {Array} Array of object with segments data
2101
+ */
2102
+ function mergeSegments(segs) {
2103
+ return segs.reduce(function(acc, curr) {
2104
+ const prevSeg = acc.length - 1 >= 0 ? acc[acc.length - 1] : null;
2105
+ if (prevSeg && prevSeg.mode === curr.mode) {
2106
+ acc[acc.length - 1].data += curr.data;
2107
+ return acc;
2108
+ }
2109
+ acc.push(curr);
2110
+ return acc;
2111
+ }, []);
2112
+ }
2113
+ /**
2114
+ * Generates a list of all possible nodes combination which
2115
+ * will be used to build a segments graph.
2116
+ *
2117
+ * Nodes are divided by groups. Each group will contain a list of all the modes
2118
+ * in which is possible to encode the given text.
2119
+ *
2120
+ * For example the text '12345' can be encoded as Numeric, Alphanumeric or Byte.
2121
+ * The group for '12345' will contain then 3 objects, one for each
2122
+ * possible encoding mode.
2123
+ *
2124
+ * Each node represents a possible segment.
2125
+ *
2126
+ * @param {Array} segs Array of object with segments data
2127
+ * @return {Array} Array of object with segments data
2128
+ */
2129
+ function buildNodes(segs) {
2130
+ const nodes = [];
2131
+ for (let i = 0; i < segs.length; i++) {
2132
+ const seg = segs[i];
2133
+ switch (seg.mode) {
2134
+ case Mode.NUMERIC:
2135
+ nodes.push([
2136
+ seg,
2137
+ {
2138
+ data: seg.data,
2139
+ mode: Mode.ALPHANUMERIC,
2140
+ length: seg.length
2141
+ },
2142
+ {
2143
+ data: seg.data,
2144
+ mode: Mode.BYTE,
2145
+ length: seg.length
2146
+ }
2147
+ ]);
2148
+ break;
2149
+ case Mode.ALPHANUMERIC:
2150
+ nodes.push([seg, {
2151
+ data: seg.data,
2152
+ mode: Mode.BYTE,
2153
+ length: seg.length
2154
+ }]);
2155
+ break;
2156
+ case Mode.KANJI:
2157
+ nodes.push([seg, {
2158
+ data: seg.data,
2159
+ mode: Mode.BYTE,
2160
+ length: getStringByteLength(seg.data)
2161
+ }]);
2162
+ break;
2163
+ case Mode.BYTE: nodes.push([{
2164
+ data: seg.data,
2165
+ mode: Mode.BYTE,
2166
+ length: getStringByteLength(seg.data)
2167
+ }]);
2168
+ }
2169
+ }
2170
+ return nodes;
2171
+ }
2172
+ /**
2173
+ * Builds a graph from a list of nodes.
2174
+ * All segments in each node group will be connected with all the segments of
2175
+ * the next group and so on.
2176
+ *
2177
+ * At each connection will be assigned a weight depending on the
2178
+ * segment's byte length.
2179
+ *
2180
+ * @param {Array} nodes Array of object with segments data
2181
+ * @param {Number} version QR Code version
2182
+ * @return {Object} Graph of all possible segments
2183
+ */
2184
+ function buildGraph(nodes, version) {
2185
+ const table = {};
2186
+ const graph = { start: {} };
2187
+ let prevNodeIds = ["start"];
2188
+ for (let i = 0; i < nodes.length; i++) {
2189
+ const nodeGroup = nodes[i];
2190
+ const currentNodeIds = [];
2191
+ for (let j = 0; j < nodeGroup.length; j++) {
2192
+ const node = nodeGroup[j];
2193
+ const key = "" + i + j;
2194
+ currentNodeIds.push(key);
2195
+ table[key] = {
2196
+ node,
2197
+ lastCount: 0
2198
+ };
2199
+ graph[key] = {};
2200
+ for (let n = 0; n < prevNodeIds.length; n++) {
2201
+ const prevNodeId = prevNodeIds[n];
2202
+ if (table[prevNodeId] && table[prevNodeId].node.mode === node.mode) {
2203
+ graph[prevNodeId][key] = getSegmentBitsLength(table[prevNodeId].lastCount + node.length, node.mode) - getSegmentBitsLength(table[prevNodeId].lastCount, node.mode);
2204
+ table[prevNodeId].lastCount += node.length;
2205
+ } else {
2206
+ if (table[prevNodeId]) table[prevNodeId].lastCount = node.length;
2207
+ graph[prevNodeId][key] = getSegmentBitsLength(node.length, node.mode) + 4 + Mode.getCharCountIndicator(node.mode, version);
2208
+ }
2209
+ }
2210
+ }
2211
+ prevNodeIds = currentNodeIds;
2212
+ }
2213
+ for (let n = 0; n < prevNodeIds.length; n++) graph[prevNodeIds[n]].end = 0;
2214
+ return {
2215
+ map: graph,
2216
+ table
2217
+ };
2218
+ }
2219
+ /**
2220
+ * Builds a segment from a specified data and mode.
2221
+ * If a mode is not specified, the more suitable will be used.
2222
+ *
2223
+ * @param {String} data Input data
2224
+ * @param {Mode | String} modesHint Data mode
2225
+ * @return {Segment} Segment
2226
+ */
2227
+ function buildSingleSegment(data, modesHint) {
2228
+ let mode;
2229
+ const bestMode = Mode.getBestModeForData(data);
2230
+ mode = Mode.from(modesHint, bestMode);
2231
+ 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));
2232
+ if (mode === Mode.KANJI && !Utils.isKanjiModeEnabled()) mode = Mode.BYTE;
2233
+ switch (mode) {
2234
+ case Mode.NUMERIC: return new NumericData(data);
2235
+ case Mode.ALPHANUMERIC: return new AlphanumericData(data);
2236
+ case Mode.KANJI: return new KanjiData(data);
2237
+ case Mode.BYTE: return new ByteData(data);
2238
+ }
2239
+ }
2240
+ /**
2241
+ * Builds a list of segments from an array.
2242
+ * Array can contain Strings or Objects with segment's info.
2243
+ *
2244
+ * For each item which is a string, will be generated a segment with the given
2245
+ * string and the more appropriate encoding mode.
2246
+ *
2247
+ * For each item which is an object, will be generated a segment with the given
2248
+ * data and mode.
2249
+ * Objects must contain at least the property "data".
2250
+ * If property "mode" is not present, the more suitable mode will be used.
2251
+ *
2252
+ * @param {Array} array Array of objects with segments data
2253
+ * @return {Array} Array of Segments
2254
+ */
2255
+ exports.fromArray = function fromArray(array) {
2256
+ return array.reduce(function(acc, seg) {
2257
+ if (typeof seg === "string") acc.push(buildSingleSegment(seg, null));
2258
+ else if (seg.data) acc.push(buildSingleSegment(seg.data, seg.mode));
2259
+ return acc;
2260
+ }, []);
2261
+ };
2262
+ /**
2263
+ * Builds an optimized sequence of segments from a string,
2264
+ * which will produce the shortest possible bitstream.
2265
+ *
2266
+ * @param {String} data Input string
2267
+ * @param {Number} version QR Code version
2268
+ * @return {Array} Array of segments
2269
+ */
2270
+ exports.fromString = function fromString(data, version) {
2271
+ const graph = buildGraph(buildNodes(getSegmentsFromString(data, Utils.isKanjiModeEnabled())), version);
2272
+ const path = dijkstra.find_path(graph.map, "start", "end");
2273
+ const optimizedSegs = [];
2274
+ for (let i = 1; i < path.length - 1; i++) optimizedSegs.push(graph.table[path[i]].node);
2275
+ return exports.fromArray(mergeSegments(optimizedSegs));
2276
+ };
2277
+ /**
2278
+ * Splits a string in various segments with the modes which
2279
+ * best represent their content.
2280
+ * The produced segments are far from being optimized.
2281
+ * The output of this function is only used to estimate a QR Code version
2282
+ * which may contain the data.
2283
+ *
2284
+ * @param {string} data Input string
2285
+ * @return {Array} Array of segments
2286
+ */
2287
+ exports.rawSplit = function rawSplit(data) {
2288
+ return exports.fromArray(getSegmentsFromString(data, Utils.isKanjiModeEnabled()));
2289
+ };
2290
+ }));
2291
+ //#endregion
2292
+ //#region node_modules/.pnpm/qrcode@1.5.4/node_modules/qrcode/lib/core/qrcode.js
2293
+ var require_qrcode = /* @__PURE__ */ __commonJSMin(((exports) => {
2294
+ var Utils = require_utils$1();
2295
+ var ECLevel = require_error_correction_level();
2296
+ var BitBuffer = require_bit_buffer();
2297
+ var BitMatrix = require_bit_matrix();
2298
+ var AlignmentPattern = require_alignment_pattern();
2299
+ var FinderPattern = require_finder_pattern();
2300
+ var MaskPattern = require_mask_pattern();
2301
+ var ECCode = require_error_correction_code();
2302
+ var ReedSolomonEncoder = require_reed_solomon_encoder();
2303
+ var Version = require_version();
2304
+ var FormatInfo = require_format_info();
2305
+ var Mode = require_mode();
2306
+ var Segments = require_segments();
2307
+ /**
2308
+ * QRCode for JavaScript
2309
+ *
2310
+ * modified by Ryan Day for nodejs support
2311
+ * Copyright (c) 2011 Ryan Day
2312
+ *
2313
+ * Licensed under the MIT license:
2314
+ * http://www.opensource.org/licenses/mit-license.php
2315
+ *
2316
+ //---------------------------------------------------------------------
2317
+ // QRCode for JavaScript
2318
+ //
2319
+ // Copyright (c) 2009 Kazuhiko Arase
2320
+ //
2321
+ // URL: http://www.d-project.com/
2322
+ //
2323
+ // Licensed under the MIT license:
2324
+ // http://www.opensource.org/licenses/mit-license.php
2325
+ //
2326
+ // The word "QR Code" is registered trademark of
2327
+ // DENSO WAVE INCORPORATED
2328
+ // http://www.denso-wave.com/qrcode/faqpatent-e.html
2329
+ //
2330
+ //---------------------------------------------------------------------
2331
+ */
2332
+ /**
2333
+ * Add finder patterns bits to matrix
2334
+ *
2335
+ * @param {BitMatrix} matrix Modules matrix
2336
+ * @param {Number} version QR Code version
2337
+ */
2338
+ function setupFinderPattern(matrix, version) {
2339
+ const size = matrix.size;
2340
+ const pos = FinderPattern.getPositions(version);
2341
+ for (let i = 0; i < pos.length; i++) {
2342
+ const row = pos[i][0];
2343
+ const col = pos[i][1];
2344
+ for (let r = -1; r <= 7; r++) {
2345
+ if (row + r <= -1 || size <= row + r) continue;
2346
+ for (let c = -1; c <= 7; c++) {
2347
+ if (col + c <= -1 || size <= col + c) continue;
2348
+ if (r >= 0 && r <= 6 && (c === 0 || c === 6) || c >= 0 && c <= 6 && (r === 0 || r === 6) || r >= 2 && r <= 4 && c >= 2 && c <= 4) matrix.set(row + r, col + c, true, true);
2349
+ else matrix.set(row + r, col + c, false, true);
2350
+ }
2351
+ }
2352
+ }
2353
+ }
2354
+ /**
2355
+ * Add timing pattern bits to matrix
2356
+ *
2357
+ * Note: this function must be called before {@link setupAlignmentPattern}
2358
+ *
2359
+ * @param {BitMatrix} matrix Modules matrix
2360
+ */
2361
+ function setupTimingPattern(matrix) {
2362
+ const size = matrix.size;
2363
+ for (let r = 8; r < size - 8; r++) {
2364
+ const value = r % 2 === 0;
2365
+ matrix.set(r, 6, value, true);
2366
+ matrix.set(6, r, value, true);
2367
+ }
2368
+ }
2369
+ /**
2370
+ * Add alignment patterns bits to matrix
2371
+ *
2372
+ * Note: this function must be called after {@link setupTimingPattern}
2373
+ *
2374
+ * @param {BitMatrix} matrix Modules matrix
2375
+ * @param {Number} version QR Code version
2376
+ */
2377
+ function setupAlignmentPattern(matrix, version) {
2378
+ const pos = AlignmentPattern.getPositions(version);
2379
+ for (let i = 0; i < pos.length; i++) {
2380
+ const row = pos[i][0];
2381
+ const col = pos[i][1];
2382
+ for (let r = -2; r <= 2; r++) for (let c = -2; c <= 2; c++) if (r === -2 || r === 2 || c === -2 || c === 2 || r === 0 && c === 0) matrix.set(row + r, col + c, true, true);
2383
+ else matrix.set(row + r, col + c, false, true);
2384
+ }
2385
+ }
2386
+ /**
2387
+ * Add version info bits to matrix
2388
+ *
2389
+ * @param {BitMatrix} matrix Modules matrix
2390
+ * @param {Number} version QR Code version
2391
+ */
2392
+ function setupVersionInfo(matrix, version) {
2393
+ const size = matrix.size;
2394
+ const bits = Version.getEncodedBits(version);
2395
+ let row, col, mod;
2396
+ for (let i = 0; i < 18; i++) {
2397
+ row = Math.floor(i / 3);
2398
+ col = i % 3 + size - 8 - 3;
2399
+ mod = (bits >> i & 1) === 1;
2400
+ matrix.set(row, col, mod, true);
2401
+ matrix.set(col, row, mod, true);
2402
+ }
2403
+ }
2404
+ /**
2405
+ * Add format info bits to matrix
2406
+ *
2407
+ * @param {BitMatrix} matrix Modules matrix
2408
+ * @param {ErrorCorrectionLevel} errorCorrectionLevel Error correction level
2409
+ * @param {Number} maskPattern Mask pattern reference value
2410
+ */
2411
+ function setupFormatInfo(matrix, errorCorrectionLevel, maskPattern) {
2412
+ const size = matrix.size;
2413
+ const bits = FormatInfo.getEncodedBits(errorCorrectionLevel, maskPattern);
2414
+ let i, mod;
2415
+ for (i = 0; i < 15; i++) {
2416
+ mod = (bits >> i & 1) === 1;
2417
+ if (i < 6) matrix.set(i, 8, mod, true);
2418
+ else if (i < 8) matrix.set(i + 1, 8, mod, true);
2419
+ else matrix.set(size - 15 + i, 8, mod, true);
2420
+ if (i < 8) matrix.set(8, size - i - 1, mod, true);
2421
+ else if (i < 9) matrix.set(8, 15 - i - 1 + 1, mod, true);
2422
+ else matrix.set(8, 15 - i - 1, mod, true);
2423
+ }
2424
+ matrix.set(size - 8, 8, 1, true);
2425
+ }
2426
+ /**
2427
+ * Add encoded data bits to matrix
2428
+ *
2429
+ * @param {BitMatrix} matrix Modules matrix
2430
+ * @param {Uint8Array} data Data codewords
2431
+ */
2432
+ function setupData(matrix, data) {
2433
+ const size = matrix.size;
2434
+ let inc = -1;
2435
+ let row = size - 1;
2436
+ let bitIndex = 7;
2437
+ let byteIndex = 0;
2438
+ for (let col = size - 1; col > 0; col -= 2) {
2439
+ if (col === 6) col--;
2440
+ while (true) {
2441
+ for (let c = 0; c < 2; c++) if (!matrix.isReserved(row, col - c)) {
2442
+ let dark = false;
2443
+ if (byteIndex < data.length) dark = (data[byteIndex] >>> bitIndex & 1) === 1;
2444
+ matrix.set(row, col - c, dark);
2445
+ bitIndex--;
2446
+ if (bitIndex === -1) {
2447
+ byteIndex++;
2448
+ bitIndex = 7;
2449
+ }
2450
+ }
2451
+ row += inc;
2452
+ if (row < 0 || size <= row) {
2453
+ row -= inc;
2454
+ inc = -inc;
2455
+ break;
2456
+ }
2457
+ }
2458
+ }
2459
+ }
2460
+ /**
2461
+ * Create encoded codewords from data input
2462
+ *
2463
+ * @param {Number} version QR Code version
2464
+ * @param {ErrorCorrectionLevel} errorCorrectionLevel Error correction level
2465
+ * @param {ByteData} data Data input
2466
+ * @return {Uint8Array} Buffer containing encoded codewords
2467
+ */
2468
+ function createData(version, errorCorrectionLevel, segments) {
2469
+ const buffer = new BitBuffer();
2470
+ segments.forEach(function(data) {
2471
+ buffer.put(data.mode.bit, 4);
2472
+ buffer.put(data.getLength(), Mode.getCharCountIndicator(data.mode, version));
2473
+ data.write(buffer);
2474
+ });
2475
+ const dataTotalCodewordsBits = (Utils.getSymbolTotalCodewords(version) - ECCode.getTotalCodewordsCount(version, errorCorrectionLevel)) * 8;
2476
+ if (buffer.getLengthInBits() + 4 <= dataTotalCodewordsBits) buffer.put(0, 4);
2477
+ while (buffer.getLengthInBits() % 8 !== 0) buffer.putBit(0);
2478
+ const remainingByte = (dataTotalCodewordsBits - buffer.getLengthInBits()) / 8;
2479
+ for (let i = 0; i < remainingByte; i++) buffer.put(i % 2 ? 17 : 236, 8);
2480
+ return createCodewords(buffer, version, errorCorrectionLevel);
2481
+ }
2482
+ /**
2483
+ * Encode input data with Reed-Solomon and return codewords with
2484
+ * relative error correction bits
2485
+ *
2486
+ * @param {BitBuffer} bitBuffer Data to encode
2487
+ * @param {Number} version QR Code version
2488
+ * @param {ErrorCorrectionLevel} errorCorrectionLevel Error correction level
2489
+ * @return {Uint8Array} Buffer containing encoded codewords
2490
+ */
2491
+ function createCodewords(bitBuffer, version, errorCorrectionLevel) {
2492
+ const totalCodewords = Utils.getSymbolTotalCodewords(version);
2493
+ const dataTotalCodewords = totalCodewords - ECCode.getTotalCodewordsCount(version, errorCorrectionLevel);
2494
+ const ecTotalBlocks = ECCode.getBlocksCount(version, errorCorrectionLevel);
2495
+ const blocksInGroup1 = ecTotalBlocks - totalCodewords % ecTotalBlocks;
2496
+ const totalCodewordsInGroup1 = Math.floor(totalCodewords / ecTotalBlocks);
2497
+ const dataCodewordsInGroup1 = Math.floor(dataTotalCodewords / ecTotalBlocks);
2498
+ const dataCodewordsInGroup2 = dataCodewordsInGroup1 + 1;
2499
+ const ecCount = totalCodewordsInGroup1 - dataCodewordsInGroup1;
2500
+ const rs = new ReedSolomonEncoder(ecCount);
2501
+ let offset = 0;
2502
+ const dcData = new Array(ecTotalBlocks);
2503
+ const ecData = new Array(ecTotalBlocks);
2504
+ let maxDataSize = 0;
2505
+ const buffer = new Uint8Array(bitBuffer.buffer);
2506
+ for (let b = 0; b < ecTotalBlocks; b++) {
2507
+ const dataSize = b < blocksInGroup1 ? dataCodewordsInGroup1 : dataCodewordsInGroup2;
2508
+ dcData[b] = buffer.slice(offset, offset + dataSize);
2509
+ ecData[b] = rs.encode(dcData[b]);
2510
+ offset += dataSize;
2511
+ maxDataSize = Math.max(maxDataSize, dataSize);
2512
+ }
2513
+ const data = new Uint8Array(totalCodewords);
2514
+ let index = 0;
2515
+ let i, r;
2516
+ for (i = 0; i < maxDataSize; i++) for (r = 0; r < ecTotalBlocks; r++) if (i < dcData[r].length) data[index++] = dcData[r][i];
2517
+ for (i = 0; i < ecCount; i++) for (r = 0; r < ecTotalBlocks; r++) data[index++] = ecData[r][i];
2518
+ return data;
2519
+ }
2520
+ /**
2521
+ * Build QR Code symbol
2522
+ *
2523
+ * @param {String} data Input string
2524
+ * @param {Number} version QR Code version
2525
+ * @param {ErrorCorretionLevel} errorCorrectionLevel Error level
2526
+ * @param {MaskPattern} maskPattern Mask pattern
2527
+ * @return {Object} Object containing symbol data
2528
+ */
2529
+ function createSymbol(data, version, errorCorrectionLevel, maskPattern) {
2530
+ let segments;
2531
+ if (Array.isArray(data)) segments = Segments.fromArray(data);
2532
+ else if (typeof data === "string") {
2533
+ let estimatedVersion = version;
2534
+ if (!estimatedVersion) {
2535
+ const rawSegments = Segments.rawSplit(data);
2536
+ estimatedVersion = Version.getBestVersionForData(rawSegments, errorCorrectionLevel);
2537
+ }
2538
+ segments = Segments.fromString(data, estimatedVersion || 40);
2539
+ } else throw new Error("Invalid data");
2540
+ const bestVersion = Version.getBestVersionForData(segments, errorCorrectionLevel);
2541
+ if (!bestVersion) throw new Error("The amount of data is too big to be stored in a QR Code");
2542
+ if (!version) version = bestVersion;
2543
+ else if (version < bestVersion) throw new Error("\nThe chosen QR Code version cannot contain this amount of data.\nMinimum version required to store current data is: " + bestVersion + ".\n");
2544
+ const dataBits = createData(version, errorCorrectionLevel, segments);
2545
+ const modules = new BitMatrix(Utils.getSymbolSize(version));
2546
+ setupFinderPattern(modules, version);
2547
+ setupTimingPattern(modules);
2548
+ setupAlignmentPattern(modules, version);
2549
+ setupFormatInfo(modules, errorCorrectionLevel, 0);
2550
+ if (version >= 7) setupVersionInfo(modules, version);
2551
+ setupData(modules, dataBits);
2552
+ if (isNaN(maskPattern)) maskPattern = MaskPattern.getBestMask(modules, setupFormatInfo.bind(null, modules, errorCorrectionLevel));
2553
+ MaskPattern.applyMask(maskPattern, modules);
2554
+ setupFormatInfo(modules, errorCorrectionLevel, maskPattern);
2555
+ return {
2556
+ modules,
2557
+ version,
2558
+ errorCorrectionLevel,
2559
+ maskPattern,
2560
+ segments
2561
+ };
2562
+ }
2563
+ /**
2564
+ * QR Code
2565
+ *
2566
+ * @param {String | Array} data Input data
2567
+ * @param {Object} options Optional configurations
2568
+ * @param {Number} options.version QR Code version
2569
+ * @param {String} options.errorCorrectionLevel Error correction level
2570
+ * @param {Function} options.toSJISFunc Helper func to convert utf8 to sjis
2571
+ */
2572
+ exports.create = function create(data, options) {
2573
+ if (typeof data === "undefined" || data === "") throw new Error("No input text");
2574
+ let errorCorrectionLevel = ECLevel.M;
2575
+ let version;
2576
+ let mask;
2577
+ if (typeof options !== "undefined") {
2578
+ errorCorrectionLevel = ECLevel.from(options.errorCorrectionLevel, ECLevel.M);
2579
+ version = Version.from(options.version);
2580
+ mask = MaskPattern.from(options.maskPattern);
2581
+ if (options.toSJISFunc) Utils.setToSJISFunction(options.toSJISFunc);
2582
+ }
2583
+ return createSymbol(data, version, errorCorrectionLevel, mask);
2584
+ };
2585
+ }));
2586
+ //#endregion
2587
+ //#region node_modules/.pnpm/qrcode@1.5.4/node_modules/qrcode/lib/renderer/utils.js
2588
+ var require_utils = /* @__PURE__ */ __commonJSMin(((exports) => {
2589
+ function hex2rgba(hex) {
2590
+ if (typeof hex === "number") hex = hex.toString();
2591
+ if (typeof hex !== "string") throw new Error("Color should be defined as hex string");
2592
+ let hexCode = hex.slice().replace("#", "").split("");
2593
+ if (hexCode.length < 3 || hexCode.length === 5 || hexCode.length > 8) throw new Error("Invalid hex color: " + hex);
2594
+ if (hexCode.length === 3 || hexCode.length === 4) hexCode = Array.prototype.concat.apply([], hexCode.map(function(c) {
2595
+ return [c, c];
2596
+ }));
2597
+ if (hexCode.length === 6) hexCode.push("F", "F");
2598
+ const hexValue = parseInt(hexCode.join(""), 16);
2599
+ return {
2600
+ r: hexValue >> 24 & 255,
2601
+ g: hexValue >> 16 & 255,
2602
+ b: hexValue >> 8 & 255,
2603
+ a: hexValue & 255,
2604
+ hex: "#" + hexCode.slice(0, 6).join("")
2605
+ };
2606
+ }
2607
+ exports.getOptions = function getOptions(options) {
2608
+ if (!options) options = {};
2609
+ if (!options.color) options.color = {};
2610
+ const margin = typeof options.margin === "undefined" || options.margin === null || options.margin < 0 ? 4 : options.margin;
2611
+ const width = options.width && options.width >= 21 ? options.width : void 0;
2612
+ const scale = options.scale || 4;
2613
+ return {
2614
+ width,
2615
+ scale: width ? 4 : scale,
2616
+ margin,
2617
+ color: {
2618
+ dark: hex2rgba(options.color.dark || "#000000ff"),
2619
+ light: hex2rgba(options.color.light || "#ffffffff")
2620
+ },
2621
+ type: options.type,
2622
+ rendererOpts: options.rendererOpts || {}
2623
+ };
2624
+ };
2625
+ exports.getScale = function getScale(qrSize, opts) {
2626
+ return opts.width && opts.width >= qrSize + opts.margin * 2 ? opts.width / (qrSize + opts.margin * 2) : opts.scale;
2627
+ };
2628
+ exports.getImageWidth = function getImageWidth(qrSize, opts) {
2629
+ const scale = exports.getScale(qrSize, opts);
2630
+ return Math.floor((qrSize + opts.margin * 2) * scale);
2631
+ };
2632
+ exports.qrToImageData = function qrToImageData(imgData, qr, opts) {
2633
+ const size = qr.modules.size;
2634
+ const data = qr.modules.data;
2635
+ const scale = exports.getScale(size, opts);
2636
+ const symbolSize = Math.floor((size + opts.margin * 2) * scale);
2637
+ const scaledMargin = opts.margin * scale;
2638
+ const palette = [opts.color.light, opts.color.dark];
2639
+ for (let i = 0; i < symbolSize; i++) for (let j = 0; j < symbolSize; j++) {
2640
+ let posDst = (i * symbolSize + j) * 4;
2641
+ let pxColor = opts.color.light;
2642
+ if (i >= scaledMargin && j >= scaledMargin && i < symbolSize - scaledMargin && j < symbolSize - scaledMargin) {
2643
+ const iSrc = Math.floor((i - scaledMargin) / scale);
2644
+ const jSrc = Math.floor((j - scaledMargin) / scale);
2645
+ pxColor = palette[data[iSrc * size + jSrc] ? 1 : 0];
2646
+ }
2647
+ imgData[posDst++] = pxColor.r;
2648
+ imgData[posDst++] = pxColor.g;
2649
+ imgData[posDst++] = pxColor.b;
2650
+ imgData[posDst] = pxColor.a;
2651
+ }
2652
+ };
2653
+ }));
2654
+ //#endregion
2655
+ //#region node_modules/.pnpm/qrcode@1.5.4/node_modules/qrcode/lib/renderer/canvas.js
2656
+ var require_canvas = /* @__PURE__ */ __commonJSMin(((exports) => {
2657
+ var Utils = require_utils();
2658
+ function clearCanvas(ctx, canvas, size) {
2659
+ ctx.clearRect(0, 0, canvas.width, canvas.height);
2660
+ if (!canvas.style) canvas.style = {};
2661
+ canvas.height = size;
2662
+ canvas.width = size;
2663
+ canvas.style.height = size + "px";
2664
+ canvas.style.width = size + "px";
2665
+ }
2666
+ function getCanvasElement() {
2667
+ try {
2668
+ return document.createElement("canvas");
2669
+ } catch (e) {
2670
+ throw new Error("You need to specify a canvas element");
2671
+ }
2672
+ }
2673
+ exports.render = function render(qrData, canvas, options) {
2674
+ let opts = options;
2675
+ let canvasEl = canvas;
2676
+ if (typeof opts === "undefined" && (!canvas || !canvas.getContext)) {
2677
+ opts = canvas;
2678
+ canvas = void 0;
2679
+ }
2680
+ if (!canvas) canvasEl = getCanvasElement();
2681
+ opts = Utils.getOptions(opts);
2682
+ const size = Utils.getImageWidth(qrData.modules.size, opts);
2683
+ const ctx = canvasEl.getContext("2d");
2684
+ const image = ctx.createImageData(size, size);
2685
+ Utils.qrToImageData(image.data, qrData, opts);
2686
+ clearCanvas(ctx, canvasEl, size);
2687
+ ctx.putImageData(image, 0, 0);
2688
+ return canvasEl;
2689
+ };
2690
+ exports.renderToDataURL = function renderToDataURL(qrData, canvas, options) {
2691
+ let opts = options;
2692
+ if (typeof opts === "undefined" && (!canvas || !canvas.getContext)) {
2693
+ opts = canvas;
2694
+ canvas = void 0;
2695
+ }
2696
+ if (!opts) opts = {};
2697
+ const canvasEl = exports.render(qrData, canvas, opts);
2698
+ const type = opts.type || "image/png";
2699
+ const rendererOpts = opts.rendererOpts || {};
2700
+ return canvasEl.toDataURL(type, rendererOpts.quality);
2701
+ };
2702
+ }));
2703
+ //#endregion
2704
+ //#region node_modules/.pnpm/qrcode@1.5.4/node_modules/qrcode/lib/renderer/svg-tag.js
2705
+ var require_svg_tag = /* @__PURE__ */ __commonJSMin(((exports) => {
2706
+ var Utils = require_utils();
2707
+ function getColorAttrib(color, attrib) {
2708
+ const alpha = color.a / 255;
2709
+ const str = attrib + "=\"" + color.hex + "\"";
2710
+ return alpha < 1 ? str + " " + attrib + "-opacity=\"" + alpha.toFixed(2).slice(1) + "\"" : str;
2711
+ }
2712
+ function svgCmd(cmd, x, y) {
2713
+ let str = cmd + x;
2714
+ if (typeof y !== "undefined") str += " " + y;
2715
+ return str;
2716
+ }
2717
+ function qrToPath(data, size, margin) {
2718
+ let path = "";
2719
+ let moveBy = 0;
2720
+ let newRow = false;
2721
+ let lineLength = 0;
2722
+ for (let i = 0; i < data.length; i++) {
2723
+ const col = Math.floor(i % size);
2724
+ const row = Math.floor(i / size);
2725
+ if (!col && !newRow) newRow = true;
2726
+ if (data[i]) {
2727
+ lineLength++;
2728
+ if (!(i > 0 && col > 0 && data[i - 1])) {
2729
+ path += newRow ? svgCmd("M", col + margin, .5 + row + margin) : svgCmd("m", moveBy, 0);
2730
+ moveBy = 0;
2731
+ newRow = false;
2732
+ }
2733
+ if (!(col + 1 < size && data[i + 1])) {
2734
+ path += svgCmd("h", lineLength);
2735
+ lineLength = 0;
2736
+ }
2737
+ } else moveBy++;
2738
+ }
2739
+ return path;
2740
+ }
2741
+ exports.render = function render(qrData, options, cb) {
2742
+ const opts = Utils.getOptions(options);
2743
+ const size = qrData.modules.size;
2744
+ const data = qrData.modules.data;
2745
+ const qrcodesize = size + opts.margin * 2;
2746
+ const bg = !opts.color.light.a ? "" : "<path " + getColorAttrib(opts.color.light, "fill") + " d=\"M0 0h" + qrcodesize + "v" + qrcodesize + "H0z\"/>";
2747
+ const path = "<path " + getColorAttrib(opts.color.dark, "stroke") + " d=\"" + qrToPath(data, size, opts.margin) + "\"/>";
2748
+ const viewBox = "viewBox=\"0 0 " + qrcodesize + " " + qrcodesize + "\"";
2749
+ const svgTag = "<svg xmlns=\"http://www.w3.org/2000/svg\" " + (!opts.width ? "" : "width=\"" + opts.width + "\" height=\"" + opts.width + "\" ") + viewBox + " shape-rendering=\"crispEdges\">" + bg + path + "</svg>\n";
2750
+ if (typeof cb === "function") cb(null, svgTag);
2751
+ return svgTag;
2752
+ };
2753
+ }));
2754
+ //#endregion
2755
+ //#region src/qr/limits.ts
2756
+ var import_browser = /* @__PURE__ */ __toESM((/* @__PURE__ */ __commonJSMin(((exports) => {
2757
+ var canPromise = require_can_promise();
2758
+ var QRCode = require_qrcode();
2759
+ var CanvasRenderer = require_canvas();
2760
+ var SvgRenderer = require_svg_tag();
2761
+ function renderCanvas(renderFunc, canvas, text, opts, cb) {
2762
+ const args = [].slice.call(arguments, 1);
2763
+ const argsNum = args.length;
2764
+ const isLastArgCb = typeof args[argsNum - 1] === "function";
2765
+ if (!isLastArgCb && !canPromise()) throw new Error("Callback required as last argument");
2766
+ if (isLastArgCb) {
2767
+ if (argsNum < 2) throw new Error("Too few arguments provided");
2768
+ if (argsNum === 2) {
2769
+ cb = text;
2770
+ text = canvas;
2771
+ canvas = opts = void 0;
2772
+ } else if (argsNum === 3) {
2773
+ if (canvas.getContext && typeof cb === "undefined") {
2774
+ cb = opts;
2775
+ opts = void 0;
2776
+ } else {
2777
+ cb = opts;
2778
+ opts = text;
2779
+ text = canvas;
2780
+ canvas = void 0;
2781
+ }
2782
+ }
2783
+ } else {
2784
+ if (argsNum < 1) throw new Error("Too few arguments provided");
2785
+ if (argsNum === 1) {
2786
+ text = canvas;
2787
+ canvas = opts = void 0;
2788
+ } else if (argsNum === 2 && !canvas.getContext) {
2789
+ opts = text;
2790
+ text = canvas;
2791
+ canvas = void 0;
2792
+ }
2793
+ return new Promise(function(resolve, reject) {
2794
+ try {
2795
+ resolve(renderFunc(QRCode.create(text, opts), canvas, opts));
2796
+ } catch (e) {
2797
+ reject(e);
2798
+ }
2799
+ });
2800
+ }
2801
+ try {
2802
+ const data = QRCode.create(text, opts);
2803
+ cb(null, renderFunc(data, canvas, opts));
2804
+ } catch (e) {
2805
+ cb(e);
2806
+ }
2807
+ }
2808
+ exports.create = QRCode.create;
2809
+ exports.toCanvas = renderCanvas.bind(null, CanvasRenderer.render);
2810
+ exports.toDataURL = renderCanvas.bind(null, CanvasRenderer.renderToDataURL);
2811
+ exports.toString = renderCanvas.bind(null, function(data, _, opts) {
2812
+ return SvgRenderer.render(data, opts);
2813
+ });
2814
+ })))(), 1);
2815
+ /**
2816
+ * Transport limits with their units and boundary conditions.
2817
+ *
2818
+ * Every length here counts characters. Payloads are restricted to printable
2819
+ * ASCII, so one character is one UTF-16 code unit and one byte; character
2820
+ * counts and byte counts agree.
2821
+ */
2822
+ /**
2823
+ * Largest carried message. Boundary: 1 <= messageLength <= MAX_MESSAGE_LENGTH;
2824
+ * zero is rejected.
2825
+ *
2826
+ * The effective ceiling is lower than this value for most error correction
2827
+ * levels, because MAX_PART_COUNT parts of (QR version 40 capacity - envelope
2828
+ * header) characters run out first:
2829
+ *
2830
+ * L: 2953 - 362 = 2591 chars/part -> 165,824 for 64 parts (this value binds)
2831
+ * M: 2331 - 362 = 1969 chars/part -> 126,016 for 64 parts (part count binds)
2832
+ * Q: 1663 - 362 = 1301 chars/part -> 83,264 for 64 parts (part count binds)
2833
+ * H: 1273 - 362 = 911 chars/part -> 58,304 for 64 parts (part count binds)
2834
+ *
2835
+ * Exceeding either ceiling fails while splitting, with `message-too-large` or
2836
+ * `too-many-parts`.
2837
+ */
2838
+ var MAX_MESSAGE_LENGTH = 131072;
2839
+ /**
2840
+ * Payload characters per part. Always larger than the capacity a QR symbol can
2841
+ * actually carry, so this is a guard against hostile input rather than the
2842
+ * value that drives splitting.
2843
+ */
2844
+ var MAX_CHUNK_LENGTH = 4096;
2845
+ /** Largest accepted QR text. Covers the envelope header plus its payload. */
2846
+ var MAX_PART_TEXT_LENGTH = 8192;
2847
+ //#endregion
2848
+ //#region src/qr/envelope.ts
2849
+ /**
2850
+ * Transport format identifier.
2851
+ *
2852
+ * `twmp-qr/1` from turbowarp-realtime-motion-capture is the starting point, but
2853
+ * this format adds three required fields (`senderPeerId`, `targetPeerId`, and
2854
+ * `replyTo`) that the older one cannot express, so it gets its own namespace
2855
+ * and version. `twmp-qr/1` is rejected with `unsupported-protocol` rather than
2856
+ * accepted in a compatibility mode: an explicit failure is safer than an
2857
+ * ambiguous acceptance that could pair the wrong peers.
2858
+ */
2859
+ var QR_PROTOCOL = "twqr/1";
2860
+ /** Printable ASCII. Pairing codes are base64url, so this never rejects a valid payload. */
2861
+ var printableAscii$1 = /^[ -~]+$/u;
2862
+ var base64Url = /^[A-Za-z0-9_-]+$/u;
2863
+ /** Separator for identity keys. Cannot occur in printable-ASCII fields. */
2864
+ var identitySeparator = "\0";
2865
+ function serializeEnvelope(envelope) {
2866
+ validateEnvelope(envelope);
2867
+ return JSON.stringify(envelope);
2868
+ }
2869
+ function parseEnvelope(text) {
2870
+ if (typeof text !== "string") throw new QrPairingError("invalid-json", "QR part must be text.");
2871
+ if (text.length > 8192) throw new QrPairingError("part-too-large", `QR part text must be at most ${MAX_PART_TEXT_LENGTH} characters.`);
2872
+ let parsed;
2873
+ try {
2874
+ parsed = JSON.parse(text);
2875
+ } catch (error) {
2876
+ throw new QrPairingError("invalid-json", "QR part is not valid JSON.", { cause: error });
2877
+ }
2878
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw new QrPairingError("invalid-envelope", "QR part must be an object.");
2879
+ const envelope = parsed;
2880
+ validateEnvelope(envelope);
2881
+ return envelope;
2882
+ }
2883
+ function validateEnvelope(envelope) {
2884
+ if (envelope.protocol !== "twqr/1") throw new QrPairingError("unsupported-protocol", `QR part protocol must be ${QR_PROTOCOL}.`);
2885
+ requireIdentifier(envelope.sessionId, "session ID");
2886
+ requireIdentifier(envelope.senderPeerId, "sender peer ID");
2887
+ requireIdentifier(envelope.targetPeerId, "target peer ID");
2888
+ requireIdentifier(envelope.messageId, "message ID");
2889
+ if (envelope.kind !== "offer" && envelope.kind !== "answer") throw new QrPairingError("invalid-envelope", "QR message kind must be offer or answer.");
2890
+ if (envelope.kind === "answer") requireIdentifier(envelope.replyTo, "reply-to message ID");
2891
+ else if (envelope.replyTo !== "") throw new QrPairingError("invalid-envelope", "An offer QR part must not set reply-to.");
2892
+ if (!Number.isSafeInteger(envelope.createdAt) || envelope.createdAt < 0) throw new QrPairingError("invalid-envelope", "QR creation timestamp is invalid.");
2893
+ if (!Number.isInteger(envelope.partCount) || envelope.partCount < 1 || envelope.partCount > 64) throw new QrPairingError("invalid-envelope", `QR part count must be between 1 and 64.`);
2894
+ if (!Number.isInteger(envelope.partIndex) || envelope.partIndex < 0 || envelope.partIndex >= envelope.partCount) throw new QrPairingError("index-out-of-range", "QR part index must be within the declared part count.");
2895
+ if (!Number.isInteger(envelope.messageLength) || envelope.messageLength < 1) throw new QrPairingError("invalid-envelope", "QR message length must be a positive integer.");
2896
+ if (envelope.messageLength > 131072) throw new QrPairingError("message-too-large", `QR message length must be at most ${MAX_MESSAGE_LENGTH} characters.`);
2897
+ if (typeof envelope.messageHash !== "string" || envelope.messageHash.length !== 43 || !base64Url.test(envelope.messageHash)) throw new QrPairingError("invalid-envelope", "QR message hash is malformed.");
2898
+ if (typeof envelope.payload !== "string" || envelope.payload.length > 4096) throw new QrPairingError("invalid-envelope", `QR part payload must be at most ${MAX_CHUNK_LENGTH} characters.`);
2899
+ if (envelope.payload.length > 0 && !printableAscii$1.test(envelope.payload)) throw new QrPairingError("invalid-envelope", "QR part payload must be printable ASCII.");
2900
+ }
2901
+ /**
2902
+ * Everything that must agree across the parts of one message. `partIndex` and
2903
+ * `payload` are the only fields allowed to differ.
2904
+ */
2905
+ function envelopeIdentity(envelope) {
2906
+ return [
2907
+ envelope.protocol,
2908
+ envelope.sessionId,
2909
+ envelope.senderPeerId,
2910
+ envelope.targetPeerId,
2911
+ envelope.kind,
2912
+ envelope.messageId,
2913
+ envelope.replyTo,
2914
+ envelope.createdAt,
2915
+ envelope.partCount,
2916
+ envelope.messageLength,
2917
+ envelope.messageHash
2918
+ ].join(identitySeparator);
2919
+ }
2920
+ function requireIdentifier(value, label) {
2921
+ if (typeof value !== "string" || value.length < 1 || value.length > 128 || !printableAscii$1.test(value)) throw new QrPairingError("invalid-envelope", `Invalid ${label}.`);
2922
+ return value;
2923
+ }
2924
+ //#endregion
2925
+ //#region src/qr/hash.ts
2926
+ /**
2927
+ * SHA-256 as unpadded base64url.
2928
+ *
2929
+ * The digest detects optical transport damage. It is not an authentication
2930
+ * mechanism: anyone who can photograph the QR codes can also recompute it.
2931
+ */
2932
+ async function sha256Base64Url(value) {
2933
+ const bytes = new TextEncoder().encode(value);
2934
+ const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));
2935
+ let binary = "";
2936
+ for (const byte of digest) binary += String.fromCharCode(byte);
2937
+ return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/u, "");
2938
+ }
2939
+ //#endregion
2940
+ //#region src/qr/courier.ts
2941
+ var printableAscii = /^[ -~]+$/u;
2942
+ /**
2943
+ * Splits a pairing code into parts that each fit one QR symbol.
2944
+ *
2945
+ * The chunk length depends on the envelope header, which in turn depends on the
2946
+ * part count, so the loop repeats until the two agree.
2947
+ */
2948
+ async function createParts(message, options) {
2949
+ requireMessage(message);
2950
+ const senderPeerId = requireIdentifier(options.senderPeerId, "sender peer ID");
2951
+ const targetPeerId = requireIdentifier(options.targetPeerId, "target peer ID");
2952
+ if (options.kind !== "offer" && options.kind !== "answer") throw new QrPairingError("invalid-argument", "QR message kind must be offer or answer.");
2953
+ const replyTo = options.kind === "answer" ? requireIdentifier(options.replyTo ?? "", "reply-to message ID") : "";
2954
+ if (options.kind === "offer" && (options.replyTo ?? "") !== "") throw new QrPairingError("invalid-argument", "An offer must not set reply-to.");
2955
+ const sessionId = requireIdentifier(options.sessionId ?? crypto.randomUUID(), "session ID");
2956
+ const createdAt = options.createdAt ?? Date.now();
2957
+ if (!Number.isSafeInteger(createdAt) || createdAt < 0) throw new QrPairingError("invalid-argument", "QR creation timestamp is invalid.");
2958
+ const errorCorrectionLevel = options.errorCorrectionLevel ?? "M";
2959
+ const messageHash = await sha256Base64Url(message);
2960
+ const messageId = `${sessionId}.${messageHash.slice(0, 12)}`;
2961
+ let partCount = 1;
2962
+ let chunkLength = 0;
2963
+ for (;;) {
2964
+ chunkLength = maximumPayloadLength({
2965
+ protocol: QR_PROTOCOL,
2966
+ sessionId,
2967
+ senderPeerId,
2968
+ targetPeerId,
2969
+ kind: options.kind,
2970
+ messageId,
2971
+ replyTo,
2972
+ createdAt,
2973
+ partIndex: partCount - 1,
2974
+ partCount,
2975
+ messageLength: message.length,
2976
+ messageHash,
2977
+ payload: ""
2978
+ }, errorCorrectionLevel);
2979
+ if (chunkLength < 1) throw new QrPairingError("invalid-envelope", "QR encoder capacity is too small for the part envelope.");
2980
+ const required = Math.ceil(message.length / chunkLength);
2981
+ if (required > 64) throw new QrPairingError("too-many-parts", `Splitting needs ${required} parts, which exceeds the limit of 64.`);
2982
+ if (required === partCount) break;
2983
+ partCount = required;
2984
+ }
2985
+ const parts = Array.from({ length: partCount }, (_unused, partIndex) => ({
2986
+ protocol: QR_PROTOCOL,
2987
+ sessionId,
2988
+ senderPeerId,
2989
+ targetPeerId,
2990
+ kind: options.kind,
2991
+ messageId,
2992
+ replyTo,
2993
+ createdAt,
2994
+ partIndex,
2995
+ partCount,
2996
+ messageLength: message.length,
2997
+ messageHash,
2998
+ payload: message.slice(partIndex * chunkLength, (partIndex + 1) * chunkLength)
2999
+ }));
3000
+ const texts = parts.map(serializeEnvelope);
3001
+ for (const text of texts) import_browser.create(text, { errorCorrectionLevel });
3002
+ return {
3003
+ parts,
3004
+ texts,
3005
+ sessionId,
3006
+ messageId
3007
+ };
3008
+ }
3009
+ /** Collects the parts of exactly one message and verifies the result. */
3010
+ var PartAssembler = class {
3011
+ constructor() {
3012
+ this.parts = /* @__PURE__ */ new Map();
3013
+ }
3014
+ add(envelope) {
3015
+ const identity = envelopeIdentity(envelope);
3016
+ if (this.identity !== void 0 && this.identity !== identity) throw new QrPairingError("message-mismatch", "QR part does not belong to the message being assembled.");
3017
+ this.identity = identity;
3018
+ const existing = this.parts.get(envelope.partIndex);
3019
+ if (existing && existing.payload !== envelope.payload) throw new QrPairingError("conflicting-part", `QR part ${envelope.partIndex + 1} arrived twice with different content.`);
3020
+ this.parts.set(envelope.partIndex, envelope);
3021
+ return {
3022
+ received: this.parts.size,
3023
+ total: envelope.partCount,
3024
+ duplicate: existing !== void 0
3025
+ };
3026
+ }
3027
+ receivedCount() {
3028
+ return this.parts.size;
3029
+ }
3030
+ /** Zero until the first part arrives, because the part count is carried by the parts. */
3031
+ requiredCount() {
3032
+ return this.first()?.partCount ?? 0;
3033
+ }
3034
+ /** Zero-based indices that have not arrived yet, in ascending order. */
3035
+ missingParts() {
3036
+ const total = this.requiredCount();
3037
+ const missing = [];
3038
+ for (let index = 0; index < total; index += 1) if (!this.parts.has(index)) missing.push(index);
3039
+ return missing;
3040
+ }
3041
+ isComplete() {
3042
+ const total = this.requiredCount();
3043
+ return total > 0 && this.parts.size === total;
3044
+ }
3045
+ /** Joins the parts and verifies length and hash before returning anything. */
3046
+ async assemble() {
3047
+ const first = this.first();
3048
+ if (!first) throw new QrPairingError("missing-parts", "No QR parts have been received.");
3049
+ if (this.parts.size !== first.partCount) throw new QrPairingError("missing-parts", `QR message is missing ${first.partCount - this.parts.size} of ${first.partCount} parts.`);
3050
+ const message = Array.from({ length: first.partCount }, (_unused, index) => {
3051
+ const part = this.parts.get(index);
3052
+ if (!part) throw new QrPairingError("missing-parts", `QR message is missing part ${index + 1}.`);
3053
+ return part.payload;
3054
+ }).join("");
3055
+ if (message.length !== first.messageLength) throw new QrPairingError("length-mismatch", "Reassembled QR message has the wrong length.");
3056
+ if (await sha256Base64Url(message) !== first.messageHash) throw new QrPairingError("hash-mismatch", "Reassembled QR message failed its hash check.");
3057
+ return message;
3058
+ }
3059
+ clear() {
3060
+ this.parts.clear();
3061
+ this.identity = void 0;
3062
+ }
3063
+ first() {
3064
+ return this.parts.values().next().value;
3065
+ }
3066
+ };
3067
+ /**
3068
+ * Largest payload that still lets the whole envelope fit a version 40 symbol at
3069
+ * the given error correction level.
3070
+ */
3071
+ function maximumPayloadLength(base, errorCorrectionLevel) {
3072
+ let low = 0;
3073
+ let high = MAX_CHUNK_LENGTH;
3074
+ while (low < high) {
3075
+ const middle = Math.ceil((low + high) / 2);
3076
+ const text = JSON.stringify({
3077
+ ...base,
3078
+ payload: "A".repeat(middle)
3079
+ });
3080
+ try {
3081
+ import_browser.create([{
3082
+ data: new TextEncoder().encode(text),
3083
+ mode: "byte"
3084
+ }], {
3085
+ version: 40,
3086
+ errorCorrectionLevel
3087
+ });
3088
+ low = middle;
3089
+ } catch {
3090
+ high = middle - 1;
3091
+ }
3092
+ }
3093
+ return low;
3094
+ }
3095
+ function requireMessage(value) {
3096
+ if (typeof value !== "string" || value.length < 1) throw new QrPairingError("invalid-argument", "Pairing code is empty.");
3097
+ if (value.length > 131072) throw new QrPairingError("message-too-large", `Pairing code must be at most ${MAX_MESSAGE_LENGTH} characters.`);
3098
+ if (!printableAscii.test(value)) throw new QrPairingError("invalid-argument", "Pairing code must be printable ASCII.");
3099
+ }
3100
+ //#endregion
3101
+ //#region src/qr/svg.ts
3102
+ var QUIET_ZONE_MODULES = 4;
3103
+ function createQrSvg(text, errorCorrectionLevel = "M") {
3104
+ const qr = import_browser.create([{
3105
+ data: new TextEncoder().encode(text),
3106
+ mode: "byte"
3107
+ }], { errorCorrectionLevel });
3108
+ const size = qr.modules.size;
3109
+ const viewSize = size + 8;
3110
+ const commands = [];
3111
+ for (let row = 0; row < size; row += 1) for (let column = 0; column < size; column += 1) if (qr.modules.get(row, column)) commands.push(`M${column + QUIET_ZONE_MODULES} ${row + QUIET_ZONE_MODULES}h1v1h-1z`);
3112
+ return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${viewSize} ${viewSize}" shape-rendering="crispEdges"><rect width="100%" height="100%" fill="#fff"/><path d="${commands.join("")}" fill="#000"/></svg>`;
3113
+ }
3114
+ //#endregion
3115
+ //#region src/pairing/limits.ts
3116
+ var MAX_TIMEOUT_SECONDS = 3600;
3117
+ //#endregion
3118
+ //#region src/pairing/types.ts
3119
+ var terminalPhases = /* @__PURE__ */ new Set([
3120
+ "connected",
3121
+ "cancelled",
3122
+ "expired",
3123
+ "failed"
3124
+ ]);
3125
+ function isTerminalPhase(phase) {
3126
+ return terminalPhases.has(phase);
3127
+ }
3128
+ //#endregion
3129
+ //#region src/ports/display.ts
3130
+ /**
3131
+ * Swaps a sprite's skin for a QR image and puts the original back.
3132
+ *
3133
+ * The original skin ID is captured on the first swap so that repeated part
3134
+ * changes never lose it, and every exit path restores it: ending the display,
3135
+ * cancelling, stopping the project, removing the sprite, or disposing the
3136
+ * runtime.
3137
+ */
3138
+ var TemporarySpriteSkinManager = class {
3139
+ constructor(runtime) {
3140
+ this.runtime = runtime;
3141
+ this.displays = /* @__PURE__ */ new Map();
3142
+ }
3143
+ validateTarget(target) {
3144
+ if (!target || target.isStage) throw new QrPairingError("invalid-argument", "A pairing QR must be displayed on a sprite target.");
3145
+ if (target.isOriginal === false) throw new QrPairingError("invalid-argument", "Pairing QR display does not support sprite clones.");
3146
+ if (!Number.isInteger(target.drawableID) || Number(target.drawableID) < 0) throw new QrPairingError("renderer-unavailable", "The pairing QR sprite target has no valid drawable.");
3147
+ return target;
3148
+ }
3149
+ show(targetValue, svg) {
3150
+ const target = this.validateTarget(targetValue);
3151
+ const renderer = requireRenderer(this.runtime.renderer);
3152
+ const drawableId = Number(target.drawableID);
3153
+ const current = this.displays.get(target);
3154
+ const originalSkinId = current?.originalSkinId ?? currentSkinId(renderer, drawableId);
3155
+ const temporarySkinId = renderer.createSVGSkin(svg);
3156
+ if (!Number.isInteger(temporarySkinId) || temporarySkinId < 0) throw new QrPairingError("renderer-unavailable", "The renderer could not create a temporary QR skin.");
3157
+ try {
3158
+ renderer.updateDrawableSkinId(drawableId, temporarySkinId);
3159
+ } catch (error) {
3160
+ renderer.destroySkin(temporarySkinId);
3161
+ throw new QrPairingError("renderer-unavailable", "The renderer could not display the temporary QR skin.", { cause: error });
3162
+ }
3163
+ this.displays.set(target, {
3164
+ target,
3165
+ drawableId,
3166
+ originalSkinId,
3167
+ temporarySkinId
3168
+ });
3169
+ if (current) renderer.destroySkin(current.temporarySkinId);
3170
+ this.runtime.requestRedraw?.();
3171
+ return target;
3172
+ }
3173
+ releaseTarget(target) {
3174
+ const record = this.displays.get(target);
3175
+ if (!record) return;
3176
+ this.displays.delete(target);
3177
+ const renderer = this.runtime.renderer;
3178
+ try {
3179
+ if (renderer?.updateDrawableSkinId && this.runtime.targets?.includes(target) !== false) renderer.updateDrawableSkinId(record.drawableId, record.originalSkinId);
3180
+ } finally {
3181
+ renderer?.destroySkin?.(record.temporarySkinId);
3182
+ this.runtime.requestRedraw?.();
3183
+ }
3184
+ }
3185
+ releaseAll() {
3186
+ for (const target of [...this.displays.keys()]) this.releaseTarget(target);
3187
+ }
3188
+ isDisplaying(target) {
3189
+ return this.displays.has(target);
3190
+ }
3191
+ };
3192
+ function requireRenderer(renderer) {
3193
+ if (!renderer || typeof renderer.createSVGSkin !== "function" || typeof renderer.destroySkin !== "function" || typeof renderer.updateDrawableSkinId !== "function") throw new QrPairingError("renderer-unavailable", "The TurboWarp renderer does not provide temporary SVG skin APIs.");
3194
+ return renderer;
3195
+ }
3196
+ function currentSkinId(renderer, drawableId) {
3197
+ const skinId = renderer._allDrawables?.[drawableId]?._skin?._id;
3198
+ if (!Number.isInteger(skinId) || Number(skinId) < 0) throw new QrPairingError("renderer-unavailable", "The renderer could not determine the sprite original skin.");
3199
+ return Number(skinId);
3200
+ }
3201
+ //#endregion
3202
+ //#region src/ports/qr-scan.ts
3203
+ var QR_DECODER_KEY = "ext_kubohiroyajsqr";
3204
+ var CAMERA_SOURCE_KEY = "ext_kubohiroyacamerasource";
3205
+ /**
3206
+ * Reads QR texts from a camera for the length of a pairing session.
3207
+ *
3208
+ * The jsQR extension's own `waitForQrText` acquires and releases a camera lease
3209
+ * per call, which would restart the camera between every part. This holds one
3210
+ * lease for the whole session instead and reuses jsQR only for decoding, so the
3211
+ * camera-source lease rules are respected and other holders keep the camera
3212
+ * alive after the session ends.
3213
+ */
3214
+ var CameraQrScanner = class {
3215
+ constructor(runtime, owner) {
3216
+ this.runtime = runtime;
3217
+ this.owner = owner;
3218
+ this.leasedCameraId = "";
3219
+ }
3220
+ async scanOnce(options) {
3221
+ if (options.signal.aborted) throw cancelled();
3222
+ const decoder = this.decoder();
3223
+ const lease = await this.acquire(options.cameraId);
3224
+ if (options.signal.aborted) throw cancelled();
3225
+ const interval = Math.max(50, options.intervalMilliseconds ?? 150);
3226
+ return new Promise((resolve, reject) => {
3227
+ let timer;
3228
+ const cleanup = () => {
3229
+ if (timer !== void 0) clearTimeout(timer);
3230
+ options.signal.removeEventListener("abort", onAbort);
3231
+ };
3232
+ const onAbort = () => {
3233
+ cleanup();
3234
+ reject(cancelled());
3235
+ };
3236
+ const tick = () => {
3237
+ if (options.signal.aborted) {
3238
+ onAbort();
3239
+ return;
3240
+ }
3241
+ try {
3242
+ const text = decoder.scanFrame(lease.getFrameSource());
3243
+ if (text !== null) {
3244
+ cleanup();
3245
+ resolve(text);
3246
+ return;
3247
+ }
3248
+ } catch (error) {
3249
+ cleanup();
3250
+ reject(new QrPairingError("camera-unavailable", "Reading the camera frame failed.", { cause: error }));
3251
+ return;
3252
+ }
3253
+ timer = setTimeout(tick, interval);
3254
+ };
3255
+ options.signal.addEventListener("abort", onAbort, { once: true });
3256
+ tick();
3257
+ });
3258
+ }
3259
+ async release() {
3260
+ const lease = this.lease;
3261
+ this.lease = void 0;
3262
+ this.leasedCameraId = "";
3263
+ await lease?.release();
3264
+ }
3265
+ async acquire(cameraId) {
3266
+ if (this.lease && this.leasedCameraId === cameraId) return this.lease;
3267
+ await this.release();
3268
+ const lease = await this.cameraSource().acquireCamera({
3269
+ owner: this.owner,
3270
+ cameraId
3271
+ });
3272
+ this.lease = lease;
3273
+ this.leasedCameraId = cameraId;
3274
+ return lease;
3275
+ }
3276
+ decoder() {
3277
+ const candidate = this.runtime[QR_DECODER_KEY];
3278
+ if (!isRecord(candidate) || typeof candidate.scanFrame !== "function") throw new QrPairingError("qr-decoder-missing", "Scanning pairing QR codes requires @kubohiroya/turbowarp-jsqr.");
3279
+ return candidate;
3280
+ }
3281
+ cameraSource() {
3282
+ const candidate = this.runtime[CAMERA_SOURCE_KEY];
3283
+ if (!isRecord(candidate) || typeof candidate.acquireCamera !== "function") throw new QrPairingError("camera-unavailable", "Scanning pairing QR codes requires @kubohiroya/turbowarp-camera-source.");
3284
+ return candidate;
3285
+ }
3286
+ };
3287
+ function cancelled() {
3288
+ return new QrPairingError("cancelled", "QR scanning was cancelled.");
3289
+ }
3290
+ function isRecord(value) {
3291
+ return typeof value === "object" && value !== null;
3292
+ }
3293
+ //#endregion
3294
+ //#region src/ports/webrtc.ts
3295
+ var WEBRTC_CAPABILITY_KEY = "kubohiroyaWebRtcCapability";
3296
+ var requiredMethods = [
3297
+ "requireVersion",
3298
+ "createOffer",
3299
+ "getOffer",
3300
+ "acceptOffer",
3301
+ "getAnswer",
3302
+ "acceptAnswer",
3303
+ "connectionState",
3304
+ "closePeer"
3305
+ ];
3306
+ function requireWebRtcPairingPort(runtime) {
3307
+ const candidate = runtime[WEBRTC_CAPABILITY_KEY];
3308
+ if (typeof candidate !== "object" || candidate === null) throw new QrPairingError("webrtc-capability-missing", "TurboWarp WebRTC is not loaded.");
3309
+ const record = candidate;
3310
+ for (const method of requiredMethods) if (typeof record[method] !== "function") throw new QrPairingError("webrtc-capability-missing", `TurboWarp WebRTC runtime capability v3 is required.`);
3311
+ try {
3312
+ record.requireVersion(3);
3313
+ } catch (error) {
3314
+ throw new QrPairingError("webrtc-capability-missing", `TurboWarp WebRTC runtime capability v3 is required.`, { cause: error });
3315
+ }
3316
+ return candidate;
3317
+ }
3318
+ //#endregion
3319
+ //#region src/pairing/controller.ts
3320
+ /**
3321
+ * Errors that only mean "that was not our QR code".
3322
+ *
3323
+ * A camera pointed at a projection also sees posters, other sessions, and the
3324
+ * previous exchange's codes, so scanning skips these and keeps looking. Damage
3325
+ * to a code that does belong to this exchange is not in this set: that is
3326
+ * reported, because silently retrying would hide a real problem.
3327
+ */
3328
+ var skippableWhileScanning = /* @__PURE__ */ new Set([
3329
+ "invalid-json",
3330
+ "unsupported-protocol",
3331
+ "invalid-envelope",
3332
+ "part-too-large",
3333
+ "index-out-of-range",
3334
+ "message-too-large",
3335
+ "unexpected-kind",
3336
+ "stale-exchange",
3337
+ "peer-mismatch",
3338
+ "reply-mismatch",
3339
+ "message-mismatch"
3340
+ ]);
3341
+ var idlePhase = "idle";
3342
+ /**
3343
+ * Drives one QR-carried offer/answer exchange per session key.
3344
+ *
3345
+ * The controller owns no display and no camera: it turns pairing codes into QR
3346
+ * texts, accepts decoded texts back, and hands verified codes to WebRTC exactly
3347
+ * once. Display and scanning adapters build on top of it.
3348
+ */
3349
+ var PairingController = class {
3350
+ constructor(options = {}) {
3351
+ this.sessions = /* @__PURE__ */ new Map();
3352
+ this.activeScans = 0;
3353
+ this.runtime = options.runtime ?? Scratch.vm?.runtime ?? {};
3354
+ this.enabled = options.enabled ?? featureFlags.qrCodePairing;
3355
+ this.errorCorrectionLevel = options.errorCorrectionLevel ?? qrConfig.errorCorrectionLevel;
3356
+ this.injectedWebRtc = options.webrtc;
3357
+ this.injectedDisplay = options.display;
3358
+ this.injectedScan = options.scan;
3359
+ this.clock = options.clock ?? systemMonotonicClock;
3360
+ this.now = options.now ?? (() => Date.now());
3361
+ }
3362
+ /** Hub side: create an offer and prepare its QR parts. */
3363
+ async startOfferPairing(input) {
3364
+ this.requireEnabled();
3365
+ const sessionKey = requireSessionKey(input.sessionKey);
3366
+ if (this.sessions.has(sessionKey)) throw new QrPairingError("session-exists", `Pairing session ${sessionKey} is already open.`);
3367
+ this.requireCapacity();
3368
+ const localPeerId = requireIdentifier(input.localPeerId.trim(), "local peer name");
3369
+ const remotePeerId = requireIdentifier(input.remotePeerId.trim(), "remote peer name");
3370
+ const session = this.createSession({
3371
+ sessionKey,
3372
+ role: "hub",
3373
+ expectedLocalPeerId: localPeerId,
3374
+ localPeerId,
3375
+ remotePeerId
3376
+ });
3377
+ this.sessions.set(sessionKey, session);
3378
+ await this.runOfferExchange(session);
3379
+ }
3380
+ /**
3381
+ * Camera side: wait for an offer.
3382
+ *
3383
+ * `expectedLocalPeerId` may be empty, in which case this device adopts the
3384
+ * name the offer assigns to it. A non-empty value is verified instead, which
3385
+ * catches an operator scanning the wrong projection.
3386
+ */
3387
+ startAnswerPairing(input) {
3388
+ this.requireEnabled();
3389
+ const sessionKey = requireSessionKey(input.sessionKey);
3390
+ if (this.sessions.has(sessionKey)) throw new QrPairingError("session-exists", `Pairing session ${sessionKey} is already open.`);
3391
+ this.requireCapacity();
3392
+ const expectedLocalPeerId = input.expectedLocalPeerId.trim();
3393
+ if (expectedLocalPeerId !== "") requireIdentifier(expectedLocalPeerId, "local peer name");
3394
+ const session = this.createSession({
3395
+ sessionKey,
3396
+ role: "camera",
3397
+ expectedLocalPeerId,
3398
+ localPeerId: expectedLocalPeerId,
3399
+ remotePeerId: ""
3400
+ });
3401
+ session.phase = "awaiting-offer";
3402
+ this.sessions.set(sessionKey, session);
3403
+ this.scheduleTick(session);
3404
+ }
3405
+ /**
3406
+ * Accepts one decoded QR text. When the last part arrives, the reassembled
3407
+ * code is verified and handed to WebRTC once.
3408
+ */
3409
+ async ingestQrText(sessionKey, text) {
3410
+ this.requireEnabled();
3411
+ const session = this.requireSession(sessionKey);
3412
+ if (isTerminalPhase(session.phase)) throw new QrPairingError(session.phase === "connected" ? "already-accepted" : "stale-exchange", `Pairing session ${session.sessionKey} is no longer receiving parts.`);
3413
+ const envelope = parseEnvelope(text);
3414
+ this.verifyEnvelope(session, envelope);
3415
+ if (session.delivered) throw new QrPairingError("already-accepted", "The pairing code for this exchange has already been accepted.");
3416
+ if (session.role === "camera" && session.exchangeId === "") this.adoptOffer(session, envelope);
3417
+ session.assembler.add(envelope);
3418
+ if (!isTerminalPhase(session.phase)) session.phase = session.role === "hub" ? "awaiting-answer" : "receiving";
3419
+ if (!session.assembler.isComplete()) return;
3420
+ const epoch = session.epoch;
3421
+ let message;
3422
+ try {
3423
+ message = await session.assembler.assemble();
3424
+ } catch (error) {
3425
+ if (!this.isStale(session, epoch)) this.failFrom(session, error);
3426
+ throw error;
3427
+ }
3428
+ if (this.isStale(session, epoch)) return;
3429
+ session.incomingMessageId = envelope.messageId;
3430
+ session.phase = session.role === "hub" ? "answer-received" : "offer-received";
3431
+ session.delivered = true;
3432
+ if (session.role === "hub") await this.acceptAnswer(session, message, epoch);
3433
+ else await this.acceptOfferAndPrepareAnswer(session, message, epoch);
3434
+ }
3435
+ /** Selects the one-based part to display and returns its SVG. */
3436
+ selectPart(sessionKey, oneBasedIndex) {
3437
+ const session = this.requireSession(sessionKey);
3438
+ const total = session.outgoingSvgs.length;
3439
+ if (total === 0) throw new QrPairingError("no-session", "No QR parts have been prepared yet.");
3440
+ if (!Number.isInteger(oneBasedIndex) || oneBasedIndex < 1 || oneBasedIndex > total) throw new QrPairingError("invalid-argument", `QR part index must be between 1 and ${total}.`);
3441
+ session.outgoingCurrentIndex = oneBasedIndex - 1;
3442
+ return session.outgoingSvgs[session.outgoingCurrentIndex] ?? "";
3443
+ }
3444
+ /** Advances to the next part, wrapping from the last part to the first. */
3445
+ selectNextPart(sessionKey) {
3446
+ const session = this.requireSession(sessionKey);
3447
+ const total = session.outgoingSvgs.length;
3448
+ if (total === 0) throw new QrPairingError("no-session", "No QR parts have been prepared yet.");
3449
+ return this.selectPart(sessionKey, (session.outgoingCurrentIndex + 1) % total + 1);
3450
+ }
3451
+ partSvg(sessionKey, oneBasedIndex) {
3452
+ return this.requireSession(sessionKey).outgoingSvgs[oneBasedIndex - 1] ?? "";
3453
+ }
3454
+ partText(sessionKey, oneBasedIndex) {
3455
+ return this.requireSession(sessionKey).outgoing?.texts[oneBasedIndex - 1] ?? "";
3456
+ }
3457
+ /** Shows the one-based part on the supplied sprite, keeping its original skin. */
3458
+ showPart(sessionKey, oneBasedIndex, target) {
3459
+ const session = this.requireSession(sessionKey);
3460
+ const svg = this.selectPart(sessionKey, oneBasedIndex);
3461
+ session.displayTargets.add(this.display().show(target, svg));
3462
+ }
3463
+ showNextPart(sessionKey, target) {
3464
+ const session = this.requireSession(sessionKey);
3465
+ const svg = this.selectNextPart(sessionKey);
3466
+ session.displayTargets.add(this.display().show(target, svg));
3467
+ }
3468
+ /** Restores the sprites this session changed. The session itself stays open. */
3469
+ endDisplay(sessionKey) {
3470
+ this.releaseDisplay(this.requireSession(sessionKey));
3471
+ }
3472
+ /** Called when the runtime removes a sprite, so its skin is not restored onto nothing. */
3473
+ handleTargetRemoved(target) {
3474
+ for (const session of this.sessions.values()) {
3475
+ if (!session.displayTargets.delete(target)) continue;
3476
+ this.display().releaseTarget(target);
3477
+ }
3478
+ }
3479
+ /**
3480
+ * Reads parts from a camera until the exchange has everything it needs.
3481
+ *
3482
+ * Codes that belong to something else are skipped rather than reported: a
3483
+ * camera aimed at a projection also sees whatever else is in frame.
3484
+ */
3485
+ async scanFromCamera(sessionKey, cameraId) {
3486
+ this.requireEnabled();
3487
+ const session = this.requireSession(sessionKey);
3488
+ const camera = cameraId.trim() || "default";
3489
+ if (session.scanAbort) throw new QrPairingError("invalid-argument", `Pairing session ${session.sessionKey} is already scanning.`);
3490
+ const epoch = session.epoch;
3491
+ const abort = new AbortController();
3492
+ session.scanAbort = abort;
3493
+ this.activeScans += 1;
3494
+ const scan = this.scanner();
3495
+ try {
3496
+ while (!this.isStale(session, epoch) && !isTerminalPhase(session.phase)) {
3497
+ if (session.delivered) return;
3498
+ const text = await scan.scanOnce({
3499
+ cameraId: camera,
3500
+ signal: abort.signal
3501
+ });
3502
+ if (this.isStale(session, epoch)) return;
3503
+ try {
3504
+ await this.ingestQrText(sessionKey, text);
3505
+ } catch (error) {
3506
+ if (!(error instanceof QrPairingError) || !skippableWhileScanning.has(error.code)) throw error;
3507
+ }
3508
+ }
3509
+ } catch (error) {
3510
+ if (error instanceof QrPairingError && error.code === "cancelled") return;
3511
+ throw error;
3512
+ } finally {
3513
+ if (session.scanAbort === abort) session.scanAbort = void 0;
3514
+ this.activeScans -= 1;
3515
+ if (this.activeScans === 0) await scan.release();
3516
+ }
3517
+ }
3518
+ cancelPairing(sessionKey) {
3519
+ const session = this.sessions.get(requireSessionKey(sessionKey));
3520
+ if (!session) return;
3521
+ this.finish(session, "cancelled", "", "");
3522
+ }
3523
+ /** Cancels the current exchange and starts a new one with a fresh exchange ID. */
3524
+ async retryPairing(sessionKey) {
3525
+ this.requireEnabled();
3526
+ const session = this.requireSession(sessionKey);
3527
+ this.finish(session, "cancelled", "", "");
3528
+ this.resetSession(session);
3529
+ if (session.role === "hub") await this.runOfferExchange(session);
3530
+ else {
3531
+ session.phase = "awaiting-offer";
3532
+ this.scheduleTick(session);
3533
+ }
3534
+ }
3535
+ setTimeoutSeconds(sessionKey, seconds) {
3536
+ const session = this.requireSession(sessionKey);
3537
+ if (!Number.isFinite(seconds) || seconds < 1 || seconds > 3600) throw new QrPairingError("invalid-argument", `Pairing timeout must be between 1 and ${MAX_TIMEOUT_SECONDS} seconds.`);
3538
+ session.timeoutMilliseconds = Math.floor(seconds * 1e3);
3539
+ }
3540
+ progress(sessionKey) {
3541
+ const session = this.sessions.get(sessionKey.trim());
3542
+ if (!session) return {
3543
+ phase: this.enabled ? idlePhase : "disabled",
3544
+ role: "hub",
3545
+ sessionKey: sessionKey.trim(),
3546
+ exchangeId: "",
3547
+ localPeerId: "",
3548
+ remotePeerId: "",
3549
+ outgoingPartCount: 0,
3550
+ outgoingCurrentPart: 0,
3551
+ receivedParts: 0,
3552
+ requiredParts: 0,
3553
+ missingParts: [],
3554
+ connectionState: "",
3555
+ errorCode: "",
3556
+ errorMessage: "",
3557
+ remainingSeconds: 0
3558
+ };
3559
+ const elapsed = this.clock.nowMilliseconds() - session.startedAtMonotonic;
3560
+ const remaining = Math.max(0, session.timeoutMilliseconds - elapsed);
3561
+ return {
3562
+ phase: this.enabled ? session.phase : "disabled",
3563
+ role: session.role,
3564
+ sessionKey: session.sessionKey,
3565
+ exchangeId: session.exchangeId,
3566
+ localPeerId: session.localPeerId,
3567
+ remotePeerId: session.remotePeerId,
3568
+ outgoingPartCount: session.outgoingSvgs.length,
3569
+ outgoingCurrentPart: session.outgoingCurrentIndex + 1,
3570
+ receivedParts: session.assembler.receivedCount(),
3571
+ requiredParts: session.assembler.requiredCount(),
3572
+ missingParts: session.assembler.missingParts().map((index) => index + 1),
3573
+ connectionState: session.peerCreated ? this.readConnectionState(session) : "",
3574
+ errorCode: session.errorCode,
3575
+ errorMessage: session.errorMessage,
3576
+ remainingSeconds: isTerminalPhase(session.phase) ? 0 : Math.ceil(remaining / 1e3)
3577
+ };
3578
+ }
3579
+ sessionKeys() {
3580
+ return [...this.sessions.keys()];
3581
+ }
3582
+ isConnected(sessionKey) {
3583
+ return this.sessions.get(sessionKey.trim())?.phase === "connected";
3584
+ }
3585
+ /** Resolves on connection, rejects on failure, cancellation, or expiry. */
3586
+ waitUntilConnected(sessionKey) {
3587
+ const session = this.requireSession(sessionKey);
3588
+ if (session.phase === "connected") return Promise.resolve();
3589
+ if (isTerminalPhase(session.phase)) return Promise.reject(this.terminalError(session));
3590
+ return new Promise((resolve, reject) => {
3591
+ session.waiters.push({
3592
+ resolve,
3593
+ reject
3594
+ });
3595
+ });
3596
+ }
3597
+ /**
3598
+ * Project run stop. Cancels exchanges in progress and releases what this
3599
+ * controller owns. Established connections stay up: closing them is the
3600
+ * application's explicit decision.
3601
+ */
3602
+ stopTransient() {
3603
+ for (const session of [...this.sessions.values()]) {
3604
+ if (session.phase === "connected") {
3605
+ this.clearTimer(session);
3606
+ session.scanAbort?.abort();
3607
+ this.releaseDisplay(session);
3608
+ continue;
3609
+ }
3610
+ this.finish(session, "cancelled", "", "");
3611
+ }
3612
+ this.releaseScanner();
3613
+ }
3614
+ /** Runtime disposal. Drops every session and its retained state. */
3615
+ dispose() {
3616
+ for (const session of [...this.sessions.values()]) this.finish(session, "cancelled", "", "");
3617
+ this.sessions.clear();
3618
+ this.lazyDisplay?.releaseAll();
3619
+ this.releaseScanner();
3620
+ }
3621
+ async runOfferExchange(session) {
3622
+ const epoch = session.epoch;
3623
+ session.phase = "creating-offer";
3624
+ this.scheduleTick(session);
3625
+ try {
3626
+ const webrtc = this.webrtc();
3627
+ const created = await webrtc.createOffer(session.remotePeerId);
3628
+ if (this.isStale(session, epoch)) return;
3629
+ session.peerCreated = true;
3630
+ const code = created || webrtc.getOffer(session.remotePeerId);
3631
+ if (!code) throw new QrPairingError("webrtc-rejected", "TurboWarp WebRTC did not return an offer pairing code.");
3632
+ const parts = await createParts(code, this.partOptions(session, "offer"));
3633
+ if (this.isStale(session, epoch)) return;
3634
+ this.attachOutgoing(session, parts);
3635
+ session.phase = "offer-ready";
3636
+ } catch (error) {
3637
+ if (!this.isStale(session, epoch)) this.failFrom(session, error);
3638
+ throw error;
3639
+ }
3640
+ }
3641
+ async acceptAnswer(session, message, epoch) {
3642
+ try {
3643
+ await this.webrtc().acceptAnswer(session.remotePeerId, message);
3644
+ if (this.isStale(session, epoch)) return;
3645
+ session.phase = "connecting";
3646
+ this.scheduleTick(session);
3647
+ } catch (error) {
3648
+ if (!this.isStale(session, epoch)) this.failFrom(session, error);
3649
+ throw error;
3650
+ }
3651
+ }
3652
+ async acceptOfferAndPrepareAnswer(session, message, epoch) {
3653
+ session.phase = "creating-answer";
3654
+ try {
3655
+ const webrtc = this.webrtc();
3656
+ const created = await webrtc.acceptOffer(session.remotePeerId, message);
3657
+ if (this.isStale(session, epoch)) return;
3658
+ session.peerCreated = true;
3659
+ const code = created || webrtc.getAnswer(session.remotePeerId);
3660
+ if (!code) throw new QrPairingError("webrtc-rejected", "TurboWarp WebRTC did not return an answer pairing code.");
3661
+ const parts = await createParts(code, this.partOptions(session, "answer"));
3662
+ if (this.isStale(session, epoch)) return;
3663
+ this.attachOutgoing(session, parts);
3664
+ session.phase = "answer-ready";
3665
+ this.scheduleTick(session);
3666
+ } catch (error) {
3667
+ if (!this.isStale(session, epoch)) this.failFrom(session, error);
3668
+ throw error;
3669
+ }
3670
+ }
3671
+ partOptions(session, kind) {
3672
+ const common = {
3673
+ senderPeerId: session.localPeerId,
3674
+ targetPeerId: session.remotePeerId,
3675
+ errorCorrectionLevel: this.errorCorrectionLevel,
3676
+ createdAt: this.now()
3677
+ };
3678
+ return kind === "offer" ? {
3679
+ ...common,
3680
+ kind
3681
+ } : {
3682
+ ...common,
3683
+ kind,
3684
+ sessionId: session.exchangeId,
3685
+ replyTo: session.incomingMessageId
3686
+ };
3687
+ }
3688
+ attachOutgoing(session, parts) {
3689
+ session.outgoing = parts;
3690
+ session.outgoingSvgs = parts.texts.map((text) => createQrSvg(text, this.errorCorrectionLevel));
3691
+ session.outgoingCurrentIndex = -1;
3692
+ session.exchangeId = parts.sessionId;
3693
+ session.outgoingMessageId = parts.messageId;
3694
+ }
3695
+ /**
3696
+ * Checks that a part belongs to this exchange, this role, and this peer pair
3697
+ * before any of it reaches the assembler.
3698
+ */
3699
+ verifyEnvelope(session, envelope) {
3700
+ const expectedKind = session.role === "hub" ? "answer" : "offer";
3701
+ if (envelope.kind !== expectedKind) throw new QrPairingError("unexpected-kind", `This session expects ${expectedKind} parts.`);
3702
+ if (session.role === "hub") {
3703
+ if (envelope.sessionId !== session.exchangeId) throw new QrPairingError("stale-exchange", "QR part belongs to a different pairing exchange.");
3704
+ if (envelope.replyTo !== session.outgoingMessageId) throw new QrPairingError("reply-mismatch", "QR part answers a different offer.");
3705
+ if (envelope.senderPeerId !== session.remotePeerId || envelope.targetPeerId !== session.localPeerId) throw new QrPairingError("peer-mismatch", "QR part names a different pair of peers.");
3706
+ return;
3707
+ }
3708
+ if (session.exchangeId !== "" && envelope.sessionId !== session.exchangeId) throw new QrPairingError("stale-exchange", "QR part belongs to a different pairing exchange.");
3709
+ if (session.expectedLocalPeerId !== "" && envelope.targetPeerId !== session.expectedLocalPeerId) throw new QrPairingError("peer-mismatch", "QR part is addressed to a different device.");
3710
+ if (session.remotePeerId !== "" && envelope.senderPeerId !== session.remotePeerId) throw new QrPairingError("peer-mismatch", "QR part names a different sender.");
3711
+ }
3712
+ /**
3713
+ * Adopts the peer naming the offer carries. The sender's name for itself
3714
+ * becomes this device's WebRTC peer key, so the two ends never need to be
3715
+ * configured with the same identifiers.
3716
+ */
3717
+ adoptOffer(session, envelope) {
3718
+ session.exchangeId = envelope.sessionId;
3719
+ session.localPeerId = envelope.targetPeerId;
3720
+ session.remotePeerId = envelope.senderPeerId;
3721
+ }
3722
+ createSession(input) {
3723
+ return {
3724
+ sessionKey: input.sessionKey,
3725
+ role: input.role,
3726
+ expectedLocalPeerId: input.expectedLocalPeerId,
3727
+ localPeerId: input.localPeerId,
3728
+ remotePeerId: input.remotePeerId,
3729
+ phase: idlePhase,
3730
+ epoch: 0,
3731
+ exchangeId: "",
3732
+ outgoingMessageId: "",
3733
+ incomingMessageId: "",
3734
+ outgoing: void 0,
3735
+ outgoingSvgs: [],
3736
+ outgoingCurrentIndex: -1,
3737
+ assembler: new PartAssembler(),
3738
+ delivered: false,
3739
+ peerCreated: false,
3740
+ timeoutMilliseconds: 6e5,
3741
+ startedAtMonotonic: this.clock.nowMilliseconds(),
3742
+ errorCode: "",
3743
+ errorMessage: "",
3744
+ tickTimer: void 0,
3745
+ displayTargets: /* @__PURE__ */ new Set(),
3746
+ scanAbort: void 0,
3747
+ waiters: []
3748
+ };
3749
+ }
3750
+ /** Prepares an existing session entry for a new exchange after a retry. */
3751
+ resetSession(session) {
3752
+ session.epoch += 1;
3753
+ session.phase = idlePhase;
3754
+ session.exchangeId = "";
3755
+ session.outgoingMessageId = "";
3756
+ session.incomingMessageId = "";
3757
+ session.outgoing = void 0;
3758
+ session.outgoingSvgs = [];
3759
+ session.outgoingCurrentIndex = -1;
3760
+ session.assembler = new PartAssembler();
3761
+ session.delivered = false;
3762
+ session.peerCreated = false;
3763
+ session.startedAtMonotonic = this.clock.nowMilliseconds();
3764
+ session.errorCode = "";
3765
+ session.errorMessage = "";
3766
+ session.scanAbort = void 0;
3767
+ if (session.role === "camera") {
3768
+ session.localPeerId = session.expectedLocalPeerId;
3769
+ session.remotePeerId = "";
3770
+ }
3771
+ }
3772
+ scheduleTick(session) {
3773
+ if (session.tickTimer !== void 0) return;
3774
+ session.tickTimer = setTimeout(() => {
3775
+ session.tickTimer = void 0;
3776
+ this.tick(session);
3777
+ }, 250);
3778
+ }
3779
+ tick(session) {
3780
+ if (this.sessions.get(session.sessionKey) !== session) return;
3781
+ if (isTerminalPhase(session.phase)) return;
3782
+ if (this.clock.nowMilliseconds() - session.startedAtMonotonic >= session.timeoutMilliseconds) {
3783
+ this.finish(session, "expired", "timeout", "The pairing exchange timed out.");
3784
+ return;
3785
+ }
3786
+ if (session.peerCreated) {
3787
+ const state = this.readConnectionState(session);
3788
+ if (state === "connected") {
3789
+ this.finish(session, "connected", "", "");
3790
+ return;
3791
+ }
3792
+ if (state === "failed" || state === "closed") {
3793
+ this.finish(session, "failed", "webrtc-rejected", "WebRTC reported that the connection could not be established.");
3794
+ return;
3795
+ }
3796
+ }
3797
+ this.scheduleTick(session);
3798
+ }
3799
+ /**
3800
+ * Moves a session to a terminal phase and releases what it owns.
3801
+ *
3802
+ * Everything but an established RTCPeerConnection is released: timers, the
3803
+ * receive buffer, and the peer connection when it never connected.
3804
+ */
3805
+ finish(session, phase, errorCode, errorMessage) {
3806
+ if (isTerminalPhase(session.phase) && session.phase !== "connected") return;
3807
+ const connected = phase === "connected";
3808
+ session.epoch += 1;
3809
+ session.phase = phase;
3810
+ session.errorCode = errorCode;
3811
+ session.errorMessage = errorMessage;
3812
+ this.clearTimer(session);
3813
+ session.scanAbort?.abort();
3814
+ this.releaseDisplay(session);
3815
+ if (!connected) {
3816
+ session.assembler.clear();
3817
+ if (session.peerCreated) {
3818
+ try {
3819
+ this.webrtc().closePeer(session.remotePeerId);
3820
+ } catch {}
3821
+ session.peerCreated = false;
3822
+ }
3823
+ }
3824
+ const waiters = session.waiters.splice(0, session.waiters.length);
3825
+ for (const waiter of waiters) if (connected) waiter.resolve();
3826
+ else waiter.reject(this.terminalError(session));
3827
+ }
3828
+ failFrom(session, error) {
3829
+ const code = error instanceof QrPairingError ? error.code : "webrtc-rejected";
3830
+ const message = error instanceof Error ? error.message : "Pairing failed.";
3831
+ this.finish(session, "failed", code, message);
3832
+ }
3833
+ terminalError(session) {
3834
+ if (session.phase === "cancelled") return new QrPairingError("cancelled", "The pairing exchange was cancelled.");
3835
+ if (session.phase === "expired") return new QrPairingError("timeout", "The pairing exchange timed out.");
3836
+ return new QrPairingError(session.errorCode === "" ? "webrtc-rejected" : session.errorCode, session.errorMessage || "The pairing exchange failed.");
3837
+ }
3838
+ clearTimer(session) {
3839
+ if (session.tickTimer === void 0) return;
3840
+ clearTimeout(session.tickTimer);
3841
+ session.tickTimer = void 0;
3842
+ }
3843
+ readConnectionState(session) {
3844
+ try {
3845
+ return this.webrtc().connectionState(session.remotePeerId);
3846
+ } catch {
3847
+ return "";
3848
+ }
3849
+ }
3850
+ async releaseScanner() {
3851
+ if (this.activeScans > 0) return;
3852
+ await this.lazyScan?.release();
3853
+ }
3854
+ releaseDisplay(session) {
3855
+ if (session.displayTargets.size === 0) return;
3856
+ const display = this.display();
3857
+ for (const target of [...session.displayTargets]) display.releaseTarget(target);
3858
+ session.displayTargets.clear();
3859
+ }
3860
+ webrtc() {
3861
+ return this.injectedWebRtc ?? requireWebRtcPairingPort(this.runtime);
3862
+ }
3863
+ display() {
3864
+ this.lazyDisplay ?? (this.lazyDisplay = this.injectedDisplay ?? new TemporarySpriteSkinManager(this.runtime));
3865
+ return this.lazyDisplay;
3866
+ }
3867
+ scanner() {
3868
+ this.lazyScan ?? (this.lazyScan = this.injectedScan ?? new CameraQrScanner(this.runtime, "webrtc-qrcode-pairing"));
3869
+ return this.lazyScan;
3870
+ }
3871
+ requireEnabled() {
3872
+ if (this.enabled) return;
3873
+ throw new QrPairingError("feature-disabled", "QR code pairing is disabled. Enable it before the project starts.");
3874
+ }
3875
+ requireCapacity() {
3876
+ if (this.sessions.size < 8) return;
3877
+ throw new QrPairingError("session-limit", `At most 8 pairing sessions can be open at once.`);
3878
+ }
3879
+ requireSession(sessionKey) {
3880
+ const session = this.sessions.get(requireSessionKey(sessionKey));
3881
+ if (!session) throw new QrPairingError("no-session", `Pairing session ${sessionKey.trim()} is not open.`);
3882
+ return session;
3883
+ }
3884
+ isStale(session, epoch) {
3885
+ return session.epoch !== epoch || this.sessions.get(session.sessionKey) !== session;
3886
+ }
3887
+ };
3888
+ function requireSessionKey(value) {
3889
+ const key = typeof value === "string" ? value.trim() : "";
3890
+ if (key === "") throw new QrPairingError("invalid-argument", "Pairing session name must not be empty.");
3891
+ return key;
3892
+ }
3893
+ //#endregion
3894
+ //#region src/extension.ts
3895
+ var blockDefinitions = block_definitions_default.blocks;
3896
+ /**
3897
+ * Block facade.
3898
+ *
3899
+ * Every method casts its arguments and delegates. Pairing logic lives in
3900
+ * PairingController, which has no Scratch dependency and can be tested without
3901
+ * a runtime.
3902
+ */
3903
+ var WebRtcQrCodePairingExtension = class {
3904
+ constructor(options = {}) {
3905
+ this.stopListener = () => this.pairing.stopTransient();
3906
+ this.resetListener = () => this.pairing.dispose();
3907
+ this.disposeListener = () => this.dispose();
3908
+ this.targetRemovedListener = (target) => {
3909
+ if (isTarget(target)) this.pairing.handleTargetRemoved(target);
3910
+ };
3911
+ this.enabled = options.enabled ?? featureFlags.qrCodePairing;
3912
+ this.runtime = options.runtime ?? Scratch.vm?.runtime ?? {};
3913
+ this.pairing = new PairingController({
3914
+ ...options,
3915
+ runtime: this.runtime
3916
+ });
3917
+ this.runtime.on?.("PROJECT_RUN_STOP", this.stopListener);
3918
+ this.runtime.on?.("PROJECT_STOP_ALL", this.stopListener);
3919
+ this.runtime.on?.("PROJECT_LOADED", this.resetListener);
3920
+ this.runtime.on?.("RUNTIME_DISPOSED", this.disposeListener);
3921
+ this.runtime.on?.("targetWasRemoved", this.targetRemovedListener);
3922
+ }
3923
+ getInfo() {
3924
+ return {
3925
+ id: extensionConfig.id,
3926
+ name: Scratch.translate(block_definitions_default.extensionName),
3927
+ docsURI: extensionConfig.docsURI,
3928
+ blockIconURI: extensionConfig.blockIconURI,
3929
+ blocks: this.enabled ? blockDefinitions.map((block) => this.toScratchBlock(block)) : []
3930
+ };
3931
+ }
3932
+ async startOfferPairing(args) {
3933
+ await this.pairing.startOfferPairing({
3934
+ sessionKey: Scratch.Cast.toString(args.SESSION),
3935
+ localPeerId: Scratch.Cast.toString(args.LOCAL_PEER),
3936
+ remotePeerId: Scratch.Cast.toString(args.REMOTE_PEER)
3937
+ });
3938
+ }
3939
+ startAnswerPairing(args) {
3940
+ this.pairing.startAnswerPairing({
3941
+ sessionKey: Scratch.Cast.toString(args.SESSION),
3942
+ expectedLocalPeerId: Scratch.Cast.toString(args.LOCAL_PEER)
3943
+ });
3944
+ }
3945
+ async ingestPairingQrText(args) {
3946
+ await this.pairing.ingestQrText(Scratch.Cast.toString(args.SESSION), Scratch.Cast.toString(args.TEXT));
3947
+ }
3948
+ async scanPairingQrFromCamera(args) {
3949
+ await this.pairing.scanFromCamera(Scratch.Cast.toString(args.SESSION), Scratch.Cast.toString(args.CAMERA_ID));
3950
+ }
3951
+ pairingReceivedParts(args) {
3952
+ return this.progress(args).receivedParts;
3953
+ }
3954
+ pairingRequiredParts(args) {
3955
+ return this.progress(args).requiredParts;
3956
+ }
3957
+ pairingMissingParts(args) {
3958
+ return this.progress(args).missingParts.join(",");
3959
+ }
3960
+ showPairingQrPart(args, util) {
3961
+ this.pairing.showPart(Scratch.Cast.toString(args.SESSION), Scratch.Cast.toNumber(args.INDEX), util?.target);
3962
+ }
3963
+ showNextPairingQrPart(args, util) {
3964
+ this.pairing.showNextPart(Scratch.Cast.toString(args.SESSION), util?.target);
3965
+ }
3966
+ pairingQrPartCount(args) {
3967
+ return this.progress(args).outgoingPartCount;
3968
+ }
3969
+ pairingQrCurrentPart(args) {
3970
+ return this.progress(args).outgoingCurrentPart;
3971
+ }
3972
+ pairingQrPartSvg(args) {
3973
+ return this.partSvg(args);
3974
+ }
3975
+ pairingQrPartDataUri(args) {
3976
+ const svg = this.partSvg(args);
3977
+ return svg === "" ? "" : `data:image/svg+xml;base64,${btoa(svg)}`;
3978
+ }
3979
+ endPairingQrDisplay(args) {
3980
+ this.pairing.endDisplay(Scratch.Cast.toString(args.SESSION));
3981
+ }
3982
+ pairingPhase(args) {
3983
+ return this.progress(args).phase;
3984
+ }
3985
+ pairingConnectionState(args) {
3986
+ return this.progress(args).connectionState;
3987
+ }
3988
+ isPairingConnected(args) {
3989
+ return this.pairing.isConnected(Scratch.Cast.toString(args.SESSION));
3990
+ }
3991
+ async waitUntilPairingConnected(args) {
3992
+ await this.pairing.waitUntilConnected(Scratch.Cast.toString(args.SESSION));
3993
+ }
3994
+ pairingError(args) {
3995
+ return this.progress(args).errorCode;
3996
+ }
3997
+ pairingErrorMessage(args) {
3998
+ return this.progress(args).errorMessage;
3999
+ }
4000
+ pairingLocalPeer(args) {
4001
+ return this.progress(args).localPeerId;
4002
+ }
4003
+ pairingRemotePeer(args) {
4004
+ return this.progress(args).remotePeerId;
4005
+ }
4006
+ pairingExchangeId(args) {
4007
+ return this.progress(args).exchangeId;
4008
+ }
4009
+ pairingRemainingSeconds(args) {
4010
+ return this.progress(args).remainingSeconds;
4011
+ }
4012
+ pairingSessions() {
4013
+ return this.pairing.sessionKeys().join(",");
4014
+ }
4015
+ cancelPairing(args) {
4016
+ this.pairing.cancelPairing(Scratch.Cast.toString(args.SESSION));
4017
+ }
4018
+ async retryPairing(args) {
4019
+ await this.pairing.retryPairing(Scratch.Cast.toString(args.SESSION));
4020
+ }
4021
+ setPairingTimeout(args) {
4022
+ this.pairing.setTimeoutSeconds(Scratch.Cast.toString(args.SESSION), Scratch.Cast.toNumber(args.SECONDS));
4023
+ }
4024
+ dispose() {
4025
+ this.pairing.dispose();
4026
+ this.runtime.off?.("PROJECT_RUN_STOP", this.stopListener);
4027
+ this.runtime.off?.("PROJECT_STOP_ALL", this.stopListener);
4028
+ this.runtime.off?.("PROJECT_LOADED", this.resetListener);
4029
+ this.runtime.off?.("RUNTIME_DISPOSED", this.disposeListener);
4030
+ this.runtime.off?.("targetWasRemoved", this.targetRemovedListener);
4031
+ }
4032
+ progress(args) {
4033
+ return this.pairing.progress(Scratch.Cast.toString(args.SESSION));
4034
+ }
4035
+ /** Reporters report; they never stop a script, so an unknown session is an empty string. */
4036
+ partSvg(args) {
4037
+ try {
4038
+ return this.pairing.partSvg(Scratch.Cast.toString(args.SESSION), Scratch.Cast.toNumber(args.INDEX));
4039
+ } catch {
4040
+ return "";
4041
+ }
4042
+ }
4043
+ toScratchBlock(block) {
4044
+ return {
4045
+ opcode: block.opcode,
4046
+ blockType: Scratch.BlockType[block.blockType],
4047
+ text: Scratch.translate(block.text),
4048
+ arguments: Object.fromEntries(Object.entries(block.arguments).map(([name, argument]) => [name, {
4049
+ type: Scratch.ArgumentType[argument.type],
4050
+ defaultValue: argument.defaultValue
4051
+ }]))
4052
+ };
4053
+ }
4054
+ };
4055
+ function isTarget(value) {
4056
+ return typeof value === "object" && value !== null;
4057
+ }
4058
+ //#endregion
4059
+ //#region src/index.ts
4060
+ if (extensionConfig.unsandboxed && !Scratch.extensions.unsandboxed) throw new Error(`${extensionConfig.name} must run unsandboxed.`);
4061
+ Scratch.extensions.register(new WebRtcQrCodePairingExtension());
4062
+ //#endregion
4063
+
4064
+ })(Scratch);