@headwall/websnapper-cli 0.0.0-stage → 1.0.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.
- package/CHANGELOG.md +54 -0
- package/LICENSE +21 -0
- package/README.md +47 -2
- package/bin/wsnap +3 -0
- package/dist/args.js +85 -0
- package/dist/cli.js +189 -0
- package/dist/command.js +2 -0
- package/dist/commands/capture.js +357 -0
- package/dist/commands/host.js +173 -0
- package/dist/commands/status.js +90 -0
- package/dist/commands/viewports.js +39 -0
- package/dist/config/env.js +102 -0
- package/dist/config/store.js +267 -0
- package/dist/exit-codes.js +17 -0
- package/dist/failover.js +91 -0
- package/dist/hosts.js +84 -0
- package/dist/http/classify.js +120 -0
- package/dist/http/request.js +99 -0
- package/dist/http/websnapper.js +152 -0
- package/dist/logger.js +24 -0
- package/dist/output.js +38 -0
- package/dist/prompt.js +101 -0
- package/dist/results.js +35 -0
- package/package.json +54 -4
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
export const ERROR_HEADER = 'x-websnapper-error';
|
|
2
|
+
const UPSTREAM_STATUS_HEADER = 'x-websnapper-upstream-status';
|
|
3
|
+
const RETRY_AFTER_HEADER = 'retry-after';
|
|
4
|
+
const STATUS_OK = 200;
|
|
5
|
+
export const BODY_INTERRUPTED_DETAIL = 'body_interrupted';
|
|
6
|
+
/** Server codes reported as the --json error: the target failed (exit 2) or the request was refused (exit 3). */
|
|
7
|
+
export const TARGET_FAILED_CODES = ['upstream_error', 'upstream_timeout'];
|
|
8
|
+
export const REFUSED_CODES = ['invalid_request', 'url_blocked'];
|
|
9
|
+
/** Every outcome kind, checked complete by the type. */
|
|
10
|
+
const OUTCOME_KIND_SET = {
|
|
11
|
+
success: true, unreachable: true, unhealthy: true, bad_key: true, rate_limited: true, busy: true, target_failed: true, refused: true,
|
|
12
|
+
};
|
|
13
|
+
export const OUTCOME_KINDS = Object.keys(OUTCOME_KIND_SET);
|
|
14
|
+
const EXPECTED_MEDIA_TYPES = {
|
|
15
|
+
image: ['image/png', 'image/jpeg', 'image/webp'],
|
|
16
|
+
json: ['application/json'],
|
|
17
|
+
text: ['text/plain'],
|
|
18
|
+
};
|
|
19
|
+
/** Outcomes that send a capture on to the next host. */
|
|
20
|
+
const FAILOVER_KINDS = ['unreachable', 'unhealthy', 'bad_key', 'rate_limited', 'busy'];
|
|
21
|
+
/** Reads a single header value, taking the first when repeated. */
|
|
22
|
+
function headerValue(headers, name) {
|
|
23
|
+
const value = headers[name];
|
|
24
|
+
return Array.isArray(value) ? value[0] : value;
|
|
25
|
+
}
|
|
26
|
+
/** Parses a whole number of seconds, or undefined. */
|
|
27
|
+
function wholeNumber(value) {
|
|
28
|
+
const parsed = value === undefined ? Number.NaN : Number(value.trim());
|
|
29
|
+
return Number.isInteger(parsed) && parsed >= 0 ? parsed : undefined;
|
|
30
|
+
}
|
|
31
|
+
/** The media type of a Content-Type header, lower-cased, without parameters. */
|
|
32
|
+
export function mediaType(headers) {
|
|
33
|
+
return (headerValue(headers, 'content-type') ?? '').split(';')[0]?.trim().toLowerCase() ?? '';
|
|
34
|
+
}
|
|
35
|
+
/** Classifies a response by its status and headers alone. */
|
|
36
|
+
export function classifyResponse(status, headers, expected) {
|
|
37
|
+
const errorCode = headerValue(headers, ERROR_HEADER);
|
|
38
|
+
const retryAfter = wholeNumber(headerValue(headers, RETRY_AFTER_HEADER));
|
|
39
|
+
const retry = retryAfter === undefined ? {} : { retryAfter };
|
|
40
|
+
let outcome;
|
|
41
|
+
if (status === STATUS_OK && EXPECTED_MEDIA_TYPES[expected].includes(mediaType(headers))) {
|
|
42
|
+
outcome = { kind: 'success' };
|
|
43
|
+
}
|
|
44
|
+
else if (status === STATUS_OK) {
|
|
45
|
+
outcome = { kind: 'unhealthy', detail: `200 with Content-Type "${mediaType(headers)}"` };
|
|
46
|
+
}
|
|
47
|
+
else if (errorCode === undefined) {
|
|
48
|
+
// Not from websnapper: a proxy whose backend is down, a captive portal, another server.
|
|
49
|
+
outcome = { kind: 'unhealthy', detail: `HTTP ${status} without ${ERROR_HEADER}` };
|
|
50
|
+
}
|
|
51
|
+
else if (errorCode === 'unauthorised') {
|
|
52
|
+
outcome = { kind: 'bad_key' };
|
|
53
|
+
}
|
|
54
|
+
else if (errorCode === 'rate_limited') {
|
|
55
|
+
outcome = { kind: 'rate_limited', ...retry };
|
|
56
|
+
}
|
|
57
|
+
else if (errorCode === 'unavailable') {
|
|
58
|
+
outcome = { kind: 'busy', ...retry };
|
|
59
|
+
}
|
|
60
|
+
else if (TARGET_FAILED_CODES.includes(errorCode)) {
|
|
61
|
+
const upstreamStatus = wholeNumber(headerValue(headers, UPSTREAM_STATUS_HEADER));
|
|
62
|
+
outcome = { kind: 'target_failed', error: errorCode, ...(upstreamStatus === undefined ? {} : { upstreamStatus }) };
|
|
63
|
+
}
|
|
64
|
+
else if (REFUSED_CODES.includes(errorCode)) {
|
|
65
|
+
outcome = { kind: 'refused', error: errorCode };
|
|
66
|
+
}
|
|
67
|
+
else if (errorCode === 'not_found' || errorCode === 'method_not_allowed') {
|
|
68
|
+
outcome = { kind: 'unhealthy', detail: `${errorCode}: check the host's URL and path prefix` };
|
|
69
|
+
}
|
|
70
|
+
else {
|
|
71
|
+
outcome = { kind: 'unhealthy', detail: `HTTP ${status} ${errorCode}` };
|
|
72
|
+
}
|
|
73
|
+
return outcome;
|
|
74
|
+
}
|
|
75
|
+
/** Classifies a request that failed before or during the response. */
|
|
76
|
+
export function classifyNetworkError(error, duringBody) {
|
|
77
|
+
return { kind: 'unreachable', detail: duringBody ? `${BODY_INTERRUPTED_DETAIL}: ${error.detail}` : error.detail };
|
|
78
|
+
}
|
|
79
|
+
/** True when the outcome is a host problem, so a capture tries the next host. */
|
|
80
|
+
export function isFailover(outcome) {
|
|
81
|
+
return FAILOVER_KINDS.includes(outcome.kind);
|
|
82
|
+
}
|
|
83
|
+
/** The text of the first <p> in a websnapper error page, unescaped. */
|
|
84
|
+
export function errorPageMessage(html) {
|
|
85
|
+
const match = /<p>([\s\S]*?)<\/p>/i.exec(html);
|
|
86
|
+
return match?.[1]
|
|
87
|
+
?.replace(/</g, '<')
|
|
88
|
+
.replace(/>/g, '>')
|
|
89
|
+
.replace(/"/g, '"')
|
|
90
|
+
.replace(/'/g, '\'')
|
|
91
|
+
.replace(/&/g, '&')
|
|
92
|
+
.replace(/\s+/g, ' ')
|
|
93
|
+
.trim();
|
|
94
|
+
}
|
|
95
|
+
/** A short human description: "online", "busy (retry after 5 s)", "unreachable (ECONNREFUSED)". */
|
|
96
|
+
export function describeOutcome(outcome) {
|
|
97
|
+
const retry = 'retryAfter' in outcome && outcome.retryAfter !== undefined ? ` (retry after ${outcome.retryAfter} s)` : '';
|
|
98
|
+
const descriptions = {
|
|
99
|
+
success: 'online',
|
|
100
|
+
unreachable: `unreachable (${'detail' in outcome ? outcome.detail : ''})`,
|
|
101
|
+
unhealthy: `unhealthy (${'detail' in outcome ? outcome.detail : ''})`,
|
|
102
|
+
bad_key: 'bad key',
|
|
103
|
+
rate_limited: `rate limited${retry}`,
|
|
104
|
+
busy: `busy${retry}`,
|
|
105
|
+
target_failed: 'target failed',
|
|
106
|
+
refused: 'refused',
|
|
107
|
+
};
|
|
108
|
+
return descriptions[outcome.kind];
|
|
109
|
+
}
|
|
110
|
+
/** The optional fields of an outcome, for --json output. */
|
|
111
|
+
export function outcomeFields(outcome) {
|
|
112
|
+
const fields = {
|
|
113
|
+
detail: 'detail' in outcome ? outcome.detail : undefined,
|
|
114
|
+
retryAfter: 'retryAfter' in outcome ? outcome.retryAfter : undefined,
|
|
115
|
+
upstreamStatus: 'upstreamStatus' in outcome ? outcome.upstreamStatus : undefined,
|
|
116
|
+
message: 'message' in outcome ? outcome.message : undefined,
|
|
117
|
+
};
|
|
118
|
+
return Object.fromEntries(Object.entries(fields).filter((entry) => entry[1] !== undefined));
|
|
119
|
+
}
|
|
120
|
+
//# sourceMappingURL=classify.js.map
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import http, {} from 'node:http';
|
|
2
|
+
import https from 'node:https';
|
|
3
|
+
/** A request that failed at the network level. detail is an errno code (ECONNREFUSED), connect_timeout or timeout. */
|
|
4
|
+
export class NetworkError extends Error {
|
|
5
|
+
detail;
|
|
6
|
+
constructor(detail, message, options) {
|
|
7
|
+
super(message, options);
|
|
8
|
+
this.name = 'NetworkError';
|
|
9
|
+
this.detail = detail;
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
export const CONNECT_TIMEOUT_DETAIL = 'connect_timeout';
|
|
13
|
+
export const TIMEOUT_DETAIL = 'timeout';
|
|
14
|
+
export const INTERRUPTED_DETAIL = 'interrupted';
|
|
15
|
+
const FALLBACK_DETAIL = 'network_error';
|
|
16
|
+
/** Wraps any error from the socket or stream as a NetworkError, keeping one that already is. */
|
|
17
|
+
export function toNetworkError(error) {
|
|
18
|
+
const code = error.code;
|
|
19
|
+
return error instanceof NetworkError
|
|
20
|
+
? error
|
|
21
|
+
: new NetworkError(code ?? FALLBACK_DETAIL, error.message, { cause: error });
|
|
22
|
+
}
|
|
23
|
+
/** GETs a URL with a connect timeout and an overall timeout. Resolves at the headers; rejects with NetworkError. */
|
|
24
|
+
export function request(options) {
|
|
25
|
+
return new Promise((resolve, reject) => {
|
|
26
|
+
const transport = options.url.protocol === 'https:' ? https : http;
|
|
27
|
+
let response;
|
|
28
|
+
const outgoing = transport.request(options.url, {
|
|
29
|
+
method: 'GET',
|
|
30
|
+
headers: options.headers,
|
|
31
|
+
agent: false,
|
|
32
|
+
...(options.lookup === undefined ? {} : { lookup: options.lookup }),
|
|
33
|
+
}, (incoming) => {
|
|
34
|
+
clearTimeout(connectTimer);
|
|
35
|
+
response = incoming;
|
|
36
|
+
incoming.once('close', finish);
|
|
37
|
+
resolve({ status: incoming.statusCode ?? 0, headers: incoming.headers, body: incoming });
|
|
38
|
+
});
|
|
39
|
+
const connectTimer = setTimeout(() => {
|
|
40
|
+
outgoing.destroy(new NetworkError(CONNECT_TIMEOUT_DETAIL, `No connection within ${options.connectTimeoutMs} ms.`));
|
|
41
|
+
}, options.connectTimeoutMs);
|
|
42
|
+
const overallTimer = setTimeout(() => {
|
|
43
|
+
const error = new NetworkError(TIMEOUT_DETAIL, `No complete response within ${options.timeoutMs} ms.`);
|
|
44
|
+
// After the headers, destroying the response is what makes its body stream fail with this error.
|
|
45
|
+
(response ?? outgoing).destroy(error);
|
|
46
|
+
}, options.timeoutMs);
|
|
47
|
+
const onAbort = () => {
|
|
48
|
+
(response ?? outgoing).destroy(new NetworkError(INTERRUPTED_DETAIL, 'Interrupted.'));
|
|
49
|
+
};
|
|
50
|
+
/** Stops the overall timer and the abort listener once the exchange is over. */
|
|
51
|
+
function finish() {
|
|
52
|
+
clearTimeout(overallTimer);
|
|
53
|
+
options.signal?.removeEventListener('abort', onAbort);
|
|
54
|
+
}
|
|
55
|
+
outgoing.on('socket', (socket) => {
|
|
56
|
+
if (socket.connecting) {
|
|
57
|
+
socket.once('connect', () => clearTimeout(connectTimer));
|
|
58
|
+
}
|
|
59
|
+
else {
|
|
60
|
+
clearTimeout(connectTimer);
|
|
61
|
+
}
|
|
62
|
+
});
|
|
63
|
+
outgoing.on('error', (error) => {
|
|
64
|
+
clearTimeout(connectTimer);
|
|
65
|
+
if (response === undefined) {
|
|
66
|
+
finish();
|
|
67
|
+
}
|
|
68
|
+
// Once resolved, the same error reaches the caller through the body stream instead.
|
|
69
|
+
reject(toNetworkError(error));
|
|
70
|
+
});
|
|
71
|
+
if (options.signal?.aborted === true) {
|
|
72
|
+
onAbort();
|
|
73
|
+
}
|
|
74
|
+
else {
|
|
75
|
+
options.signal?.addEventListener('abort', onAbort, { once: true });
|
|
76
|
+
}
|
|
77
|
+
outgoing.end();
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
/** Reads a body as UTF-8 text, keeping at most limitBytes and destroying the rest. Rejects with NetworkError. */
|
|
81
|
+
export async function readBodyText(body, limitBytes) {
|
|
82
|
+
const chunks = [];
|
|
83
|
+
let totalBytes = 0;
|
|
84
|
+
try {
|
|
85
|
+
for await (const chunk of body) {
|
|
86
|
+
const buffer = chunk;
|
|
87
|
+
chunks.push(buffer.subarray(0, Math.max(0, limitBytes - totalBytes)));
|
|
88
|
+
totalBytes += buffer.length;
|
|
89
|
+
if (totalBytes >= limitBytes) {
|
|
90
|
+
break;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
catch (error) {
|
|
95
|
+
throw toNetworkError(error);
|
|
96
|
+
}
|
|
97
|
+
return Buffer.concat(chunks).toString('utf8');
|
|
98
|
+
}
|
|
99
|
+
//# sourceMappingURL=request.js.map
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import { classifyNetworkError, classifyResponse, ERROR_HEADER, errorPageMessage, mediaType } from './classify.js';
|
|
2
|
+
import { NetworkError, readBodyText, request } from './request.js';
|
|
3
|
+
export const ROUTES = { health: '/health', viewports: '/v1/viewports', snapshot: '/v1/snapshot' };
|
|
4
|
+
const ERROR_BODY_LIMIT_BYTES = 64 * 1024;
|
|
5
|
+
const SMALL_BODY_LIMIT_BYTES = 1024 * 1024;
|
|
6
|
+
const HEALTH_OK_BODY = 'ok';
|
|
7
|
+
const FINAL_URL_HEADER = 'x-websnapper-final-url';
|
|
8
|
+
const UPSTREAM_STATUS_HEADER = 'x-websnapper-upstream-status';
|
|
9
|
+
const RENDER_MS_HEADER = 'x-websnapper-render-ms';
|
|
10
|
+
/** The full URL of a route on a host, keeping the host's path prefix. */
|
|
11
|
+
export function routeUrl(host, route, query) {
|
|
12
|
+
const url = new URL(`${host.url}${route}`);
|
|
13
|
+
if (query !== undefined) {
|
|
14
|
+
url.search = query.toString();
|
|
15
|
+
}
|
|
16
|
+
return url;
|
|
17
|
+
}
|
|
18
|
+
/** Request headers for a host: the bearer key when it has one and the route needs it. */
|
|
19
|
+
export function requestHeaders(host, options, sendKey = true) {
|
|
20
|
+
return {
|
|
21
|
+
'User-Agent': options.userAgent,
|
|
22
|
+
...(host.key === undefined || !sendKey ? {} : { Authorization: `Bearer ${host.key}` }),
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
/** Reads an error page for its message; a page cut off in transit just has none. */
|
|
26
|
+
async function readErrorPage(response) {
|
|
27
|
+
let html = '';
|
|
28
|
+
try {
|
|
29
|
+
html = await readBodyText(response.body, ERROR_BODY_LIMIT_BYTES);
|
|
30
|
+
}
|
|
31
|
+
catch (error) {
|
|
32
|
+
// The status and header already decided the outcome; only the explanation is lost.
|
|
33
|
+
if (!(error instanceof NetworkError)) {
|
|
34
|
+
throw error;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
return html;
|
|
38
|
+
}
|
|
39
|
+
/** Adds the error page's message to an outcome, only when websnapper itself sent the page. */
|
|
40
|
+
function withMessage(outcome, headers, html) {
|
|
41
|
+
const message = headers[ERROR_HEADER] === undefined ? undefined : errorPageMessage(html);
|
|
42
|
+
return message === undefined || outcome.kind === 'success' || outcome.kind === 'unreachable' ? outcome : { ...outcome, message };
|
|
43
|
+
}
|
|
44
|
+
/** GETs a route and classifies it, reading the error page of a failure. Never throws for network failures. */
|
|
45
|
+
async function openRoute(host, route, expected, options, query) {
|
|
46
|
+
let headersReceived = false;
|
|
47
|
+
let result;
|
|
48
|
+
try {
|
|
49
|
+
const response = await request({
|
|
50
|
+
url: routeUrl(host, route, query),
|
|
51
|
+
headers: requestHeaders(host, options, route !== ROUTES.health),
|
|
52
|
+
connectTimeoutMs: options.connectTimeoutMs,
|
|
53
|
+
timeoutMs: options.timeoutMs,
|
|
54
|
+
...(options.lookup === undefined ? {} : { lookup: options.lookup }),
|
|
55
|
+
...(options.signal === undefined ? {} : { signal: options.signal }),
|
|
56
|
+
});
|
|
57
|
+
headersReceived = true;
|
|
58
|
+
const outcome = classifyResponse(response.status, response.headers, expected);
|
|
59
|
+
result = outcome.kind === 'success'
|
|
60
|
+
? { outcome, response }
|
|
61
|
+
: { outcome: withMessage(outcome, response.headers, await readErrorPage(response)) };
|
|
62
|
+
}
|
|
63
|
+
catch (error) {
|
|
64
|
+
if (!(error instanceof NetworkError)) {
|
|
65
|
+
throw error;
|
|
66
|
+
}
|
|
67
|
+
result = { outcome: classifyNetworkError(error, headersReceived) };
|
|
68
|
+
}
|
|
69
|
+
return result;
|
|
70
|
+
}
|
|
71
|
+
/** GETs a small route on a host, classifies it and reads its body. Never throws for network failures. */
|
|
72
|
+
export async function getRoute(host, route, expected, options) {
|
|
73
|
+
const opened = await openRoute(host, route, expected, options);
|
|
74
|
+
let result = { outcome: opened.outcome };
|
|
75
|
+
if (opened.response !== undefined) {
|
|
76
|
+
try {
|
|
77
|
+
result = { outcome: opened.outcome, body: await readBodyText(opened.response.body, SMALL_BODY_LIMIT_BYTES) };
|
|
78
|
+
}
|
|
79
|
+
catch (error) {
|
|
80
|
+
if (!(error instanceof NetworkError)) {
|
|
81
|
+
throw error;
|
|
82
|
+
}
|
|
83
|
+
result = { outcome: classifyNetworkError(error, true) };
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
return result;
|
|
87
|
+
}
|
|
88
|
+
/** Requests a screenshot. On success the image body is left unread, to be streamed by the caller. */
|
|
89
|
+
export function openSnapshot(host, query, options) {
|
|
90
|
+
return openRoute(host, ROUTES.snapshot, 'image', options, query);
|
|
91
|
+
}
|
|
92
|
+
/** Reads the X-Websnapper-* success headers and the image type. */
|
|
93
|
+
export function snapshotMetadata(headers) {
|
|
94
|
+
const text = (name) => {
|
|
95
|
+
const value = headers[name];
|
|
96
|
+
return Array.isArray(value) ? value[0] : value;
|
|
97
|
+
};
|
|
98
|
+
const integer = (name) => {
|
|
99
|
+
const value = Number(text(name));
|
|
100
|
+
return text(name) !== undefined && Number.isInteger(value) ? value : undefined;
|
|
101
|
+
};
|
|
102
|
+
const finalUrl = text(FINAL_URL_HEADER);
|
|
103
|
+
const upstreamStatus = integer(UPSTREAM_STATUS_HEADER);
|
|
104
|
+
const renderMs = integer(RENDER_MS_HEADER);
|
|
105
|
+
return {
|
|
106
|
+
contentType: mediaType(headers),
|
|
107
|
+
...(finalUrl === undefined ? {} : { finalUrl }),
|
|
108
|
+
...(upstreamStatus === undefined ? {} : { upstreamStatus }),
|
|
109
|
+
...(renderMs === undefined ? {} : { renderMs }),
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
/** Checks /health: success only for 200 "ok". */
|
|
113
|
+
export async function checkHealth(host, options) {
|
|
114
|
+
const { outcome, body } = await getRoute(host, ROUTES.health, 'text', options);
|
|
115
|
+
return outcome.kind === 'success' && body?.trim() !== HEALTH_OK_BODY
|
|
116
|
+
? { kind: 'unhealthy', detail: `/health answered 200 "${body?.replace(/\s+/g, ' ').trim().slice(0, 40)}"` }
|
|
117
|
+
: outcome;
|
|
118
|
+
}
|
|
119
|
+
/** True for a parsed /v1/viewports body. */
|
|
120
|
+
function isViewportList(value) {
|
|
121
|
+
const viewports = value?.viewports;
|
|
122
|
+
return Array.isArray(viewports) && viewports.every((viewport) => {
|
|
123
|
+
const entry = viewport;
|
|
124
|
+
return typeof entry?.slug === 'string' && typeof entry.label === 'string' && typeof entry.width === 'number' && typeof entry.height === 'number';
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
/** Parses a /v1/viewports body; a body that isn't a viewport list makes the host unhealthy. */
|
|
128
|
+
function parseViewports(body) {
|
|
129
|
+
let result;
|
|
130
|
+
try {
|
|
131
|
+
const parsed = JSON.parse(body);
|
|
132
|
+
result = isViewportList(parsed)
|
|
133
|
+
? { outcome: { kind: 'success' }, viewports: parsed.viewports }
|
|
134
|
+
: { outcome: { kind: 'unhealthy', detail: '/v1/viewports sent JSON without a viewports list' } };
|
|
135
|
+
}
|
|
136
|
+
catch (error) {
|
|
137
|
+
result = { outcome: { kind: 'unhealthy', detail: `/v1/viewports sent invalid JSON: ${error.message}` } };
|
|
138
|
+
}
|
|
139
|
+
return result;
|
|
140
|
+
}
|
|
141
|
+
/** Fetches /v1/viewports, which also proves the key works. */
|
|
142
|
+
export async function fetchViewports(host, options) {
|
|
143
|
+
const { outcome, body } = await getRoute(host, ROUTES.viewports, 'json', options);
|
|
144
|
+
return outcome.kind === 'success' ? parseViewports(body ?? '') : { outcome };
|
|
145
|
+
}
|
|
146
|
+
/** Overall timeout for checks (status, test, host add): short, since nothing renders. */
|
|
147
|
+
export const CHECK_TIMEOUT_MS = 10_000;
|
|
148
|
+
/** Client options for a check: the configured timeouts, capped at CHECK_TIMEOUT_MS overall. */
|
|
149
|
+
export function checkOptions(options) {
|
|
150
|
+
return { ...options, timeoutMs: Math.min(options.timeoutMs, CHECK_TIMEOUT_MS) };
|
|
151
|
+
}
|
|
152
|
+
//# sourceMappingURL=websnapper.js.map
|
package/dist/logger.js
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/** error always writes; the configured level adds warn, info and debug below it. */
|
|
2
|
+
const SEVERITY_ORDER = { debug: 10, info: 20, warn: 30, error: 40 };
|
|
3
|
+
/** Converts Error values in details into plain objects that JSON.stringify can show. */
|
|
4
|
+
function serialiseDetails(details) {
|
|
5
|
+
return JSON.stringify(details, (unusedKey, value) => (value instanceof Error ? { name: value.name, message: value.message, stack: value.stack } : value));
|
|
6
|
+
}
|
|
7
|
+
/** Creates a levelled logger writing single lines to stderr, keeping stdout for data. */
|
|
8
|
+
export function createLogger(options) {
|
|
9
|
+
const threshold = SEVERITY_ORDER[options.level];
|
|
10
|
+
const write = (severity, message, details) => {
|
|
11
|
+
if (SEVERITY_ORDER[severity] >= threshold) {
|
|
12
|
+
const suffix = details === undefined ? '' : ` ${serialiseDetails(details)}`;
|
|
13
|
+
console.error(`${new Date().toISOString()} ${severity.padEnd(5)} [${options.tag}] ${message}${suffix}`);
|
|
14
|
+
}
|
|
15
|
+
};
|
|
16
|
+
return {
|
|
17
|
+
error: (message, details) => write('error', message, details),
|
|
18
|
+
warn: (message, details) => write('warn', message, details),
|
|
19
|
+
info: (message, details) => write('info', message, details),
|
|
20
|
+
debug: (message, details) => write('debug', message, details),
|
|
21
|
+
child: (tag) => createLogger({ ...options, tag: `${options.tag}:${tag}` }),
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
//# sourceMappingURL=logger.js.map
|
package/dist/output.js
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
const BYTES_PER_UNIT = 1000;
|
|
2
|
+
const UNITS = ['B', 'KB', 'MB', 'GB'];
|
|
3
|
+
/** Below this, sizes in KB and up keep one decimal. */
|
|
4
|
+
const WHOLE_NUMBER_FROM = 10;
|
|
5
|
+
const COLUMN_GAP = ' ';
|
|
6
|
+
/** A size in decimal units: "999 B", "1.4 KB", "123 KB". */
|
|
7
|
+
export function formatBytes(bytes) {
|
|
8
|
+
let value = bytes;
|
|
9
|
+
let unitIndex = 0;
|
|
10
|
+
while (value >= BYTES_PER_UNIT && unitIndex < UNITS.length - 1) {
|
|
11
|
+
value /= BYTES_PER_UNIT;
|
|
12
|
+
unitIndex += 1;
|
|
13
|
+
}
|
|
14
|
+
// Rounding 9.96 to one decimal gives "10.0"; show it as a whole number instead.
|
|
15
|
+
const oneDecimal = Math.round(value * 10) / 10;
|
|
16
|
+
const text = unitIndex === 0 || oneDecimal >= WHOLE_NUMBER_FROM ? String(Math.round(value)) : oneDecimal.toFixed(1);
|
|
17
|
+
return `${text} ${UNITS[unitIndex]}`;
|
|
18
|
+
}
|
|
19
|
+
/** Lays rows out in columns, every column but the last padded to its widest cell. */
|
|
20
|
+
export function columns(rows) {
|
|
21
|
+
const widths = [];
|
|
22
|
+
for (const row of rows) {
|
|
23
|
+
row.forEach((cell, index) => {
|
|
24
|
+
widths[index] = Math.max(widths[index] ?? 0, cell.length);
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
return rows.map((row) => row.map((cell, index) => (index === row.length - 1 ? cell : cell.padEnd(widths[index] ?? 0))).join(COLUMN_GAP));
|
|
28
|
+
}
|
|
29
|
+
/** "No hosts configured", "One host configured:", "3 hosts configured:". */
|
|
30
|
+
export function hostCountHeading(count) {
|
|
31
|
+
return count === 0 ? 'No hosts configured' : `${count === 1 ? 'One host' : `${count} hosts`} configured:`;
|
|
32
|
+
}
|
|
33
|
+
const CONTROL_CHARACTERS_EXCEPT_NEWLINE = /(?!\n)\p{Cc}/gu;
|
|
34
|
+
/** Shows control characters as \xNN, so text from a server can't drive the terminal. Line breaks are kept. */
|
|
35
|
+
export function escapeControlCharacters(text) {
|
|
36
|
+
return text.replace(CONTROL_CHARACTERS_EXCEPT_NEWLINE, (character) => `\\x${character.charCodeAt(0).toString(16).padStart(2, '0')}`);
|
|
37
|
+
}
|
|
38
|
+
//# sourceMappingURL=output.js.map
|
package/dist/prompt.js
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
/** Thrown when the user presses Ctrl-C at a prompt. */
|
|
2
|
+
export class InterruptedError extends Error {
|
|
3
|
+
constructor() {
|
|
4
|
+
super('Interrupted.');
|
|
5
|
+
this.name = 'InterruptedError';
|
|
6
|
+
}
|
|
7
|
+
}
|
|
8
|
+
/** Thrown when stdin holds more than one API key could be. */
|
|
9
|
+
export class InputTooLongError extends Error {
|
|
10
|
+
constructor(limitBytes) {
|
|
11
|
+
super(`stdin holds more than ${limitBytes} bytes; expected one API key.`);
|
|
12
|
+
this.name = 'InputTooLongError';
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
const ENTER = '\r';
|
|
16
|
+
const NEWLINE = '\n';
|
|
17
|
+
const CTRL_C = '\u0003';
|
|
18
|
+
const CTRL_D = '\u0004';
|
|
19
|
+
const CTRL_H = '\b';
|
|
20
|
+
const DELETE = '\u007f';
|
|
21
|
+
const ESCAPE = '\u001b';
|
|
22
|
+
const FIRST_PRINTABLE = ' ';
|
|
23
|
+
export const STDIN_KEY_LIMIT_BYTES = 4096;
|
|
24
|
+
/** Applies one chunk of raw-mode input to the line being typed. */
|
|
25
|
+
export function applyKeystrokes(state, chunk) {
|
|
26
|
+
const next = { ...state };
|
|
27
|
+
for (const character of chunk) {
|
|
28
|
+
if (next.done || next.interrupted) {
|
|
29
|
+
break;
|
|
30
|
+
}
|
|
31
|
+
if (character === ENTER || character === NEWLINE || character === CTRL_D) {
|
|
32
|
+
next.done = true;
|
|
33
|
+
}
|
|
34
|
+
else if (character === CTRL_C) {
|
|
35
|
+
next.interrupted = true;
|
|
36
|
+
}
|
|
37
|
+
else if (character === DELETE || character === CTRL_H) {
|
|
38
|
+
next.text = Array.from(next.text).slice(0, -1).join('');
|
|
39
|
+
}
|
|
40
|
+
else if (character === ESCAPE) {
|
|
41
|
+
// An arrow or function key arrives as ESC plus printable characters in one chunk: drop the rest.
|
|
42
|
+
break;
|
|
43
|
+
}
|
|
44
|
+
else if (character >= FIRST_PRINTABLE) {
|
|
45
|
+
next.text += character;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
return next;
|
|
49
|
+
}
|
|
50
|
+
/** Prompts on output and reads one line from a TTY in raw mode, echoing nothing. Resolves to the trimmed line. */
|
|
51
|
+
export function readHiddenLine(promptText, input, output) {
|
|
52
|
+
return new Promise((resolve, reject) => {
|
|
53
|
+
let state = { text: '', done: false, interrupted: false };
|
|
54
|
+
const finish = () => {
|
|
55
|
+
input.removeListener('data', onData);
|
|
56
|
+
input.removeListener('end', onEnd);
|
|
57
|
+
input.setRawMode?.(false);
|
|
58
|
+
input.pause();
|
|
59
|
+
output.write(NEWLINE);
|
|
60
|
+
};
|
|
61
|
+
const onData = (chunk) => {
|
|
62
|
+
state = applyKeystrokes(state, chunk);
|
|
63
|
+
if (state.interrupted) {
|
|
64
|
+
finish();
|
|
65
|
+
reject(new InterruptedError());
|
|
66
|
+
}
|
|
67
|
+
else if (state.done) {
|
|
68
|
+
finish();
|
|
69
|
+
resolve(state.text.trim());
|
|
70
|
+
}
|
|
71
|
+
};
|
|
72
|
+
const onEnd = () => {
|
|
73
|
+
finish();
|
|
74
|
+
resolve(state.text.trim());
|
|
75
|
+
};
|
|
76
|
+
output.write(promptText);
|
|
77
|
+
input.setRawMode?.(true);
|
|
78
|
+
input.setEncoding('utf8');
|
|
79
|
+
input.on('data', onData);
|
|
80
|
+
input.on('end', onEnd);
|
|
81
|
+
input.resume();
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
/** Reads all of input and trims it, refusing more than limitBytes. */
|
|
85
|
+
export async function readAllInput(input, limitBytes = STDIN_KEY_LIMIT_BYTES) {
|
|
86
|
+
const chunks = [];
|
|
87
|
+
let totalBytes = 0;
|
|
88
|
+
for await (const chunk of input) {
|
|
89
|
+
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk));
|
|
90
|
+
totalBytes += buffer.length;
|
|
91
|
+
if (totalBytes > limitBytes) {
|
|
92
|
+
break;
|
|
93
|
+
}
|
|
94
|
+
chunks.push(buffer);
|
|
95
|
+
}
|
|
96
|
+
if (totalBytes > limitBytes) {
|
|
97
|
+
throw new InputTooLongError(limitBytes);
|
|
98
|
+
}
|
|
99
|
+
return Buffer.concat(chunks).toString('utf8').trim();
|
|
100
|
+
}
|
|
101
|
+
//# sourceMappingURL=prompt.js.map
|
package/dist/results.js
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { ExitCode } from './exit-codes.js';
|
|
2
|
+
export const CLI_NAME = 'wsnap';
|
|
3
|
+
/** The client's own --json error codes; docs/json-output.md lists each one. */
|
|
4
|
+
export const ClientError = {
|
|
5
|
+
usage: 'usage',
|
|
6
|
+
configError: 'config_error',
|
|
7
|
+
writeError: 'write_error',
|
|
8
|
+
interrupted: 'interrupted',
|
|
9
|
+
unknownHost: 'unknown_host',
|
|
10
|
+
verifyFailed: 'verify_failed',
|
|
11
|
+
noHost: 'no_host',
|
|
12
|
+
notConfigured: 'not_configured',
|
|
13
|
+
unexpectedError: 'unexpected_error',
|
|
14
|
+
};
|
|
15
|
+
/** A usage error: exit 1, every problem listed. */
|
|
16
|
+
export function usageError(problems) {
|
|
17
|
+
return {
|
|
18
|
+
exitCode: ExitCode.localError,
|
|
19
|
+
data: { error: ClientError.usage, message: problems.join(' '), problems },
|
|
20
|
+
text: [...problems, `Run "${CLI_NAME} help" for usage.`].join('\n'),
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
/** A local error other than usage (config_error, write_error, unknown_host, not_configured): exit 1. */
|
|
24
|
+
export function localError(error, problems) {
|
|
25
|
+
return {
|
|
26
|
+
exitCode: ExitCode.localError,
|
|
27
|
+
data: { error, message: problems.join(' '), problems },
|
|
28
|
+
text: problems.join('\n'),
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
/** Interrupted by Ctrl-C: exit 130. */
|
|
32
|
+
export function interruptedResult(message) {
|
|
33
|
+
return { exitCode: ExitCode.interrupted, data: { error: ClientError.interrupted, message }, text: message };
|
|
34
|
+
}
|
|
35
|
+
//# sourceMappingURL=results.js.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,56 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@headwall/websnapper-cli",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "wsnap: a command-line client for websnapper screenshot servers, with host failover.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"websnapper",
|
|
7
|
+
"screenshot",
|
|
8
|
+
"cli",
|
|
9
|
+
"chromium",
|
|
10
|
+
"headless"
|
|
11
|
+
],
|
|
12
|
+
"homepage": "https://github.com/headwalluk/websnapper-cli#readme",
|
|
13
|
+
"bugs": {
|
|
14
|
+
"url": "https://github.com/headwalluk/websnapper-cli/issues"
|
|
15
|
+
},
|
|
16
|
+
"repository": {
|
|
17
|
+
"type": "git",
|
|
18
|
+
"url": "git+https://github.com/headwalluk/websnapper-cli.git"
|
|
19
|
+
},
|
|
20
|
+
"type": "module",
|
|
21
|
+
"license": "MIT",
|
|
22
|
+
"author": "Paul Faulkner (https://headwall-hosting.com)",
|
|
23
|
+
"engines": {
|
|
24
|
+
"node": ">=22"
|
|
25
|
+
},
|
|
26
|
+
"bin": {
|
|
27
|
+
"wsnap": "bin/wsnap"
|
|
28
|
+
},
|
|
29
|
+
"files": [
|
|
30
|
+
"bin",
|
|
31
|
+
"dist",
|
|
32
|
+
"!dist/**/*.map",
|
|
33
|
+
"CHANGELOG.md"
|
|
34
|
+
],
|
|
35
|
+
"scripts": {
|
|
36
|
+
"wsnap": "tsx src/cli.ts",
|
|
37
|
+
"build": "tsc -p tsconfig.build.json",
|
|
38
|
+
"typecheck": "tsc -p tsconfig.json --noEmit",
|
|
39
|
+
"lint": "eslint .",
|
|
40
|
+
"test": "node --import tsx --test --test-concurrency=1 'tests/**/*.test.ts' 'tools/**/*.test.js'",
|
|
41
|
+
"check": "npm run typecheck && npm run lint && npm test",
|
|
42
|
+
"prepack": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\" && npm run build",
|
|
43
|
+
"prepublishOnly": "npm run check"
|
|
44
|
+
},
|
|
45
|
+
"devDependencies": {
|
|
46
|
+
"@eslint/js": "^10.0.1",
|
|
47
|
+
"@types/node": "^22.20.5",
|
|
48
|
+
"eslint": "^10.15.0",
|
|
49
|
+
"tsx": "^4.23.15",
|
|
50
|
+
"typescript": "^6.0.3",
|
|
51
|
+
"typescript-eslint": "^8.74.0"
|
|
52
|
+
},
|
|
53
|
+
"publishConfig": {
|
|
54
|
+
"access": "public"
|
|
55
|
+
}
|
|
56
|
+
}
|