@sess.si/sdk 0.1.0-rc.8 → 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 (139) hide show
  1. package/CHANGELOG.md +66 -9
  2. package/NOTICE +1 -1
  3. package/README.md +92 -16
  4. package/dist/ask.d.ts +0 -1
  5. package/dist/ask.js +0 -1
  6. package/dist/cli/main.d.ts +0 -1
  7. package/dist/cli/main.js +0 -1
  8. package/dist/cli/verify.d.ts +0 -1
  9. package/dist/cli/verify.js +0 -1
  10. package/dist/client.d.ts +0 -1
  11. package/dist/client.js +0 -1
  12. package/dist/commerce/builders.d.ts +99 -0
  13. package/dist/commerce/builders.js +208 -0
  14. package/dist/commerce/currency.d.ts +4 -0
  15. package/dist/commerce/currency.js +25 -0
  16. package/dist/commerce/items.d.ts +119 -0
  17. package/dist/commerce/items.js +280 -0
  18. package/dist/commerce/lint.d.ts +16 -0
  19. package/dist/commerce/lint.js +56 -0
  20. package/dist/errors.d.ts +5 -2
  21. package/dist/errors.js +15 -25
  22. package/dist/generated/openapi.d.ts +12 -13
  23. package/dist/generated/openapi.js +0 -1
  24. package/dist/index.d.ts +6 -1
  25. package/dist/index.js +3 -1
  26. package/dist/internal/decode.d.ts +0 -1
  27. package/dist/internal/decode.js +9 -2
  28. package/dist/internal/json.d.ts +0 -1
  29. package/dist/internal/json.js +0 -1
  30. package/dist/internal/time.d.ts +0 -1
  31. package/dist/internal/time.js +0 -1
  32. package/dist/internal/version.d.ts +2 -0
  33. package/dist/internal/version.js +2 -0
  34. package/dist/polling.d.ts +0 -1
  35. package/dist/polling.js +0 -1
  36. package/dist/qr/encoder.d.ts +0 -1
  37. package/dist/qr/encoder.js +0 -1
  38. package/dist/qr/index.d.ts +0 -1
  39. package/dist/qr/index.js +0 -1
  40. package/dist/receipts/bundle.d.ts +0 -1
  41. package/dist/receipts/bundle.js +0 -1
  42. package/dist/receipts/index.d.ts +0 -1
  43. package/dist/receipts/index.js +0 -1
  44. package/dist/receipts/json.d.ts +0 -1
  45. package/dist/receipts/json.js +0 -1
  46. package/dist/receipts/key-cache.d.ts +0 -1
  47. package/dist/receipts/key-cache.js +0 -1
  48. package/dist/receipts/renderers.d.ts +0 -1
  49. package/dist/receipts/renderers.js +1 -2
  50. package/dist/receipts/resource.d.ts +0 -1
  51. package/dist/receipts/resource.js +0 -1
  52. package/dist/receipts/verify.d.ts +0 -1
  53. package/dist/receipts/verify.js +0 -1
  54. package/dist/sessions.d.ts +0 -1
  55. package/dist/sessions.js +0 -1
  56. package/dist/transport.d.ts +0 -1
  57. package/dist/transport.js +35 -5
  58. package/dist/types.d.ts +56 -2
  59. package/dist/types.js +0 -1
  60. package/dist/webhook-resource.d.ts +0 -1
  61. package/dist/webhook-resource.js +0 -1
  62. package/dist/webhooks/index.d.ts +0 -1
  63. package/dist/webhooks/index.js +0 -1
  64. package/package.json +8 -3
  65. package/dist/ask.d.ts.map +0 -1
  66. package/dist/ask.js.map +0 -1
  67. package/dist/cli/main.d.ts.map +0 -1
  68. package/dist/cli/main.js.map +0 -1
  69. package/dist/cli/verify.d.ts.map +0 -1
  70. package/dist/cli/verify.js.map +0 -1
  71. package/dist/client.d.ts.map +0 -1
  72. package/dist/client.js.map +0 -1
  73. package/dist/errors.d.ts.map +0 -1
  74. package/dist/errors.js.map +0 -1
  75. package/dist/generated/openapi.d.ts.map +0 -1
  76. package/dist/generated/openapi.js.map +0 -1
  77. package/dist/index.d.ts.map +0 -1
  78. package/dist/index.js.map +0 -1
  79. package/dist/internal/decode.d.ts.map +0 -1
  80. package/dist/internal/decode.js.map +0 -1
  81. package/dist/internal/json.d.ts.map +0 -1
  82. package/dist/internal/json.js.map +0 -1
  83. package/dist/internal/time.d.ts.map +0 -1
  84. package/dist/internal/time.js.map +0 -1
  85. package/dist/polling.d.ts.map +0 -1
  86. package/dist/polling.js.map +0 -1
  87. package/dist/qr/encoder.d.ts.map +0 -1
  88. package/dist/qr/encoder.js.map +0 -1
  89. package/dist/qr/index.d.ts.map +0 -1
  90. package/dist/qr/index.js.map +0 -1
  91. package/dist/receipts/bundle.d.ts.map +0 -1
  92. package/dist/receipts/bundle.js.map +0 -1
  93. package/dist/receipts/index.d.ts.map +0 -1
  94. package/dist/receipts/index.js.map +0 -1
  95. package/dist/receipts/json.d.ts.map +0 -1
  96. package/dist/receipts/json.js.map +0 -1
  97. package/dist/receipts/key-cache.d.ts.map +0 -1
  98. package/dist/receipts/key-cache.js.map +0 -1
  99. package/dist/receipts/renderers.d.ts.map +0 -1
  100. package/dist/receipts/renderers.js.map +0 -1
  101. package/dist/receipts/resource.d.ts.map +0 -1
  102. package/dist/receipts/resource.js.map +0 -1
  103. package/dist/receipts/verify.d.ts.map +0 -1
  104. package/dist/receipts/verify.js.map +0 -1
  105. package/dist/sessions.d.ts.map +0 -1
  106. package/dist/sessions.js.map +0 -1
  107. package/dist/transport.d.ts.map +0 -1
  108. package/dist/transport.js.map +0 -1
  109. package/dist/types.d.ts.map +0 -1
  110. package/dist/types.js.map +0 -1
  111. package/dist/webhook-resource.d.ts.map +0 -1
  112. package/dist/webhook-resource.js.map +0 -1
  113. package/dist/webhooks/index.d.ts.map +0 -1
  114. package/dist/webhooks/index.js.map +0 -1
  115. package/src/ask.ts +0 -683
  116. package/src/cli/main.ts +0 -8
  117. package/src/cli/verify.ts +0 -349
  118. package/src/client.ts +0 -55
  119. package/src/errors.ts +0 -127
  120. package/src/generated/openapi.ts +0 -8586
  121. package/src/index.ts +0 -5
  122. package/src/internal/decode.ts +0 -348
  123. package/src/internal/json.ts +0 -64
  124. package/src/internal/time.ts +0 -85
  125. package/src/polling.ts +0 -173
  126. package/src/qr/encoder.ts +0 -345
  127. package/src/qr/index.ts +0 -203
  128. package/src/receipts/bundle.ts +0 -547
  129. package/src/receipts/index.ts +0 -29
  130. package/src/receipts/json.ts +0 -168
  131. package/src/receipts/key-cache.ts +0 -143
  132. package/src/receipts/renderers.ts +0 -220
  133. package/src/receipts/resource.ts +0 -264
  134. package/src/receipts/verify.ts +0 -554
  135. package/src/sessions.ts +0 -238
  136. package/src/transport.ts +0 -566
  137. package/src/types.ts +0 -219
  138. package/src/webhook-resource.ts +0 -81
  139. package/src/webhooks/index.ts +0 -246
