qrcat 0.0.0-stage → 0.0.2

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 (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +136 -2
  3. package/bin/qrcat.js +308 -0
  4. package/package.json +38 -4
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 Joan Miquel Torres Rigo <joanmi@gmail.com>
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,137 @@
1
- # Temporary Holding Version
1
+ qrcat - Add QR codes for urls in your terminal output
2
+ -----------------------------------------------------
2
3
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
4
+
5
+ qrcat is a terminal filter that detects URLs in your terminal output and generates additional rows with QR codes for those URLs. This allows you to easily scan the QR codes with your phone or other device to quickly access the URLs.
6
+
7
+ **Example:**
8
+
9
+ ```bash
10
+ $ # Login to npm in your computer by scanning a QR code with your phone
11
+ $ npm login | qrcat
12
+
13
+ $ # Or let qrcat run the command in a pseudo-terminal for you
14
+ $ qrcat -c "npm publish"
15
+ ```
16
+
17
+ > **Note:** some interactive commands do not work with a simple pipe and need
18
+ > special redirection or a pseudo-terminal. Use `qrcat -c <command>` for such
19
+ > cases instead. See
20
+ > [Interactive commands and output streams](#interactive-commands-and-output-streams)
21
+ > for more information.
22
+
23
+ ## Install
24
+
25
+ ```bash
26
+ npm install -g qrcat
27
+ ```
28
+
29
+ ## Usage
30
+
31
+ Pipe any command through `qrcat` or use `qrcat -c` for interactive commands.
32
+ Each line is echoed unchanged; after any line containing an `http(s)` URL, one
33
+ QR code per URL is printed directly below it. Multiple URLs on one line each
34
+ get their own QR code.
35
+
36
+ ```bash
37
+ command | qrcat
38
+ qrcat -c "command"
39
+ qrcat --help
40
+ qrcat --version
41
+ ```
42
+
43
+ ### Interactive commands and output streams
44
+
45
+ qrcat reads **stdin only**, and a plain `|` only pipes the command's stdout.
46
+ Interactive commands are trickier: they may write URLs to different streams,
47
+ and redirecting their output can change how they behave (for example, npm only
48
+ runs its interactive web-auth flow when stdout is a TTY).
49
+
50
+ The recommended way to run them is `-c`, which executes the command inside a
51
+ pseudo-terminal and processes its output directly (requires the util-linux
52
+ `script` utility, present on most GNU/Linux systems):
53
+
54
+ ```bash
55
+ qrcat -c "npm publish"
56
+ ```
57
+
58
+ qrcat keeps the command's TTY checks intact, prints QR codes for its output as
59
+ it arrives, and restores your terminal settings when the command exits or is
60
+ interrupted, so Ctrl+C is safe.
61
+
62
+ For non-interactive commands, ordinary pipes or process substitution are
63
+ simpler; choose the stream(s) that actually contain the URLs. If `-c` is not
64
+ available or does not fit your case, the
65
+ [Appendix](#appendix-manual-workarounds-for-interactive-commands) explains what
66
+ `-c` does and provides equivalent manual commands.
67
+
68
+ ### Output handling notes
69
+
70
+ qrcat emits newline-terminated lines as soon as they arrive. It also flushes an
71
+ unterminated line after 100 ms of input inactivity, which supports interactive
72
+ prompts that write partial lines. This idle flush may split a line if a program
73
+ pauses for longer than 100 ms while writing it.
74
+
75
+ ANSI colour codes are stripped before URL detection, so coloured output works,
76
+ including URLs split by colour sequences and OSC 8 hyperlinks.
77
+
78
+ QR codes are drawn with Unicode half-block characters and 24-bit ANSI colour, so
79
+ they need a terminal with truecolor and `▀` support.
80
+
81
+ ## Development
82
+
83
+ ```bash
84
+ npm install
85
+ npm test # node:test suite
86
+ npm link . # Install locally for testing in your terminal
87
+ ```
88
+
89
+ ## Appendix: manual workarounds for interactive commands
90
+
91
+ `qrcat -c "cmd"` is roughly equivalent to wrapping the command with util-linux
92
+ `script` and piping it through qrcat:
93
+
94
+ ```bash
95
+ (
96
+ trap 'stty sane' EXIT
97
+ script -qefc 'cmd' /dev/null | qrcat
98
+ )
99
+ ```
100
+
101
+ `script` runs the command inside a pseudo-terminal, so the command keeps its
102
+ TTYs while its combined stdout and stderr flow into qrcat.
103
+
104
+ The `trap` restores the outer terminal settings because interrupting `script`
105
+ with Ctrl+C can leave them in raw mode: you may stop seeing typed input, and
106
+ Ctrl+C may no longer interrupt the next command. Recover manually with:
107
+
108
+ ```bash
109
+ stty sane
110
+ ```
111
+
112
+ If you prefer to capture a single stream, process substitution connects it to
113
+ qrcat without touching the other one:
114
+
115
+ ```bash
116
+ some-command 2> >(qrcat) # capture stderr only
117
+ some-command > >(qrcat) # capture stdout only
118
+ ```
119
+
120
+ Beware that a plain `|` only pipes stdout, and `some-command 2>&1 | qrcat`
121
+ merges both streams into a pipe. Interactive commands can behave differently
122
+ when their stdout is not a TTY: npm, for instance, exits with `EOTP` instead of
123
+ starting its web-auth flow.
124
+
125
+ Platform notes:
126
+
127
+ - Process substitution (`> >(qrcat)`) requires bash or zsh; it is not POSIX `sh`.
128
+ - The `script -qefc` flags used by `-c` are util-linux's (GNU/Linux). BSD/macOS
129
+ `script` uses different flags, so `-c` is currently GNU/Linux-oriented.
130
+
131
+ ## License
132
+
133
+ [MIT](LICENSE)
134
+
135
+ ## Keywords
136
+
137
+ filter – cat – url – cli – terminal
package/bin/qrcat.js ADDED
@@ -0,0 +1,308 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { readFileSync, realpathSync } from 'node:fs';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { spawn, execFileSync } from 'node:child_process';
6
+ import QRCode from 'qrcode';
7
+
8
+ const RESET = '\x1b[0m';
9
+ const FG_DARK = '\x1b[38;2;0;0;0m';
10
+ const FG_LIGHT = '\x1b[38;2;255;255;255m';
11
+ const BG_DARK = '\x1b[48;2;0;0;0m';
12
+ const BG_LIGHT = '\x1b[48;2;255;255;255m';
13
+
14
+ // CSI, OSC (BEL or ST terminated), other single-byte escapes, and C1 CSI.
15
+ const ANSI_RE = /\x1b(?:\[[0-?]*[ -/]*[@-~]|\][^\x07\x1b]*(?:\x07|\x1b\\)|[()#][\x20-\x7e]|[@-_])|\x9b[0-?]*[ -/]*[@-~]/g;
16
+ const URL_RE = /https?:\/\/[^\s<>"'`\x1b]+/gi;
17
+ const TRAILING_PUNCT_RE = /[.,;:!?)\]}'">]+$/;
18
+
19
+ const DEFAULT_OPTIONS = { errorCorrectionLevel: 'M', quietZone: 4 };
20
+ const IDLE_FLUSH_MS = 100;
21
+
22
+ /** Remove terminal escape sequences (colours, OSC 8 links, etc.). */
23
+ export function stripAnsi(text) {
24
+ return text.replace(ANSI_RE, '');
25
+ }
26
+
27
+ function extractUrls(text) {
28
+ const urls = new Set();
29
+ for (const match of text.matchAll(URL_RE)) {
30
+ const url = match[0].replace(TRAILING_PUNCT_RE, '');
31
+ if (url) urls.add(url);
32
+ }
33
+ return urls;
34
+ }
35
+
36
+ /**
37
+ * Extract unique http(s) URLs from a line, trimming adjacent punctuation.
38
+ * The stripped copy handles URLs split by colour codes; the raw copy keeps
39
+ * URLs that only exist inside OSC 8 hyperlinks. Raw fragments that are just a
40
+ * prefix of a complete stripped URL are discarded.
41
+ */
42
+ export function findUrls(text) {
43
+ const stripped = extractUrls(stripAnsi(text));
44
+ const urls = new Set(stripped);
45
+ for (const url of extractUrls(text)) {
46
+ const isFragment = [...stripped].some((full) => full.length > url.length && full.startsWith(url));
47
+ if (!isFragment) urls.add(url);
48
+ }
49
+ return [...urls];
50
+ }
51
+
52
+ /**
53
+ * Render a URL as a QR using Unicode upper-half blocks: the foreground colour
54
+ * is the top module, the background colour the bottom one. Two module rows are
55
+ * packed into each terminal row, which keeps the code roughly square.
56
+ */
57
+ export function renderQr(url, options = {}) {
58
+ const { errorCorrectionLevel, quietZone } = { ...DEFAULT_OPTIONS, ...options };
59
+ const qr = QRCode.create(url, { errorCorrectionLevel });
60
+ const size = qr.modules.size + 2 * quietZone;
61
+
62
+ const isDark = (row, col) => {
63
+ const r = row - quietZone;
64
+ const c = col - quietZone;
65
+ if (r < 0 || c < 0 || r >= qr.modules.size || c >= qr.modules.size) return false;
66
+ return qr.modules.get(r, c) === 1;
67
+ };
68
+
69
+ const lines = [];
70
+ for (let row = 0; row < size; row += 2) {
71
+ let line = '';
72
+ for (let col = 0; col < size; col++) {
73
+ const top = isDark(row, col);
74
+ const bottom = row + 1 < size ? isDark(row + 1, col) : false;
75
+ line += (top ? FG_DARK : FG_LIGHT) + (bottom ? BG_DARK : BG_LIGHT) + '▀';
76
+ }
77
+ lines.push(line + RESET);
78
+ }
79
+ return lines.join('\n');
80
+ }
81
+
82
+ /** Full output block for one input line: the original line, then a QR per URL. */
83
+ export function formatLine(line, options = {}) {
84
+ const urls = findUrls(line);
85
+ if (urls.length === 0) return line;
86
+ const blocks = urls.map((url) => `\n\n${renderQr(url, options)}`);
87
+ return line + blocks.join('') + '\n';
88
+ }
89
+
90
+ /**
91
+ * Process input as it arrives. Complete lines are emitted immediately; an
92
+ * unterminated line is emitted after a short idle period so interactive tools
93
+ * that write a URL without a final newline can still produce a QR promptly.
94
+ */
95
+ export function processInput(input, output = process.stdout, idleFlushMs = IDLE_FLUSH_MS) {
96
+ input.setEncoding('utf8');
97
+
98
+ return new Promise((resolve, reject) => {
99
+ let pending = '';
100
+ let timer;
101
+ let previousWasCR = false;
102
+ let skipNextDelimiter = false;
103
+
104
+ const clearTimer = () => {
105
+ if (timer) clearTimeout(timer);
106
+ timer = undefined;
107
+ };
108
+
109
+ const lineEnding = output.isTTY ? '\r\n' : '\n';
110
+ const emitLine = (line) =>
111
+ output.write((formatLine(line) + '\n').replace(/\n/g, lineEnding));
112
+
113
+ const onError = (error) => {
114
+ clearTimer();
115
+ reject(error);
116
+ };
117
+
118
+ const flushIdle = () => {
119
+ timer = undefined;
120
+ if (!pending) return;
121
+ try {
122
+ emitLine(pending);
123
+ pending = '';
124
+ // The idle flush supplies the line ending; don't emit an extra empty
125
+ // line if the input's actual delimiter arrives later.
126
+ skipNextDelimiter = true;
127
+ } catch (error) {
128
+ onError(error);
129
+ }
130
+ };
131
+
132
+ const onData = (chunk) => {
133
+ clearTimer();
134
+ try {
135
+ for (const char of chunk) {
136
+ if (char === '\n' && previousWasCR) {
137
+ previousWasCR = false;
138
+ continue;
139
+ }
140
+
141
+ previousWasCR = false;
142
+ if (char === '\n' || char === '\r') {
143
+ if (skipNextDelimiter) {
144
+ skipNextDelimiter = false;
145
+ } else {
146
+ emitLine(pending);
147
+ pending = '';
148
+ }
149
+ previousWasCR = char === '\r';
150
+ continue;
151
+ }
152
+
153
+ skipNextDelimiter = false;
154
+ pending += char;
155
+ }
156
+
157
+ if (pending) timer = setTimeout(flushIdle, idleFlushMs);
158
+ } catch (error) {
159
+ onError(error);
160
+ }
161
+ };
162
+
163
+ const onEnd = () => {
164
+ clearTimer();
165
+ try {
166
+ if (pending) emitLine(pending);
167
+ resolve();
168
+ } catch (error) {
169
+ reject(error);
170
+ }
171
+ };
172
+
173
+ input.on('data', onData);
174
+ input.once('end', onEnd);
175
+ input.once('error', onError);
176
+ });
177
+ }
178
+
179
+ function printHelp() {
180
+ process.stdout.write(
181
+ 'qrcat - add QR codes for URLs in terminal output\n\n' +
182
+ 'Usage: command | qrcat\n' +
183
+ ' qrcat -c "command"\n\n' +
184
+ 'qrcat reads the output of a command and prints a scannable QR code for\n' +
185
+ 'every http(s) URL it finds, so you can open the URL with your phone\n' +
186
+ 'instead of copying it by hand:\n\n' +
187
+ ' $ npm login | qrcat\n\n' +
188
+ 'Some interactive commands do not work "as is" and need special\n' +
189
+ 'redirection or a pseudo-terminal. With -c, qrcat runs the command in a\n' +
190
+ 'pseudo-terminal for you and prints its QR codes directly:\n\n' +
191
+ ' $ qrcat -c "npm publish"\n\n' +
192
+ 'Check the docs for details:\n\n' +
193
+ ' https://www.npmjs.com/package/qrcat\n\n' +
194
+ 'Tip: run `qrcat --help | qrcat` and get a QR code to the docs.\n\n' +
195
+ 'Options:\n' +
196
+ ' -c, --command run the given command in a pseudo-terminal and process\n' +
197
+ ' its output (requires the `script` utility)\n' +
198
+ ' -h, --help show this help\n' +
199
+ ' -v, --version show version\n',
200
+ );
201
+ }
202
+
203
+ /**
204
+ * Run `command` inside a pseudo-terminal (via the `script` utility) so the
205
+ * command keeps its TTY while qrcat processes its combined output, and restore
206
+ * the outer terminal settings on the way out (util-linux `script` can leave
207
+ * them in raw mode when interrupted).
208
+ */
209
+ async function runCommand(command) {
210
+ let savedTermios = null;
211
+ if (process.stdin.isTTY) {
212
+ try {
213
+ savedTermios = execFileSync('stty', ['-g'], {
214
+ stdio: ['ignore', 'pipe', 'ignore'],
215
+ encoding: 'utf8',
216
+ }).trim();
217
+ } catch {
218
+ savedTermios = null; // best effort: fall back to `stty sane` below
219
+ }
220
+ }
221
+
222
+ const restore = () => {
223
+ if (!process.stdin.isTTY) return;
224
+ try {
225
+ execFileSync('stty', [savedTermios ?? 'sane'], { stdio: ['ignore', 'ignore', 'ignore'] });
226
+ } catch {
227
+ // Nothing sensible left to try; the outer shell can still `stty sane`.
228
+ }
229
+ };
230
+
231
+ const child = spawn('script', ['-qefc', command, '/dev/null'], {
232
+ stdio: ['inherit', 'pipe', 'inherit'],
233
+ });
234
+
235
+ let childError = null;
236
+ child.on('error', (error) => {
237
+ childError = error;
238
+ });
239
+
240
+ const onSignal = (signal) => {
241
+ child.kill(signal);
242
+ };
243
+ process.on('SIGINT', onSignal);
244
+ process.on('SIGTERM', onSignal);
245
+
246
+ try {
247
+ await processInput(child.stdout);
248
+ } finally {
249
+ process.off('SIGINT', onSignal);
250
+ process.off('SIGTERM', onSignal);
251
+ restore();
252
+ }
253
+
254
+ const exitCode = await new Promise((resolve) => {
255
+ if (childError) return resolve(null);
256
+ child.on('close', (code) => resolve(code));
257
+ });
258
+ if (childError) throw childError;
259
+ if (exitCode !== 0) process.exitCode = exitCode ?? 1;
260
+ }
261
+
262
+ async function main() {
263
+ const args = process.argv.slice(2);
264
+ if (args.includes('-h') || args.includes('--help')) {
265
+ printHelp();
266
+ return;
267
+ }
268
+ if (args.includes('-v') || args.includes('--version')) {
269
+ const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
270
+ process.stdout.write(`${pkg.version}\n`);
271
+ return;
272
+ }
273
+
274
+ process.stdout.on('error', (err) => {
275
+ if (err.code === 'EPIPE') process.exit(0);
276
+ throw err;
277
+ });
278
+
279
+ const commandIndex = args.findIndex((arg) => arg === '-c' || arg === '--command');
280
+ if (commandIndex !== -1) {
281
+ const command = args[commandIndex + 1];
282
+ if (!command || command.startsWith('-')) {
283
+ process.stderr.write('qrcat: -c/--command requires a command string\n');
284
+ process.exitCode = 1;
285
+ return;
286
+ }
287
+ await runCommand(command);
288
+ return;
289
+ }
290
+
291
+ await processInput(process.stdin);
292
+ }
293
+
294
+ function isMainModule() {
295
+ if (!process.argv[1]) return false;
296
+ try {
297
+ return realpathSync(process.argv[1]) === fileURLToPath(import.meta.url);
298
+ } catch {
299
+ return false;
300
+ }
301
+ }
302
+
303
+ if (isMainModule()) {
304
+ main().catch((err) => {
305
+ process.stderr.write(`qrcat: ${err.message}\n`);
306
+ process.exitCode = 1;
307
+ });
308
+ }
package/package.json CHANGED
@@ -1,6 +1,40 @@
1
1
  {
2
2
  "name": "qrcat",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.2",
4
+ "description": "Output filter to add QR codes to URLs",
5
+ "keywords": [
6
+ "QR",
7
+ "filter",
8
+ "cat",
9
+ "url",
10
+ "cli",
11
+ "terminal"
12
+ ],
13
+ "homepage": "https://github.com/bitifet/qrcat#readme",
14
+ "bugs": {
15
+ "url": "https://github.com/bitifet/qrcat/issues"
16
+ },
17
+ "repository": {
18
+ "type": "git",
19
+ "url": "git+https://github.com/bitifet/qrcat.git"
20
+ },
21
+ "license": "MIT",
22
+ "author": "Joan Miquel Torres <joanmi@gmail.com>",
23
+ "type": "module",
24
+ "main": "bin/qrcat.js",
25
+ "bin": {
26
+ "qrcat": "bin/qrcat.js"
27
+ },
28
+ "files": [
29
+ "bin"
30
+ ],
31
+ "engines": {
32
+ "node": ">=18"
33
+ },
34
+ "scripts": {
35
+ "test": "node --test"
36
+ },
37
+ "dependencies": {
38
+ "qrcode": "1.5.4"
39
+ }
40
+ }