@greenmind/cli 0.0.0-stage → 0.9.40

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/src/client.ts ADDED
@@ -0,0 +1,549 @@
1
+ import {
2
+ type CollectionStorageAnswer,
3
+ type CollectionStorageName,
4
+ type CollectionStorageSetRequest,
5
+ collectionStorageAnswer,
6
+ type ConfigDefaultsAnswer,
7
+ type ConfigDefaultsRequest,
8
+ type ConnectorCheckAnswer,
9
+ configDefaultsAnswer,
10
+ connectorCheckAnswer,
11
+ type FlowSwitchRequest,
12
+ type FunctionRuntimeSetRequest,
13
+ s,
14
+ type EnvironmentListAnswer,
15
+ type EnvironmentStatus,
16
+ environmentListAnswer,
17
+ environmentStatus,
18
+ type EventsReplayAnswer,
19
+ type EventsReplayRequest,
20
+ eventsReplayAnswer,
21
+ type ExtToolDiscovery,
22
+ extToolDiscovery,
23
+ type FlowSwitchAnswer,
24
+ type FunctionRuntimeAnswer,
25
+ type FunctionRuntimeName,
26
+ flowSwitchAnswer,
27
+ functionRuntimeAnswer,
28
+ type JobEnqueueRequest,
29
+ type Json,
30
+ type KeyCreateRequest,
31
+ type KeyUpdateRequest,
32
+ type PoolCreateRequestWire,
33
+ type PoolSettingsWire,
34
+ parserOf,
35
+ type Schema,
36
+ type SeededValue,
37
+ DEVELOPER_CLI_PATH,
38
+ type DeveloperEnvironment,
39
+ type DeveloperRefusal,
40
+ developerPaths,
41
+ developerRefusal,
42
+ environmentAddressOf,
43
+ platformFailure,
44
+ } from '@greenmind/ext-schema'
45
+ import type { CompiledDefinition } from '@greenmind/ext-sdk'
46
+ import { CLI_VERSION, ENV_ORG, VERSION_HEADER } from './constants'
47
+ import {
48
+ type CheckAnswer,
49
+ type CheckIssue,
50
+ checkAnswer,
51
+ checkIssues,
52
+ type FunctionUploadAnswer,
53
+ type FunctionUploadRequest,
54
+ functionUploadAnswer,
55
+ type PushAnswer,
56
+ pushAnswer,
57
+ type SourceRef,
58
+ } from './protocol'
59
+
60
+ /** The platform said no, or said something this tool does not understand. */
61
+ export class PlatformError extends Error {
62
+ override readonly name: string = 'PlatformError'
63
+ constructor(
64
+ message: string,
65
+ readonly status: number,
66
+ readonly failure?: DeveloperRefusal,
67
+ ) {
68
+ super(message)
69
+ }
70
+
71
+ /** The refusal's code, such as `forbidden` or `not-found`. */
72
+ get code(): string | undefined {
73
+ return this.failure?.code
74
+ }
75
+
76
+ /** The definitions' issues, when the platform refused them. */
77
+ get issues(): readonly CheckIssue[] {
78
+ const parsed = parserOf(checkIssues).safeParse(this.failure?.details?.issues)
79
+ return parsed.success ? parsed.data : []
80
+ }
81
+ }
82
+
83
+ /** The platform needs a newer `gm` than this one, whatever code it said so with. */
84
+ export class UpgradeRequiredError extends PlatformError {
85
+ override readonly name = 'UpgradeRequiredError'
86
+ }
87
+
88
+ /**
89
+ * Where a signed-in person's access token comes from. `refresh` is given the token a request was
90
+ * refused with and answers a new one, or nothing where the person has to sign in again.
91
+ */
92
+ export interface TokenSource {
93
+ accessToken(): Promise<string>
94
+ refresh(rejected: string): Promise<string | undefined>
95
+ }
96
+
97
+ interface CommonOptions {
98
+ /** The developer API's origin, such as `https://developer.publishing.example.test`. */
99
+ readonly baseUrl: string
100
+ /** The handle of the org whose environments the calls name; every environment's call needs one. */
101
+ readonly org?: string
102
+ /** The environment a call that names none is for: the one `--env` named, say. */
103
+ readonly appKey?: string
104
+ /** Replaced in tests; defaults to the global `fetch`. */
105
+ readonly fetch?: typeof fetch
106
+ /** Sent as `x-gm-cli-version`; the package's own version unless a test says otherwise. */
107
+ readonly cliVersion?: string
108
+ }
109
+
110
+ export type PlatformClientOptions = CommonOptions &
111
+ (
112
+ | {
113
+ /**
114
+ * An org key, held by the platform to its scope and permissions in each environment a call
115
+ * names: `edit_config` to push, upload, seed or switch flows, `view_config` to check.
116
+ */
117
+ readonly orgKey: string
118
+ readonly tokens?: undefined
119
+ }
120
+ | { readonly tokens: TokenSource; readonly orgKey?: undefined }
121
+ )
122
+
123
+ interface DefinitionsBody {
124
+ readonly definitions: readonly CompiledDefinition[]
125
+ readonly source?: SourceRef
126
+ readonly live?: boolean
127
+ }
128
+
129
+ /**
130
+ * Everything this client's own calls send, and `RequestBody` for what a command outside this package
131
+ * sends through `request`: a request shape from `@greenmind/ext-schema`, never an arbitrary object.
132
+ */
133
+ type Body =
134
+ | DefinitionsBody
135
+ | FunctionUploadRequest
136
+ | ConfigDefaultsRequest
137
+ | FlowSwitchRequest
138
+ | EventsReplayRequest
139
+ | FunctionRuntimeSetRequest
140
+ | CollectionStorageSetRequest
141
+ | KeyCreateRequest
142
+ | KeyUpdateRequest
143
+ | PoolCreateRequestWire
144
+ | PoolSettingsWire
145
+ | JobEnqueueRequest
146
+ | RequestBody
147
+
148
+ /** A body for `request`: one of the wire's request shapes, which are plain JSON. */
149
+ export type RequestBody = { readonly [field: string]: Json | readonly string[] }
150
+
151
+ const minimumVersion = parserOf(s.string({ minLength: 1, maxLength: 64 }))
152
+
153
+ interface Exchange {
154
+ readonly status: number
155
+ readonly json: Json | undefined
156
+ }
157
+
158
+ function parseJson(text: string): Json | undefined {
159
+ try {
160
+ return JSON.parse(text)
161
+ } catch {
162
+ return undefined
163
+ }
164
+ }
165
+
166
+ /**
167
+ * A refusal in the developer API's `{ code, message, retryable }` form, or in the platform's
168
+ * `{ error, message }` form, said the developer API's way; undefined for an answer that is
169
+ * neither.
170
+ */
171
+ function refusalOf(got: Exchange): DeveloperRefusal | undefined {
172
+ const developer = parserOf(developerRefusal).safeParse(got.json)
173
+ if (developer.success) return developer.data
174
+ const platform = parserOf(platformFailure).safeParse(got.json)
175
+ if (!platform.success) return undefined
176
+ const { error, message, details } = platform.data
177
+ return { code: error, message, retryable: got.status === 503, details }
178
+ }
179
+
180
+ /** The code of a refusal, if the answer is one. */
181
+ function refusalCodeOf(got: Exchange): string | undefined {
182
+ return refusalOf(got)?.code
183
+ }
184
+
185
+ /**
186
+ * What a platform says about signing in to it (`DEVELOPER_CLI_PATH`), asked with no credential
187
+ * before anybody has one. Throws a `PlatformError` where it answers anything else.
188
+ */
189
+ export async function readToolDiscovery(
190
+ platformUrl: string,
191
+ send: typeof fetch = fetch,
192
+ ): Promise<ExtToolDiscovery> {
193
+ const url = `${platformUrl.replace(/\/+$/, '')}${DEVELOPER_CLI_PATH}`
194
+ let response: Response
195
+ try {
196
+ response = await send(url, {
197
+ headers: { accept: 'application/json', [VERSION_HEADER]: CLI_VERSION },
198
+ signal: AbortSignal.timeout(20_000),
199
+ })
200
+ } catch (error) {
201
+ throw new PlatformError(
202
+ `Could not reach the platform at ${platformUrl}: ${error instanceof Error ? error.message : error}.`,
203
+ 0,
204
+ )
205
+ }
206
+ const parsed = parserOf(extToolDiscovery).safeParse(parseJson(await response.text()))
207
+ if (!response.ok || !parsed.success) {
208
+ throw new PlatformError(
209
+ `${url} did not say where to sign in (status ${response.status}). Give the identity server with --issuer.`,
210
+ response.status,
211
+ )
212
+ }
213
+ return parsed.data
214
+ }
215
+
216
+ /**
217
+ * Calls the developer API with an org key or as a signed-in person, and parses every answer with
218
+ * the shape `@greenmind/ext-schema` gives it. A refusal becomes a `PlatformError` naming its code.
219
+ */
220
+ export class PlatformClient {
221
+ private readonly base: string
222
+ private readonly org?: string
223
+ private readonly appKey?: string
224
+ private readonly orgKey?: string
225
+ private readonly tokens?: TokenSource
226
+ private readonly send: typeof fetch
227
+ private readonly version: string
228
+
229
+ constructor(options: PlatformClientOptions) {
230
+ this.base = options.baseUrl.replace(/\/+$/, '')
231
+ this.org = options.org
232
+ this.appKey = options.appKey
233
+ this.orgKey = options.orgKey
234
+ this.tokens = options.tokens
235
+ this.send = options.fetch ?? fetch
236
+ this.version = options.cliVersion ?? CLI_VERSION
237
+ }
238
+
239
+ /** A client with this one's credential for another GreenMind service, at `baseUrl`. */
240
+ at(baseUrl: string): PlatformClient {
241
+ const common = {
242
+ baseUrl,
243
+ org: this.org,
244
+ appKey: this.appKey,
245
+ fetch: this.send,
246
+ cliVersion: this.version,
247
+ }
248
+ if (this.tokens) return new PlatformClient({ ...common, tokens: this.tokens })
249
+ return new PlatformClient({ ...common, orgKey: this.orgKey ?? '' })
250
+ }
251
+
252
+ /**
253
+ * Any route, for commands this client has no method of its own for: the answer parsed with
254
+ * `answer`, a refusal a `PlatformError`, and a refused sign-in renewed once, as every call is.
255
+ */
256
+ request<T>(method: string, path: string, body: Body | undefined, answer: Schema<T>) {
257
+ return this.call(method, path, body, answer)
258
+ }
259
+
260
+ /** As `request`, for a route answered 204 with nothing. */
261
+ requestNoContent(method: string, path: string, body?: RequestBody): Promise<void> {
262
+ return this.callNoContent(method, path, body)
263
+ }
264
+
265
+ /** The address this client calls, without a trailing slash. */
266
+ get address(): string {
267
+ return this.base
268
+ }
269
+
270
+ /**
271
+ * What the environment's validation says of these definitions, and which environment it is.
272
+ * `appKey` names the environment, or the client's own when left out, as for every call.
273
+ */
274
+ check(definitions: readonly CompiledDefinition[], appKey?: string): Promise<CheckAnswer> {
275
+ return this.call(
276
+ 'POST',
277
+ this.pathOf(appKey, developerPaths.definitionsCheck),
278
+ { definitions },
279
+ checkAnswer,
280
+ )
281
+ }
282
+
283
+ /**
284
+ * Makes each definition a new version in the environment, unless it already holds that hash; with
285
+ * `live`, then makes each pushed version live, and with `retire` too, takes the flows and
286
+ * schedules an earlier push made live and this one leaves out off the live set.
287
+ */
288
+ push(
289
+ definitions: readonly CompiledDefinition[],
290
+ source?: SourceRef,
291
+ live?: boolean,
292
+ appKey?: string,
293
+ retire?: boolean,
294
+ ): Promise<PushAnswer> {
295
+ return this.call(
296
+ 'POST',
297
+ this.pathOf(appKey, developerPaths.definitions),
298
+ { definitions, source, live, ...(retire && { retire }) },
299
+ pushAnswer,
300
+ )
301
+ }
302
+
303
+ /** Stores a built bundle in the environment and saves its functions as versions naming it. */
304
+ upload(body: FunctionUploadRequest, appKey?: string): Promise<FunctionUploadAnswer> {
305
+ return this.call(
306
+ 'POST',
307
+ this.pathOf(appKey, developerPaths.functions),
308
+ body,
309
+ functionUploadAnswer,
310
+ )
311
+ }
312
+
313
+ /**
314
+ * An environment's route on the developer API. The address names the org, the project and the
315
+ * environment, so every call needs an org and an environment, the call's or the client's own.
316
+ */
317
+ private pathOf(
318
+ appKey: string | undefined,
319
+ route: (environment: DeveloperEnvironment) => string,
320
+ ): string {
321
+ return route(this.environmentOf(appKey))
322
+ }
323
+
324
+ /** The address of `appKey`, or of the client's own environment, in the client's org. */
325
+ environmentOf(appKey?: string): DeveloperEnvironment {
326
+ const named = appKey ?? this.appKey
327
+ if (named === undefined) {
328
+ throw new PlatformError('Name the environment with --env <app key>.', 400)
329
+ }
330
+ return environmentAddressOf({ org: this.orgHandle(), appKey: named })
331
+ }
332
+
333
+ /** The org the calls name; refused when none was given. */
334
+ orgHandle(): string {
335
+ if (!this.org) {
336
+ throw new PlatformError(
337
+ `Name the organisation the environment is in with --org <handle> or ${ENV_ORG}.`,
338
+ 400,
339
+ )
340
+ }
341
+ return this.org
342
+ }
343
+
344
+ /** Every environment of `project` the person may read. */
345
+ listEnvironments(project: string): Promise<EnvironmentListAnswer> {
346
+ return this.call(
347
+ 'GET',
348
+ developerPaths.apps({ org: this.orgHandle(), project }),
349
+ undefined,
350
+ environmentListAnswer,
351
+ )
352
+ }
353
+
354
+ environmentStatus(appKey: string): Promise<EnvironmentStatus> {
355
+ return this.call(
356
+ 'GET',
357
+ this.pathOf(appKey, developerPaths.environment),
358
+ undefined,
359
+ environmentStatus,
360
+ )
361
+ }
362
+
363
+ /** Gives the environment each value it lacks; one it holds is left as it is. */
364
+ seedConfigDefaults(
365
+ values: readonly SeededValue[],
366
+ appKey?: string,
367
+ ): Promise<ConfigDefaultsAnswer> {
368
+ return this.call(
369
+ 'POST',
370
+ this.pathOf(appKey, developerPaths.configDefaults),
371
+ { values },
372
+ configDefaultsAnswer,
373
+ )
374
+ }
375
+
376
+ switchFlows(
377
+ flows: readonly { readonly key: string; readonly enabled: boolean }[],
378
+ appKey?: string,
379
+ ): Promise<FlowSwitchAnswer> {
380
+ return this.call(
381
+ 'PATCH',
382
+ this.pathOf(appKey, developerPaths.flows),
383
+ { flows },
384
+ flowSwitchAnswer,
385
+ )
386
+ }
387
+
388
+ /** One call of a replay of kept events into a flow; send `next` back as `after` to carry on. */
389
+ replayEvents(request: EventsReplayRequest, appKey?: string): Promise<EventsReplayAnswer> {
390
+ return this.call(
391
+ 'POST',
392
+ this.pathOf(appKey, developerPaths.eventsReplay),
393
+ request,
394
+ eventsReplayAnswer,
395
+ )
396
+ }
397
+
398
+ /** Whether this client acts as a signed-in person rather than with an org key. */
399
+ get signedIn(): boolean {
400
+ return this.tokens !== undefined
401
+ }
402
+
403
+ /** The org handle the calls name, if one was given. */
404
+ get orgName(): string | undefined {
405
+ return this.org
406
+ }
407
+
408
+ functionRuntime(appKey: string): Promise<FunctionRuntimeAnswer> {
409
+ return this.call(
410
+ 'GET',
411
+ this.pathOf(appKey, developerPaths.functionsRuntime),
412
+ undefined,
413
+ functionRuntimeAnswer,
414
+ )
415
+ }
416
+
417
+ /** `null` clears the environment's own choice, so it follows the stage default. */
418
+ setFunctionRuntime(
419
+ appKey: string,
420
+ runtime: FunctionRuntimeName | null,
421
+ ): Promise<FunctionRuntimeAnswer> {
422
+ return this.call(
423
+ 'PUT',
424
+ this.pathOf(appKey, developerPaths.functionsRuntime),
425
+ { runtime },
426
+ functionRuntimeAnswer,
427
+ )
428
+ }
429
+
430
+ collectionStorage(appKey: string): Promise<CollectionStorageAnswer> {
431
+ return this.call(
432
+ 'GET',
433
+ this.pathOf(appKey, developerPaths.collectionsStorage),
434
+ undefined,
435
+ collectionStorageAnswer,
436
+ )
437
+ }
438
+
439
+ /** `null` clears the environment's own default, so it follows its organisation's. */
440
+ setCollectionStorageDefault(
441
+ appKey: string,
442
+ mode: CollectionStorageName | null,
443
+ ): Promise<CollectionStorageAnswer> {
444
+ return this.call(
445
+ 'PUT',
446
+ this.pathOf(appKey, developerPaths.collectionsStorage),
447
+ { default: mode },
448
+ collectionStorageAnswer,
449
+ )
450
+ }
451
+
452
+ /** Runs the connector check of the data connection `connection` for self-hosted collections. */
453
+ checkConnector(appKey: string, connection: string): Promise<ConnectorCheckAnswer> {
454
+ return this.call(
455
+ 'POST',
456
+ this.pathOf(appKey, (environment) => developerPaths.connectionCheck(environment, connection)),
457
+ {},
458
+ connectorCheckAnswer,
459
+ )
460
+ }
461
+
462
+ private async call<T>(
463
+ method: string,
464
+ path: string,
465
+ body: Body | undefined,
466
+ answer: Schema<T>,
467
+ ): Promise<T> {
468
+ const got = await this.exchange(method, path, body)
469
+ if (got.status >= 400) throw this.refusal(got)
470
+ const parsed = parserOf(answer).safeParse(got.json)
471
+ if (!parsed.success) {
472
+ const why = parsed.error.issues[0]?.message ?? 'invalid'
473
+ throw new PlatformError(
474
+ `The platform's answer to ${path} is not what this tool expects: ${why}.`,
475
+ got.status,
476
+ )
477
+ }
478
+ return parsed.data
479
+ }
480
+
481
+ /** For a route answered 204 with no body; any other success is not what this tool expects. */
482
+ private async callNoContent(method: string, path: string, body?: Body): Promise<void> {
483
+ const got = await this.exchange(method, path, body)
484
+ if (got.status >= 400) throw this.refusal(got)
485
+ if (got.status !== 204) {
486
+ throw new PlatformError(
487
+ `The answer to ${path} is not what this tool expects: status ${got.status}, not 204.`,
488
+ got.status,
489
+ )
490
+ }
491
+ }
492
+
493
+ /**
494
+ * One request, and where a signed-in person's token was refused as `unauthorized`, one more with
495
+ * a fresh one: the refresh token is spent once and a second refusal is the answer, so this never
496
+ * loops. A 401 that is not the platform's refusal of the sign-in (a proxy's, say) spends nothing.
497
+ */
498
+ private async exchange(method: string, path: string, body: Body | undefined): Promise<Exchange> {
499
+ const token = this.tokens ? await this.tokens.accessToken() : this.orgKey
500
+ const first = await this.once(method, path, body, token)
501
+ if (first.status !== 401 || !this.tokens || !token) return first
502
+ if (refusalCodeOf(first) !== 'unauthorized') return first
503
+ const renewed = await this.tokens.refresh(token)
504
+ return renewed ? this.once(method, path, body, renewed) : first
505
+ }
506
+
507
+ private async once(
508
+ method: string,
509
+ path: string,
510
+ body: Body | undefined,
511
+ token: string | undefined,
512
+ ): Promise<Exchange> {
513
+ const headers = new Headers({
514
+ accept: 'application/json',
515
+ authorization: `Bearer ${token}`,
516
+ [VERSION_HEADER]: this.version,
517
+ })
518
+ if (body !== undefined) headers.set('content-type', 'application/json')
519
+ const response = await this.send(`${this.base}${path}`, {
520
+ method,
521
+ headers,
522
+ body: body === undefined ? undefined : JSON.stringify(body),
523
+ })
524
+ return { status: response.status, json: parseJson(await response.text()) }
525
+ }
526
+
527
+ private refusal(got: Exchange): PlatformError {
528
+ const details = refusalOf(got)
529
+ // Only the platform's own refusal naming the version it needs: a 426 from anything in between
530
+ // (a proxy asking for another protocol) is not about this tool's version.
531
+ const minimum = minimumVersion.safeParse(details?.details?.['minimum'])
532
+ if (got.status === 426 && minimum.success) {
533
+ return new UpgradeRequiredError(
534
+ `This version of gm (${this.version}) is too old for the platform: ${minimum.data} or newer is needed. Update @greenmind/cli and the packages beside it, and run the command again.`,
535
+ got.status,
536
+ details,
537
+ )
538
+ }
539
+ if (got.status === 401 && this.tokens && details?.code === 'unauthorized') {
540
+ return new PlatformError(
541
+ 'The platform did not accept your sign-in. Run `gm login` to sign in again.',
542
+ got.status,
543
+ details,
544
+ )
545
+ }
546
+ if (!details) return new PlatformError(`The platform answered ${got.status}.`, got.status)
547
+ return new PlatformError(`${details.code}: ${details.message}`, got.status, details)
548
+ }
549
+ }