@zyro-sec/util 1.0.2 → 1.0.4

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 (78) hide show
  1. package/docs/layer-node.md +155 -155
  2. package/package.json +1 -1
  3. package/script/build.ts +9 -9
  4. package/script/pack.ts +5 -5
  5. package/src/abort.ts +9 -9
  6. package/src/activity-calendar.ts +50 -50
  7. package/src/artifact.ts +95 -95
  8. package/src/base64.ts +29 -29
  9. package/src/binary.ts +30 -30
  10. package/src/bom.ts +46 -46
  11. package/src/cross-spawn-spawner.ts +694 -694
  12. package/src/duration.ts +22 -22
  13. package/src/effect/app-node-platform.ts +40 -40
  14. package/src/effect/app-node.ts +14 -14
  15. package/src/effect/layer-node.ts +360 -360
  16. package/src/effect-flock.ts +313 -313
  17. package/src/encode.ts +39 -39
  18. package/src/execute-output.ts +23 -23
  19. package/src/flock.ts +346 -346
  20. package/src/fs-util.ts +271 -271
  21. package/src/glob.ts +38 -38
  22. package/src/global-roots.ts +19 -19
  23. package/src/global-roots.workerd.ts +16 -16
  24. package/src/global.ts +88 -88
  25. package/src/hash.ts +11 -11
  26. package/src/heap-snapshot.ts +44 -44
  27. package/src/no-timeout-fetch.ts +5 -5
  28. package/src/npm-config.ts +41 -41
  29. package/src/npm.ts +557 -557
  30. package/src/observability/logging.ts +179 -179
  31. package/src/observability/otlp.ts +109 -109
  32. package/src/observability/shared.ts +8 -8
  33. package/src/observability.ts +60 -60
  34. package/src/open.ts +12 -12
  35. package/src/patch.ts +382 -382
  36. package/src/path.ts +149 -149
  37. package/src/process-signal.ts +23 -23
  38. package/src/process.ts +270 -270
  39. package/src/qr.ts +323 -323
  40. package/src/record.ts +3 -3
  41. package/src/retry.ts +51 -51
  42. package/src/runtime/import.bun.ts +10 -10
  43. package/src/runtime/import.node.ts +61 -61
  44. package/src/runtime/import.workerd.ts +9 -9
  45. package/src/runtime-import.ts +1 -1
  46. package/src/session-mention.ts +24 -24
  47. package/src/session-title-fallback.ts +36 -36
  48. package/src/session-turn.ts +82 -82
  49. package/src/teardown.ts +19 -19
  50. package/src/text-boundary.ts +36 -36
  51. package/src/uuid.ts +15 -15
  52. package/test/fixtures/qr.json +625 -625
  53. package/tsconfig.build.json +12 -12
  54. package/tsconfig.dist.json +10 -10
  55. package/tsconfig.json +14 -14
  56. package/src/abort.test.ts +0 -16
  57. package/src/activity-calendar.test.ts +0 -136
  58. package/src/artifact.test.ts +0 -29
  59. package/src/base64.test.ts +0 -12
  60. package/src/binary.test.ts +0 -19
  61. package/src/bom.test.ts +0 -21
  62. package/src/encode.test.ts +0 -32
  63. package/src/execute-output.test.ts +0 -36
  64. package/src/no-timeout-fetch.test.ts +0 -33
  65. package/src/open.test.ts +0 -16
  66. package/src/path.test.ts +0 -89
  67. package/src/process-signal.test.ts +0 -38
  68. package/src/retry.test.ts +0 -87
  69. package/src/session-mention.test.ts +0 -19
  70. package/src/session-turn.test.ts +0 -131
  71. package/src/text-boundary.test.ts +0 -39
  72. package/src/uuid.test.ts +0 -80
  73. package/test/glob.test.ts +0 -11
  74. package/test/global-roots.test.ts +0 -62
  75. package/test/global.test.ts +0 -99
  76. package/test/observability-otlp.test.ts +0 -45
  77. package/test/qr.test.ts +0 -113
  78. package/test/session-title-fallback.test.ts +0 -49
