-
Notifications
You must be signed in to change notification settings - Fork 250
Expand file tree
/
Copy pathui.tsx
More file actions
699 lines (641 loc) · 25.7 KB
/
ui.tsx
File metadata and controls
699 lines (641 loc) · 25.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
/* eslint-disable tsdoc/syntax */
import {AbortError, AbortSilentError, FatalError as Fatal} from './error.js'
import {outputContent, outputDebug, outputToken, TokenizedString} from './output.js'
import {terminalSupportsPrompting} from './system.js'
import {AbortController} from './abort.js'
import {runWithTimer} from './metadata.js'
import {ConcurrentOutput, ConcurrentOutputProps} from '../../private/node/ui/components/ConcurrentOutput.js'
import {handleCtrlC, render, renderOnce} from '../../private/node/ui.js'
import {alert, AlertOptions} from '../../private/node/ui/alert.js'
import {CustomSection} from '../../private/node/ui/components/Alert.js'
import {FatalError} from '../../private/node/ui/components/FatalError.js'
import ScalarDict from '../../private/node/ui/components/Table/ScalarDict.js'
import {Table, TableColumn, TableProps} from '../../private/node/ui/components/Table/Table.js'
import {
Token,
tokenItemToString,
InlineToken,
LinkToken,
ListToken,
TokenItem,
} from '../../private/node/ui/components/TokenizedText.js'
import {
DangerousConfirmationPrompt,
DangerousConfirmationPromptProps,
} from '../../private/node/ui/components/DangerousConfirmationPrompt.js'
import {SelectPrompt, SelectPromptProps} from '../../private/node/ui/components/SelectPrompt.js'
import {Tasks, Task} from '../../private/node/ui/components/Tasks.js'
import {TextPrompt, TextPromptProps} from '../../private/node/ui/components/TextPrompt.js'
import {AutocompletePromptProps, AutocompletePrompt} from '../../private/node/ui/components/AutocompletePrompt.js'
import {InfoTableSection} from '../../private/node/ui/components/Prompts/InfoTable.js'
import {InfoMessageProps} from '../../private/node/ui/components/Prompts/InfoMessage.js'
import {SingleTask} from '../../private/node/ui/components/SingleTask.js'
import React from 'react'
import {Key as InkKey, RenderOptions} from 'ink'
type PartialBy<T, TKey extends keyof T> = Omit<T, TKey> & Partial<Pick<T, TKey>>
interface UIDebugOptions {
/** If true, don't check if the current terminal is interactive or not */
skipTTYCheck?: boolean
}
const defaultUIDebugOptions: UIDebugOptions = {
skipTTYCheck: false,
}
export interface RenderConcurrentOptions extends PartialBy<ConcurrentOutputProps, 'abortSignal'> {
renderOptions?: RenderOptions
}
/**
* Renders output from concurrent processes to the terminal with {@link ConcurrentOutput}.
* @example
* 00:00:00 │ backend │ first backend message
* 00:00:00 │ backend │ second backend message
* 00:00:00 │ backend │ third backend message
* 00:00:00 │ frontend │ first frontend message
* 00:00:00 │ frontend │ second frontend message
* 00:00:00 │ frontend │ third frontend message
*
*/
export async function renderConcurrent({renderOptions, ...props}: RenderConcurrentOptions) {
const abortSignal = props.abortSignal ?? new AbortController().signal
return render(<ConcurrentOutput {...props} abortSignal={abortSignal} />, renderOptions)
}
export type AlertCustomSection = CustomSection
export type RenderAlertOptions = Omit<AlertOptions, 'type'>
/**
* Renders an information banner to the console.
* @example Basic
* ╭─ info ───────────────────────────────────────────────────╮
* │ │
* │ CLI update available. │
* │ │
* │ Run `npm run shopify upgrade`. │
* │ │
* ╰──────────────────────────────────────────────────────────╯
*
* @example Complete
* ╭─ info ───────────────────────────────────────────────────╮
* │ │
* │ my-app initialized and ready to build. │
* │ │
* │ Next steps │
* │ • Run `cd verification-app` │
* │ • To preview your project, run `npm app dev` │
* │ • To add extensions, run `npm generate extension` │
* │ │
* │ Reference │
* │ • Run `npm shopify help` │
* │ • Dev docs [1] │
* │ │
* │ Custom section │
* │ • Item 1 [2] │
* │ • Item 2 │
* │ • Item 3 [3] │
* │ │
* ╰──────────────────────────────────────────────────────────╯
* [1] https://shopify.dev
* [2] https://www.google.com/search?q=jh56t9l34kpo35tw8s28hn7s
* 9s2xvzla01d8cn6j7yq&rlz=1C1GCEU_enUS832US832&oq=jh56t9l34kpo
* 35tw8s28hn7s9s2xvzla01d8cn6j7yq&aqs=chrome.0.35i39l2j0l4j46j
* 69i60.2711j0j7&sourceid=chrome&ie=UTF-8
* [3] https://shopify.com
*
*/
export function renderInfo(options: RenderAlertOptions) {
return alert({...options, type: 'info'})
}
/**
* Renders a success banner to the console.
* @example Basic
* ╭─ success ────────────────────────────────────────────────╮
* │ │
* │ CLI updated. │
* │ │
* │ You are now running version 3.47. │
* │ │
* ╰──────────────────────────────────────────────────────────╯
*
* @example Complete
* ╭─ success ────────────────────────────────────────────────╮
* │ │
* │ Deployment successful. │
* │ │
* │ Your extensions have been uploaded to your Shopify │
* │ Partners Dashboard. │
* │ │
* │ Next steps │
* │ • See your deployment and set it live [1] │
* │ │
* ╰──────────────────────────────────────────────────────────╯
* [1] https://partners.shopify.com/1797046/apps/4523695/deploy
* ments
*
*/
export function renderSuccess(options: RenderAlertOptions) {
return alert({...options, type: 'success'})
}
/**
* Renders a warning banner to the console.
* @example Basic
* ╭─ warning ────────────────────────────────────────────────╮
* │ │
* │ You have reached your limit of checkout extensions for │
* │ this app. │
* │ │
* │ You can free up space for a new one by deleting an │
* │ existing one. │
* │ │
* ╰──────────────────────────────────────────────────────────╯
*
* @example Complete
* ╭─ warning ────────────────────────────────────────────────╮
* │ │
* │ Required access scope update. │
* │ │
* │ The deadline for re-selecting your app scopes is May │
* │ 1, 2022. │
* │ │
* │ Reference │
* │ • Dev docs [1] │
* │ │
* ╰──────────────────────────────────────────────────────────╯
* [1] https://shopify.dev/app/scopes
*
*/
export function renderWarning(options: RenderAlertOptions) {
return alert({...options, type: 'warning'})
}
/**
* Renders an error banner to the console.
* @example
* ╭─ error ──────────────────────────────────────────────────╮
* │ │
* │ Version couldn't be released. │
* │ │
* │ This version needs to be submitted for review and │
* │ approved by Shopify before it can be released. │
* │ │
* ╰──────────────────────────────────────────────────────────╯
*
*/
export function renderError(options: RenderAlertOptions) {
return alert({...options, type: 'error'})
}
interface RenderFatalErrorOptions {
renderOptions?: RenderOptions
}
/**
* Renders a Fatal error to the console inside a banner.
* @example Basic
* ╭─ error ──────────────────────────────────────────────────╮
* │ │
* │ Something went wrong. │
* │ │
* │ To investigate the issue, examine this stack trace: │
* │ at _compile (internal/modules/cjs/loader.js:1137) │
* │ at js (internal/modules/cjs/loader.js:1157) │
* │ at load (internal/modules/cjs/loader.js:985) │
* │ at _load (internal/modules/cjs/loader.js:878) │
* │ │
* ╰──────────────────────────────────────────────────────────╯
*
* @example Complete
* ╭─ error ──────────────────────────────────────────────────╮
* │ │
* │ No Organization found │
* │ │
* │ Next steps │
* │ • Have you created a Shopify Partners organization │
* │ [1]? │
* │ • Have you confirmed your accounts from the emails │
* │ you received? │
* │ • Need to connect to a different App or │
* │ organization? Run the command again with `--reset` │
* │ │
* │ amortizable-marketplace-ext │
* │ • Some other error │
* │ Validation errors │
* │ • Missing expected key(s). │
* │ │
* │ amortizable-marketplace-ext-2 │
* │ • Something was not found │
* │ │
* ╰──────────────────────────────────────────────────────────╯
* [1] https://partners.shopify.com/signup
*
*/
export function renderFatalError(error: Fatal, {renderOptions}: RenderFatalErrorOptions = {}) {
return renderOnce(<FatalError error={error} />, {logLevel: 'error', renderOptions})
}
export interface RenderSelectPromptOptions<T> extends Omit<SelectPromptProps<T>, 'onSubmit'> {
isConfirmationPrompt?: boolean
renderOptions?: RenderOptions
}
/**
* Renders a select prompt to the console.
* @example
* ? Associate your project with the org Castile Ventures?
*
* ┃ Add
* ┃ • new-ext
* ┃
* ┃ Remove
* ┃ • integrated-demand-ext
* ┃ • order-discount
*
* Automations
* > fifth
* sixth
*
* Merchant Admin
* eighth
* ninth
*
* Other
* first
* second
* third (limit reached)
* fourth
* seventh
* tenth
*
* Press ↑↓ arrows to select, enter to confirm.
*
*/
export async function renderSelectPrompt<T>(
{renderOptions, isConfirmationPrompt, ...props}: RenderSelectPromptOptions<T>,
uiDebugOptions: UIDebugOptions = defaultUIDebugOptions,
): Promise<T> {
throwInNonTTY({message: props.message, stdin: renderOptions?.stdin}, uiDebugOptions)
return runWithTimer('cmd_all_timing_prompts_ms')(async () => {
let selectedValue: T
await render(
<SelectPrompt
{...props}
onSubmit={(value: T) => {
selectedValue = value
}}
/>,
{
...renderOptions,
exitOnCtrlC: false,
},
)
return selectedValue!
})
}
export interface RenderConfirmationPromptOptions extends Pick<
SelectPromptProps<boolean>,
'message' | 'infoTable' | 'infoMessage' | 'abortSignal'
> {
confirmationMessage?: string
cancellationMessage?: string
renderOptions?: RenderOptions
defaultValue?: boolean
}
/**
* Renders a confirmation prompt to the console.
* @example
* ? Delete the following themes from the store?
*
* ┃ Info message title
* ┃
* ┃ Info message body
* ┃
* ┃ • first theme (#1)
* ┃ • second theme (#2)
*
* > (y) Yes, confirm changes
* (n) Cancel
*
* Press ↑↓ arrows to select, enter or a shortcut to
* confirm.
*
*/
export async function renderConfirmationPrompt({
message,
infoTable,
confirmationMessage = 'Yes, confirm',
cancellationMessage = 'No, cancel',
renderOptions,
defaultValue = true,
abortSignal,
infoMessage,
}: RenderConfirmationPromptOptions): Promise<boolean> {
const choices = [
{
label: confirmationMessage,
value: true,
key: 'y',
},
{
label: cancellationMessage,
value: false,
key: 'n',
},
]
return renderSelectPrompt({
choices,
message,
infoTable,
renderOptions,
defaultValue,
isConfirmationPrompt: true,
abortSignal,
infoMessage,
})
}
export interface RenderAutocompleteOptions<T> extends PartialBy<
Omit<AutocompletePromptProps<T>, 'onSubmit'>,
'search'
> {
renderOptions?: RenderOptions
}
/**
* Renders an autocomplete prompt to the console.
* @example
* ? Select a template: Type to search...
*
* ┃ Info message title
* ┃
* ┃ Info message body
*
* > first
* second
* third
* fourth
* fifth
* sixth
* seventh
* eighth
* ninth
* tenth
* eleventh
* twelfth
* thirteenth
* fourteenth
* fifteenth
* sixteenth
* seventeenth
* eighteenth
* nineteenth (disabled)
* twentieth
* twenty-first
* twenty-second
* twenty-third
* twenty-fourth
* twenty-fifth
*
* Press ↑↓ arrows to select, enter to confirm.
*
*/
export async function renderAutocompletePrompt<T>(
{renderOptions, ...props}: RenderAutocompleteOptions<T>,
uiDebugOptions: UIDebugOptions = defaultUIDebugOptions,
): Promise<T> {
throwInNonTTY({message: props.message, stdin: renderOptions?.stdin}, uiDebugOptions)
const newProps = {
search(term: string) {
const lowerTerm = term.toLowerCase()
return Promise.resolve({
data: props.choices.filter((item) => {
return item.label.toLowerCase().includes(lowerTerm) || item.group?.toLowerCase().includes(lowerTerm)
}),
})
},
...props,
}
return runWithTimer('cmd_all_timing_prompts_ms')(async () => {
let selectedValue: T | undefined
await render(
<AutocompletePrompt
{...newProps}
onSubmit={(value: T) => {
selectedValue = value
}}
/>,
{
...renderOptions,
exitOnCtrlC: false,
},
)
if (selectedValue === undefined) {
throw new Error(
'Prompt was interrupted before a selection was made. This can happen if the process received a signal, was terminated, or the prompt was aborted.',
)
}
return selectedValue
})
}
interface RenderTableOptions<T extends ScalarDict> extends TableProps<T> {
renderOptions?: RenderOptions
}
/**
* Renders a table to the console.
* @example
* ID Name email
* ── ────────── ─────────────
* 1 John Doe jon@doe.com
* 2 Jane Doe jane@doe.com
* 3 John Smith jon@smith.com
*/
export function renderTable<T extends ScalarDict>({renderOptions, ...props}: RenderTableOptions<T>) {
return renderOnce(<Table {...props} />, {renderOptions})
}
interface RenderTasksOptions {
renderOptions?: RenderOptions
noProgressBar?: boolean
}
/**
* Runs async tasks and displays their progress to the console.
* @example
* ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀
* Installing dependencies ...
*/
export async function renderTasks<TContext>(
tasks: Task<TContext>[],
{renderOptions, noProgressBar}: RenderTasksOptions = {},
): Promise<TContext> {
let result: TContext | undefined
let taskError: Error | undefined
await render(
<Tasks
tasks={tasks}
onComplete={(ctx) => {
result = ctx
}}
noProgressBar={noProgressBar}
/>,
{
...renderOptions,
exitOnCtrlC: false,
},
).catch((error) => {
taskError = error
})
if (taskError) throw taskError
return result as TContext
}
export interface RenderSingleTaskOptions<T> {
title: TokenizedString
task: (updateStatus: (status: TokenizedString) => void) => Promise<T>
onAbort?: () => void
renderOptions?: RenderOptions
}
/**
* Awaits a single task and displays a loading bar while it's in progress. The task's result is returned.
* @param options - Configuration object
* @param options.title - The initial title to display with the loading bar
* @param options.task - The async task to execute. Receives an updateStatus callback to change the displayed title.
* @param options.renderOptions - Optional render configuration
* @returns The result of the task
* @example
* ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀
* Loading app ...
*/
export async function renderSingleTask<T>({
title,
task,
onAbort,
renderOptions,
}: RenderSingleTaskOptions<T>): Promise<T> {
// Result/error come from callbacks because render() may resolve prematurely
// when multiple concurrent ink instances interfere with each other's waitUntilExit().
// We race the callback promise against render() to handle both cases:
// - Normal: callback fires, then render() completes
// - Concurrent: render() resolves early due to cross-instance interference
const callbackPromise = new Promise<T>((resolve, reject) => {
render(<SingleTask title={title} task={task} onComplete={resolve} onError={reject} onAbort={onAbort} />, {
...renderOptions,
exitOnCtrlC: false,
}).catch(reject)
})
return callbackPromise
}
export interface RenderTextPromptOptions extends Omit<TextPromptProps, 'onSubmit'> {
renderOptions?: RenderOptions
}
/**
* Renders a text prompt to the console.
* @example
* ? App project name (can be changed later):
* > expansive commerce app
* ▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
*
*/
export async function renderTextPrompt(
{renderOptions, ...props}: RenderTextPromptOptions,
uiDebugOptions: UIDebugOptions = defaultUIDebugOptions,
): Promise<string> {
throwInNonTTY({message: props.message, stdin: renderOptions?.stdin}, uiDebugOptions)
return runWithTimer('cmd_all_timing_prompts_ms')(async () => {
let enteredText = ''
await render(
<TextPrompt
{...props}
onSubmit={(value: string) => {
enteredText = value
}}
/>,
{
...renderOptions,
exitOnCtrlC: false,
},
)
return enteredText
})
}
export interface RenderDangerousConfirmationPromptOptions extends Omit<DangerousConfirmationPromptProps, 'onSubmit'> {
renderOptions?: RenderOptions
}
/**
* Renders a dangerous confirmation prompt to the console, forcing the user to
* type a confirmation string to proceed.
* @example
* ? Release a new version of nightly-app-2023-06-19?
*
* ┃ Includes:
* ┃ + web-px (new)
* ┃ + sub-ui-ext
* ┃ + theme-app-ext
* ┃ + paymentify (from Partner Dashboard)
* ┃
* ┃ Removes:
* ┃ - prod-discount-fun
* ┃
* ┃ This can permanently delete app user data.
*
* Type nightly-app-2023-06-19 to confirm, or press Escape
* to cancel.
* > █
* ▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔
*
*/
export async function renderDangerousConfirmationPrompt(
{renderOptions, ...props}: RenderDangerousConfirmationPromptOptions,
uiDebugOptions: UIDebugOptions = defaultUIDebugOptions,
): Promise<boolean> {
throwInNonTTY({message: props.message, stdin: renderOptions?.stdin}, uiDebugOptions)
return runWithTimer('cmd_all_timing_prompts_ms')(async () => {
let confirmed: boolean
await render(
<DangerousConfirmationPrompt
{...props}
onSubmit={(value: boolean) => {
confirmed = value
}}
/>,
{
...renderOptions,
exitOnCtrlC: false,
},
)
return confirmed!
})
}
/** Waits for any key to be pressed except Ctrl+C which will terminate the process. */
export const keypress = async (stdin = process.stdin, uiDebugOptions: UIDebugOptions = defaultUIDebugOptions) => {
throwInNonTTY({message: 'Press any key'}, uiDebugOptions)
return runWithTimer('cmd_all_timing_prompts_ms')(() => {
return new Promise((resolve, reject) => {
const handler = (buffer: Buffer) => {
stdin.setRawMode(false)
const bytes = Array.from(buffer)
if (bytes.length && bytes[0] === 3) {
outputDebug('Canceled keypress, User pressed CTRL+C')
reject(new AbortSilentError())
}
stdin.unref()
process.nextTick(resolve)
}
stdin.setRawMode(true)
stdin.once('data', handler)
// We want to indicate that we're still using stdin, so that the process
// doesn't exit early.
stdin.ref()
})
})
}
interface IsTTYOptions {
stdin?: NodeJS.ReadStream
uiDebugOptions?: UIDebugOptions
}
export function isTTY({stdin = undefined, uiDebugOptions = defaultUIDebugOptions}: IsTTYOptions = {}) {
return Boolean(uiDebugOptions.skipTTYCheck || stdin || terminalSupportsPrompting())
}
interface ThrowInNonTTYOptions {
message: TokenItem
stdin?: NodeJS.ReadStream
}
function throwInNonTTY({message, stdin = undefined}: ThrowInNonTTYOptions, uiDebugOptions: UIDebugOptions) {
if (isTTY({stdin, uiDebugOptions})) return
const promptText = tokenItemToString(message)
const errorMessage = `Failed to prompt:
${outputContent`${outputToken.cyan(promptText)}`.value}
This usually happens when running a command non-interactively, for example in a CI environment, or when piping to or from another process.`
throw new AbortError(
errorMessage,
'To resolve this, specify the option in the command, or run the command in an interactive environment such as your local terminal.',
)
}
export type Key = InkKey
export type InfoMessage = InfoMessageProps['message']
export {Token, Task, TokenItem, InlineToken, LinkToken, TableColumn, InfoTableSection, ListToken, render, handleCtrlC}