-
Notifications
You must be signed in to change notification settings - Fork 52
/
index.tsx
321 lines (296 loc) · 8.7 KB
/
index.tsx
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
#!/usr/bin/env node
// Default to production, so that React error messages are not shown.
// Note: this must happen before we import React.
process.env.NODE_ENV = process.env.NODE_ENV || 'production'
import React, { createContext } from 'react'
import { render } from 'ink'
import { Token, Version, Build, Help, Init, ErrorBoundary } from './commands'
import { CLIArguments } from './index'
import Analytics from 'analytics-node'
import typewriter from '../analytics'
import { Config, getConfig, getTokenMethod } from './config'
import { machineId } from 'node-machine-id'
import { version } from '../../package.json'
import { loadTrackingPlan } from './api'
export interface StandardProps extends AnalyticsProps {
configPath: string
config?: Config
}
export interface AnalyticsProps {
analyticsProps: AsyncReturnType<typeof typewriterLibraryProperties>
anonymousId: string
}
export interface CLIArguments {
/** Any commands passed in to a yargs CLI. */
_: string[]
/** An optional path to a typewriter.yml (or directory with a typewriter.yml). **/
config: string
/** An optional (hidden) flag for enabling Ink debug mode. */
debug: boolean
/** Standard --version flag to print the version of this CLI. */
version: boolean
/** Standard -v flag to print the version of this CLI. */
v: boolean
/** Standard --help flag to print help on a command. */
help: boolean
/** Standard -h flag to print help on a command. */
h: boolean
}
const commandDefaults = {
builder: {
config: {
type: 'string',
default: './',
},
version: {
type: 'boolean',
default: false,
},
v: {
type: 'boolean',
default: false,
},
help: {
type: 'boolean',
default: false,
},
h: {
type: 'boolean',
default: false,
},
debug: {
type: 'boolean',
default: false,
},
},
}
// The `.argv` below will boot a Yargs CLI.
require('yargs')
.command({
...commandDefaults,
command: ['init', 'initialize', 'quickstart'],
handler: toYargsHandler(Init, {}),
})
.command({
...commandDefaults,
command: ['update', 'u', '*'],
handler: toYargsHandler(Build, { production: false, update: true }, { validateDefault: true }),
})
.command({
...commandDefaults,
command: ['build', 'b', 'd', 'dev', 'development'],
handler: toYargsHandler(Build, { production: false, update: false }),
})
.command({
...commandDefaults,
command: ['prod', 'p', 'production'],
handler: toYargsHandler(Build, { production: true, update: false }),
})
.command({
...commandDefaults,
command: ['token', 'tokens', 't'],
handler: toYargsHandler(Token, {}),
})
.command({
...commandDefaults,
command: 'version',
handler: toYargsHandler(Version, {}),
})
.command({
...commandDefaults,
command: 'help',
handler: toYargsHandler(Help, {}),
})
.strict(true)
// We override help + version ourselves.
.help(false)
.showHelpOnFail(false)
.version(false).argv
interface DebugContextProps {
/** Whether or not debug mode is enabled. */
debug: boolean
}
export const DebugContext = createContext<DebugContextProps>({ debug: false })
// Initialize analytics-node
const writeKey =
process.env.NODE_ENV === 'production'
? // Production: https://app.segment.com/segment_prod/sources/typewriter/overview
'ahPefUgNCh3w1BdkWX68vOpVgR2Blm5e'
: // Development: https://app.segment.com/segment_prod/sources/typewriter_dev/overview
'NwUMoJltCrmiW5gQZyiyvKpESDcwsj1r'
const analyticsNode = new Analytics(writeKey, {
flushAt: 1,
flushInterval: -1,
})
// Initialize the typewriter client that this CLI uses.
typewriter.setTypewriterOptions({
analytics: analyticsNode,
})
function toYargsHandler<P = {}>(
Command: React.FC<StandardProps & P>,
props: P,
cliOptions?: { validateDefault?: boolean }
) {
// Return a closure which yargs will execute if this command is run.
return async (args: CLIArguments) => {
let anonymousId = 'unknown'
try {
anonymousId = await getAnonymousId()
} catch (error) {
typewriter.errorFired({
/* eslint-disable @typescript-eslint/camelcase */
error_string: 'Failed to generate an anonymous id',
error,
})
}
try {
// The '*' command is a catch-all. We want to fail the CLI if an unknown command is
// supplied ('yarn typewriter footothebar'), instead of just running the default command.
const isValidCommand =
!cliOptions ||
!cliOptions.validateDefault ||
args._.length === 0 ||
['update', 'u'].includes(args._[0])
// We'll measure how long it takes to render this command.
const startTime = process.hrtime()
// Attempt to read a config, if one is available.
const cfg = await getConfig(args.config)
const analyticsProps = await typewriterLibraryProperties(args, cfg)
// Figure out which component to render.
let Component = Command
// Certain flags (--version, --help) will overide whatever command was provided.
if (!!args.version || !!args.v || Command.displayName === Version.displayName) {
// We override the --version flag from yargs with our own output. If it was supplied, print
// the `version` component instead.
Component = Version as typeof Command
} else if (
!isValidCommand ||
!!args.help ||
!!args.h ||
args._.includes('help') ||
Command.displayName === Help.displayName
) {
// Same goes for the --help flag.
Component = Help as typeof Command
}
// 🌟Render the command.
try {
const { waitUntilExit } = render(
<DebugContext.Provider value={{ debug: args.debug }}>
<ErrorBoundary
anonymousId={anonymousId}
analyticsProps={analyticsProps}
debug={args.debug}
>
<Component
configPath={args.config}
config={cfg}
anonymousId={anonymousId}
analyticsProps={analyticsProps}
{...props}
/>
</ErrorBoundary>
</DebugContext.Provider>,
{ debug: !!args.debug }
)
await waitUntilExit()
} catch (err) {
// Errors are handled/reported in ErrorBoundary.
process.exitCode = 1
}
// Measure how long this command took.
const [sec, nsec] = process.hrtime(startTime)
const ms = sec * 1000 + nsec / 1000000
// Fire analytics to Segment on typewriter command usage.
typewriter.commandRun({
properties: {
...analyticsProps,
duration: Math.round(ms),
},
anonymousId,
})
// If this isn't a valid command, make sure we exit with a non-zero exit code.
if (!isValidCommand) {
process.exitCode = 1
}
} catch (error) {
// If an error was thrown in the command logic above (but outside of the ErrorBoundary in Component)
// then render an ErrorBoundary.
try {
const { waitUntilExit } = render(
<DebugContext.Provider value={{ debug: args.debug }}>
<ErrorBoundary
error={error}
anonymousId={anonymousId}
analyticsProps={await typewriterLibraryProperties(args)}
debug={args.debug}
/>
</DebugContext.Provider>,
{
debug: !!args.debug,
}
)
await waitUntilExit()
} catch {
// Errors are handled/reported in ErrorBoundary.
process.exitCode = 1
}
}
}
}
/** Helper to fetch the name of the current yargs CLI command. */
function getCommand(args: CLIArguments) {
return args._.length === 0 ? 'update' : args._.join(' ')
}
/**
* Helper to generate the shared library properties shared by all analytics calls.
* See: https://app.segment.com/segment_prod/protocols/libraries/rs_1OL4GFYCh62cOIRi3PJuIOdN7uM
*/
async function typewriterLibraryProperties(
args: CLIArguments,
cfg: Config | undefined = undefined
) {
// In CI environments, or if there is no internet, we may not be able to execute the
// the token script.
let tokenMethod: string | undefined = undefined
try {
tokenMethod = await getTokenMethod(cfg, args.config)
} catch {}
// Attempt to read the name of the Tracking Plan from a local `plan.json`.
// If this fails, that's fine -- we'll still have the id from the config.
let trackingPlanName = ''
try {
if (cfg && cfg.trackingPlans.length > 0) {
const tp = await loadTrackingPlan(args.config, cfg.trackingPlans[0])
if (tp) {
trackingPlanName = tp.display_name
}
}
} catch {}
return {
/* eslint-disable @typescript-eslint/camelcase */
version,
client: cfg && {
language: cfg.client.language,
sdk: cfg.client.sdk,
},
command: getCommand(args),
is_ci: Boolean(process.env.CI),
token_method: tokenMethod,
tracking_plan:
cfg && cfg.trackingPlans && cfg.trackingPlans.length > 0
? {
name: trackingPlanName,
id: cfg.trackingPlans[0].id,
workspace_slug: cfg.trackingPlans[0].workspaceSlug,
}
: undefined,
}
}
/**
* We generate an anonymous ID that is unique per user, s.t. we can group analytics from
* the same user together.
*/
async function getAnonymousId() {
return await machineId(false)
}