@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.
@@ -0,0 +1,62 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.listPromos = void 0;
4
+ const errors_1 = require("../errors");
5
+ const read_1 = require("../read");
6
+ const STATE = {
7
+ live: 'live',
8
+ changed: 'live, changes not published',
9
+ draft: 'not published yet',
10
+ off: 'off',
11
+ };
12
+ async function listPromos(read, rest) {
13
+ const event = (0, read_1.named)(rest, 'list', 'event');
14
+ const { rows, more, first } = await (0, read_1.pages)(read, `/events/${encodeURIComponent(event)}/promos`, (body) => body.promos ?? []);
15
+ const imports = first?.imports ?? [];
16
+ if (read.json) {
17
+ read.io.out(JSON.stringify({ event: first?.event, promos: rows, more, imports }));
18
+ return errors_1.EXIT.ok;
19
+ }
20
+ const out = read.io.out;
21
+ if (rows.length) {
22
+ for (const line of (0, read_1.table)([
23
+ ['CODE', 'OFF', 'USED', 'OF', 'EACH', 'TICKET', 'KIND', 'STATE'],
24
+ ...rows.map((p) => [
25
+ p.code,
26
+ `${p.percentOff}%`,
27
+ String(p.used),
28
+ p.uses === null ? 'any' : String(p.uses),
29
+ p.perPerson === null ? '' : String(p.perPerson),
30
+ p.ticketType ?? 'any',
31
+ p.bulk ? 'bulk' : 'code',
32
+ STATE[p.state] ?? p.state,
33
+ ]),
34
+ ]))
35
+ out(line);
36
+ if (more)
37
+ out('More codes: use --all, or --limit.');
38
+ }
39
+ else
40
+ out('No promo codes yet.');
41
+ if (imports.length) {
42
+ out('');
43
+ out('Bulk imports:');
44
+ for (const line of (0, read_1.table)([
45
+ ['WHEN', 'CODES', 'STILL ON', 'BY', ''],
46
+ ...imports.map((i) => [
47
+ (0, read_1.day)(i.at),
48
+ String(i.codes),
49
+ String(i.stillOn),
50
+ i.by ?? '',
51
+ i.undoneAt ? `undone ${(0, read_1.day)(i.undoneAt)}` : '',
52
+ ]),
53
+ ]))
54
+ out(` ${line}`);
55
+ }
56
+ if (first?.path) {
57
+ out('');
58
+ out(`Add, import or switch off codes on Blocklive: ${read.base}${first.path}`);
59
+ }
60
+ return errors_1.EXIT.ok;
61
+ }
62
+ exports.listPromos = listPromos;
@@ -0,0 +1,119 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.showRequest = exports.confirmOnBlocklive = exports.confirmLink = void 0;
4
+ const errors_1 = require("../errors");
5
+ const read_1 = require("../read");
6
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
7
+ const unexpected = () => new errors_1.CliError('Blocklive sent an unexpected answer. Try again.');
8
+ // The confirm page is always on the Blocklive this CLI talks to, whatever an
9
+ // answer says: a path there (/cli/confirm#request=…), never another address
10
+ // (//elsewhere, @elsewhere) for the browser to open.
11
+ function confirmLink(base, path) {
12
+ const link = (0, read_1.blocklivePath)(base, path);
13
+ if (!link)
14
+ throw unexpected();
15
+ return link;
16
+ }
17
+ exports.confirmLink = confirmLink;
18
+ const until = (expiresAt) => new Date(expiresAt).toLocaleTimeString();
19
+ /** The request as --json prints it: Blocklive's answer, with its link. */
20
+ function shown(read, request) {
21
+ return { ...request, url: confirmLink(read.base, request.path) };
22
+ }
23
+ /**
24
+ * Prints where to confirm the request and opens it; then waits for the
25
+ * answer and returns it once confirmed, or throws when it was declined or
26
+ * not confirmed in time. With --no-wait, prints the request and returns
27
+ * undefined: the command stops there, with exit code 0.
28
+ */
29
+ async function confirmOnBlocklive(read, asked, { confirm = 'Confirm it on Blocklive, with a code from your authenticator', nothing = 'Nothing changed.', } = {}) {
30
+ if (typeof asked.id !== 'string' || !UUID.test(asked.id))
31
+ throw unexpected();
32
+ const link = confirmLink(read.base, asked.path);
33
+ const err = read.io.err;
34
+ err(`${confirm}, before ${until(asked.expiresAt)}:`);
35
+ err(` ${link}`);
36
+ // With --json nothing opens by itself: a program may be running it.
37
+ if (read.io.browser && !read.values['no-browser'] && !read.json)
38
+ await Promise.resolve(read.io.browser.open(link)).catch(() => undefined);
39
+ if (read.values['no-wait']) {
40
+ if (read.json)
41
+ read.io.out(JSON.stringify({ request: shown(read, asked) }));
42
+ else
43
+ read.io.out(`Not waiting for the answer. See how it went: ${later(read, asked.id)}`);
44
+ return undefined;
45
+ }
46
+ return answered(read, asked, nothing);
47
+ }
48
+ exports.confirmOnBlocklive = confirmOnBlocklive;
49
+ // The command that reads it later, with this profile.
50
+ function later(read, id) {
51
+ return `blocklive request show ${id}${read.profile === 'default' ? '' : ` --profile ${read.profile}`} --wait`;
52
+ }
53
+ // Waits while it is pending (every 2 seconds, until a few seconds past its
54
+ // end), then: the confirmed request, or why nothing happened.
55
+ async function answered(read, asked, nothing) {
56
+ let now = asked;
57
+ const ends = Date.parse(asked.expiresAt) + 5000;
58
+ while (now.state === 'pending' && Date.now() <= ends) {
59
+ await read.io.wait(2000);
60
+ now = await read.client.get(`/requests/${asked.id}`);
61
+ }
62
+ if (now.state === 'confirmed')
63
+ return now;
64
+ if (now.state === 'declined')
65
+ throw new errors_1.CliError(`Declined on Blocklive. ${nothing}`, errors_1.EXIT.refused, 'declined');
66
+ throw new errors_1.CliError(`Not confirmed in time. ${nothing} Run the command again.`, errors_1.EXIT.refused, 'expired');
67
+ }
68
+ const ACTIONS = {
69
+ 'promo.import': 'Import bulk codes',
70
+ 'developer.add': 'Add a developer',
71
+ 'developer.invite': 'Invite a developer',
72
+ 'payment.switch': 'Move card payments to another account',
73
+ 'domain.claim': 'Connect a custom domain',
74
+ 'invoice.issue': "Issue an order's invoice",
75
+ };
76
+ const nothingFor = (r) => r.action === 'promo.import' ? 'Nothing was imported.' : 'Nothing changed.';
77
+ // `blocklive request show <request> [--wait]`: where one of this sign-in's
78
+ // requests stands (GET requests/{request}). Another sign-in's is not found.
79
+ async function showRequest(read, rest) {
80
+ const args = rest[0] === 'show' ? rest.slice(1) : rest;
81
+ if (args.length !== 1 || !UUID.test(args[0]))
82
+ throw (0, errors_1.usage)('Name the request by its ID, as --no-wait printed it.');
83
+ const id = args[0].toLowerCase();
84
+ let now = await read.client.get(`/requests/${id}`);
85
+ const link = confirmLink(read.base, now.path);
86
+ if (read.values.wait) {
87
+ if (now.state === 'pending') {
88
+ read.io.err(`Waiting for it to be confirmed on Blocklive, before ${until(now.expiresAt)}:`);
89
+ read.io.err(` ${link}`);
90
+ }
91
+ now = await answered(read, now, nothingFor(now));
92
+ }
93
+ if (read.json) {
94
+ read.io.out(JSON.stringify({ request: shown(read, now) }));
95
+ return errors_1.EXIT.ok;
96
+ }
97
+ const out = read.io.out;
98
+ const where = now.event?.title ?? now.place?.name;
99
+ out(`${ACTIONS[now.action] ?? now.action}${where ? ` · ${where}` : ''}`);
100
+ out(`State: ${state(now)}`);
101
+ if (now.state === 'pending')
102
+ out(`Confirm it on Blocklive: ${link}`);
103
+ return errors_1.EXIT.ok;
104
+ }
105
+ exports.showRequest = showRequest;
106
+ function state(r) {
107
+ switch (r.state) {
108
+ case 'pending':
109
+ return `waiting to be confirmed on Blocklive, until ${until(r.expiresAt)}`;
110
+ case 'confirmed':
111
+ return `confirmed${r.answeredAt ? ` on ${(0, read_1.day)(r.answeredAt)}` : ''}`;
112
+ case 'declined':
113
+ return `declined on Blocklive. ${nothingFor(r)}`;
114
+ case 'expired':
115
+ return `not confirmed in time. ${nothingFor(r)}`;
116
+ default:
117
+ return String(r.state);
118
+ }
119
+ }
@@ -0,0 +1,386 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.removeTicket = exports.editTicket = exports.addTicket = exports.listTickets = void 0;
4
+ const change_1 = require("../change");
5
+ const errors_1 = require("../errors");
6
+ const image_file_1 = require("../image-file");
7
+ const read_1 = require("../read");
8
+ // The words of `promos list`, and a removal that isn't published yet.
9
+ const STATE = {
10
+ live: 'live',
11
+ changed: 'live, changes not published',
12
+ draft: 'not published yet',
13
+ off: 'off',
14
+ };
15
+ const stateOf = (t) => t.state === 'changed' && t.removed
16
+ ? 'live, removal not published'
17
+ : STATE[t.state] ?? t.state;
18
+ // An amount with its currency: "25 USD", "12.50 USD".
19
+ const money = (amount, currency) => `${Number.isInteger(amount) ? amount : amount.toFixed(2)} ${currency}`;
20
+ const priceOf = (t) => t.price > 0 ? money(t.price, t.currency) : 'free';
21
+ // A price in a plan: with the fees added on top, when there are any.
22
+ function pricedAs(t, pricing) {
23
+ return pricing && pricing.onTop > 0
24
+ ? `${priceOf(t)} (${money(pricing.entered, pricing.currency)} and ${money(pricing.onTop, pricing.currency)} of fees added on top)`
25
+ : priceOf(t);
26
+ }
27
+ // Where the times are: the event's time zone, else UTC.
28
+ const zoneOf = (zone) => zone || 'UTC';
29
+ function windowOf(t, zone) {
30
+ const from = (0, read_1.when)(t.saleStartsAt, zone);
31
+ const to = (0, read_1.when)(t.saleEndsAt, zone);
32
+ return from || to ? `${from || '…'} – ${to || '…'}` : '';
33
+ }
34
+ const linkOf = (read, path) => (0, read_1.blocklivePath)(read.base, path);
35
+ async function listTickets(read, rest) {
36
+ const event = (0, read_1.named)(rest, 'list', 'event');
37
+ const answer = await read.client.get(`/events/${encodeURIComponent(event)}/tickets`);
38
+ if (read.json) {
39
+ read.io.out(JSON.stringify(answer));
40
+ return errors_1.EXIT.ok;
41
+ }
42
+ const out = read.io.out;
43
+ const zone = answer.event?.timeZone ?? null;
44
+ if (answer.ticketTypes.length)
45
+ for (const line of (0, read_1.table)([
46
+ [
47
+ 'TICKET TYPE',
48
+ 'PRICE',
49
+ 'SOLD',
50
+ 'SALE',
51
+ 'ON SALE',
52
+ 'SHOWN',
53
+ 'STATE',
54
+ 'ID',
55
+ ],
56
+ ...answer.ticketTypes.map((t) => [
57
+ t.title,
58
+ priceOf(t),
59
+ `${t.sold} of ${t.supply}`,
60
+ windowOf(t, zone),
61
+ t.onSale ? 'on sale' : 'paused',
62
+ t.hidden ? 'hidden' : 'shown',
63
+ stateOf(t),
64
+ t.id,
65
+ ]),
66
+ ]))
67
+ out(line);
68
+ else
69
+ out('No ticket types yet.');
70
+ if (answer.ticketTypes.some((t) => windowOf(t, zone)))
71
+ out(`Sale times are ${zoneOf(zone)} time.`);
72
+ const dayTickets = answer.ticketTypes.filter((t) => t.validDays?.length);
73
+ if (dayTickets.length)
74
+ out(`Good only on some days: ${dayTickets
75
+ .map((t) => `${t.title} (${(0, read_1.dayWords)(t.validDays)})`)
76
+ .join(', ')}.`);
77
+ // An event never published has nothing live: every type is a draft.
78
+ if (answer.ticketTypes.length &&
79
+ answer.ticketTypes.every((t) => t.state === 'draft'))
80
+ out("The event isn't published yet: none of these is live until it is published, on blocklive.io or with `blocklive event publish`.");
81
+ const link = linkOf(read, answer.path);
82
+ if (link) {
83
+ out('');
84
+ out(`Art, and putting back a removed ticket type, are in the event editor: ${link}`);
85
+ }
86
+ return errors_1.EXIT.ok;
87
+ }
88
+ exports.listTickets = listTickets;
89
+ // A number option: a whole number from 1 to `most`.
90
+ function count(value, name, most) {
91
+ if (value === undefined)
92
+ return undefined;
93
+ if (!/^[1-9][0-9]{0,6}$/.test(value) || Number(value) > most)
94
+ throw (0, errors_1.usage)(`${name} is a whole number from 1 to ${most.toLocaleString('en-GB')}.`);
95
+ return Number(value);
96
+ }
97
+ // --price: an amount in the event's currency, 0 for free.
98
+ function price(value) {
99
+ if (value === undefined)
100
+ return undefined;
101
+ if (!/^(0|[1-9][0-9]{0,9})(\.[0-9]{1,2})?$/.test(value) ||
102
+ Number(value) > 1000000000)
103
+ throw (0, errors_1.usage)("--price is an amount in the event's currency, like 25 or 12.50 (0 for free), up to 1,000,000,000.");
104
+ return Number(value);
105
+ }
106
+ // --currency: only a check that the price is in the event's own.
107
+ function currency(read) {
108
+ const value = read.values.currency;
109
+ if (value === undefined)
110
+ return undefined;
111
+ if (read.values.price === undefined)
112
+ throw (0, errors_1.usage)("--currency goes with --price: it checks the price is in the event's currency.");
113
+ if (!/^[A-Za-z][A-Za-z0-9]{1,9}$/.test(value))
114
+ throw (0, errors_1.usage)('--currency is a code like USD.');
115
+ return value.toUpperCase();
116
+ }
117
+ /** What the options ask for, as the route takes it. */
118
+ function fields(read, editing) {
119
+ const v = read.values;
120
+ if (v.title !== undefined && !v.title.trim())
121
+ throw (0, errors_1.usage)('--title is the ticket type’s name: it can’t be empty.');
122
+ const out = {
123
+ title: v.title,
124
+ price: price(v.price),
125
+ currency: currency(read),
126
+ description: v.description,
127
+ supply: count(v.supply, '--supply', 1000000),
128
+ perPerson: count(v['per-person'], '--per-person', 1000000),
129
+ saleStartsAt: (0, change_1.time)(v['sale-starts'], '--sale-starts'),
130
+ saleEndsAt: (0, change_1.time)(v['sale-ends'], '--sale-ends'),
131
+ hidden: editing
132
+ ? (0, change_1.either)(read, 'hidden', 'shown')
133
+ : v.hidden || undefined,
134
+ onSale: editing
135
+ ? (0, change_1.either)(read, 'on-sale', 'paused')
136
+ : v.paused
137
+ ? false
138
+ : undefined,
139
+ hideSales: editing
140
+ ? (0, change_1.either)(read, 'hide-sales', 'show-sales')
141
+ : v['show-sales']
142
+ ? false
143
+ : undefined,
144
+ transferable: editing
145
+ ? (0, change_1.either)(read, 'transferable', 'not-transferable')
146
+ : v['not-transferable']
147
+ ? false
148
+ : undefined,
149
+ order: editing ? count(v.order, '--order', 10000) : undefined,
150
+ };
151
+ // An option `tickets add` doesn't take (--shown, --order, …) is refused
152
+ // before this, with every other command's (cli.ts).
153
+ return Object.fromEntries(Object.entries(out).filter(([, value]) => value !== undefined));
154
+ }
155
+ const NAMES = {
156
+ title: 'title',
157
+ description: 'description',
158
+ supply: 'quantity',
159
+ perPerson: 'limit per person',
160
+ saleStartsAt: 'sale starts',
161
+ saleEndsAt: 'sale ends',
162
+ hidden: 'on the event page',
163
+ onSale: 'on sale',
164
+ hideSales: 'sales shown',
165
+ transferable: 'transferable',
166
+ order: 'place in the list',
167
+ price: 'price',
168
+ };
169
+ function valueOf(t, name, zone, pricing) {
170
+ switch (name) {
171
+ case 'price':
172
+ return pricedAs(t, pricing);
173
+ case 'title':
174
+ return t.title;
175
+ case 'description':
176
+ return t.description ? t.description : '(none)';
177
+ case 'supply':
178
+ return String(t.supply);
179
+ case 'perPerson':
180
+ return String(t.perPerson);
181
+ case 'saleStartsAt':
182
+ case 'saleEndsAt': {
183
+ const at = (0, read_1.when)(t[name], zone);
184
+ return at ? `${at} (${zoneOf(zone)})` : '(none)';
185
+ }
186
+ case 'hidden':
187
+ return t.hidden ? 'hidden' : 'shown';
188
+ case 'onSale':
189
+ return t.onSale ? 'on sale' : 'paused';
190
+ case 'hideSales':
191
+ return t.hideSales ? 'no' : 'yes';
192
+ case 'transferable':
193
+ return t.transferable ? 'yes' : 'no';
194
+ case 'order':
195
+ return String(t.order);
196
+ default:
197
+ return '';
198
+ }
199
+ }
200
+ /** The plan in plain words, from the dry run's answer. */
201
+ function showPlan(read, plan, editing) {
202
+ const out = read.io.out;
203
+ const t = plan.ticketType;
204
+ const zone = plan.event?.timeZone ?? null;
205
+ if (editing) {
206
+ out(`Change ${t.title} at ${plan.event.title}, as a draft:`);
207
+ for (const line of (0, read_1.table)((plan.changed ?? []).map((name) => [
208
+ ` ${NAMES[name] ?? name}`,
209
+ valueOf(t, name, zone, plan.pricing),
210
+ ])))
211
+ out(line);
212
+ }
213
+ else {
214
+ out(`Add a ticket type to ${plan.event.title}, as a draft:`);
215
+ out(` ${t.title} · ${pricedAs(t, plan.pricing)} · ${t.supply} of them · ${t.perPerson} a person`);
216
+ const window = windowOf(t, zone);
217
+ if (window)
218
+ out(` On sale ${window} (${zoneOf(zone)})`);
219
+ out(` ${t.onSale ? 'on sale' : 'paused'}, ${t.hidden ? 'hidden from' : 'shown on'} the event page, sales ${t.hideSales ? 'hidden' : 'shown'}, ${t.transferable ? 'transferable' : 'not transferable'}`);
220
+ if (t.description)
221
+ out(` ${t.description}`);
222
+ }
223
+ const link = linkOf(read, plan.path);
224
+ out(`It goes live only when the event is published, on blocklive.io${link ? ` (${link})` : ''} or with \`blocklive event publish\`.`);
225
+ // A live ticket type keeps its live price until then.
226
+ if (editing && t.live && (plan.changed ?? []).includes('price'))
227
+ out(`Until then it stays ${priceOf(t.live)} for buyers.`);
228
+ }
229
+ async function change(read, event, ticket) {
230
+ const editing = ticket !== undefined;
231
+ const body = fields(read, editing);
232
+ if (editing && !Object.keys(body).length)
233
+ throw (0, errors_1.usage)('Say what to change: --title, --price, --supply, --sale-ends, --paused, --order, … (blocklive help).');
234
+ if (!editing && body.title === undefined)
235
+ throw (0, errors_1.usage)('Name the ticket type: --title "Early bird".');
236
+ return (0, change_1.change)(read, {
237
+ path: `/events/${encodeURIComponent(event)}/tickets${editing ? `/${ticket}` : ''}`,
238
+ body,
239
+ question: editing ? 'Make these changes?' : 'Add this ticket type?',
240
+ show: (plan) => showPlan(read, plan, editing),
241
+ // Blocklive's own list of what would change, from the values it holds.
242
+ unchanged: (sent) => editing && !(sent.changed ?? []).length,
243
+ nothing: (plan) => `${plan.ticketType.title} is like that already: nothing to change.`,
244
+ done: (done, key, tried) => {
245
+ if (read.json) {
246
+ read.io.out((0, change_1.answered)(done, key, tried));
247
+ return;
248
+ }
249
+ const t = done.ticketType;
250
+ const link = linkOf(read, done.path);
251
+ const already = done.replayed
252
+ ? ' (sent before with this key: done once)'
253
+ : '';
254
+ if (editing && done.edited === false && !done.replayed) {
255
+ read.io.out(`Nothing changed: ${t.title} is like that already.`);
256
+ return;
257
+ }
258
+ read.io.out(editing
259
+ ? `Changed ${t.title} at ${done.event.title}, as a draft${already}.`
260
+ : `Added ${t.title} to ${done.event.title}, as a draft${already}. Its ID: ${t.id}`);
261
+ if (done.pricing && (!editing || done.changed?.includes('price')))
262
+ read.io.out(`Its price in the draft: ${priceOf(t)}.`);
263
+ read.io.out(`Publish the event to put it live, on blocklive.io${link ? ` (${link})` : ''} or with \`blocklive event publish\`.`);
264
+ },
265
+ });
266
+ }
267
+ async function addTicket(read, rest) {
268
+ return change(read, (0, read_1.named)(rest, 'add', 'event'), undefined);
269
+ }
270
+ exports.addTicket = addTicket;
271
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
272
+ async function editTicket(read, rest) {
273
+ const args = rest[0] === 'edit' ? rest.slice(1) : rest;
274
+ if (args.length !== 2)
275
+ throw (0, errors_1.usage)('Name the event and the ticket type: blocklive tickets edit <event> <ticket> (its ID, as `tickets list` shows it).');
276
+ const event = (0, read_1.named)([args[0]], 'edit', 'event');
277
+ if (!UUID.test(args[1]))
278
+ throw (0, errors_1.usage)('A ticket type is named by its ID, as `blocklive tickets list <event>` shows it.');
279
+ // Art goes on its own: it is another change, with its own rules (never
280
+ // an unattended sign-in), sent another way.
281
+ if (read.values.art !== undefined) {
282
+ if (Object.keys(fields(read, true)).length)
283
+ throw (0, errors_1.usage)('--art goes on its own: set the art in one command, and change the rest in another.');
284
+ return setArt(read, event, args[1].toLowerCase(), read.values.art);
285
+ }
286
+ return change(read, event, args[1].toLowerCase());
287
+ }
288
+ exports.editTicket = editTicket;
289
+ /** `tickets edit <event> <ticket> --art <file>`: the ticket type's art in
290
+ * its draft. The file is sent as it is; Blocklive checks it, stores it and
291
+ * puts it in the draft, after the plan and a yes, once, as every change. */
292
+ async function setArt(read, event, ticket, file) {
293
+ const bytes = (0, image_file_1.imageFile)(file, '--art');
294
+ const path = `/images/events/${encodeURIComponent(event)}/tickets/${ticket}/art`;
295
+ const published = (plan) => {
296
+ const link = linkOf(read, plan.path);
297
+ return `on blocklive.io${link ? ` (${link})` : ''} or with \`blocklive event publish\``;
298
+ };
299
+ return (0, change_1.change)(read, {
300
+ path,
301
+ body: {},
302
+ send: (key, options) => read.client.upload(path, bytes, key, options),
303
+ question: 'Set this art?',
304
+ unchanged: (sent) => sent.changed === false,
305
+ nothing: (plan) => `${plan.ticketType.title} has that art already: nothing to change.`,
306
+ show: (plan) => {
307
+ read.io.out(`Set the art of ${plan.ticketType.title} at ${plan.event.title}, in its draft:`);
308
+ read.io.out(` ${(0, image_file_1.imageWords)(plan.image)}`);
309
+ read.io.out(`It goes live only when the event is published, ${published(plan)}. Tickets already issued keep the art they have.`);
310
+ },
311
+ done: (done, key, tried) => {
312
+ if (read.json) {
313
+ read.io.out((0, change_1.answered)(done, key, tried));
314
+ return;
315
+ }
316
+ read.io.out(done.changed === false && !done.replayed
317
+ ? `Nothing changed: ${done.ticketType.title} has that art already.`
318
+ : `Done: the draft of ${done.ticketType.title} at ${done.event.title} has that art${done.replayed
319
+ ? ' (sent before with this key: done once)'
320
+ : ''}.`);
321
+ read.io.out(`Publish the event to put it live, ${published(done)}.`);
322
+ },
323
+ });
324
+ }
325
+ const counted = (n, one, many) => `${n} ${n === 1 ? one : many}`;
326
+ /** What goes with a removed ticket type: "2 promo codes and 1 token gate". */
327
+ function withIt(plan) {
328
+ return [
329
+ ...(plan.codes
330
+ ? [counted(plan.codes, 'promo code', 'promo codes')]
331
+ : []),
332
+ ...(plan.gates
333
+ ? [counted(plan.gates, 'token gate', 'token gates')]
334
+ : []),
335
+ ].join(' and ');
336
+ }
337
+ /**
338
+ * `blocklive tickets remove <event> <ticket>`: the ticket type's draft marked
339
+ * removed, with the promo codes and token gates that unlock it. Tried first
340
+ * (every check, nothing written), shown, asked, then sent once with its key,
341
+ * as every change. Blocklive refuses it once any are sold or in an open
342
+ * order, and for a sponsor package's or a free-ticket type for guests.
343
+ */
344
+ async function removeTicket(read, rest) {
345
+ const args = rest[0] === 'remove' ? rest.slice(1) : rest;
346
+ if (args.length !== 2)
347
+ throw (0, errors_1.usage)('Name the event and the ticket type: blocklive tickets remove <event> <ticket> (its ID, as `tickets list` shows it).');
348
+ const event = (0, read_1.named)([args[0]], 'remove', 'event');
349
+ if (!UUID.test(args[1]))
350
+ throw (0, errors_1.usage)('A ticket type is named by its ID, as `blocklive tickets list <event>` shows it.');
351
+ const ticket = args[1].toLowerCase();
352
+ const published = (link) => `on blocklive.io${link ? ` (${link})` : ''} or with \`blocklive event publish\``;
353
+ return (0, change_1.change)(read, {
354
+ path: `/events/${encodeURIComponent(event)}/tickets/${ticket}/remove`,
355
+ body: {},
356
+ question: 'Remove this ticket type?',
357
+ show: (plan) => {
358
+ const out = read.io.out;
359
+ const t = plan.ticketType;
360
+ const link = linkOf(read, plan.path);
361
+ out(`Remove ${t.title} from ${plan.event.title}, as a draft:`);
362
+ out(` ${t.title} · ${priceOf(t)} · none sold · ${plan.wasLive ? 'live now' : 'not published yet'}`);
363
+ const going = withIt(plan);
364
+ if (going)
365
+ out(` Removed with it: ${going} that unlock it.`);
366
+ out(plan.wasLive
367
+ ? `It stays on sale as it is until the event is published, ${published(link)}.`
368
+ : 'It was never published, so nobody could get it: it is gone from the draft at once.');
369
+ out(`To put it back, use the event editor on blocklive.io${link ? ` (${link})` : ''}: it comes back without its promo codes and token gates.`);
370
+ },
371
+ done: (done, key, tried) => {
372
+ if (read.json) {
373
+ read.io.out((0, change_1.answered)(done, key, tried));
374
+ return;
375
+ }
376
+ const going = withIt(done);
377
+ read.io.out(`Removed ${done.ticketType.title} from ${done.event.title}, as a draft${going ? `, with ${going}` : ''}${done.replayed
378
+ ? ' (sent before with this key: done once)'
379
+ : ''}.`);
380
+ read.io.out(done.wasLive
381
+ ? `It stays on sale until you publish the event, ${published(linkOf(read, done.path))}.`
382
+ : 'It was never published: nothing to take down.');
383
+ },
384
+ });
385
+ }
386
+ exports.removeTicket = removeTicket;
package/dist/safe.js ADDED
@@ -0,0 +1,88 @@
1
+ "use strict";
2
+ // Text the CLI prints that came from Blocklive was typed by other people:
3
+ // anyone can buy a ticket under any name, and event titles, team names,
4
+ // emails, codes and reasons are all someone's input. Printed raw, such text
5
+ // could move the cursor, rewrite a line, set the window title, add a link
6
+ // that shows one address and opens another, hide words (a bell, a carriage
7
+ // return, a reversed run of text, characters of no width) or smuggle
8
+ // instructions to an agent reading the output in invisible tag characters.
9
+ //
10
+ // So it is made safe twice, in places no command can skip:
11
+ //
12
+ // 1. As it comes in (http.ts): in text mode every string of every answer,
13
+ // its keys too, is cleaned by `cleanData` before any command sees it.
14
+ // Commands format plain strings and never have to remember to.
15
+ // 2. As it goes out (`guard`, applied once in runCli to the Io every command
16
+ // gets): text lines are cleaned again, letting through only the exact
17
+ // colour codes style.ts makes (STYLE_CODES) and the CLI's own line
18
+ // breaks; with --json, stdout is JSON with every dangerous character
19
+ // escaped as \uXXXX (still the same JSON, so nothing is lost) and stderr
20
+ // is cleaned with no colour at all, since there the answers arrive raw.
21
+ //
22
+ // Cleaning at the boundary alone can't tell the CLI's own colour codes from
23
+ // the same bytes in a name, and cleaning only where answers come in would
24
+ // miss text the CLI echoes back (an unknown command, a file name). Together
25
+ // they leave nothing dangerous from either.
26
+ Object.defineProperty(exports, "__esModule", { value: true });
27
+ exports.cleanLine = exports.escapeJson = exports.cleanData = exports.cleanText = exports.dangerous = void 0;
28
+ // Control characters (C0, DEL, C1), the bidirectional controls, characters
29
+ // of no width, the line and paragraph separators, invisible operators,
30
+ // interlinear annotation marks, and Unicode tags (U+E0000 to U+E007F, as
31
+ // their surrogate pairs).
32
+ const DANGER_CLASS = '\\u0000-\\u001f\\u007f-\\u009f\\u061c\\u180e\\u200b-\\u200f\\u202a-\\u202e' +
33
+ '\\u2028\\u2029\\u2060-\\u2064\\u2066-\\u2069\\ufeff\\ufff9-\\ufffb';
34
+ const TAG = '\\udb40[\\udc00-\\udc7f]';
35
+ const DANGER = new RegExp(`[${DANGER_CLASS}]|${TAG}`, 'g');
36
+ const DANGER_TEST = new RegExp(`[${DANGER_CLASS}]|${TAG}`);
37
+ // Escape sequences, removed whole: CSI (ESC [ … final), OSC (ESC ] … BEL or
38
+ // ST), DCS, SOS, PM and APC strings (… ST), and any other ESC with its
39
+ // intermediates and final byte. An unterminated string runs to the end.
40
+ const ESCAPES = /\x1b(?:\[[0-?]*[ -\/]*[@-~]?|\][^\x07\x1b]*(?:\x07|\x1b\\)?|[PX^_][^\x1b]*(?:\x1b\\)?|[ -\/]*[0-~]?)/g;
41
+ // What breaks or spaces a line becomes one space, so words stay apart.
42
+ const SPACES = /[\t\n\v\f\r\u0085\u2028\u2029]/g;
43
+ /** True when the text holds anything `cleanText` would change. */
44
+ function dangerous(text) {
45
+ return DANGER_TEST.test(text);
46
+ }
47
+ exports.dangerous = dangerous;
48
+ /** One field, safe to print: escape sequences and invisible characters
49
+ * removed, line breaks and tabs turned into spaces. */
50
+ function cleanText(text) {
51
+ return text.replace(ESCAPES, '').replace(SPACES, ' ').replace(DANGER, '');
52
+ }
53
+ exports.cleanText = cleanText;
54
+ /** Every string in an answer, keys included, cleaned. */
55
+ function cleanData(value) {
56
+ if (typeof value === 'string')
57
+ return cleanText(value);
58
+ if (Array.isArray(value))
59
+ return value.map(cleanData);
60
+ if (value && typeof value === 'object') {
61
+ const clean = {};
62
+ for (const [key, item] of Object.entries(value))
63
+ clean[cleanText(key)] = cleanData(item);
64
+ return clean;
65
+ }
66
+ return value;
67
+ }
68
+ exports.cleanData = cleanData;
69
+ /** JSON text with every dangerous character escaped as \uXXXX. JSON.stringify
70
+ * already escapes those below U+0020; the others can only stand inside a
71
+ * string, where the escape means the same character, so the JSON reads the
72
+ * same and is safe on a terminal. */
73
+ function escapeJson(text) {
74
+ return text.replace(DANGER, (found) => Array.from({ length: found.length }, (_, i) => `\\u${found.charCodeAt(i).toString(16).padStart(4, '0')}`).join(''));
75
+ }
76
+ exports.escapeJson = escapeJson;
77
+ /** One line of the CLI's own text: kept line breaks, kept colour codes from
78
+ * `keep` (style.ts makes them), everything else cleaned. */
79
+ function cleanLine(line, keep) {
80
+ return line
81
+ .split('\n')
82
+ .map((part) => part
83
+ .split(/(\x1b\[[0-9;]*m)/)
84
+ .map((piece, i) => i % 2 ? (keep.has(piece) ? piece : '') : cleanText(piece))
85
+ .join(''))
86
+ .join('\n');
87
+ }
88
+ exports.cleanLine = cleanLine;