@sess.si/sdk 0.0.0-stage → 0.1.0-rc.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +185 -0
- package/LICENSE +201 -0
- package/NOTICE +27 -0
- package/README.md +327 -2
- package/dist/ask.d.ts +161 -0
- package/dist/ask.js +499 -0
- package/dist/cli/main.d.ts +2 -0
- package/dist/cli/main.js +7 -0
- package/dist/cli/verify.d.ts +13 -0
- package/dist/cli/verify.js +322 -0
- package/dist/client.d.ts +19 -0
- package/dist/client.js +43 -0
- package/dist/commerce/builders.d.ts +99 -0
- package/dist/commerce/builders.js +208 -0
- package/dist/commerce/currency.d.ts +4 -0
- package/dist/commerce/currency.js +25 -0
- package/dist/commerce/items.d.ts +119 -0
- package/dist/commerce/items.js +280 -0
- package/dist/commerce/lint.d.ts +16 -0
- package/dist/commerce/lint.js +56 -0
- package/dist/errors.d.ts +61 -0
- package/dist/errors.js +63 -0
- package/dist/generated/openapi.d.ts +8360 -0
- package/dist/generated/openapi.js +1 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.js +6 -0
- package/dist/internal/decode.d.ts +20 -0
- package/dist/internal/decode.js +380 -0
- package/dist/internal/json.d.ts +3 -0
- package/dist/internal/json.js +74 -0
- package/dist/internal/time.d.ts +10 -0
- package/dist/internal/time.js +70 -0
- package/dist/internal/version.d.ts +2 -0
- package/dist/internal/version.js +2 -0
- package/dist/polling.d.ts +11 -0
- package/dist/polling.js +137 -0
- package/dist/qr/encoder.d.ts +10 -0
- package/dist/qr/encoder.js +343 -0
- package/dist/qr/index.d.ts +55 -0
- package/dist/qr/index.js +150 -0
- package/dist/receipts/bundle.d.ts +123 -0
- package/dist/receipts/bundle.js +423 -0
- package/dist/receipts/index.d.ts +8 -0
- package/dist/receipts/index.js +3 -0
- package/dist/receipts/json.d.ts +21 -0
- package/dist/receipts/json.js +151 -0
- package/dist/receipts/key-cache.d.ts +27 -0
- package/dist/receipts/key-cache.js +109 -0
- package/dist/receipts/renderers.d.ts +57 -0
- package/dist/receipts/renderers.js +153 -0
- package/dist/receipts/resource.d.ts +38 -0
- package/dist/receipts/resource.js +145 -0
- package/dist/receipts/verify.d.ts +112 -0
- package/dist/receipts/verify.js +339 -0
- package/dist/sessions.d.ts +18 -0
- package/dist/sessions.js +151 -0
- package/dist/transport.d.ts +30 -0
- package/dist/transport.js +511 -0
- package/dist/types.d.ts +283 -0
- package/dist/types.js +8 -0
- package/dist/webhook-resource.d.ts +12 -0
- package/dist/webhook-resource.js +51 -0
- package/dist/webhooks/index.d.ts +21 -0
- package/dist/webhooks/index.js +183 -0
- package/package.json +82 -4
package/dist/polling.js
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import { SessError } from './errors.js';
|
|
2
|
+
import { abortError, boundedNumber, deadline, delay } from './internal/time.js';
|
|
3
|
+
import { isInteractiveSession } from './types.js';
|
|
4
|
+
/**
|
|
5
|
+
* Once a Session's link has reached its end (its deadline, `action_expires_at`, or while the
|
|
6
|
+
* person can still extend it, its horizon), the wait reads it once more when the runtime clock is
|
|
7
|
+
* this far past that end, then ends: an answer accepted before the end is returned; otherwise the
|
|
8
|
+
* wait ends with `LINK_EXPIRED`. Two seconds covers the one-second
|
|
9
|
+
* resolution of the HTTP `Date` header plus an answer accepted just before the expiry whose write
|
|
10
|
+
* is still landing, and keeps the end prompt.
|
|
11
|
+
*/
|
|
12
|
+
export const LINK_EXPIRY_GRACE_MS = 2000;
|
|
13
|
+
/** An RFC 3339 UTC instant in milliseconds since the epoch, when the value is a valid one. */
|
|
14
|
+
function instant(value) {
|
|
15
|
+
if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?Z$/.test(value))
|
|
16
|
+
return undefined;
|
|
17
|
+
const ms = Date.parse(value);
|
|
18
|
+
return Number.isFinite(ms) ? ms : undefined;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* The link's state as read and the instant it ends for good as far as this read shows: its
|
|
22
|
+
* horizon while the person can still extend it (an extension left), else its deadline
|
|
23
|
+
* (`action_expires_at`). No state from a runtime before link timing (Decision 0009 Amendment 10).
|
|
24
|
+
*/
|
|
25
|
+
function linkEnd(session) {
|
|
26
|
+
const v = session;
|
|
27
|
+
const deadline = instant(v.action_expires_at);
|
|
28
|
+
const horizon = instant(v.action_expires_horizon);
|
|
29
|
+
const extendable = horizon !== undefined && typeof v.extensions_used === 'number' && v.extensions_used < 10;
|
|
30
|
+
return {
|
|
31
|
+
state: typeof v.link_state === 'string' ? v.link_state : undefined,
|
|
32
|
+
endsAt: extendable && deadline !== undefined ? Math.max(horizon, deadline) : deadline,
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
export async function waitForResponse(retrieve, id, input, clientOperationTimeoutMs) {
|
|
36
|
+
if (!input || typeof input !== 'object')
|
|
37
|
+
throw new SessError('configuration', 'waitForResponse requires an exact revision.');
|
|
38
|
+
const options = { ...input };
|
|
39
|
+
const revision = boundedNumber(options.revision, 0, 'revision');
|
|
40
|
+
const timeoutMs = boundedNumber(options.timeoutMs, 10 * 60_000, 'timeoutMs');
|
|
41
|
+
const intervalMs = boundedNumber(options.intervalMs, 1500, 'intervalMs', 1000);
|
|
42
|
+
if (options.operationTimeoutMs !== undefined && typeof options.operationTimeoutMs !== 'number')
|
|
43
|
+
throw new SessError('configuration', 'operationTimeoutMs must be a positive integer duration.', {
|
|
44
|
+
outcome: 'not_sent',
|
|
45
|
+
});
|
|
46
|
+
// Validate before clamping so malformed overrides cannot become usable durations.
|
|
47
|
+
const operationTimeoutMs = boundedNumber(options.operationTimeoutMs, clientOperationTimeoutMs, 'operationTimeoutMs');
|
|
48
|
+
const budget = deadline(timeoutMs, options.signal);
|
|
49
|
+
const expires = performance.now() + timeoutMs;
|
|
50
|
+
/**
|
|
51
|
+
* The first read in a row that showed the link expired with no answer at an instant the clocks
|
|
52
|
+
* cannot place past its end: its runtime clock, that clock's resolution, and whether the clock
|
|
53
|
+
* was the runtime's (HTTP Date) or this machine's. Such a read is final only once a later one,
|
|
54
|
+
* at least LINK_EXPIRY_GRACE_MS (plus the resolution) after it on the same clock, still shows it.
|
|
55
|
+
*/
|
|
56
|
+
let expiredSince;
|
|
57
|
+
const ended = (code, message) => new SessError('wait_ended', message, { code, sessionId: id, revision });
|
|
58
|
+
try {
|
|
59
|
+
for (;;) {
|
|
60
|
+
if (budget.signal.aborted)
|
|
61
|
+
throw abortError(budget.signal);
|
|
62
|
+
const remainingMs = Math.ceil(expires - performance.now());
|
|
63
|
+
if (remainingMs <= 0)
|
|
64
|
+
throw ended('WAIT_TIMEOUT', 'Human wait timed out. Resume using the same Session and revision.');
|
|
65
|
+
const current = await retrieve({
|
|
66
|
+
signal: budget.signal,
|
|
67
|
+
operationTimeoutMs: Math.min(operationTimeoutMs, remainingMs),
|
|
68
|
+
maxRetries: options.maxRetries,
|
|
69
|
+
maxResponseBytes: options.maxResponseBytes,
|
|
70
|
+
});
|
|
71
|
+
if (!isInteractiveSession(current.data))
|
|
72
|
+
throw ended('NOT_INTERACTIVE', 'A display Session has no accepted human responses.');
|
|
73
|
+
const session = current.data;
|
|
74
|
+
const response = session.responses.find((item) => item.revision === revision);
|
|
75
|
+
// Retained history remains readable after a later revision or completion.
|
|
76
|
+
if (response)
|
|
77
|
+
return { session, response, meta: current.meta };
|
|
78
|
+
if (session.status === 'completed')
|
|
79
|
+
throw ended('CLOSED_WITHOUT_RESPONSE', 'Session completed without an accepted response for this revision.');
|
|
80
|
+
if (session.revision > revision)
|
|
81
|
+
throw ended('REVISION_SUPERSEDED', 'The requested unanswered revision was superseded.');
|
|
82
|
+
// The link's end (Decision 0009 Amendments 7 and 10): an answer accepted while the link
|
|
83
|
+
// was live is in every later read. The runtime clock is the response's HTTP Date (at or
|
|
84
|
+
// before the read), else this machine's. Nothing is completed here.
|
|
85
|
+
// - live or lapsed: the Session is still open (a lapsed link takes no answer, but the
|
|
86
|
+
// person can still ask for more time until the horizon). The wait never ends on the
|
|
87
|
+
// link; it reads again soon after the link could end.
|
|
88
|
+
// - expired: final once a read made at least LINK_EXPIRY_GRACE_MS past the link's end, or a
|
|
89
|
+
// read at least the grace after the first expired read on the same clock (an end the
|
|
90
|
+
// clocks cannot place, such as a revocation), still shows it expired with no answer. A
|
|
91
|
+
// short polling interval reads again sooner but never ends the wait inside the grace.
|
|
92
|
+
// - no link_state (a runtime before link timing): the deadline is final, as before.
|
|
93
|
+
let untilFinalReadMs = Number.POSITIVE_INFINITY;
|
|
94
|
+
const link = linkEnd(session);
|
|
95
|
+
const observedAt = current.meta.serverDate ?? Date.now();
|
|
96
|
+
// A Date header has whole seconds: one more second puts the next read past the instant.
|
|
97
|
+
const resolutionMs = current.meta.serverDate === undefined ? 0 : 1000;
|
|
98
|
+
const server = current.meta.serverDate !== undefined;
|
|
99
|
+
if (link.state !== 'expired' || (expiredSince !== undefined && expiredSince.server !== server))
|
|
100
|
+
expiredSince = undefined;
|
|
101
|
+
if (link.state === 'live' || link.state === 'lapsed') {
|
|
102
|
+
if (link.endsAt !== undefined && link.endsAt + LINK_EXPIRY_GRACE_MS > observedAt)
|
|
103
|
+
untilFinalReadMs = link.endsAt + LINK_EXPIRY_GRACE_MS - observedAt + resolutionMs;
|
|
104
|
+
}
|
|
105
|
+
else if (link.state === 'expired' || link.endsAt !== undefined) {
|
|
106
|
+
const finalAt = (link.endsAt ?? observedAt) + LINK_EXPIRY_GRACE_MS;
|
|
107
|
+
// Whole-second Date headers: a full grace plus one second between the two headers puts
|
|
108
|
+
// more than the grace between the two reads.
|
|
109
|
+
const graceSeenAt = expiredSince === undefined
|
|
110
|
+
? Number.POSITIVE_INFINITY
|
|
111
|
+
: expiredSince.at + LINK_EXPIRY_GRACE_MS + expiredSince.resolutionMs;
|
|
112
|
+
if (observedAt >= finalAt || observedAt >= graceSeenAt)
|
|
113
|
+
throw ended('LINK_EXPIRED', 'The Sess link expired with no accepted response for this revision. Nothing was completed.');
|
|
114
|
+
untilFinalReadMs = finalAt - observedAt + resolutionMs;
|
|
115
|
+
if (link.state === 'expired') {
|
|
116
|
+
expiredSince ??= { at: observedAt, resolutionMs, server };
|
|
117
|
+
const graceEndsAt = expiredSince.at + LINK_EXPIRY_GRACE_MS + expiredSince.resolutionMs;
|
|
118
|
+
untilFinalReadMs = Math.min(untilFinalReadMs, Math.max(1, graceEndsAt - observedAt));
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
await delay(Math.min(intervalMs + Math.floor(Math.random() * 150), untilFinalReadMs, Math.max(1, Math.ceil(expires - performance.now()))), budget.signal);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
catch (error) {
|
|
125
|
+
if (options.signal?.aborted)
|
|
126
|
+
throw new SessError('aborted', 'Human wait was aborted. The Session remains available.', {
|
|
127
|
+
sessionId: id,
|
|
128
|
+
revision,
|
|
129
|
+
});
|
|
130
|
+
if (budget.signal.aborted || performance.now() >= expires)
|
|
131
|
+
throw ended('WAIT_TIMEOUT', 'Human wait timed out. Resume using the same Session and revision.');
|
|
132
|
+
throw error;
|
|
133
|
+
}
|
|
134
|
+
finally {
|
|
135
|
+
budget.dispose();
|
|
136
|
+
}
|
|
137
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/** A square module matrix: true is dark. */
|
|
2
|
+
export type QrMatrix = boolean[][];
|
|
3
|
+
/** Alignment pattern centre coordinates of a version (both axes). */
|
|
4
|
+
export declare function alignmentPositions(ver: number): number[];
|
|
5
|
+
/** The 15 format bits for level M and `mask` (BCH(15,5), XOR-masked). */
|
|
6
|
+
export declare function formatBits(mask: number): number;
|
|
7
|
+
/** The mask condition: true where a data module is inverted. */
|
|
8
|
+
export declare function maskBit(mask: number, x: number, y: number): boolean;
|
|
9
|
+
/** Encodes `text` (UTF-8, byte mode, level M) at the smallest version 1–10 that holds it. */
|
|
10
|
+
export declare function encodeQr(text: string): QrMatrix;
|
|
@@ -0,0 +1,343 @@
|
|
|
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
|
+
const MAX_VERSION = 10;
|
|
25
|
+
/** Level M: error-correction codewords per block and the number of blocks, per version. */
|
|
26
|
+
const ECC_PER_BLOCK = [0, 10, 16, 26, 18, 24, 16, 18, 22, 22, 26];
|
|
27
|
+
const BLOCKS = [0, 1, 1, 1, 2, 2, 4, 4, 4, 5, 5];
|
|
28
|
+
/** Level M's two format bits. */
|
|
29
|
+
const ECL_M_BITS = 0;
|
|
30
|
+
function rawDataModules(ver) {
|
|
31
|
+
let result = (16 * ver + 128) * ver + 64;
|
|
32
|
+
if (ver >= 2) {
|
|
33
|
+
const align = Math.floor(ver / 7) + 2;
|
|
34
|
+
result -= (25 * align - 10) * align - 55;
|
|
35
|
+
if (ver >= 7)
|
|
36
|
+
result -= 36;
|
|
37
|
+
}
|
|
38
|
+
return result;
|
|
39
|
+
}
|
|
40
|
+
const dataCodewords = (ver) => Math.floor(rawDataModules(ver) / 8) - (ECC_PER_BLOCK[ver] ?? 0) * (BLOCKS[ver] ?? 0);
|
|
41
|
+
/** Alignment pattern centre coordinates of a version (both axes). */
|
|
42
|
+
export function alignmentPositions(ver) {
|
|
43
|
+
if (ver === 1)
|
|
44
|
+
return [];
|
|
45
|
+
const count = Math.floor(ver / 7) + 2;
|
|
46
|
+
const size = ver * 4 + 17;
|
|
47
|
+
const step = Math.ceil((ver * 4 + 4) / (count * 2 - 2)) * 2;
|
|
48
|
+
const result = [6];
|
|
49
|
+
for (let pos = size - 7; result.length < count; pos -= step)
|
|
50
|
+
result.splice(1, 0, pos);
|
|
51
|
+
return result;
|
|
52
|
+
}
|
|
53
|
+
// ---- GF(256) Reed–Solomon (polynomial 0x11D) --------------------------------------------------
|
|
54
|
+
function gfMul(x, y) {
|
|
55
|
+
let z = 0;
|
|
56
|
+
for (let i = 7; i >= 0; i--) {
|
|
57
|
+
z = (z << 1) ^ ((z >>> 7) * 0x11d);
|
|
58
|
+
z ^= ((y >>> i) & 1) * x;
|
|
59
|
+
}
|
|
60
|
+
return z & 0xff;
|
|
61
|
+
}
|
|
62
|
+
function rsDivisor(degree) {
|
|
63
|
+
const result = new Array(degree).fill(0);
|
|
64
|
+
result[degree - 1] = 1;
|
|
65
|
+
let root = 1;
|
|
66
|
+
for (let i = 0; i < degree; i++) {
|
|
67
|
+
for (let j = 0; j < degree; j++) {
|
|
68
|
+
result[j] = gfMul(result[j], root);
|
|
69
|
+
if (j + 1 < degree)
|
|
70
|
+
result[j] = result[j] ^ result[j + 1];
|
|
71
|
+
}
|
|
72
|
+
root = gfMul(root, 0x02);
|
|
73
|
+
}
|
|
74
|
+
return result;
|
|
75
|
+
}
|
|
76
|
+
function rsRemainder(data, divisor) {
|
|
77
|
+
const result = new Array(divisor.length).fill(0);
|
|
78
|
+
for (const b of data) {
|
|
79
|
+
const factor = b ^ result.shift();
|
|
80
|
+
result.push(0);
|
|
81
|
+
divisor.forEach((coef, i) => {
|
|
82
|
+
result[i] = result[i] ^ gfMul(coef, factor);
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
return result;
|
|
86
|
+
}
|
|
87
|
+
// ---- Encoding --------------------------------------------------------------------------------
|
|
88
|
+
/** The codewords (data then error correction, interleaved) of `bytes` at `ver`. */
|
|
89
|
+
function codewords(bytes, ver) {
|
|
90
|
+
const capacityBits = dataCodewords(ver) * 8;
|
|
91
|
+
const bits = [];
|
|
92
|
+
const put = (value, len) => {
|
|
93
|
+
for (let i = len - 1; i >= 0; i--)
|
|
94
|
+
bits.push((value >>> i) & 1);
|
|
95
|
+
};
|
|
96
|
+
put(0b0100, 4); // byte mode
|
|
97
|
+
put(bytes.length, ver <= 9 ? 8 : 16);
|
|
98
|
+
for (const b of bytes)
|
|
99
|
+
put(b, 8);
|
|
100
|
+
put(0, Math.min(4, capacityBits - bits.length));
|
|
101
|
+
put(0, (8 - (bits.length % 8)) % 8);
|
|
102
|
+
for (let pad = 0xec; bits.length < capacityBits; pad ^= 0xec ^ 0x11)
|
|
103
|
+
put(pad, 8);
|
|
104
|
+
const data = [];
|
|
105
|
+
for (let i = 0; i < bits.length; i += 8) {
|
|
106
|
+
let b = 0;
|
|
107
|
+
for (let j = 0; j < 8; j++)
|
|
108
|
+
b = (b << 1) | bits[i + j];
|
|
109
|
+
data.push(b);
|
|
110
|
+
}
|
|
111
|
+
// Split into blocks (short blocks first), add each block's ECC, then interleave.
|
|
112
|
+
const numBlocks = BLOCKS[ver];
|
|
113
|
+
const eccLen = ECC_PER_BLOCK[ver];
|
|
114
|
+
const rawCodewords = Math.floor(rawDataModules(ver) / 8);
|
|
115
|
+
const numShort = numBlocks - (rawCodewords % numBlocks);
|
|
116
|
+
const shortLen = Math.floor(rawCodewords / numBlocks);
|
|
117
|
+
const divisor = rsDivisor(eccLen);
|
|
118
|
+
const blocks = [];
|
|
119
|
+
for (let i = 0, k = 0; i < numBlocks; i++) {
|
|
120
|
+
const len = shortLen - eccLen + (i < numShort ? 0 : 1);
|
|
121
|
+
const dat = data.slice(k, k + len);
|
|
122
|
+
k += len;
|
|
123
|
+
const ecc = rsRemainder(dat, divisor);
|
|
124
|
+
if (i < numShort)
|
|
125
|
+
dat.push(0); // placeholder, skipped when interleaving
|
|
126
|
+
blocks.push([...dat, ...ecc]);
|
|
127
|
+
}
|
|
128
|
+
const result = [];
|
|
129
|
+
for (let i = 0; i < blocks[0].length; i++) {
|
|
130
|
+
blocks.forEach((block, j) => {
|
|
131
|
+
if (i !== shortLen - eccLen || j >= numShort)
|
|
132
|
+
result.push(block[i]);
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
return result;
|
|
136
|
+
}
|
|
137
|
+
class Grid {
|
|
138
|
+
version;
|
|
139
|
+
size;
|
|
140
|
+
dark;
|
|
141
|
+
fn;
|
|
142
|
+
constructor(version) {
|
|
143
|
+
this.version = version;
|
|
144
|
+
this.size = version * 4 + 17;
|
|
145
|
+
this.dark = Array.from({ length: this.size }, () => new Array(this.size).fill(false));
|
|
146
|
+
this.fn = Array.from({ length: this.size }, () => new Array(this.size).fill(false));
|
|
147
|
+
}
|
|
148
|
+
set(x, y, dark) {
|
|
149
|
+
this.dark[y][x] = dark;
|
|
150
|
+
this.fn[y][x] = true;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
function drawFunctionPatterns(g) {
|
|
154
|
+
const { size, version } = g;
|
|
155
|
+
for (let i = 0; i < size; i++) {
|
|
156
|
+
g.set(6, i, i % 2 === 0);
|
|
157
|
+
g.set(i, 6, i % 2 === 0);
|
|
158
|
+
}
|
|
159
|
+
const finder = (cx, cy) => {
|
|
160
|
+
for (let dy = -4; dy <= 4; dy++) {
|
|
161
|
+
for (let dx = -4; dx <= 4; dx++) {
|
|
162
|
+
const d = Math.max(Math.abs(dx), Math.abs(dy));
|
|
163
|
+
const x = cx + dx;
|
|
164
|
+
const y = cy + dy;
|
|
165
|
+
if (x >= 0 && x < size && y >= 0 && y < size)
|
|
166
|
+
g.set(x, y, d !== 2 && d !== 4);
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
};
|
|
170
|
+
finder(3, 3);
|
|
171
|
+
finder(size - 4, 3);
|
|
172
|
+
finder(3, size - 4);
|
|
173
|
+
const align = alignmentPositions(version);
|
|
174
|
+
const n = align.length;
|
|
175
|
+
for (let i = 0; i < n; i++) {
|
|
176
|
+
for (let j = 0; j < n; j++) {
|
|
177
|
+
if ((i === 0 && j === 0) || (i === 0 && j === n - 1) || (i === n - 1 && j === 0))
|
|
178
|
+
continue;
|
|
179
|
+
for (let dy = -2; dy <= 2; dy++) {
|
|
180
|
+
for (let dx = -2; dx <= 2; dx++) {
|
|
181
|
+
g.set(align[i] + dx, align[j] + dy, Math.max(Math.abs(dx), Math.abs(dy)) !== 1);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
drawFormatBits(g, 0); // reserve; redrawn with the chosen mask
|
|
187
|
+
if (version >= 7) {
|
|
188
|
+
let rem = version;
|
|
189
|
+
for (let i = 0; i < 12; i++)
|
|
190
|
+
rem = (rem << 1) ^ ((rem >>> 11) * 0x1f25);
|
|
191
|
+
const bits = (version << 12) | rem;
|
|
192
|
+
for (let i = 0; i < 18; i++) {
|
|
193
|
+
const bit = ((bits >>> i) & 1) !== 0;
|
|
194
|
+
const a = size - 11 + (i % 3);
|
|
195
|
+
const b = Math.floor(i / 3);
|
|
196
|
+
g.set(a, b, bit);
|
|
197
|
+
g.set(b, a, bit);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
/** The 15 format bits for level M and `mask` (BCH(15,5), XOR-masked). */
|
|
202
|
+
export function formatBits(mask) {
|
|
203
|
+
const data = (ECL_M_BITS << 3) | mask;
|
|
204
|
+
let rem = data;
|
|
205
|
+
for (let i = 0; i < 10; i++)
|
|
206
|
+
rem = (rem << 1) ^ ((rem >>> 9) * 0x537);
|
|
207
|
+
return ((data << 10) | rem) ^ 0x5412;
|
|
208
|
+
}
|
|
209
|
+
function drawFormatBits(g, mask) {
|
|
210
|
+
const bits = formatBits(mask);
|
|
211
|
+
const bit = (i) => ((bits >>> i) & 1) !== 0;
|
|
212
|
+
const { size } = g;
|
|
213
|
+
for (let i = 0; i <= 5; i++)
|
|
214
|
+
g.set(8, i, bit(i));
|
|
215
|
+
g.set(8, 7, bit(6));
|
|
216
|
+
g.set(8, 8, bit(7));
|
|
217
|
+
g.set(7, 8, bit(8));
|
|
218
|
+
for (let i = 9; i < 15; i++)
|
|
219
|
+
g.set(14 - i, 8, bit(i));
|
|
220
|
+
for (let i = 0; i < 8; i++)
|
|
221
|
+
g.set(size - 1 - i, 8, bit(i));
|
|
222
|
+
for (let i = 8; i < 15; i++)
|
|
223
|
+
g.set(8, size - 15 + i, bit(i));
|
|
224
|
+
g.set(8, size - 8, true); // the dark module
|
|
225
|
+
}
|
|
226
|
+
function drawCodewords(g, data) {
|
|
227
|
+
const { size } = g;
|
|
228
|
+
let i = 0;
|
|
229
|
+
for (let right = size - 1; right >= 1; right -= 2) {
|
|
230
|
+
if (right === 6)
|
|
231
|
+
right = 5;
|
|
232
|
+
for (let vert = 0; vert < size; vert++) {
|
|
233
|
+
for (let j = 0; j < 2; j++) {
|
|
234
|
+
const x = right - j;
|
|
235
|
+
const upward = ((right + 1) & 2) === 0;
|
|
236
|
+
const y = upward ? size - 1 - vert : vert;
|
|
237
|
+
if (!g.fn[y][x] && i < data.length * 8) {
|
|
238
|
+
g.dark[y][x] = ((data[i >>> 3] >>> (7 - (i & 7))) & 1) !== 0;
|
|
239
|
+
i++;
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
/** The mask condition: true where a data module is inverted. */
|
|
246
|
+
export function maskBit(mask, x, y) {
|
|
247
|
+
switch (mask) {
|
|
248
|
+
case 0:
|
|
249
|
+
return (x + y) % 2 === 0;
|
|
250
|
+
case 1:
|
|
251
|
+
return y % 2 === 0;
|
|
252
|
+
case 2:
|
|
253
|
+
return x % 3 === 0;
|
|
254
|
+
case 3:
|
|
255
|
+
return (x + y) % 3 === 0;
|
|
256
|
+
case 4:
|
|
257
|
+
return (Math.floor(x / 3) + Math.floor(y / 2)) % 2 === 0;
|
|
258
|
+
case 5:
|
|
259
|
+
return ((x * y) % 2) + ((x * y) % 3) === 0;
|
|
260
|
+
case 6:
|
|
261
|
+
return (((x * y) % 2) + ((x * y) % 3)) % 2 === 0;
|
|
262
|
+
default:
|
|
263
|
+
return (((x + y) % 2) + ((x * y) % 3)) % 2 === 0;
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
function applyMask(g, mask) {
|
|
267
|
+
for (let y = 0; y < g.size; y++) {
|
|
268
|
+
for (let x = 0; x < g.size; x++) {
|
|
269
|
+
if (!g.fn[y][x] && maskBit(mask, x, y)) {
|
|
270
|
+
g.dark[y][x] = !g.dark[y][x];
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
/** The standard penalty score (rules N1–N4) of a finished matrix. */
|
|
276
|
+
function penalty(m) {
|
|
277
|
+
const size = m.length;
|
|
278
|
+
let score = 0;
|
|
279
|
+
const line = (get) => {
|
|
280
|
+
let run = 1;
|
|
281
|
+
for (let i = 1; i <= size; i++) {
|
|
282
|
+
if (i < size && get(i) === get(i - 1))
|
|
283
|
+
run++;
|
|
284
|
+
else {
|
|
285
|
+
if (run >= 5)
|
|
286
|
+
score += 3 + (run - 5);
|
|
287
|
+
run = 1;
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
const seq = Array.from({ length: size }, (_, i) => (get(i) ? 1 : 0)).join('');
|
|
291
|
+
for (const p of ['10111010000', '00001011101']) {
|
|
292
|
+
for (let at = seq.indexOf(p); at >= 0; at = seq.indexOf(p, at + 1))
|
|
293
|
+
score += 40;
|
|
294
|
+
}
|
|
295
|
+
};
|
|
296
|
+
for (let y = 0; y < size; y++)
|
|
297
|
+
line((x) => m[y][x]);
|
|
298
|
+
for (let x = 0; x < size; x++)
|
|
299
|
+
line((y) => m[y][x]);
|
|
300
|
+
let dark = 0;
|
|
301
|
+
for (let y = 0; y < size; y++) {
|
|
302
|
+
for (let x = 0; x < size; x++) {
|
|
303
|
+
const c = m[y][x];
|
|
304
|
+
if (c)
|
|
305
|
+
dark++;
|
|
306
|
+
if (x + 1 < size &&
|
|
307
|
+
y + 1 < size &&
|
|
308
|
+
c === m[y][x + 1] &&
|
|
309
|
+
c === m[y + 1][x] &&
|
|
310
|
+
c === m[y + 1][x + 1])
|
|
311
|
+
score += 3;
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
score += 10 * Math.floor(Math.abs((dark * 100) / (size * size) - 50) / 5);
|
|
315
|
+
return score;
|
|
316
|
+
}
|
|
317
|
+
/** Encodes `text` (UTF-8, byte mode, level M) at the smallest version 1–10 that holds it. */
|
|
318
|
+
export function encodeQr(text) {
|
|
319
|
+
const bytes = new TextEncoder().encode(text);
|
|
320
|
+
let version = 0;
|
|
321
|
+
for (let v = 1; v <= MAX_VERSION; v++) {
|
|
322
|
+
const needed = 4 + (v <= 9 ? 8 : 16) + bytes.length * 8;
|
|
323
|
+
if (needed <= dataCodewords(v) * 8) {
|
|
324
|
+
version = v;
|
|
325
|
+
break;
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
if (version === 0)
|
|
329
|
+
throw new RangeError('text too long for a version 1–10 QR code');
|
|
330
|
+
const data = codewords(bytes, version);
|
|
331
|
+
let best = null;
|
|
332
|
+
for (let mask = 0; mask < 8; mask++) {
|
|
333
|
+
const g = new Grid(version);
|
|
334
|
+
drawFunctionPatterns(g);
|
|
335
|
+
drawCodewords(g, data);
|
|
336
|
+
applyMask(g, mask);
|
|
337
|
+
drawFormatBits(g, mask);
|
|
338
|
+
const score = penalty(g.dark);
|
|
339
|
+
if (best === null || score < best.score)
|
|
340
|
+
best = { score, matrix: g.dark };
|
|
341
|
+
}
|
|
342
|
+
return best.matrix;
|
|
343
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
/** The accessible name of the SVG drawing (its one `title`). */
|
|
2
|
+
export declare const QR_TITLE = "QR code for this Sess link";
|
|
3
|
+
/** The line `printQr` prints before the code. */
|
|
4
|
+
export declare const QR_HEADING = "Scan to answer on your phone";
|
|
5
|
+
export type QrFormat = 'svg' | 'png' | 'terminal';
|
|
6
|
+
export interface QrSvgOptions {
|
|
7
|
+
format: 'svg';
|
|
8
|
+
}
|
|
9
|
+
export interface QrPngOptions {
|
|
10
|
+
format: 'png';
|
|
11
|
+
}
|
|
12
|
+
export interface QrTerminalOptions {
|
|
13
|
+
format: 'terminal';
|
|
14
|
+
/**
|
|
15
|
+
* Draw black on white with ANSI colours, so the code scans in light and dark terminal themes
|
|
16
|
+
* (default true). False: characters only (for `NO_COLOR`); the code is then drawn in the
|
|
17
|
+
* terminal's own text colour.
|
|
18
|
+
*/
|
|
19
|
+
color?: boolean;
|
|
20
|
+
}
|
|
21
|
+
export type QrOptions = QrSvgOptions | QrPngOptions | QrTerminalOptions;
|
|
22
|
+
/**
|
|
23
|
+
* Draws `url` (an absolute http(s) URL of at most 213 bytes, such as the `url` of a created Session)
|
|
24
|
+
* as a QR code: error correction level M, a 4-module quiet zone, deterministic, no network access.
|
|
25
|
+
*
|
|
26
|
+
* - `svg`: an SVG string with an accessible title ({@link QR_TITLE}).
|
|
27
|
+
* - `png`: PNG bytes, 8 pixels per module.
|
|
28
|
+
* - `terminal`: text with Unicode half blocks, for an interactive terminal (see {@link printQr}).
|
|
29
|
+
*
|
|
30
|
+
* The drawing is the link itself in another encoding: keep it wherever the link may be, and never
|
|
31
|
+
* in logs, analytics or a URL.
|
|
32
|
+
*/
|
|
33
|
+
export declare function qr(url: string, options: QrSvgOptions | QrTerminalOptions): string;
|
|
34
|
+
export declare function qr(url: string, options: QrPngOptions): Uint8Array;
|
|
35
|
+
export interface PrintQrOptions {
|
|
36
|
+
/** Where to print (default `process.stdout`). Printed only when it is an interactive terminal. */
|
|
37
|
+
stream?: {
|
|
38
|
+
isTTY?: boolean | undefined;
|
|
39
|
+
write(text: string): unknown;
|
|
40
|
+
};
|
|
41
|
+
/** The environment (default `process.env`): `CI`, `NODE_ENV` and `NO_COLOR` are read. */
|
|
42
|
+
env?: Readonly<Record<string, string | undefined>>;
|
|
43
|
+
/** The command-line arguments (default `process.argv`): `--no-qr` turns the code off. */
|
|
44
|
+
argv?: readonly string[];
|
|
45
|
+
/** False turns the code off, as `--no-qr` does. */
|
|
46
|
+
qr?: boolean;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* For development: prints "Scan to answer on your phone" and `url` as a terminal QR code, and
|
|
50
|
+
* returns true, only on an interactive terminal. It prints nothing and returns false when the
|
|
51
|
+
* stream is not a TTY (a pipe, a file, a log collector), in CI (`CI` set), in production
|
|
52
|
+
* (`NODE_ENV=production`), with `--no-qr` or with `qr: false`. `NO_COLOR` draws it without colour.
|
|
53
|
+
* Print the link itself as well: the code is a shortcut, not the only way in.
|
|
54
|
+
*/
|
|
55
|
+
export declare function printQr(url: string, options?: PrintQrOptions): boolean;
|