@blocklive/cli 0.0.0-stage → 0.7.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/LICENSE +3 -0
- package/README.md +202 -2
- package/dist/browser.js +194 -0
- package/dist/catalog.js +1016 -0
- package/dist/change.js +181 -0
- package/dist/cli.js +1176 -0
- package/dist/config.js +105 -0
- package/dist/csv.js +76 -0
- package/dist/errors.js +75 -0
- package/dist/http.js +189 -0
- package/dist/idempotency.js +39 -0
- package/dist/image-file.js +95 -0
- package/dist/lock.js +186 -0
- package/dist/login.js +203 -0
- package/dist/main.js +49 -0
- package/dist/read.js +155 -0
- package/dist/reads/developer-request.js +31 -0
- package/dist/reads/developers.js +53 -0
- package/dist/reads/domains.js +84 -0
- package/dist/reads/events.js +956 -0
- package/dist/reads/index.js +47 -0
- package/dist/reads/invoices.js +177 -0
- package/dist/reads/payment-account.js +177 -0
- package/dist/reads/places.js +55 -0
- package/dist/reads/promo-import.js +183 -0
- package/dist/reads/promos.js +62 -0
- package/dist/reads/requests.js +119 -0
- package/dist/reads/tickets.js +386 -0
- package/dist/safe.js +88 -0
- package/dist/secrets.js +267 -0
- package/dist/stdin.js +72 -0
- package/dist/style.js +44 -0
- package/dist/unattended.js +311 -0
- package/package.json +30 -5
package/dist/config.js
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.baseUrl = exports.profileName = exports.updateProfile = exports.readConfig = exports.emptyConfig = exports.configDir = exports.PRODUCTION_URL = void 0;
|
|
4
|
+
const fs_1 = require("fs");
|
|
5
|
+
const os_1 = require("os");
|
|
6
|
+
const path_1 = require("path");
|
|
7
|
+
const lock_1 = require("./lock");
|
|
8
|
+
const errors_1 = require("./errors");
|
|
9
|
+
// What the CLI remembers that isn't secret: one entry per profile (--profile),
|
|
10
|
+
// with the Blocklive it talks to and the sign-in it last made. The sign-in's
|
|
11
|
+
// token is kept apart, in the OS keychain (secrets.ts).
|
|
12
|
+
exports.PRODUCTION_URL = 'https://blocklive.io';
|
|
13
|
+
function configDir(env = process.env) {
|
|
14
|
+
const base = env.XDG_CONFIG_HOME && env.XDG_CONFIG_HOME.startsWith('/')
|
|
15
|
+
? env.XDG_CONFIG_HOME
|
|
16
|
+
: (0, path_1.join)((0, os_1.homedir)(), '.config');
|
|
17
|
+
return (0, path_1.join)(base, 'blocklive');
|
|
18
|
+
}
|
|
19
|
+
exports.configDir = configDir;
|
|
20
|
+
const EMPTY = { version: 1, profiles: {} };
|
|
21
|
+
const emptyConfig = () => structuredClone(EMPTY);
|
|
22
|
+
exports.emptyConfig = emptyConfig;
|
|
23
|
+
// None yet is an empty one. One that can't be read or isn't JSON stops the
|
|
24
|
+
// command with where it is; `blocklive login` writes it again (cli.ts).
|
|
25
|
+
function readConfig(dir = configDir()) {
|
|
26
|
+
const path = (0, path_1.join)(dir, 'config.json');
|
|
27
|
+
let parsed;
|
|
28
|
+
try {
|
|
29
|
+
parsed = JSON.parse((0, fs_1.readFileSync)(path, 'utf8'));
|
|
30
|
+
}
|
|
31
|
+
catch (error) {
|
|
32
|
+
if (error.code === 'ENOENT')
|
|
33
|
+
return (0, exports.emptyConfig)();
|
|
34
|
+
throw new errors_1.CliError(`Can't read the CLI's settings in ${path}. Run \`blocklive login\` to write them again.`, errors_1.EXIT.error, 'config_unreadable');
|
|
35
|
+
}
|
|
36
|
+
if (parsed?.version !== 1 ||
|
|
37
|
+
!parsed.profiles ||
|
|
38
|
+
typeof parsed.profiles !== 'object')
|
|
39
|
+
return (0, exports.emptyConfig)();
|
|
40
|
+
return parsed;
|
|
41
|
+
}
|
|
42
|
+
exports.readConfig = readConfig;
|
|
43
|
+
// Written whole and renamed into place, readable only by this user.
|
|
44
|
+
function writeConfig(config, dir = configDir()) {
|
|
45
|
+
(0, fs_1.mkdirSync)(dir, { recursive: true, mode: 0o700 });
|
|
46
|
+
(0, fs_1.chmodSync)(dir, 0o700);
|
|
47
|
+
const path = (0, path_1.join)(dir, 'config.json');
|
|
48
|
+
const temp = `${path}.${process.pid}.tmp`;
|
|
49
|
+
(0, fs_1.writeFileSync)(temp, `${JSON.stringify(config, null, 4)}\n`, {
|
|
50
|
+
mode: 0o600,
|
|
51
|
+
});
|
|
52
|
+
(0, fs_1.renameSync)(temp, path);
|
|
53
|
+
}
|
|
54
|
+
// Browser approval can take minutes. Merge this profile into the latest file
|
|
55
|
+
// while holding the lock only for the local read and atomic replacement.
|
|
56
|
+
function updateProfile(dir, name, next, recoverUnreadable = false) {
|
|
57
|
+
return (0, lock_1.withLockSync)((0, path_1.join)(dir, 'config.json.lock'), () => {
|
|
58
|
+
let config;
|
|
59
|
+
try {
|
|
60
|
+
config = readConfig(dir);
|
|
61
|
+
}
|
|
62
|
+
catch (error) {
|
|
63
|
+
if (!recoverUnreadable ||
|
|
64
|
+
!(error instanceof errors_1.CliError) ||
|
|
65
|
+
error.code !== 'config_unreadable')
|
|
66
|
+
throw error;
|
|
67
|
+
config = (0, exports.emptyConfig)();
|
|
68
|
+
}
|
|
69
|
+
if (next)
|
|
70
|
+
config.profiles[name] = next;
|
|
71
|
+
else
|
|
72
|
+
delete config.profiles[name];
|
|
73
|
+
writeConfig(config, dir);
|
|
74
|
+
return config;
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
exports.updateProfile = updateProfile;
|
|
78
|
+
const PROFILE = /^[a-z0-9][a-z0-9_-]{0,31}$/;
|
|
79
|
+
function profileName(value) {
|
|
80
|
+
const name = value ?? 'default';
|
|
81
|
+
if (!PROFILE.test(name))
|
|
82
|
+
throw (0, errors_1.usage)('A profile name is up to 32 lower-case letters, digits, - or _.');
|
|
83
|
+
return name;
|
|
84
|
+
}
|
|
85
|
+
exports.profileName = profileName;
|
|
86
|
+
// Only Blocklive over HTTPS, or a local server for development: a token is
|
|
87
|
+
// never sent in the clear to anywhere else.
|
|
88
|
+
function baseUrl(value) {
|
|
89
|
+
const raw = value ?? exports.PRODUCTION_URL;
|
|
90
|
+
let url;
|
|
91
|
+
try {
|
|
92
|
+
url = new URL(raw);
|
|
93
|
+
}
|
|
94
|
+
catch {
|
|
95
|
+
throw (0, errors_1.usage)(`${raw} isn't a URL.`);
|
|
96
|
+
}
|
|
97
|
+
const local = url.protocol === 'http:' &&
|
|
98
|
+
['localhost', '127.0.0.1', '[::1]'].includes(url.hostname);
|
|
99
|
+
if (url.protocol !== 'https:' && !local)
|
|
100
|
+
throw (0, errors_1.usage)('Use an https:// address, or http://localhost for development.');
|
|
101
|
+
if (url.username || url.password || url.search || url.hash)
|
|
102
|
+
throw (0, errors_1.usage)('The address takes no user name, query or fragment.');
|
|
103
|
+
return url.origin;
|
|
104
|
+
}
|
|
105
|
+
exports.baseUrl = baseUrl;
|
package/dist/csv.js
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.parseCsv = void 0;
|
|
4
|
+
const errors_1 = require("./errors");
|
|
5
|
+
function parseCsv(text, maxRows = 1000) {
|
|
6
|
+
const records = [];
|
|
7
|
+
let fields = [];
|
|
8
|
+
let field = '';
|
|
9
|
+
let quoted = false;
|
|
10
|
+
let line = 1;
|
|
11
|
+
let recordLine = 1;
|
|
12
|
+
let i = text.charCodeAt(0) === 0xfeff ? 1 : 0;
|
|
13
|
+
const endRecord = () => {
|
|
14
|
+
fields.push(field);
|
|
15
|
+
if (!(fields.length === 1 && fields[0] === ''))
|
|
16
|
+
records.push({ line: recordLine, fields });
|
|
17
|
+
fields = [];
|
|
18
|
+
field = '';
|
|
19
|
+
};
|
|
20
|
+
for (; i < text.length; i += 1) {
|
|
21
|
+
const c = text[i];
|
|
22
|
+
if (quoted) {
|
|
23
|
+
if (c === '"' && text[i + 1] === '"') {
|
|
24
|
+
field += '"';
|
|
25
|
+
i += 1;
|
|
26
|
+
}
|
|
27
|
+
else if (c === '"') {
|
|
28
|
+
quoted = false;
|
|
29
|
+
}
|
|
30
|
+
else {
|
|
31
|
+
if (c === '\n')
|
|
32
|
+
line += 1;
|
|
33
|
+
field += c;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
else if (c === '"' && field === '') {
|
|
37
|
+
quoted = true;
|
|
38
|
+
}
|
|
39
|
+
else if (c === ',') {
|
|
40
|
+
fields.push(field);
|
|
41
|
+
field = '';
|
|
42
|
+
}
|
|
43
|
+
else if (c === '\n' || c === '\r') {
|
|
44
|
+
if (c === '\r' && text[i + 1] === '\n')
|
|
45
|
+
i += 1;
|
|
46
|
+
endRecord();
|
|
47
|
+
line += 1;
|
|
48
|
+
recordLine = line;
|
|
49
|
+
}
|
|
50
|
+
else {
|
|
51
|
+
field += c;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
if (quoted)
|
|
55
|
+
throw (0, errors_1.usage)(`Line ${recordLine}: a quote is never closed.`);
|
|
56
|
+
if (field !== '' || fields.length > 0)
|
|
57
|
+
endRecord();
|
|
58
|
+
const [header, ...rows] = records;
|
|
59
|
+
if (!header)
|
|
60
|
+
throw (0, errors_1.usage)('The file is empty.');
|
|
61
|
+
const names = header.fields.map((name) => name.trim().toLowerCase());
|
|
62
|
+
if (names.some((name) => name === '') ||
|
|
63
|
+
new Set(names).size !== names.length)
|
|
64
|
+
throw (0, errors_1.usage)('Every column needs a different name in the first row.');
|
|
65
|
+
if (rows.length > maxRows)
|
|
66
|
+
throw (0, errors_1.usage)(`A file has at most ${maxRows} rows; this one has ${rows.length}.`);
|
|
67
|
+
return rows.map(({ line: at, fields: values }) => {
|
|
68
|
+
if (values.length !== names.length)
|
|
69
|
+
throw (0, errors_1.usage)(`Line ${at}: ${values.length} values for ${names.length} columns.`);
|
|
70
|
+
return {
|
|
71
|
+
line: at,
|
|
72
|
+
values: Object.fromEntries(names.map((name, n) => [name, values[n].trim()])),
|
|
73
|
+
};
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
exports.parseCsv = parseCsv;
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.exitCodeForStatus = exports.endedOnBlocklive = exports.usage = exports.NoAnswer = exports.CliError = exports.EXIT = void 0;
|
|
4
|
+
// Exit codes are part of the CLI's contract (docs/developer-api/cli-writes-plan.md):
|
|
5
|
+
// scripts branch on them, so a code never changes meaning.
|
|
6
|
+
exports.EXIT = {
|
|
7
|
+
ok: 0,
|
|
8
|
+
error: 1,
|
|
9
|
+
usage: 2,
|
|
10
|
+
refused: 3,
|
|
11
|
+
notFound: 4,
|
|
12
|
+
rateLimited: 5,
|
|
13
|
+
conflict: 6,
|
|
14
|
+
partial: 7,
|
|
15
|
+
};
|
|
16
|
+
// A failure the CLI explains in plain words. `code` is the server's stable
|
|
17
|
+
// code when there is one (e.g. not_allowed_by_owner), for --json output, as
|
|
18
|
+
// are `details` (a change's idempotencyKey, to send it again with).
|
|
19
|
+
// `status`, never printed, is Blocklive's HTTP status when it said 401: the
|
|
20
|
+
// sign-in is over there (endedOnBlocklive).
|
|
21
|
+
class CliError extends Error {
|
|
22
|
+
exitCode;
|
|
23
|
+
code;
|
|
24
|
+
requestId;
|
|
25
|
+
details;
|
|
26
|
+
status;
|
|
27
|
+
constructor(message, exitCode = exports.EXIT.error, code, requestId, details, status) {
|
|
28
|
+
super(message);
|
|
29
|
+
this.exitCode = exitCode;
|
|
30
|
+
this.code = code;
|
|
31
|
+
this.requestId = requestId;
|
|
32
|
+
this.details = details;
|
|
33
|
+
this.status = status;
|
|
34
|
+
this.name = 'CliError';
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
exports.CliError = CliError;
|
|
38
|
+
/** No answer that can be read: Blocklive couldn't be reached, didn't answer
|
|
39
|
+
* in time, failed on its side (5xx), or sent something that isn't its
|
|
40
|
+
* answer. A change sent then may have been made all the same (change.ts). */
|
|
41
|
+
class NoAnswer extends CliError {
|
|
42
|
+
lost = true;
|
|
43
|
+
}
|
|
44
|
+
exports.NoAnswer = NoAnswer;
|
|
45
|
+
const usage = (message) => new CliError(message, exports.EXIT.usage);
|
|
46
|
+
exports.usage = usage;
|
|
47
|
+
/** The codes Blocklive says a sign-in ended with (always with a 401). */
|
|
48
|
+
const OVER = ['not_signed_in', 'sign_in_ended', 'switched_off'];
|
|
49
|
+
/**
|
|
50
|
+
* Whether a refusal says the sign-in has ended on Blocklive, so it may be
|
|
51
|
+
* forgotten here: a 401, or a code that says so. Any other refusal leaves
|
|
52
|
+
* it live: held_elsewhere (used from a network it isn't held to) or a 403
|
|
53
|
+
* for one action.
|
|
54
|
+
*/
|
|
55
|
+
const endedOnBlocklive = (error) => error instanceof CliError &&
|
|
56
|
+
error.exitCode === exports.EXIT.refused &&
|
|
57
|
+
(error.status === 401 || OVER.includes(error.code ?? ''));
|
|
58
|
+
exports.endedOnBlocklive = endedOnBlocklive;
|
|
59
|
+
// The exit code for an HTTP refusal from Blocklive. A 409 is a conflict
|
|
60
|
+
// (6) only for an idempotency key used for another change; Blocklive's 409
|
|
61
|
+
// `refused` (a rule said no, in its words) is a refusal (3).
|
|
62
|
+
function exitCodeForStatus(status, code) {
|
|
63
|
+
if (status === 401 || status === 403)
|
|
64
|
+
return exports.EXIT.refused;
|
|
65
|
+
if (status === 404 || status === 410)
|
|
66
|
+
return exports.EXIT.notFound;
|
|
67
|
+
if (status === 409)
|
|
68
|
+
return code === 'refused' ? exports.EXIT.refused : exports.EXIT.conflict;
|
|
69
|
+
if (status === 429)
|
|
70
|
+
return exports.EXIT.rateLimited;
|
|
71
|
+
if (status === 400 || status === 422)
|
|
72
|
+
return exports.EXIT.usage;
|
|
73
|
+
return exports.EXIT.error;
|
|
74
|
+
}
|
|
75
|
+
exports.exitCodeForStatus = exitCodeForStatus;
|
package/dist/http.js
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.NOT_HERE_YET = exports.createClient = exports.retryAfter = exports.VERSION = void 0;
|
|
4
|
+
const errors_1 = require("./errors");
|
|
5
|
+
const safe_1 = require("./safe");
|
|
6
|
+
// The CLI's only way to Blocklive: /api/cli/v1 on the profile's base URL.
|
|
7
|
+
// It sends the access token and the CLI's version, renews the access token
|
|
8
|
+
// once when it was refused (it lasts 15 minutes), waits out the per-minute
|
|
9
|
+
// request limit (a 429 with Retry-After, up to a limit) and turns every
|
|
10
|
+
// refusal into a CliError with the server's code. A 429 without Retry-After
|
|
11
|
+
// is a limit that won't clear in a minute (the hourly write budget, a day's
|
|
12
|
+
// events, the dry runs' hour): said at once, in Blocklive's words. No
|
|
13
|
+
// answer that can be read (none, a failure on Blocklive's side, something
|
|
14
|
+
// that isn't its answer) is a NoAnswer: a change may have been made anyway.
|
|
15
|
+
// Every string of every answer is cleaned of control and invisible
|
|
16
|
+
// characters as it arrives (safe.ts), unless the caller prints JSON, which
|
|
17
|
+
// stays exactly as sent and is escaped where it is printed.
|
|
18
|
+
exports.VERSION = '0.7.0';
|
|
19
|
+
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
20
|
+
// Seconds from Retry-After (only the delta-seconds form), at least 1, at most 60.
|
|
21
|
+
function retryAfter(header) {
|
|
22
|
+
const seconds = header && /^\d{1,4}$/.test(header) ? Number(header) : 1;
|
|
23
|
+
return Math.min(Math.max(seconds, 1), 60);
|
|
24
|
+
}
|
|
25
|
+
exports.retryAfter = retryAfter;
|
|
26
|
+
function createClient({ baseUrl, auth, fetchImpl = fetch, wait = sleep, maxWaits = 5, onWait, timeoutMs = 30000, raw = false, }) {
|
|
27
|
+
async function request(method, path, body, idempotencyKey, options = {}) {
|
|
28
|
+
if (!/^\/[A-Za-z0-9/_.~%-]*(\?.*)?$/.test(path))
|
|
29
|
+
throw new Error('invalid_path');
|
|
30
|
+
const headers = {
|
|
31
|
+
Accept: 'application/json',
|
|
32
|
+
'Blocklive-CLI-Version': exports.VERSION,
|
|
33
|
+
};
|
|
34
|
+
// Bytes go as they are; anything else as JSON.
|
|
35
|
+
const bytes = body instanceof Uint8Array ? body : undefined;
|
|
36
|
+
if (bytes)
|
|
37
|
+
headers['Content-Type'] = 'application/octet-stream';
|
|
38
|
+
else if (body !== undefined)
|
|
39
|
+
headers['Content-Type'] = 'application/json';
|
|
40
|
+
if (idempotencyKey)
|
|
41
|
+
headers['Idempotency-Key'] = idempotencyKey;
|
|
42
|
+
let renewed = false;
|
|
43
|
+
for (let waits = 0;; waits += 1) {
|
|
44
|
+
const access = auth?.access();
|
|
45
|
+
if (access)
|
|
46
|
+
headers.Authorization = `Bearer ${access}`;
|
|
47
|
+
let response;
|
|
48
|
+
try {
|
|
49
|
+
response = await fetchImpl(`${baseUrl}/api/cli/v1${path}`, {
|
|
50
|
+
method,
|
|
51
|
+
headers,
|
|
52
|
+
body: bytes ??
|
|
53
|
+
(body === undefined ? undefined : JSON.stringify(body)),
|
|
54
|
+
redirect: 'error',
|
|
55
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
catch (error) {
|
|
59
|
+
// Nothing came back: a login waiting on its code tries again.
|
|
60
|
+
throw new errors_1.NoAnswer(error?.name === 'TimeoutError'
|
|
61
|
+
? `${baseUrl} didn't answer in time. Try again.`
|
|
62
|
+
: `Couldn't reach ${baseUrl}. Check your connection.`, errors_1.EXIT.error, 'unreachable');
|
|
63
|
+
}
|
|
64
|
+
// Only the per-minute limit says when to come back.
|
|
65
|
+
if (response.status === 429 &&
|
|
66
|
+
response.headers.get('Retry-After') !== null &&
|
|
67
|
+
waits < maxWaits) {
|
|
68
|
+
const seconds = retryAfter(response.headers.get('Retry-After'));
|
|
69
|
+
onWait?.(seconds);
|
|
70
|
+
await wait(seconds * 1000);
|
|
71
|
+
continue;
|
|
72
|
+
}
|
|
73
|
+
if (response.status === 401 && auth && !renewed) {
|
|
74
|
+
renewed = true;
|
|
75
|
+
if (await auth.renew())
|
|
76
|
+
continue;
|
|
77
|
+
}
|
|
78
|
+
let parsed;
|
|
79
|
+
try {
|
|
80
|
+
const text = await response.text();
|
|
81
|
+
// A keyed write needs its result. Some other routes just
|
|
82
|
+
// acknowledge success with an empty body.
|
|
83
|
+
if (text)
|
|
84
|
+
parsed = JSON.parse(text);
|
|
85
|
+
else if (!idempotencyKey)
|
|
86
|
+
parsed = {};
|
|
87
|
+
}
|
|
88
|
+
catch {
|
|
89
|
+
parsed = undefined;
|
|
90
|
+
}
|
|
91
|
+
// A refusal is always cleaned in text mode: its words are printed.
|
|
92
|
+
const clean = raw ? parsed : (0, safe_1.cleanData)(parsed);
|
|
93
|
+
if (response.ok && parsed !== undefined)
|
|
94
|
+
return (options.raw ? parsed : clean);
|
|
95
|
+
const refused = refusal(response.status, clean, response.headers.get('Retry-After') !== null);
|
|
96
|
+
// A command of an event that Blocklive says isn't there: the
|
|
97
|
+
// event may be missing, or this Blocklive may be older than the
|
|
98
|
+
// CLI and not have the command yet. Both are the same answer, so
|
|
99
|
+
// the event itself is asked, once: every Blocklive has that.
|
|
100
|
+
const about = !options.notFoundAsIs && bareNotFound(refused) && eventOf(path);
|
|
101
|
+
if (about) {
|
|
102
|
+
let there = false;
|
|
103
|
+
try {
|
|
104
|
+
await request('GET', `/events/${about}`);
|
|
105
|
+
there = true;
|
|
106
|
+
}
|
|
107
|
+
catch (error) {
|
|
108
|
+
if (!(error instanceof errors_1.CliError))
|
|
109
|
+
throw error;
|
|
110
|
+
}
|
|
111
|
+
if (there)
|
|
112
|
+
throw notHereYet(baseUrl, refused.requestId);
|
|
113
|
+
}
|
|
114
|
+
throw refused;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
return {
|
|
118
|
+
get(path, query, options) {
|
|
119
|
+
const params = new URLSearchParams();
|
|
120
|
+
for (const [name, value] of Object.entries(query ?? {}))
|
|
121
|
+
if (value !== undefined)
|
|
122
|
+
params.set(name, value);
|
|
123
|
+
const search = params.toString();
|
|
124
|
+
return request('GET', search ? `${path}?${search}` : path, undefined, undefined, options);
|
|
125
|
+
},
|
|
126
|
+
post(path, body, idempotencyKey, options) {
|
|
127
|
+
return request('POST', path, body, idempotencyKey, options);
|
|
128
|
+
},
|
|
129
|
+
upload(path, bytes, idempotencyKey, options) {
|
|
130
|
+
return request('POST', idempotencyKey ? path : `${path}?dryRun=true`, bytes, idempotencyKey, options);
|
|
131
|
+
},
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
exports.createClient = createClient;
|
|
135
|
+
exports.NOT_HERE_YET = 'command_unavailable';
|
|
136
|
+
/** The CLI is newer than the Blocklive it talks to: the command's route
|
|
137
|
+
* isn't there yet. Not a "not found": nothing is missing but the command. */
|
|
138
|
+
function notHereYet(baseUrl, requestId) {
|
|
139
|
+
return new errors_1.CliError(`This command isn't on this Blocklive yet (${baseUrl}): the CLI is newer than it. Try again after Blocklive's next update, or do it on blocklive.io.`, errors_1.EXIT.error, exports.NOT_HERE_YET, requestId);
|
|
140
|
+
}
|
|
141
|
+
/** Blocklive's own "not found", with no words of its own: what it answers
|
|
142
|
+
* for something that isn't there, and for a route it doesn't have. */
|
|
143
|
+
const bareNotFound = (error) => error.exitCode === errors_1.EXIT.notFound &&
|
|
144
|
+
error.code === 'not_found' &&
|
|
145
|
+
error.message === 'Blocklive refused the request (not_found).';
|
|
146
|
+
/**
|
|
147
|
+
* The event a path is a command of, when nothing else is named in it:
|
|
148
|
+
* /events/{event}/draft, /events/{event}/payment-account/choices,
|
|
149
|
+
* /images/events/{event}/cover. Not /events/{event} itself, nor a path that
|
|
150
|
+
* names something more (a ticket type, a publish, an order): there a "not
|
|
151
|
+
* found" may be that thing's.
|
|
152
|
+
*/
|
|
153
|
+
function eventOf(path) {
|
|
154
|
+
const found = /^(?:\/images)?\/events\/([A-Za-z0-9][A-Za-z0-9-]{0,199})((?:\/[a-z][a-z-]*)+)$/.exec(path.split('?')[0]);
|
|
155
|
+
return found?.[1];
|
|
156
|
+
}
|
|
157
|
+
function refusal(status, body, waited) {
|
|
158
|
+
const error = body?.error ?? {};
|
|
159
|
+
const code = typeof error.code === 'string' ? error.code : undefined;
|
|
160
|
+
const requestId = typeof error.request_id === 'string' ? error.request_id : undefined;
|
|
161
|
+
const said = typeof error.message === 'string' ? error.message : undefined;
|
|
162
|
+
// Why an unattended sign-in ended, for an agent (--json prints it).
|
|
163
|
+
const details = typeof error.reason === 'string' && /^[a-z_]{1,40}$/.test(error.reason)
|
|
164
|
+
? { reason: error.reason }
|
|
165
|
+
: undefined;
|
|
166
|
+
if (status === 426)
|
|
167
|
+
return new errors_1.CliError(said ??
|
|
168
|
+
'This version of the Blocklive CLI is too old. Update it: https://blocklive.io/docs/developers/cli#install', errors_1.EXIT.error, code ?? 'upgrade_required', requestId);
|
|
169
|
+
if (status === 401)
|
|
170
|
+
return new errors_1.CliError(said ?? 'Your sign-in ended. Run `blocklive login`.', errors_1.EXIT.refused, code ?? 'not_signed_in', requestId, details, 401);
|
|
171
|
+
// The per-minute limit, still on after waiting (Retry-After); or a
|
|
172
|
+
// limit that won't clear in a minute, in Blocklive's words, at once.
|
|
173
|
+
if (status === 429)
|
|
174
|
+
return new errors_1.CliError((!waited && said) ||
|
|
175
|
+
(waited
|
|
176
|
+
? 'Blocklive is still limiting requests. Try again in a minute.'
|
|
177
|
+
: 'Blocklive is limiting changes from the CLI for now. Try again later.'), errors_1.EXIT.rateLimited, code ?? 'rate_limited', requestId, details);
|
|
178
|
+
// A 404 that isn't Blocklive's own answer (no error code: the web
|
|
179
|
+
// app's "no such page"): this Blocklive has no such command.
|
|
180
|
+
if (status === 404 && code === undefined)
|
|
181
|
+
return notHereYet('this server', requestId);
|
|
182
|
+
// A failure on Blocklive's side (or a proxy's page instead of an
|
|
183
|
+
// answer) is not a refusal: trying again may work, and a change sent
|
|
184
|
+
// may have been made (change.ts sends it again with its key).
|
|
185
|
+
if (status >= 500 || body === undefined)
|
|
186
|
+
return new errors_1.NoAnswer(said ??
|
|
187
|
+
`Blocklive couldn't answer that just now (${code ?? status}). Try again in a minute.`, errors_1.EXIT.error, code ?? 'unavailable', requestId);
|
|
188
|
+
return new errors_1.CliError(said ?? `Blocklive refused the request (${code ?? status}).`, (0, errors_1.exitCodeForStatus)(status, code), code, requestId);
|
|
189
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.rowKey = exports.fileDigest = exports.idempotencyKey = exports.singleKey = exports.IDEMPOTENCY_KEY = void 0;
|
|
4
|
+
const crypto_1 = require("crypto");
|
|
5
|
+
const errors_1 = require("./errors");
|
|
6
|
+
// Every once-only write carries an idempotency key, a UUID (the route's
|
|
7
|
+
// Idempotency-Key header takes nothing else); Blocklive keeps the first
|
|
8
|
+
// answer for each for 24 hours and replays it. A single command gets a
|
|
9
|
+
// random one, or the one --idempotency-key names. A row of a file gets one
|
|
10
|
+
// derived from the file's contents, the command and the row's position, so
|
|
11
|
+
// running the same file again replays instead of repeating.
|
|
12
|
+
exports.IDEMPOTENCY_KEY = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
13
|
+
const singleKey = () => (0, crypto_1.randomUUID)();
|
|
14
|
+
exports.singleKey = singleKey;
|
|
15
|
+
/** The key a change is sent with: --idempotency-key's (a UUID), else a new one. */
|
|
16
|
+
function idempotencyKey(given) {
|
|
17
|
+
if (given === undefined)
|
|
18
|
+
return (0, exports.singleKey)();
|
|
19
|
+
if (!exports.IDEMPOTENCY_KEY.test(given))
|
|
20
|
+
throw (0, errors_1.usage)('--idempotency-key is a UUID, like 7b1e4c2a-0f3d-4e5b-9a61-2c8d0e4f6a17.');
|
|
21
|
+
return given.toLowerCase();
|
|
22
|
+
}
|
|
23
|
+
exports.idempotencyKey = idempotencyKey;
|
|
24
|
+
function fileDigest(contents) {
|
|
25
|
+
return (0, crypto_1.createHash)('sha256').update(contents).digest('hex');
|
|
26
|
+
}
|
|
27
|
+
exports.fileDigest = fileDigest;
|
|
28
|
+
// A UUID (version 8, RFC 9562: custom) from SHA-256 of command, file and row.
|
|
29
|
+
function rowKey(command, digest, row) {
|
|
30
|
+
const bytes = (0, crypto_1.createHash)('sha256')
|
|
31
|
+
.update(`blocklive-cli-row\0${command}\0${digest}\0${row}`)
|
|
32
|
+
.digest()
|
|
33
|
+
.subarray(0, 16);
|
|
34
|
+
bytes[6] = (bytes[6] & 0x0f) | 0x80;
|
|
35
|
+
bytes[8] = (bytes[8] & 0x3f) | 0x80;
|
|
36
|
+
const hex = bytes.toString('hex');
|
|
37
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
38
|
+
}
|
|
39
|
+
exports.rowKey = rowKey;
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.imageWords = exports.imageFile = exports.IMAGE_FILE_MAX = void 0;
|
|
4
|
+
const fs_1 = require("fs");
|
|
5
|
+
const errors_1 = require("./errors");
|
|
6
|
+
// An image file for --cover or --art, read here and sent as it is. Blocklive
|
|
7
|
+
// checks it (a still PNG, JPEG or WebP by its own bytes, no metadata, at
|
|
8
|
+
// most 4 MB, 200 to 8,000 pixels a side, at most 40 megapixels) and says
|
|
9
|
+
// why when it refuses one; this only stops what can't be one before
|
|
10
|
+
// anything is sent: no file, not a file, too big, or not one of the three
|
|
11
|
+
// kinds by its first bytes.
|
|
12
|
+
exports.IMAGE_FILE_MAX = 4 * 1024 * 1024;
|
|
13
|
+
const KINDS = "isn't a PNG, JPEG or WebP image (by its content, not its name). SVG, GIF and other kinds aren't taken.";
|
|
14
|
+
function looksLikeAnImage(bytes) {
|
|
15
|
+
return ((bytes.length >= 8 &&
|
|
16
|
+
bytes
|
|
17
|
+
.subarray(0, 8)
|
|
18
|
+
.equals(Buffer.from([
|
|
19
|
+
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a,
|
|
20
|
+
]))) ||
|
|
21
|
+
(bytes.length >= 3 &&
|
|
22
|
+
bytes[0] === 0xff &&
|
|
23
|
+
bytes[1] === 0xd8 &&
|
|
24
|
+
bytes[2] === 0xff) ||
|
|
25
|
+
(bytes.length >= 12 &&
|
|
26
|
+
bytes.toString('latin1', 0, 4) === 'RIFF' &&
|
|
27
|
+
bytes.toString('latin1', 8, 12) === 'WEBP'));
|
|
28
|
+
}
|
|
29
|
+
/** The image in a file: its bytes as they are. One handle, opened without
|
|
30
|
+
* waiting (a pipe or a device isn't a file), its size taken from it and
|
|
31
|
+
* read through it, so the file checked is the file read. */
|
|
32
|
+
function imageFile(path, option) {
|
|
33
|
+
const said = (why) => (0, errors_1.usage)(`${option}: ${why}`);
|
|
34
|
+
const tooBig = () => said(`${path} is over 4 MB; an image is at most 4 MB.`);
|
|
35
|
+
if (!path)
|
|
36
|
+
throw said('name the image file.');
|
|
37
|
+
let fd;
|
|
38
|
+
try {
|
|
39
|
+
fd = (0, fs_1.openSync)(path, fs_1.constants.O_RDONLY | (fs_1.constants.O_NONBLOCK ?? 0));
|
|
40
|
+
}
|
|
41
|
+
catch {
|
|
42
|
+
throw said(`can't read ${path}.`);
|
|
43
|
+
}
|
|
44
|
+
try {
|
|
45
|
+
let info;
|
|
46
|
+
try {
|
|
47
|
+
info = (0, fs_1.fstatSync)(fd);
|
|
48
|
+
}
|
|
49
|
+
catch {
|
|
50
|
+
throw said(`can't read ${path}.`);
|
|
51
|
+
}
|
|
52
|
+
if (!info.isFile())
|
|
53
|
+
throw said(`${path} isn't a file.`);
|
|
54
|
+
if (info.size > exports.IMAGE_FILE_MAX)
|
|
55
|
+
throw tooBig();
|
|
56
|
+
// One byte more than the most, to see a file that grew meanwhile.
|
|
57
|
+
const buffer = Buffer.alloc(exports.IMAGE_FILE_MAX + 1);
|
|
58
|
+
let length = 0;
|
|
59
|
+
for (;;) {
|
|
60
|
+
let read;
|
|
61
|
+
try {
|
|
62
|
+
read = (0, fs_1.readSync)(fd, buffer, length, buffer.length - length, null);
|
|
63
|
+
}
|
|
64
|
+
catch {
|
|
65
|
+
throw said(`can't read ${path}.`);
|
|
66
|
+
}
|
|
67
|
+
if (!read)
|
|
68
|
+
break;
|
|
69
|
+
length += read;
|
|
70
|
+
if (length > exports.IMAGE_FILE_MAX)
|
|
71
|
+
throw tooBig();
|
|
72
|
+
}
|
|
73
|
+
if (!length)
|
|
74
|
+
throw said(`${path} is empty.`);
|
|
75
|
+
const bytes = Buffer.from(buffer.subarray(0, length));
|
|
76
|
+
if (!looksLikeAnImage(bytes))
|
|
77
|
+
throw said(`${path} ${KINDS}`);
|
|
78
|
+
return bytes;
|
|
79
|
+
}
|
|
80
|
+
finally {
|
|
81
|
+
(0, fs_1.closeSync)(fd);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
exports.imageFile = imageFile;
|
|
85
|
+
const KIND = { png: 'PNG', jpg: 'JPEG', webp: 'WebP' };
|
|
86
|
+
/** "PNG, 1,200 by 630 pixels, 84 KB". */
|
|
87
|
+
function imageWords(image) {
|
|
88
|
+
if (!image)
|
|
89
|
+
return 'an image';
|
|
90
|
+
const size = image.bytes >= 1024 * 1024
|
|
91
|
+
? `${(image.bytes / (1024 * 1024)).toFixed(1)} MB`
|
|
92
|
+
: `${Math.max(1, Math.round(image.bytes / 1024))} KB`;
|
|
93
|
+
return `${KIND[image.type] ?? 'image'}, ${Number(image.width).toLocaleString('en-GB')} by ${Number(image.height).toLocaleString('en-GB')} pixels, ${size}`;
|
|
94
|
+
}
|
|
95
|
+
exports.imageWords = imageWords;
|