package/src/qr.ts CHANGED
@@ -1,323 +1,323 @@
1
- // QR Code encoder (ISO/IEC 18004) for byte-mode text at error correction level L, following the structure of
2
- // Project Nayuki's QR Code generator (MIT): https://www.nayuki.io/page/qr-code-generator-library
3
-
4
- // Error correction codewords per block and block count at level L, for versions 1 to 40.
5
- const ECC_PER_BLOCK = [
6
- 7, 10, 15, 20, 26, 18, 20, 24, 30, 18, 20, 24, 26, 30, 22, 24, 28, 30, 28, 28, 28, 28, 30, 30, 26, 28, 30, 30, 30, 30,
7
- 30, 30, 30, 30, 30, 30, 30, 30, 30, 30,
8
- ]
9
- const BLOCKS = [
10
- 1, 1, 1, 1, 1, 2, 2, 2, 2, 4, 4, 4, 4, 4, 6, 6, 6, 6, 7, 8, 8, 9, 9, 10, 12, 12, 12, 13, 14, 15, 16, 17, 18, 19, 19,
11
- 20, 21, 22, 24, 25,
12
- ]
13
-
14
- const MASKS = [
15
- (x: number, y: number) => (x + y) % 2 === 0,
16
- (_: number, y: number) => y % 2 === 0,
17
- (x: number) => x % 3 === 0,
18
- (x: number, y: number) => (x + y) % 3 === 0,
19
- (x: number, y: number) => (Math.floor(x / 3) + Math.floor(y / 2)) % 2 === 0,
20
- (x: number, y: number) => ((x * y) % 2) + ((x * y) % 3) === 0,
21
- (x: number, y: number) => (((x * y) % 2) + ((x * y) % 3)) % 2 === 0,
22
- (x: number, y: number) => (((x + y) % 2) + ((x * y) % 3)) % 2 === 0,
23
- ]
24
-
25
- type Draw = (x: number, y: number, dark: boolean) => void
26
-
27
- /** Encodes text as UTF-8 into the smallest QR Code that fits. Rows of modules without a quiet zone; true is dark. */
28
- export function encode(text: string) {
29
- const bytes = new TextEncoder().encode(text)
30
- const version = Array.from({ length: 40 }, (_, i) => i + 1).find(
31
- (v) => 4 + (v < 10 ? 8 : 16) + bytes.length * 8 <= dataCapacity(v) * 8,
32
- )
33
- if (version === undefined) throw new RangeError(`Text is too long for a QR Code: ${bytes.length} bytes`)
34
-
35
- const size = version * 4 + 17
36
- const modules = Array.from({ length: size }, () => Array<boolean>(size).fill(false))
37
- const reserved = Array.from({ length: size }, () => Array<boolean>(size).fill(false))
38
- drawFunctionPatterns(version, size, (x, y, dark) => {
39
- modules[y][x] = dark
40
- reserved[y][x] = true
41
- })
42
- drawCodewords(modules, reserved, addErrorCorrection(dataCodewords(bytes, version), version))
43
-
44
- const candidates = MASKS.map((mask, index) => {
45
- const masked = modules.map((row, y) => row.map((dark, x) => dark !== (!reserved[y][x] && mask(x, y))))
46
- drawFormat(index, size, (x, y, dark) => {
47
- masked[y][x] = dark
48
- })
49
- return masked
50
- })
51
- const scores = candidates.map(penalty)
52
- return candidates[scores.indexOf(Math.min(...scores))]
53
- }
54
-
55
- /** Renders text as an SVG QR Code with 10-unit modules and a quiet zone of `border` modules. */
56
- export function renderSVG(text: string, options: { border?: number; blackColor?: string; whiteColor?: string } = {}) {
57
- const modules = addBorder(encode(text), options.border ?? 1)
58
- const width = modules.length * 10
59
- const path = modules
60
- .flatMap((row, y) => row.flatMap((dark, x) => (dark ? [`M${x * 10},${y * 10}h10v10h-10z`] : [])))
61
- .join("")
62
- return (
63
- `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${width} ${width}">` +
64
- `<rect fill="${escapeAttribute(options.whiteColor ?? "white")}" width="${width}" height="${width}"/>` +
65
- `<path fill="${escapeAttribute(options.blackColor ?? "black")}" d="${path}"/></svg>`
66
- )
67
- }
68
-
69
- /**
70
- * Renders text as a QR Code for a terminal, two modules per character with half blocks. Light modules draw as blocks
71
- * and dark modules as the terminal background, rows are joined with "\n", and the quiet zone is `border` modules.
72
- */
73
- export function renderUnicodeCompact(text: string, options: { border?: number } = {}) {
74
- const modules = addBorder(encode(text), options.border ?? 1)
75
- return Array.from({ length: Math.ceil(modules.length / 2) }, (_, line) =>
76
- modules[line * 2]
77
- .map((top, x) => {
78
- // The symbol has an odd number of rows, so the last line's missing bottom half shows the terminal background.
79
- const bottom = modules[line * 2 + 1]?.[x] ?? true
80
- if (top) return bottom ? " " : "\u2584"
81
- return bottom ? "\u2580" : "\u2588"
82
- })
83
- .join(""),
84
- ).join("\n")
85
- }
86
-
87
- function drawFunctionPatterns(version: number, size: number, set: Draw) {
88
- for (let i = 0; i < size; i++) {
89
- set(6, i, i % 2 === 0)
90
- set(i, 6, i % 2 === 0)
91
- }
92
- for (const [cx, cy] of [
93
- [3, 3],
94
- [size - 4, 3],
95
- [3, size - 4],
96
- ])
97
- for (let dy = -4; dy <= 4; dy++)
98
- for (let dx = -4; dx <= 4; dx++) {
99
- const x = cx + dx
100
- const y = cy + dy
101
- const distance = Math.max(Math.abs(dx), Math.abs(dy))
102
- if (x >= 0 && x < size && y >= 0 && y < size) set(x, y, distance !== 2 && distance !== 4)
103
- }
104
-
105
- const positions = alignmentPositions(version, size)
106
- const last = positions.length - 1
107
- positions.forEach((cx, i) =>
108
- positions.forEach((cy, j) => {
109
- // Skip the three corners that hold finder patterns.
110
- if ((i === 0 && j === 0) || (i === 0 && j === last) || (i === last && j === 0)) return
111
- for (let dy = -2; dy <= 2; dy++)
112
- for (let dx = -2; dx <= 2; dx++) set(cx + dx, cy + dy, Math.max(Math.abs(dx), Math.abs(dy)) !== 1)
113
- }),
114
- )
115
-
116
- // Reserves the format areas; the real format bits are drawn once the mask is chosen.
117
- drawFormat(0, size, set)
118
- if (version < 7) return
119
- const bits = bch(version, 12, 0x1f25)
120
- for (let i = 0; i < 18; i++) {
121
- const a = size - 11 + (i % 3)
122
- const b = Math.floor(i / 3)
123
- const dark = ((bits >>> i) & 1) === 1
124
- set(a, b, dark)
125
- set(b, a, dark)
126
- }
127
- }
128
-
129
- function alignmentPositions(version: number, size: number) {
130
- if (version === 1) return []
131
- const count = Math.floor(version / 7) + 2
132
- const step = version === 32 ? 26 : Math.ceil((version * 4 + 4) / (count * 2 - 2)) * 2
133
- return [6, ...Array.from({ length: count - 1 }, (_, i) => size - 7 - (count - 2 - i) * step)]
134
- }
135
-
136
- function drawFormat(mask: number, size: number, set: Draw) {
137
- // Level L is 0b01 in the format information.
138
- const bits = bch((1 << 3) | mask, 10, 0x537) ^ 0x5412
139
- const bit = (i: number) => ((bits >>> i) & 1) === 1
140
- for (let i = 0; i <= 5; i++) set(8, i, bit(i))
141
- set(8, 7, bit(6))
142
- set(8, 8, bit(7))
143
- set(7, 8, bit(8))
144
- for (let i = 9; i < 15; i++) set(14 - i, 8, bit(i))
145
- for (let i = 0; i < 8; i++) set(size - 1 - i, 8, bit(i))
146
- for (let i = 8; i < 15; i++) set(8, size - 15 + i, bit(i))
147
- set(8, size - 8, true)
148
- }
149
-
150
- // Appends the BCH remainder of `data` for a generator polynomial of the given degree.
151
- function bch(data: number, degree: number, generator: number) {
152
- let remainder = data
153
- for (let i = 0; i < degree; i++) remainder = (remainder << 1) ^ ((remainder >>> (degree - 1)) * generator)
154
- return (data << degree) | remainder
155
- }
156
-
157
- function dataCodewords(bytes: Uint8Array, version: number) {
158
- const capacity = dataCapacity(version)
159
- const bits: number[] = []
160
- const append = (value: number, length: number) => {
161
- for (let i = length - 1; i >= 0; i--) bits.push((value >>> i) & 1)
162
- }
163
- append(0b0100, 4)
164
- append(bytes.length, version < 10 ? 8 : 16)
165
- bytes.forEach((byte) => append(byte, 8))
166
- append(0, Math.min(4, capacity * 8 - bits.length))
167
- append(0, (8 - (bits.length % 8)) % 8)
168
- const data = Array.from({ length: bits.length / 8 }, (_, i) =>
169
- bits.slice(i * 8, i * 8 + 8).reduce((byte, bit) => (byte << 1) | bit, 0),
170
- )
171
- return [...data, ...Array.from({ length: capacity - data.length }, (_, i) => (i % 2 === 0 ? 0xec : 0x11))]
172
- }
173
-
174
- function addErrorCorrection(data: number[], version: number) {
175
- const blocks = BLOCKS[version - 1]
176
- const ecc = ECC_PER_BLOCK[version - 1]
177
- const raw = Math.floor(rawModules(version) / 8)
178
- // The first `short` blocks hold one data codeword fewer than the rest.
179
- const short = blocks - (raw % blocks)
180
- const shortLength = Math.floor(raw / blocks) - ecc
181
- const divisor = reedSolomonDivisor(ecc)
182
- const split = Array.from({ length: blocks }, (_, i) => {
183
- const start = i * shortLength + Math.max(0, i - short)
184
- return data.slice(start, start + shortLength + (i < short ? 0 : 1))
185
- })
186
- const interleave = (rows: number[][], length: number) =>
187
- Array.from({ length }, (_, i) => rows.flatMap((row) => (i < row.length ? [row[i]] : []))).flat()
188
- return [
189
- ...interleave(split, shortLength + 1),
190
- ...interleave(
191
- split.map((block) => reedSolomonRemainder(block, divisor)),
192
- ecc,
193
- ),
194
- ]
195
- }
196
-
197
- function drawCodewords(modules: boolean[][], reserved: boolean[][], codewords: number[]) {
198
- const size = modules.length
199
- let i = 0
200
- for (let right = size - 1; right >= 1; right -= 2) {
201
- // The vertical timing pattern takes column 6, so the column pair shifts left past it.
202
- if (right === 6) right = 5
203
- for (let vertical = 0; vertical < size; vertical++)
204
- for (let j = 0; j < 2; j++) {
205
- const x = right - j
206
- const y = ((right + 1) & 2) === 0 ? size - 1 - vertical : vertical
207
- if (reserved[y][x] || i >= codewords.length * 8) continue
208
- modules[y][x] = ((codewords[i >>> 3] >>> (7 - (i & 7))) & 1) === 1
209
- i++
210
- }
211
- }
212
- }
213
-
214
- function penalty(modules: boolean[][]) {
215
- const size = modules.length
216
- const columns = modules.map((_, x) => modules.map((row) => row[x]))
217
- const lines = [...modules, ...columns].reduce((sum, line) => sum + linePenalty(line), 0)
218
- // Each 2x2 block of one colour, found from its bottom-right module.
219
- const boxes = modules
220
- .slice(1)
221
- .flatMap((row, y) =>
222
- row.slice(1).filter((dark, x) => dark === row[x] && dark === modules[y][x] && dark === modules[y][x + 1]),
223
- ).length
224
- const dark = modules.flat().filter(Boolean).length
225
- const total = size * size
226
- return lines + boxes * 3 + (Math.ceil(Math.abs(dark * 20 - total * 10) / total) - 1) * 10
227
- }
228
-
229
- // Scores runs of five or more same-coloured modules, and 1:1:3:1:1 finder-like patterns with 4 light modules on a side.
230
- function linePenalty(line: boolean[]) {
231
- const size = line.length
232
- const history = [0, 0, 0, 0, 0, 0, 0]
233
- const push = (length: number) => {
234
- history.pop()
235
- history.unshift(history[0] === 0 ? length + size : length)
236
- }
237
- const finders = () => {
238
- const n = history[1]
239
- const core = n > 0 && history[2] === n && history[3] === n * 3 && history[4] === n && history[5] === n
240
- return (
241
- (core && history[0] >= n * 4 && history[6] >= n ? 1 : 0) +
242
- (core && history[6] >= n * 4 && history[0] >= n ? 1 : 0)
243
- )
244
- }
245
- let result = 0
246
- let color = false
247
- let run = 0
248
- for (const dark of line) {
249
- if (dark === color) {
250
- run++
251
- if (run === 5) result += 3
252
- if (run > 5) result++
253
- continue
254
- }
255
- push(run)
256
- if (!color) result += finders() * 40
257
- color = dark
258
- run = 1
259
- }
260
- if (color) {
261
- push(run)
262
- run = 0
263
- }
264
- push(run + size)
265
- return result + finders() * 40
266
- }
267
-
268
- function reedSolomonDivisor(degree: number) {
269
- const result = Array<number>(degree).fill(0)
270
- result[degree - 1] = 1
271
- let root = 1
272
- for (let i = 0; i < degree; i++) {
273
- for (let j = 0; j < degree; j++) {
274
- result[j] = multiply(result[j], root)
275
- if (j + 1 < degree) result[j] ^= result[j + 1]
276
- }
277
- root = multiply(root, 2)
278
- }
279
- return result
280
- }
281
-
282
- function reedSolomonRemainder(data: number[], divisor: number[]) {
283
- return data.reduce(
284
- (remainder, byte) => {
285
- const factor = byte ^ remainder[0]
286
- return [...remainder.slice(1), 0].map((value, i) => value ^ multiply(divisor[i], factor))
287
- },
288
- divisor.map(() => 0),
289
- )
290
- }
291
-
292
- // Multiplies in GF(2^8) modulo x^8 + x^4 + x^3 + x^2 + 1.
293
- function multiply(x: number, y: number) {
294
- let z = 0
295
- for (let i = 7; i >= 0; i--) {
296
- z = (z << 1) ^ ((z >>> 7) * 0x11d)
297
- z ^= ((y >>> i) & 1) * x
298
- }
299
- return z
300
- }
301
-
302
- function rawModules(version: number) {
303
- const base = (16 * version + 128) * version + 64
304
- if (version < 2) return base
305
- const count = Math.floor(version / 7) + 2
306
- return base - ((25 * count - 10) * count - 55) - (version >= 7 ? 36 : 0)
307
- }
308
-
309
- function dataCapacity(version: number) {
310
- return Math.floor(rawModules(version) / 8) - ECC_PER_BLOCK[version - 1] * BLOCKS[version - 1]
311
- }
312
-
313
- function addBorder(modules: boolean[][], border: number) {
314
- const width = modules.length + border * 2
315
- const blank = () => Array<boolean>(width).fill(false)
316
- const edge = Array.from({ length: border }, blank)
317
- const padding = Array<boolean>(border).fill(false)
318
- return [...edge, ...modules.map((row) => [...padding, ...row, ...padding]), ...Array.from({ length: border }, blank)]
319
- }
320
-
321
- function escapeAttribute(value: string) {
322
- return value.replaceAll("&", "&amp;").replaceAll('"', "&quot;").replaceAll("<", "&lt;").replaceAll(">", "&gt;")
323
- }
1
+ // QR Code encoder (ISO/IEC 18004) for byte-mode text at error correction level L, following the structure of
2
+ // Project Nayuki's QR Code generator (MIT): https://www.nayuki.io/page/qr-code-generator-library
3
+
4
+ // Error correction codewords per block and block count at level L, for versions 1 to 40.
5
+ const ECC_PER_BLOCK = [
6
+ 7, 10, 15, 20, 26, 18, 20, 24, 30, 18, 20, 24, 26, 30, 22, 24, 28, 30, 28, 28, 28, 28, 30, 30, 26, 28, 30, 30, 30, 30,
7
+ 30, 30, 30, 30, 30, 30, 30, 30, 30, 30,
8
+ ]
9
+ const BLOCKS = [
10
+ 1, 1, 1, 1, 1, 2, 2, 2, 2, 4, 4, 4, 4, 4, 6, 6, 6, 6, 7, 8, 8, 9, 9, 10, 12, 12, 12, 13, 14, 15, 16, 17, 18, 19, 19,
11
+ 20, 21, 22, 24, 25,
12
+ ]
13
+
14
+ const MASKS = [
15
+ (x: number, y: number) => (x + y) % 2 === 0,
16
+ (_: number, y: number) => y % 2 === 0,
17
+ (x: number) => x % 3 === 0,
18
+ (x: number, y: number) => (x + y) % 3 === 0,
19
+ (x: number, y: number) => (Math.floor(x / 3) + Math.floor(y / 2)) % 2 === 0,
20
+ (x: number, y: number) => ((x * y) % 2) + ((x * y) % 3) === 0,
21
+ (x: number, y: number) => (((x * y) % 2) + ((x * y) % 3)) % 2 === 0,
22
+ (x: number, y: number) => (((x + y) % 2) + ((x * y) % 3)) % 2 === 0,
23
+ ]
24
+
25
+ type Draw = (x: number, y: number, dark: boolean) => void
26
+
27
+ /** Encodes text as UTF-8 into the smallest QR Code that fits. Rows of modules without a quiet zone; true is dark. */
28
+ export function encode(text: string) {
29
+ const bytes = new TextEncoder().encode(text)
30
+ const version = Array.from({ length: 40 }, (_, i) => i + 1).find(
31
+ (v) => 4 + (v < 10 ? 8 : 16) + bytes.length * 8 <= dataCapacity(v) * 8,
32
+ )
33
+ if (version === undefined) throw new RangeError(`Text is too long for a QR Code: ${bytes.length} bytes`)
34
+
35
+ const size = version * 4 + 17
36
+ const modules = Array.from({ length: size }, () => Array<boolean>(size).fill(false))
37
+ const reserved = Array.from({ length: size }, () => Array<boolean>(size).fill(false))
38
+ drawFunctionPatterns(version, size, (x, y, dark) => {
39
+ modules[y][x] = dark
40
+ reserved[y][x] = true
41
+ })
42
+ drawCodewords(modules, reserved, addErrorCorrection(dataCodewords(bytes, version), version))
43
+
44
+ const candidates = MASKS.map((mask, index) => {
45
+ const masked = modules.map((row, y) => row.map((dark, x) => dark !== (!reserved[y][x] && mask(x, y))))
46
+ drawFormat(index, size, (x, y, dark) => {
47
+ masked[y][x] = dark
48
+ })
49
+ return masked
50
+ })
51
+ const scores = candidates.map(penalty)
52
+ return candidates[scores.indexOf(Math.min(...scores))]
53
+ }
54
+
55
+ /** Renders text as an SVG QR Code with 10-unit modules and a quiet zone of `border` modules. */
56
+ export function renderSVG(text: string, options: { border?: number; blackColor?: string; whiteColor?: string } = {}) {
57
+ const modules = addBorder(encode(text), options.border ?? 1)
58
+ const width = modules.length * 10
59
+ const path = modules
60
+ .flatMap((row, y) => row.flatMap((dark, x) => (dark ? [`M${x * 10},${y * 10}h10v10h-10z`] : [])))
61
+ .join("")
62
+ return (
63
+ `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${width} ${width}">` +
64
+ `<rect fill="${escapeAttribute(options.whiteColor ?? "white")}" width="${width}" height="${width}"/>` +
65
+ `<path fill="${escapeAttribute(options.blackColor ?? "black")}" d="${path}"/></svg>`
66
+ )
67
+ }
68
+
69
+ /**
70
+ * Renders text as a QR Code for a terminal, two modules per character with half blocks. Light modules draw as blocks
71
+ * and dark modules as the terminal background, rows are joined with "\n", and the quiet zone is `border` modules.
72
+ */
73
+ export function renderUnicodeCompact(text: string, options: { border?: number } = {}) {
74
+ const modules = addBorder(encode(text), options.border ?? 1)
75
+ return Array.from({ length: Math.ceil(modules.length / 2) }, (_, line) =>
76
+ modules[line * 2]
77
+ .map((top, x) => {
78
+ // The symbol has an odd number of rows, so the last line's missing bottom half shows the terminal background.
79
+ const bottom = modules[line * 2 + 1]?.[x] ?? true
80
+ if (top) return bottom ? " " : "\u2584"
81
+ return bottom ? "\u2580" : "\u2588"
82
+ })
83
+ .join(""),
84
+ ).join("\n")
85
+ }
86
+
87
+ function drawFunctionPatterns(version: number, size: number, set: Draw) {
88
+ for (let i = 0; i < size; i++) {
89
+ set(6, i, i % 2 === 0)
90
+ set(i, 6, i % 2 === 0)
91
+ }
92
+ for (const [cx, cy] of [
93
+ [3, 3],
94
+ [size - 4, 3],
95
+ [3, size - 4],
96
+ ])
97
+ for (let dy = -4; dy <= 4; dy++)
98
+ for (let dx = -4; dx <= 4; dx++) {
99
+ const x = cx + dx
100
+ const y = cy + dy
101
+ const distance = Math.max(Math.abs(dx), Math.abs(dy))
102
+ if (x >= 0 && x < size && y >= 0 && y < size) set(x, y, distance !== 2 && distance !== 4)
103
+ }
104
+
105
+ const positions = alignmentPositions(version, size)
106
+ const last = positions.length - 1
107
+ positions.forEach((cx, i) =>
108
+ positions.forEach((cy, j) => {
109
+ // Skip the three corners that hold finder patterns.
110
+ if ((i === 0 && j === 0) || (i === 0 && j === last) || (i === last && j === 0)) return
111
+ for (let dy = -2; dy <= 2; dy++)
112
+ for (let dx = -2; dx <= 2; dx++) set(cx + dx, cy + dy, Math.max(Math.abs(dx), Math.abs(dy)) !== 1)
113
+ }),
114
+ )
115
+
116
+ // Reserves the format areas; the real format bits are drawn once the mask is chosen.
117
+ drawFormat(0, size, set)
118
+ if (version < 7) return
119
+ const bits = bch(version, 12, 0x1f25)
120
+ for (let i = 0; i < 18; i++) {
121
+ const a = size - 11 + (i % 3)
122
+ const b = Math.floor(i / 3)
123
+ const dark = ((bits >>> i) & 1) === 1
124
+ set(a, b, dark)
125
+ set(b, a, dark)
126
+ }
127
+ }
128
+
129
+ function alignmentPositions(version: number, size: number) {
130
+ if (version === 1) return []
131
+ const count = Math.floor(version / 7) + 2
132
+ const step = version === 32 ? 26 : Math.ceil((version * 4 + 4) / (count * 2 - 2)) * 2
133
+ return [6, ...Array.from({ length: count - 1 }, (_, i) => size - 7 - (count - 2 - i) * step)]
134
+ }
135
+
136
+ function drawFormat(mask: number, size: number, set: Draw) {
137
+ // Level L is 0b01 in the format information.
138
+ const bits = bch((1 << 3) | mask, 10, 0x537) ^ 0x5412
139
+ const bit = (i: number) => ((bits >>> i) & 1) === 1
140
+ for (let i = 0; i <= 5; i++) set(8, i, bit(i))
141
+ set(8, 7, bit(6))
142
+ set(8, 8, bit(7))
143
+ set(7, 8, bit(8))
144
+ for (let i = 9; i < 15; i++) set(14 - i, 8, bit(i))
145
+ for (let i = 0; i < 8; i++) set(size - 1 - i, 8, bit(i))
146
+ for (let i = 8; i < 15; i++) set(8, size - 15 + i, bit(i))
147
+ set(8, size - 8, true)
148
+ }
149
+
150
+ // Appends the BCH remainder of `data` for a generator polynomial of the given degree.
151
+ function bch(data: number, degree: number, generator: number) {
152
+ let remainder = data
153
+ for (let i = 0; i < degree; i++) remainder = (remainder << 1) ^ ((remainder >>> (degree - 1)) * generator)
154
+ return (data << degree) | remainder
155
+ }
156
+
157
+ function dataCodewords(bytes: Uint8Array, version: number) {
158
+ const capacity = dataCapacity(version)
159
+ const bits: number[] = []
160
+ const append = (value: number, length: number) => {
161
+ for (let i = length - 1; i >= 0; i--) bits.push((value >>> i) & 1)
162
+ }
163
+ append(0b0100, 4)
164
+ append(bytes.length, version < 10 ? 8 : 16)
165
+ bytes.forEach((byte) => append(byte, 8))
166
+ append(0, Math.min(4, capacity * 8 - bits.length))
167
+ append(0, (8 - (bits.length % 8)) % 8)
168
+ const data = Array.from({ length: bits.length / 8 }, (_, i) =>
169
+ bits.slice(i * 8, i * 8 + 8).reduce((byte, bit) => (byte << 1) | bit, 0),
170
+ )
171
+ return [...data, ...Array.from({ length: capacity - data.length }, (_, i) => (i % 2 === 0 ? 0xec : 0x11))]
172
+ }
173
+
174
+ function addErrorCorrection(data: number[], version: number) {
175
+ const blocks = BLOCKS[version - 1]
176
+ const ecc = ECC_PER_BLOCK[version - 1]
177
+ const raw = Math.floor(rawModules(version) / 8)
178
+ // The first `short` blocks hold one data codeword fewer than the rest.
179
+ const short = blocks - (raw % blocks)
180
+ const shortLength = Math.floor(raw / blocks) - ecc
181
+ const divisor = reedSolomonDivisor(ecc)
182
+ const split = Array.from({ length: blocks }, (_, i) => {
183
+ const start = i * shortLength + Math.max(0, i - short)
184
+ return data.slice(start, start + shortLength + (i < short ? 0 : 1))
185
+ })
186
+ const interleave = (rows: number[][], length: number) =>
187
+ Array.from({ length }, (_, i) => rows.flatMap((row) => (i < row.length ? [row[i]] : []))).flat()
188
+ return [
189
+ ...interleave(split, shortLength + 1),
190
+ ...interleave(
191
+ split.map((block) => reedSolomonRemainder(block, divisor)),
192
+ ecc,
193
+ ),
194
+ ]
195
+ }
196
+
197
+ function drawCodewords(modules: boolean[][], reserved: boolean[][], codewords: number[]) {
198
+ const size = modules.length
199
+ let i = 0
200
+ for (let right = size - 1; right >= 1; right -= 2) {
201
+ // The vertical timing pattern takes column 6, so the column pair shifts left past it.
202
+ if (right === 6) right = 5
203
+ for (let vertical = 0; vertical < size; vertical++)
204
+ for (let j = 0; j < 2; j++) {
205
+ const x = right - j
206
+ const y = ((right + 1) & 2) === 0 ? size - 1 - vertical : vertical
207
+ if (reserved[y][x] || i >= codewords.length * 8) continue
208
+ modules[y][x] = ((codewords[i >>> 3] >>> (7 - (i & 7))) & 1) === 1
209
+ i++
210
+ }
211
+ }
212
+ }
213
+
214
+ function penalty(modules: boolean[][]) {
215
+ const size = modules.length
216
+ const columns = modules.map((_, x) => modules.map((row) => row[x]))
217
+ const lines = [...modules, ...columns].reduce((sum, line) => sum + linePenalty(line), 0)
218
+ // Each 2x2 block of one colour, found from its bottom-right module.
219
+ const boxes = modules
220
+ .slice(1)
221
+ .flatMap((row, y) =>
222
+ row.slice(1).filter((dark, x) => dark === row[x] && dark === modules[y][x] && dark === modules[y][x + 1]),
223
+ ).length
224
+ const dark = modules.flat().filter(Boolean).length
225
+ const total = size * size
226
+ return lines + boxes * 3 + (Math.ceil(Math.abs(dark * 20 - total * 10) / total) - 1) * 10
227
+ }
228
+
229
+ // Scores runs of five or more same-coloured modules, and 1:1:3:1:1 finder-like patterns with 4 light modules on a side.
230
+ function linePenalty(line: boolean[]) {
231
+ const size = line.length
232
+ const history = [0, 0, 0, 0, 0, 0, 0]
233
+ const push = (length: number) => {
234
+ history.pop()
235
+ history.unshift(history[0] === 0 ? length + size : length)
236
+ }
237
+ const finders = () => {
238
+ const n = history[1]
239
+ const core = n > 0 && history[2] === n && history[3] === n * 3 && history[4] === n && history[5] === n
240
+ return (
241
+ (core && history[0] >= n * 4 && history[6] >= n ? 1 : 0) +
242
+ (core && history[6] >= n * 4 && history[0] >= n ? 1 : 0)
243
+ )
244
+ }
245
+ let result = 0
246
+ let color = false
247
+ let run = 0
248
+ for (const dark of line) {
249
+ if (dark === color) {
250
+ run++
251
+ if (run === 5) result += 3
252
+ if (run > 5) result++
253
+ continue
254
+ }
255
+ push(run)
256
+ if (!color) result += finders() * 40
257
+ color = dark
258
+ run = 1
259
+ }
260
+ if (color) {
261
+ push(run)
262
+ run = 0
263
+ }
264
+ push(run + size)
265
+ return result + finders() * 40
266
+ }
267
+
268
+ function reedSolomonDivisor(degree: number) {
269
+ const result = Array<number>(degree).fill(0)
270
+ result[degree - 1] = 1
271
+ let root = 1
272
+ for (let i = 0; i < degree; i++) {
273
+ for (let j = 0; j < degree; j++) {
274
+ result[j] = multiply(result[j], root)
275
+ if (j + 1 < degree) result[j] ^= result[j + 1]
276
+ }
277
+ root = multiply(root, 2)
278
+ }
279
+ return result
280
+ }
281
+
282
+ function reedSolomonRemainder(data: number[], divisor: number[]) {
283
+ return data.reduce(
284
+ (remainder, byte) => {
285
+ const factor = byte ^ remainder[0]
286
+ return [...remainder.slice(1), 0].map((value, i) => value ^ multiply(divisor[i], factor))
287
+ },
288
+ divisor.map(() => 0),
289
+ )
290
+ }
291
+
292
+ // Multiplies in GF(2^8) modulo x^8 + x^4 + x^3 + x^2 + 1.
293
+ function multiply(x: number, y: number) {
294
+ let z = 0
295
+ for (let i = 7; i >= 0; i--) {
296
+ z = (z << 1) ^ ((z >>> 7) * 0x11d)
297
+ z ^= ((y >>> i) & 1) * x
298
+ }
299
+ return z
300
+ }
301
+
302
+ function rawModules(version: number) {
303
+ const base = (16 * version + 128) * version + 64
304
+ if (version < 2) return base
305
+ const count = Math.floor(version / 7) + 2
306
+ return base - ((25 * count - 10) * count - 55) - (version >= 7 ? 36 : 0)
307
+ }
308
+
309
+ function dataCapacity(version: number) {
310
+ return Math.floor(rawModules(version) / 8) - ECC_PER_BLOCK[version - 1] * BLOCKS[version - 1]
311
+ }
312
+
313
+ function addBorder(modules: boolean[][], border: number) {
314
+ const width = modules.length + border * 2
315
+ const blank = () => Array<boolean>(width).fill(false)
316
+ const edge = Array.from({ length: border }, blank)
317
+ const padding = Array<boolean>(border).fill(false)
318
+ return [...edge, ...modules.map((row) => [...padding, ...row, ...padding]), ...Array.from({ length: border }, blank)]
319
+ }
320
+
321
+ function escapeAttribute(value: string) {
322
+ return value.replaceAll("&", "&amp;").replaceAll('"', "&quot;").replaceAll("<", "&lt;").replaceAll(">", "&gt;")
323
+ }
package/src/record.ts CHANGED
@@ -1,3 +1,3 @@
1
- /** Plain-record narrowing. Excludes arrays so JSON object checks don't accept tuples as key/value bags. */
2
- export const isRecord = (value: unknown): value is Record<string, unknown> =>
3
- typeof value === "object" && value !== null && !Array.isArray(value)
1
+ /** Plain-record narrowing. Excludes arrays so JSON object checks don't accept tuples as key/value bags. */
2
+ export const isRecord = (value: unknown): value is Record<string, unknown> =>
3
+ typeof value === "object" && value !== null && !Array.isArray(value)