package/src/qr/encoder.ts DELETED
@@ -1,345 +0,0 @@
1
- // The QR Code encoder (ISO/IEC 18004, model 2): byte mode, error correction level M, versions 1–10
2
- // (up to 213 bytes). Pure and deterministic, with no network access and no dependency.
3
- //
4
- // Vendored verbatim (apart from this header and the removal of the page-specific SVG drawing) from
5
- // the Sess repository, packages/renderer/src/qr.ts at commit b48e8e7 (w1991e/sess). Its parity with
6
- // that copy is tested against the same vectors (tests/unit/qr.test.ts).
7
- //
8
- // Structure after Project Nayuki's QR Code generator library (https://www.nayuki.io/page/qr-code-generator-library):
9
- //
10
- // Copyright (c) Project Nayuki. (MIT License)
11
- //
12
- // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
13
- // associated documentation files (the "Software"), to deal in the Software without restriction,
14
- // including without limitation the rights to use, copy, modify, merge, publish, distribute,
15
- // sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
16
- // furnished to do so, subject to the following conditions:
17
- // - The above copyright notice and this permission notice shall be included in all copies or
18
- // substantial portions of the Software.
19
- // - The Software is provided "as is", without warranty of any kind, express or implied, including
20
- // but not limited to the warranties of merchantability, fitness for a particular purpose and
21
- // noninfringement. In no event shall the authors or copyright holders be liable for any claim,
22
- // damages or other liability, whether in an action of contract, tort or otherwise, arising from,
23
- // out of or in connection with the Software or the use or other dealings in the Software.
24
-
25
- const MAX_VERSION = 10;
26
- /** Level M: error-correction codewords per block and the number of blocks, per version. */
27
- const ECC_PER_BLOCK = [0, 10, 16, 26, 18, 24, 16, 18, 22, 22, 26];
28
- const BLOCKS = [0, 1, 1, 1, 2, 2, 4, 4, 4, 5, 5];
29
- /** Level M's two format bits. */
30
- const ECL_M_BITS = 0;
31
-
32
- /** A square module matrix: true is dark. */
33
- export type QrMatrix = boolean[][];
34
-
35
- function rawDataModules(ver: number): number {
36
- let result = (16 * ver + 128) * ver + 64;
37
- if (ver >= 2) {
38
- const align = Math.floor(ver / 7) + 2;
39
- result -= (25 * align - 10) * align - 55;
40
- if (ver >= 7) result -= 36;
41
- }
42
- return result;
43
- }
44
-
45
- const dataCodewords = (ver: number) =>
46
- Math.floor(rawDataModules(ver) / 8) - (ECC_PER_BLOCK[ver] ?? 0) * (BLOCKS[ver] ?? 0);
47
-
48
- /** Alignment pattern centre coordinates of a version (both axes). */
49
- export function alignmentPositions(ver: number): number[] {
50
- if (ver === 1) return [];
51
- const count = Math.floor(ver / 7) + 2;
52
- const size = ver * 4 + 17;
53
- const step = Math.ceil((ver * 4 + 4) / (count * 2 - 2)) * 2;
54
- const result = [6];
55
- for (let pos = size - 7; result.length < count; pos -= step) result.splice(1, 0, pos);
56
- return result;
57
- }
58
-
59
- // ---- GF(256) Reed–Solomon (polynomial 0x11D) --------------------------------------------------
60
-
61
- function gfMul(x: number, y: number): number {
62
- let z = 0;
63
- for (let i = 7; i >= 0; i--) {
64
- z = (z << 1) ^ ((z >>> 7) * 0x11d);
65
- z ^= ((y >>> i) & 1) * x;
66
- }
67
- return z & 0xff;
68
- }
69
-
70
- function rsDivisor(degree: number): number[] {
71
- const result = new Array<number>(degree).fill(0);
72
- result[degree - 1] = 1;
73
- let root = 1;
74
- for (let i = 0; i < degree; i++) {
75
- for (let j = 0; j < degree; j++) {
76
- result[j] = gfMul(result[j] as number, root);
77
- if (j + 1 < degree) result[j] = (result[j] as number) ^ (result[j + 1] as number);
78
- }
79
- root = gfMul(root, 0x02);
80
- }
81
- return result;
82
- }
83
-
84
- function rsRemainder(data: number[], divisor: number[]): number[] {
85
- const result = new Array<number>(divisor.length).fill(0);
86
- for (const b of data) {
87
- const factor = b ^ (result.shift() as number);
88
- result.push(0);
89
- divisor.forEach((coef, i) => {
90
- result[i] = (result[i] as number) ^ gfMul(coef, factor);
91
- });
92
- }
93
- return result;
94
- }
95
-
96
- // ---- Encoding --------------------------------------------------------------------------------
97
-
98
- /** The codewords (data then error correction, interleaved) of `bytes` at `ver`. */
99
- function codewords(bytes: Uint8Array, ver: number): number[] {
100
- const capacityBits = dataCodewords(ver) * 8;
101
- const bits: number[] = [];
102
- const put = (value: number, len: number) => {
103
- for (let i = len - 1; i >= 0; i--) bits.push((value >>> i) & 1);
104
- };
105
- put(0b0100, 4); // byte mode
106
- put(bytes.length, ver <= 9 ? 8 : 16);
107
- for (const b of bytes) put(b, 8);
108
- put(0, Math.min(4, capacityBits - bits.length));
109
- put(0, (8 - (bits.length % 8)) % 8);
110
- for (let pad = 0xec; bits.length < capacityBits; pad ^= 0xec ^ 0x11) put(pad, 8);
111
- const data: number[] = [];
112
- for (let i = 0; i < bits.length; i += 8) {
113
- let b = 0;
114
- for (let j = 0; j < 8; j++) b = (b << 1) | (bits[i + j] as number);
115
- data.push(b);
116
- }
117
- // Split into blocks (short blocks first), add each block's ECC, then interleave.
118
- const numBlocks = BLOCKS[ver] as number;
119
- const eccLen = ECC_PER_BLOCK[ver] as number;
120
- const rawCodewords = Math.floor(rawDataModules(ver) / 8);
121
- const numShort = numBlocks - (rawCodewords % numBlocks);
122
- const shortLen = Math.floor(rawCodewords / numBlocks);
123
- const divisor = rsDivisor(eccLen);
124
- const blocks: number[][] = [];
125
- for (let i = 0, k = 0; i < numBlocks; i++) {
126
- const len = shortLen - eccLen + (i < numShort ? 0 : 1);
127
- const dat = data.slice(k, k + len);
128
- k += len;
129
- const ecc = rsRemainder(dat, divisor);
130
- if (i < numShort) dat.push(0); // placeholder, skipped when interleaving
131
- blocks.push([...dat, ...ecc]);
132
- }
133
- const result: number[] = [];
134
- for (let i = 0; i < (blocks[0] as number[]).length; i++) {
135
- blocks.forEach((block, j) => {
136
- if (i !== shortLen - eccLen || j >= numShort) result.push(block[i] as number);
137
- });
138
- }
139
- return result;
140
- }
141
-
142
- class Grid {
143
- readonly version: number;
144
- readonly size: number;
145
- readonly dark: boolean[][];
146
- readonly fn: boolean[][];
147
- constructor(version: number) {
148
- this.version = version;
149
- this.size = version * 4 + 17;
150
- this.dark = Array.from({ length: this.size }, () => new Array<boolean>(this.size).fill(false));
151
- this.fn = Array.from({ length: this.size }, () => new Array<boolean>(this.size).fill(false));
152
- }
153
- set(x: number, y: number, dark: boolean) {
154
- (this.dark[y] as boolean[])[x] = dark;
155
- (this.fn[y] as boolean[])[x] = true;
156
- }
157
- }
158
-
159
- function drawFunctionPatterns(g: Grid): void {
160
- const { size, version } = g;
161
- for (let i = 0; i < size; i++) {
162
- g.set(6, i, i % 2 === 0);
163
- g.set(i, 6, i % 2 === 0);
164
- }
165
- const finder = (cx: number, cy: number) => {
166
- for (let dy = -4; dy <= 4; dy++) {
167
- for (let dx = -4; dx <= 4; dx++) {
168
- const d = Math.max(Math.abs(dx), Math.abs(dy));
169
- const x = cx + dx;
170
- const y = cy + dy;
171
- if (x >= 0 && x < size && y >= 0 && y < size) g.set(x, y, d !== 2 && d !== 4);
172
- }
173
- }
174
- };
175
- finder(3, 3);
176
- finder(size - 4, 3);
177
- finder(3, size - 4);
178
- const align = alignmentPositions(version);
179
- const n = align.length;
180
- for (let i = 0; i < n; i++) {
181
- for (let j = 0; j < n; j++) {
182
- if ((i === 0 && j === 0) || (i === 0 && j === n - 1) || (i === n - 1 && j === 0)) continue;
183
- for (let dy = -2; dy <= 2; dy++) {
184
- for (let dx = -2; dx <= 2; dx++) {
185
- g.set(
186
- (align[i] as number) + dx,
187
- (align[j] as number) + dy,
188
- Math.max(Math.abs(dx), Math.abs(dy)) !== 1,
189
- );
190
- }
191
- }
192
- }
193
- }
194
- drawFormatBits(g, 0); // reserve; redrawn with the chosen mask
195
- if (version >= 7) {
196
- let rem = version;
197
- for (let i = 0; i < 12; i++) rem = (rem << 1) ^ ((rem >>> 11) * 0x1f25);
198
- const bits = (version << 12) | rem;
199
- for (let i = 0; i < 18; i++) {
200
- const bit = ((bits >>> i) & 1) !== 0;
201
- const a = size - 11 + (i % 3);
202
- const b = Math.floor(i / 3);
203
- g.set(a, b, bit);
204
- g.set(b, a, bit);
205
- }
206
- }
207
- }
208
-
209
- /** The 15 format bits for level M and `mask` (BCH(15,5), XOR-masked). */
210
- export function formatBits(mask: number): number {
211
- const data = (ECL_M_BITS << 3) | mask;
212
- let rem = data;
213
- for (let i = 0; i < 10; i++) rem = (rem << 1) ^ ((rem >>> 9) * 0x537);
214
- return ((data << 10) | rem) ^ 0x5412;
215
- }
216
-
217
- function drawFormatBits(g: Grid, mask: number): void {
218
- const bits = formatBits(mask);
219
- const bit = (i: number) => ((bits >>> i) & 1) !== 0;
220
- const { size } = g;
221
- for (let i = 0; i <= 5; i++) g.set(8, i, bit(i));
222
- g.set(8, 7, bit(6));
223
- g.set(8, 8, bit(7));
224
- g.set(7, 8, bit(8));
225
- for (let i = 9; i < 15; i++) g.set(14 - i, 8, bit(i));
226
- for (let i = 0; i < 8; i++) g.set(size - 1 - i, 8, bit(i));
227
- for (let i = 8; i < 15; i++) g.set(8, size - 15 + i, bit(i));
228
- g.set(8, size - 8, true); // the dark module
229
- }
230
-
231
- function drawCodewords(g: Grid, data: number[]): void {
232
- const { size } = g;
233
- let i = 0;
234
- for (let right = size - 1; right >= 1; right -= 2) {
235
- if (right === 6) right = 5;
236
- for (let vert = 0; vert < size; vert++) {
237
- for (let j = 0; j < 2; j++) {
238
- const x = right - j;
239
- const upward = ((right + 1) & 2) === 0;
240
- const y = upward ? size - 1 - vert : vert;
241
- if (!(g.fn[y] as boolean[])[x] && i < data.length * 8) {
242
- (g.dark[y] as boolean[])[x] = (((data[i >>> 3] as number) >>> (7 - (i & 7))) & 1) !== 0;
243
- i++;
244
- }
245
- }
246
- }
247
- }
248
- }
249
-
250
- /** The mask condition: true where a data module is inverted. */
251
- export function maskBit(mask: number, x: number, y: number): boolean {
252
- switch (mask) {
253
- case 0:
254
- return (x + y) % 2 === 0;
255
- case 1:
256
- return y % 2 === 0;
257
- case 2:
258
- return x % 3 === 0;
259
- case 3:
260
- return (x + y) % 3 === 0;
261
- case 4:
262
- return (Math.floor(x / 3) + Math.floor(y / 2)) % 2 === 0;
263
- case 5:
264
- return ((x * y) % 2) + ((x * y) % 3) === 0;
265
- case 6:
266
- return (((x * y) % 2) + ((x * y) % 3)) % 2 === 0;
267
- default:
268
- return (((x + y) % 2) + ((x * y) % 3)) % 2 === 0;
269
- }
270
- }
271
-
272
- function applyMask(g: Grid, mask: number): void {
273
- for (let y = 0; y < g.size; y++) {
274
- for (let x = 0; x < g.size; x++) {
275
- if (!(g.fn[y] as boolean[])[x] && maskBit(mask, x, y)) {
276
- (g.dark[y] as boolean[])[x] = !(g.dark[y] as boolean[])[x];
277
- }
278
- }
279
- }
280
- }
281
-
282
- /** The standard penalty score (rules N1–N4) of a finished matrix. */
283
- function penalty(m: boolean[][]): number {
284
- const size = m.length;
285
- let score = 0;
286
- const line = (get: (i: number) => boolean) => {
287
- let run = 1;
288
- for (let i = 1; i <= size; i++) {
289
- if (i < size && get(i) === get(i - 1)) run++;
290
- else {
291
- if (run >= 5) score += 3 + (run - 5);
292
- run = 1;
293
- }
294
- }
295
- const seq = Array.from({ length: size }, (_, i) => (get(i) ? 1 : 0)).join('');
296
- for (const p of ['10111010000', '00001011101']) {
297
- for (let at = seq.indexOf(p); at >= 0; at = seq.indexOf(p, at + 1)) score += 40;
298
- }
299
- };
300
- for (let y = 0; y < size; y++) line((x) => (m[y] as boolean[])[x] as boolean);
301
- for (let x = 0; x < size; x++) line((y) => (m[y] as boolean[])[x] as boolean);
302
- let dark = 0;
303
- for (let y = 0; y < size; y++) {
304
- for (let x = 0; x < size; x++) {
305
- const c = (m[y] as boolean[])[x];
306
- if (c) dark++;
307
- if (
308
- x + 1 < size &&
309
- y + 1 < size &&
310
- c === (m[y] as boolean[])[x + 1] &&
311
- c === (m[y + 1] as boolean[])[x] &&
312
- c === (m[y + 1] as boolean[])[x + 1]
313
- )
314
- score += 3;
315
- }
316
- }
317
- score += 10 * Math.floor(Math.abs((dark * 100) / (size * size) - 50) / 5);
318
- return score;
319
- }
320
-
321
- /** Encodes `text` (UTF-8, byte mode, level M) at the smallest version 1–10 that holds it. */
322
- export function encodeQr(text: string): QrMatrix {
323
- const bytes = new TextEncoder().encode(text);
324
- let version = 0;
325
- for (let v = 1; v <= MAX_VERSION; v++) {
326
- const needed = 4 + (v <= 9 ? 8 : 16) + bytes.length * 8;
327
- if (needed <= dataCodewords(v) * 8) {
328
- version = v;
329
- break;
330
- }
331
- }
332
- if (version === 0) throw new RangeError('text too long for a version 1–10 QR code');
333
- const data = codewords(bytes, version);
334
- let best: { score: number; matrix: QrMatrix } | null = null;
335
- for (let mask = 0; mask < 8; mask++) {
336
- const g = new Grid(version);
337
- drawFunctionPatterns(g);
338
- drawCodewords(g, data);
339
- applyMask(g, mask);
340
- drawFormatBits(g, mask);
341
- const score = penalty(g.dark);
342
- if (best === null || score < best.score) best = { score, matrix: g.dark };
343
- }
344
- return (best as { matrix: QrMatrix }).matrix;
345
- }
package/src/qr/index.ts DELETED
@@ -1,203 +0,0 @@
1
- // `@sess.si/sdk/qr`: draw a Sess link as a QR code, locally, so a person at a laptop can answer on
2
- // their phone without copying anything. Optional: Sess never sends links, and the agent decides
3
- // whether a QR helps (a desktop chat window, a dashboard, a kiosk, print) or not (SMS, or a person
4
- // already on their phone).
5
- //
6
- // The link is a private capability: the QR is the same capability in another encoding. Nothing here
7
- // contacts a service, stores the link or its drawing, or puts the link in an error message.
8
- import { crc32, deflateSync } from 'node:zlib';
9
- import { encodeQr, type QrMatrix } from './encoder.js';
10
-
11
- /** The accessible name of the SVG drawing (its one `title`). */
12
- export const QR_TITLE = 'QR code for this Sess link';
13
-
14
- /** The line `printQr` prints before the code. */
15
- export const QR_HEADING = 'Scan to answer on your phone';
16
-
17
- /** Light modules around the code, on every side (ISO/IEC 18004 asks for 4). */
18
- const QUIET = 4;
19
- /** PNG pixels per module. */
20
- const PNG_SCALE = 8;
21
-
22
- export type QrFormat = 'svg' | 'png' | 'terminal';
23
-
24
- export interface QrSvgOptions {
25
- format: 'svg';
26
- }
27
- export interface QrPngOptions {
28
- format: 'png';
29
- }
30
- export interface QrTerminalOptions {
31
- format: 'terminal';
32
- /**
33
- * Draw black on white with ANSI colours, so the code scans in light and dark terminal themes
34
- * (default true). False: characters only (for `NO_COLOR`); the code is then drawn in the
35
- * terminal's own text colour.
36
- */
37
- color?: boolean;
38
- }
39
- export type QrOptions = QrSvgOptions | QrPngOptions | QrTerminalOptions;
40
-
41
- function matrixOf(url: string): QrMatrix {
42
- // Never echo the link: it is a bearer capability.
43
- if (typeof url !== 'string' || !URL.canParse(url)) throw new TypeError('qr: url must be an absolute URL');
44
- const protocol = new URL(url).protocol;
45
- if (protocol !== 'https:' && protocol !== 'http:') throw new TypeError('qr: url must be an http(s) URL');
46
- try {
47
- return encodeQr(url);
48
- } catch {
49
- throw new RangeError('qr: url is too long for a QR code (at most 213 bytes)');
50
- }
51
- }
52
-
53
- /**
54
- * The SVG drawing: exactly one root `svg` (SVG namespace, `viewBox="0 0 N N"`, `role="img"`,
55
- * `shape-rendering="crispEdges"`) holding one `title` ({@link QR_TITLE}), one white `rect` (the
56
- * quiet zone and background) and one black `path` of unit squares. No style, script, event
57
- * attribute, link or external resource; fixed colours, so it scans in either theme.
58
- */
59
- function svgOf(m: QrMatrix): string {
60
- const size = m.length + QUIET * 2;
61
- let d = '';
62
- m.forEach((row, y) => {
63
- row.forEach((dark, x) => {
64
- if (dark) d += `M${x + QUIET} ${y + QUIET}h1v1h-1z`;
65
- });
66
- });
67
- return (
68
- `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${size} ${size}" role="img" shape-rendering="crispEdges">` +
69
- `<title>${QR_TITLE}</title>` +
70
- `<rect width="${size}" height="${size}" fill="#ffffff"/><path d="${d}" fill="#000000"/></svg>`
71
- );
72
- }
73
-
74
- /** Dark at (x, y) of the code with its quiet zone; outside is light. */
75
- function darkAt(m: QrMatrix, x: number, y: number): boolean {
76
- return m[y - QUIET]?.[x - QUIET] === true;
77
- }
78
-
79
- /**
80
- * The terminal drawing: two module rows per text line with Unicode half blocks (▀ ▄ █), quiet zone
81
- * included, lines joined by "\n" with no trailing newline.
82
- */
83
- function terminalOf(m: QrMatrix, color: boolean): string {
84
- const size = m.length + QUIET * 2;
85
- const lines: string[] = [];
86
- for (let y = 0; y < size; y += 2) {
87
- let line = '';
88
- for (let x = 0; x < size; x++) {
89
- const top = darkAt(m, x, y);
90
- const bottom = y + 1 < size && darkAt(m, x, y + 1);
91
- line += top ? (bottom ? '█' : '▀') : bottom ? '▄' : ' ';
92
- }
93
- // Black text on a bright white background, reset at the end of every line.
94
- lines.push(color ? `\u001b[30;107m${line}\u001b[0m` : line);
95
- }
96
- return lines.join('\n');
97
- }
98
-
99
- function chunk(type: string, data: Uint8Array): Uint8Array {
100
- const out = new Uint8Array(12 + data.length);
101
- const view = new DataView(out.buffer);
102
- view.setUint32(0, data.length);
103
- out.set(new TextEncoder().encode(type), 4);
104
- out.set(data, 8);
105
- view.setUint32(8 + data.length, crc32(out.subarray(4, 8 + data.length)));
106
- return out;
107
- }
108
-
109
- /** The PNG image: 1-bit greyscale, {@link PNG_SCALE} pixels per module, quiet zone included. */
110
- function pngOf(m: QrMatrix): Uint8Array {
111
- const side = (m.length + QUIET * 2) * PNG_SCALE;
112
- const stride = Math.ceil(side / 8);
113
- const raw = new Uint8Array((stride + 1) * side);
114
- for (let py = 0; py < side; py++) {
115
- const row = py * (stride + 1);
116
- raw[row] = 0; // filter: none
117
- for (let px = 0; px < side; px++) {
118
- // 1 is white in 1-bit greyscale.
119
- if (!darkAt(m, Math.floor(px / PNG_SCALE), Math.floor(py / PNG_SCALE)))
120
- raw[row + 1 + (px >> 3)]! |= 0x80 >> (px & 7);
121
- }
122
- }
123
- const header = new Uint8Array(13);
124
- const h = new DataView(header.buffer);
125
- h.setUint32(0, side);
126
- h.setUint32(4, side);
127
- header.set([1, 0, 0, 0, 0], 8); // bit depth 1, greyscale, deflate, adaptive filter, no interlace
128
- const parts = [
129
- new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
130
- chunk('IHDR', header),
131
- chunk('IDAT', deflateSync(raw, { level: 9 })),
132
- chunk('IEND', new Uint8Array(0)),
133
- ];
134
- const png = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
135
- let at = 0;
136
- for (const p of parts) {
137
- png.set(p, at);
138
- at += p.length;
139
- }
140
- return png;
141
- }
142
-
143
- /**
144
- * Draws `url` (an absolute http(s) URL of at most 213 bytes, such as the `url` of a created Session)
145
- * as a QR code: error correction level M, a 4-module quiet zone, deterministic, no network access.
146
- *
147
- * - `svg`: an SVG string with an accessible title ({@link QR_TITLE}).
148
- * - `png`: PNG bytes, 8 pixels per module.
149
- * - `terminal`: text with Unicode half blocks, for an interactive terminal (see {@link printQr}).
150
- *
151
- * The drawing is the link itself in another encoding: keep it wherever the link may be, and never
152
- * in logs, analytics or a URL.
153
- */
154
- export function qr(url: string, options: QrSvgOptions | QrTerminalOptions): string;
155
- export function qr(url: string, options: QrPngOptions): Uint8Array;
156
- export function qr(url: string, options: QrOptions): string | Uint8Array {
157
- const format = (options as { format?: unknown } | undefined)?.format;
158
- if (format !== 'svg' && format !== 'png' && format !== 'terminal')
159
- throw new TypeError('qr: format must be "svg", "png" or "terminal"');
160
- const m = matrixOf(url);
161
- if (format === 'svg') return svgOf(m);
162
- if (format === 'png') return pngOf(m);
163
- return terminalOf(m, (options as QrTerminalOptions).color !== false);
164
- }
165
-
166
- export interface PrintQrOptions {
167
- /** Where to print (default `process.stdout`). Printed only when it is an interactive terminal. */
168
- stream?: { isTTY?: boolean | undefined; write(text: string): unknown };
169
- /** The environment (default `process.env`): `CI`, `NODE_ENV` and `NO_COLOR` are read. */
170
- env?: Readonly<Record<string, string | undefined>>;
171
- /** The command-line arguments (default `process.argv`): `--no-qr` turns the code off. */
172
- argv?: readonly string[];
173
- /** False turns the code off, as `--no-qr` does. */
174
- qr?: boolean;
175
- }
176
-
177
- const set = (v: string | undefined) => v !== undefined && v !== '';
178
- const isCi = (v: string | undefined) => set(v) && v !== 'false' && v !== '0';
179
-
180
- /**
181
- * For development: prints "Scan to answer on your phone" and `url` as a terminal QR code, and
182
- * returns true, only on an interactive terminal. It prints nothing and returns false when the
183
- * stream is not a TTY (a pipe, a file, a log collector), in CI (`CI` set), in production
184
- * (`NODE_ENV=production`), with `--no-qr` or with `qr: false`. `NO_COLOR` draws it without colour.
185
- * Print the link itself as well: the code is a shortcut, not the only way in.
186
- */
187
- export function printQr(url: string, options: PrintQrOptions = {}): boolean {
188
- // The link is checked whether or not anything is printed.
189
- const m = matrixOf(url);
190
- const stream = options.stream ?? process.stdout;
191
- const env = options.env ?? process.env;
192
- const argv = options.argv ?? process.argv;
193
- if (
194
- options.qr === false ||
195
- argv.includes('--no-qr') ||
196
- stream.isTTY !== true ||
197
- isCi(env.CI) ||
198
- env.NODE_ENV === 'production'
199
- )
200
- return false;
201
- stream.write(`${QR_HEADING}\n${terminalOf(m, !set(env.NO_COLOR))}\n`);
202
- return true;
203
- }