@greenmind/cli 0.0.0-stage → 0.9.31

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,549 @@
1
+ import { readFileSync } from 'node:fs'
2
+ import {
3
+ type CollectionStorageAnswer,
4
+ type CollectionStorageName,
5
+ type CollectionStorageUnavailable,
6
+ type ConnectorCheckAnswer,
7
+ configDefaultsRequest,
8
+ type EnvironmentStatus,
9
+ type FunctionRuntimeAnswer,
10
+ type FunctionRuntimeEffect,
11
+ type FunctionRuntimeName,
12
+ parserOf,
13
+ type PublishKeyEntry,
14
+ SETUP_ITEMS_MAX,
15
+ type SeededValue,
16
+ type ServerKeyEntry,
17
+ } from '@greenmind/ext-schema'
18
+ import { type PlatformClient, PlatformError } from './client'
19
+ import { type Print, runPush, runUpload } from './commands'
20
+ import { ENV_KEY, ENV_URL } from './constants'
21
+ import type { LoadedExtConfig } from './ext-config'
22
+ import { loadDefinitions, LoadError } from './load'
23
+ import type { SourceRef } from './protocol'
24
+
25
+ /**
26
+ * What each environment-setup command does once it has a client: ask the platform, print what it
27
+ * said in a readable layout, answer whether it went well. A secret a key's creation returns is
28
+ * printed here once and nowhere else.
29
+ */
30
+
31
+ /** Rows laid out in columns two spaces apart, the last cell of each left as long as it is. */
32
+ export function columns(rows: readonly (readonly string[])[], indent = ''): string[] {
33
+ const widths = rows.reduce<number[]>((all, row) => {
34
+ row.forEach((cell, at) => {
35
+ all[at] = Math.max(all[at] ?? 0, cell.length)
36
+ })
37
+ return all
38
+ }, [])
39
+ return rows.map(
40
+ (row) =>
41
+ indent +
42
+ row
43
+ .map((cell, at) => (at === row.length - 1 ? cell : cell.padEnd(widths[at] ?? 0)))
44
+ .join(' ')
45
+ .trimEnd(),
46
+ )
47
+ }
48
+
49
+ const when = (instant: string | null) => instant ?? 'never'
50
+ const plural = (count: number, word: string) => `${count} ${word}${count === 1 ? '' : 's'}`
51
+
52
+ export async function runEnvironmentList(client: PlatformClient, print: Print): Promise<boolean> {
53
+ const { environments } = await client.listEnvironments()
54
+ if (environments.length === 0) {
55
+ print('You can read no environments.')
56
+ return true
57
+ }
58
+ const rows = environments.map((each) => [
59
+ each.appKey,
60
+ each.environment,
61
+ each.protected ? 'protected' : '',
62
+ `${each.org.name} / ${each.project.name}`,
63
+ each.level ? `can ${each.level}` : '',
64
+ ])
65
+ for (const line of columns([
66
+ ['APP KEY', 'ENVIRONMENT', '', 'ORGANISATION / PROJECT', 'ACCESS'],
67
+ ...rows,
68
+ ])) {
69
+ print(line)
70
+ }
71
+ return true
72
+ }
73
+
74
+ function runtimeLine(effect: FunctionRuntimeEffect | null): string[] {
75
+ if (!effect) return ['Runtime nothing was ever asked of it']
76
+ const lines = [
77
+ `Runtime wanted ${effect.wanted}, in effect ${effect.inEffect ?? 'not yet'} (${effect.status})`,
78
+ ` asked ${effect.requestedAt}, applied ${when(effect.appliedAt)}`,
79
+ ]
80
+ if (effect.problem) lines.push(` problem: ${effect.problem}`)
81
+ return lines
82
+ }
83
+
84
+ /** Every field of an environment's status, grouped the way somebody reads it. */
85
+ export function describeStatus(status: EnvironmentStatus): string[] {
86
+ const lines: string[] = [
87
+ `${status.appKey} ${status.name} (${status.environment}${status.protected ? ', changed by a release only' : ''})`,
88
+ `Project ${status.project.name} (${status.project.key})`,
89
+ status.gameDatabaseKey
90
+ ? `Database ${status.gameDatabaseKey}`
91
+ : 'Database none: its functions and flows run nowhere yet',
92
+ ]
93
+ const { writer } = status
94
+ lines.push(
95
+ `Writer ${writer.writer}${writer.switchedAt ? `, switched ${writer.switchedAt} by ${writer.switchedBy ?? 'unknown'}` : ', never switched'}`,
96
+ )
97
+ if (writer.waitMs !== null) {
98
+ lines.push(` paused: the engine may start in ${Math.ceil(writer.waitMs / 1000)} s`)
99
+ }
100
+ lines.push(...runtimeLine(status.runtime))
101
+ lines.push(`Flows ${status.flows.on} of ${status.flows.total} on`)
102
+ lines.push('Definitions')
103
+ if (status.definitions.length === 0) lines.push(' none')
104
+ for (const kind of status.definitions) {
105
+ lines.push(` ${kind.kind}: ${kind.total} total, ${kind.live} live`)
106
+ lines.push(
107
+ ...columns(
108
+ kind.definitions.map((each) => [
109
+ each.key,
110
+ each.liveVersion === null ? 'no live version' : `v${each.liveVersion}`,
111
+ each.contentHash?.slice(0, 12) ?? '',
112
+ ]),
113
+ ' ',
114
+ ),
115
+ )
116
+ }
117
+ const landing = status.lastLanding
118
+ if (landing) {
119
+ lines.push(
120
+ `Last landing ${landing.landingId} on ${landing.gameDatabaseKey}: ${landing.status} (${landing.scope}, ${plural(landing.attempts, 'attempt')})`,
121
+ ` queued ${landing.queuedAt}, landed ${when(landing.landedAt)}`,
122
+ )
123
+ if (landing.lastError) lines.push(` error: ${landing.lastError}`)
124
+ } else {
125
+ lines.push('Last landing nothing was ever landed or queued')
126
+ }
127
+ const { server, publish } = status.keys
128
+ lines.push(
129
+ `Server keys ${server.live} live, ${server.revoked} revoked`,
130
+ `Publish keys ${publish.live} live, ${publish.revoked} revoked`,
131
+ )
132
+ return lines
133
+ }
134
+
135
+ export async function runEnvironmentStatus(
136
+ client: PlatformClient,
137
+ appKey: string,
138
+ print: Print,
139
+ ): Promise<boolean> {
140
+ for (const line of describeStatus(await client.environmentStatus(appKey))) print(line)
141
+ return true
142
+ }
143
+
144
+ type KeyKind = 'server' | 'publish'
145
+
146
+ function describeKeys(entries: readonly (ServerKeyEntry | PublishKeyEntry)[]): string[] {
147
+ if (entries.length === 0) return ['No keys.']
148
+ return columns([
149
+ ['ID', 'NAME', 'PREFIX', 'CREATED', 'LAST USED', ''],
150
+ ...entries.map((each) => [
151
+ each.id,
152
+ 'name' in each ? each.name : each.label,
153
+ each.prefix,
154
+ each.createdAt,
155
+ when(each.lastUsedAt),
156
+ each.revokedAt ? `revoked ${each.revokedAt}` : '',
157
+ ]),
158
+ ])
159
+ }
160
+
161
+ export async function runKeysList(
162
+ client: PlatformClient,
163
+ kind: KeyKind,
164
+ appKey: string,
165
+ print: Print,
166
+ ): Promise<boolean> {
167
+ const keys =
168
+ kind === 'server'
169
+ ? (await client.listServerKeys(appKey)).keys
170
+ : (await client.listPublishKeys(appKey)).keys
171
+ for (const line of describeKeys(keys)) print(line)
172
+ return true
173
+ }
174
+
175
+ /**
176
+ * Makes a key and prints its secret, the one time the platform ever gives it. For a server key
177
+ * the next step is the studio's: its backend's own config, which this tool cannot reach.
178
+ */
179
+ export async function runKeysCreate(
180
+ client: PlatformClient,
181
+ kind: KeyKind,
182
+ appKey: string,
183
+ name: string,
184
+ print: Print,
185
+ ): Promise<boolean> {
186
+ const created =
187
+ kind === 'server'
188
+ ? await client.createServerKey(appKey, name)
189
+ : await client.createPublishKey(appKey, name)
190
+ print(`Created the ${kind} key ${created.key.prefix} for ${appKey}.`)
191
+ print('')
192
+ print(created.secret)
193
+ print('')
194
+ print(
195
+ 'This is the only time the key is shown; it is kept only as a hash and cannot be read back.',
196
+ )
197
+ if (kind === 'server') {
198
+ print(
199
+ `Next: put the platform address (${client.address}) and this key in your game backend's own config.`,
200
+ )
201
+ } else {
202
+ print(`Next: give it to your build as ${ENV_KEY}, with ${ENV_URL} set to ${client.address}.`)
203
+ }
204
+ return true
205
+ }
206
+
207
+ /** A key by its id, or by its prefix where that names exactly one. */
208
+ async function keyIdOf(
209
+ client: PlatformClient,
210
+ kind: KeyKind,
211
+ appKey: string,
212
+ given: string,
213
+ ): Promise<string> {
214
+ const keys =
215
+ kind === 'server'
216
+ ? (await client.listServerKeys(appKey)).keys
217
+ : (await client.listPublishKeys(appKey)).keys
218
+ if (keys.some((each) => each.id === given)) return given
219
+ const byPrefix = keys.filter((each) => each.prefix === given)
220
+ if (byPrefix.length === 1 && byPrefix[0]) return byPrefix[0].id
221
+ throw new PlatformError(
222
+ `${appKey} has no ${kind} key with the id or prefix ${given}. \`gm pub keys ${kind} list ${appKey}\` shows them.`,
223
+ 404,
224
+ )
225
+ }
226
+
227
+ export async function runKeysRevoke(
228
+ client: PlatformClient,
229
+ kind: KeyKind,
230
+ appKey: string,
231
+ given: string,
232
+ print: Print,
233
+ ): Promise<boolean> {
234
+ const id = await keyIdOf(client, kind, appKey, given)
235
+ if (kind === 'server') await client.revokeServerKey(appKey, id)
236
+ else await client.revokePublishKey(appKey, id)
237
+ print(`Revoked the ${kind} key ${given} of ${appKey}.`)
238
+ return true
239
+ }
240
+
241
+ /** The values in a file: `{ values: [...] }` as the route takes them, or the list alone. */
242
+ export function readSeedFile(file: string): readonly SeededValue[] {
243
+ let body: object | null
244
+ try {
245
+ body = JSON.parse(readFileSync(file, 'utf8'))
246
+ } catch (error) {
247
+ throw new LoadError(
248
+ `${file} is not valid JSON: ${error instanceof Error ? error.message : error}.`,
249
+ )
250
+ }
251
+ const parsed = parserOf(configDefaultsRequest).safeParse(
252
+ Array.isArray(body) ? { values: body } : body,
253
+ )
254
+ if (!parsed.success) {
255
+ const issue = parsed.error.issues[0]
256
+ throw new LoadError(
257
+ `${file} is not a list of config values${issue?.path.length ? ` (at ${issue.path.join('.')})` : ''}: ${issue?.message ?? 'invalid'}.`,
258
+ )
259
+ }
260
+ return parsed.data.values
261
+ }
262
+
263
+ function chunks<T>(items: readonly T[]): T[][] {
264
+ const out: T[][] = []
265
+ for (let at = 0; at < items.length; at += SETUP_ITEMS_MAX) {
266
+ out.push(items.slice(at, at + SETUP_ITEMS_MAX))
267
+ }
268
+ return out
269
+ }
270
+
271
+ /**
272
+ * The environment a setup command acts in: a publish key's own, so one named must be it (the
273
+ * platform checks); a signed-in person has to name it, since their sign-in reaches several.
274
+ */
275
+ function setupEnvironment(client: PlatformClient, appKey: string | undefined): string | undefined {
276
+ if (appKey === undefined && client.signedIn) {
277
+ throw new PlatformError(
278
+ 'Signed in as a person, name the environment with --env <app key>; a publish key needs none.',
279
+ 400,
280
+ )
281
+ }
282
+ return appKey
283
+ }
284
+
285
+ export async function runConfigSeed(
286
+ client: PlatformClient,
287
+ values: readonly SeededValue[],
288
+ print: Print,
289
+ appKey?: string,
290
+ ): Promise<boolean> {
291
+ if (values.length === 0) {
292
+ print('There are no config values to seed.')
293
+ return true
294
+ }
295
+ const environment = setupEnvironment(client, appKey)
296
+ const seeded: string[] = []
297
+ for (const part of chunks(values)) {
298
+ seeded.push(...(await client.seedConfigDefaults(part, environment)).seeded)
299
+ }
300
+ for (const name of seeded) print(`seeded ${name}`)
301
+ print(
302
+ `${seeded.length} of ${plural(values.length, 'value')} seeded; the rest the environment already holds and are left as they are.`,
303
+ )
304
+ return true
305
+ }
306
+
307
+ export async function runFlowSwitch(
308
+ client: PlatformClient,
309
+ keys: readonly string[],
310
+ enabled: boolean,
311
+ print: Print,
312
+ appKey?: string,
313
+ ): Promise<boolean> {
314
+ if (keys.length === 0) {
315
+ print('There are no flows to switch.')
316
+ return true
317
+ }
318
+ const environment = setupEnvironment(client, appKey)
319
+ for (const part of chunks(keys)) {
320
+ const answer = await client.switchFlows(
321
+ part.map((key) => ({ key, enabled })),
322
+ environment,
323
+ )
324
+ for (const flow of answer.flows) print(`${flow.enabled ? 'on ' : 'off'} ${flow.key}`)
325
+ }
326
+ print(`${plural(keys.length, 'flow')} switched ${enabled ? 'on' : 'off'}.`)
327
+ return true
328
+ }
329
+
330
+ /** Every flow the given paths define, by key. */
331
+ export async function flowKeysOf(paths: readonly string[]): Promise<string[]> {
332
+ const definitions = await loadDefinitions(paths)
333
+ return definitions.filter((definition) => definition.kind === 'flow').map((each) => each.key)
334
+ }
335
+
336
+ export function describeRuntime(answer: FunctionRuntimeAnswer): string[] {
337
+ const lines = [
338
+ `${answer.appKey}`,
339
+ `Options ${answer.options.join(', ')} (its organisation may use these)`,
340
+ `Own choice ${answer.own ?? 'none, it follows the stage default'}`,
341
+ `Stage ${answer.stageDefault ?? 'no default'}`,
342
+ `Wanted ${answer.wanted}`,
343
+ ]
344
+ if (answer.refused) {
345
+ lines.push(
346
+ `Refused its config holds ${answer.refused}, which its organisation may not use, so it runs on Lambda`,
347
+ )
348
+ }
349
+ lines.push(...runtimeLine(answer.effect))
350
+ return lines
351
+ }
352
+
353
+ export async function runRuntimeGet(
354
+ client: PlatformClient,
355
+ appKey: string,
356
+ print: Print,
357
+ ): Promise<boolean> {
358
+ for (const line of describeRuntime(await client.functionRuntime(appKey))) print(line)
359
+ return true
360
+ }
361
+
362
+ export async function runRuntimeSet(
363
+ client: PlatformClient,
364
+ appKey: string,
365
+ runtime: FunctionRuntimeName | null,
366
+ print: Print,
367
+ ): Promise<boolean> {
368
+ for (const line of describeRuntime(await client.setFunctionRuntime(appKey, runtime))) print(line)
369
+ return true
370
+ }
371
+
372
+ /** Why a mode is not available, said for a person reading a terminal. */
373
+ const UNAVAILABLE_WORDS = {
374
+ 'not-granted': 'its organisation has not been given it',
375
+ 'not-placed': 'the environment is on no game database yet',
376
+ 'shared-database':
377
+ "its game database is shared; a table of a collection's own needs the organisation's own database",
378
+ 'not-served': 'the engine it runs on does not offer it yet',
379
+ 'needs-connection': 'no data connection of the environment has passed the connector check',
380
+ } as const satisfies Record<CollectionStorageUnavailable, string>
381
+
382
+ /** What each mode is, in a line. */
383
+ const STORAGE_WORDS = {
384
+ collection: 'shared rows, in the same transaction as platform data',
385
+ dedicated:
386
+ "a table of the collection's own in the organisation's game database; every index is paid for by every write",
387
+ 'self-hosted': 'your own database behind a data connection; not atomic with platform data',
388
+ } as const satisfies Record<CollectionStorageName, string>
389
+
390
+ export function describeCollectionStorage(answer: CollectionStorageAnswer): string[] {
391
+ const lines = [`${answer.appKey}`, 'Modes']
392
+ lines.push(
393
+ ...columns(
394
+ answer.modes.map((each) => [
395
+ each.mode,
396
+ each.available ? 'available' : 'not available',
397
+ each.unavailable
398
+ ? UNAVAILABLE_WORDS[each.unavailable]
399
+ : STORAGE_WORDS[each.mode] + (each.canBeDefault ? '' : '; named per collection only'),
400
+ ]),
401
+ ' ',
402
+ ),
403
+ )
404
+ lines.push(
405
+ `Default ${answer.default} for new collections that name no mode`,
406
+ ` own ${answer.own ?? 'none, it follows its organisation'}, organisation ${answer.orgDefault}`,
407
+ )
408
+ if (answer.own !== null && answer.own !== answer.default) {
409
+ lines.push(
410
+ ` its own ${answer.own} cannot be had here now, so ${answer.default} is used`,
411
+ )
412
+ }
413
+ if (answer.collections === null) {
414
+ lines.push('Collections the engine could not be asked from here')
415
+ } else if (answer.collections.length === 0) {
416
+ lines.push('Collections none released')
417
+ } else {
418
+ lines.push('Collections')
419
+ lines.push(
420
+ ...columns(
421
+ [
422
+ ['KEY', 'KEPT IN', 'DEFINITION NAMES'],
423
+ ...answer.collections.map((each) => [
424
+ each.key,
425
+ each.mode ?? 'nothing yet',
426
+ each.wanted ?? 'no mode',
427
+ ]),
428
+ ],
429
+ ' ',
430
+ ),
431
+ )
432
+ }
433
+ return lines
434
+ }
435
+
436
+ export async function runStorageGet(
437
+ client: PlatformClient,
438
+ appKey: string,
439
+ print: Print,
440
+ ): Promise<boolean> {
441
+ for (const line of describeCollectionStorage(await client.collectionStorage(appKey))) print(line)
442
+ return true
443
+ }
444
+
445
+ export async function runStorageSetDefault(
446
+ client: PlatformClient,
447
+ appKey: string,
448
+ mode: CollectionStorageName | null,
449
+ print: Print,
450
+ ): Promise<boolean> {
451
+ const answer = await client.setCollectionStorageDefault(appKey, mode)
452
+ for (const line of describeCollectionStorage(answer)) print(line)
453
+ return true
454
+ }
455
+
456
+ /** A connector check's result, each rule on a line, the first failure's detail beside it. */
457
+ export function describeConnectorCheck(answer: ConnectorCheckAnswer): string[] {
458
+ const lines = [
459
+ `${answer.appKey} ${answer.connection}: protocol ${answer.protocol} ${answer.ok ? 'passed' : 'failed'}`,
460
+ ]
461
+ lines.push(
462
+ ...columns(
463
+ answer.checks.map((each) => [each.rule, each.ok ? 'ok' : 'FAILED', each.detail ?? '']),
464
+ ' ',
465
+ ),
466
+ )
467
+ lines.push(`Calls ${answer.calls}, the slowest ${answer.slowestMs} ms`)
468
+ lines.push(
469
+ answer.freshUntil
470
+ ? `A collection may name ${answer.connection} as its self-hosted storage until ${answer.freshUntil}.`
471
+ : `No collection may name ${answer.connection} as its self-hosted storage until a check passes.`,
472
+ )
473
+ return lines
474
+ }
475
+
476
+ export async function runConnectorCheck(
477
+ client: PlatformClient,
478
+ appKey: string,
479
+ connection: string,
480
+ print: Print,
481
+ ): Promise<boolean> {
482
+ const answer = await client.checkConnector(appKey, connection)
483
+ for (const line of describeConnectorCheck(answer)) print(line)
484
+ return answer.ok
485
+ }
486
+
487
+ export interface DeployOptions {
488
+ readonly client: PlatformClient
489
+ readonly config: LoadedExtConfig
490
+ readonly source?: SourceRef
491
+ /** The environment a signed-in person deploys to; a publish key's own needs no naming. */
492
+ readonly appKey?: string
493
+ }
494
+
495
+ /**
496
+ * Upload, push live, seed config, switch flows on, in that order from the config file, stopping at
497
+ * the first step that fails and saying which. Each step is one the commands of the same names
498
+ * take alone, so a failure can be mended and the step run again.
499
+ */
500
+ export async function runDeploy(options: DeployOptions, print: Print): Promise<boolean> {
501
+ const { client, config, source, appKey } = options
502
+ const steps: { name: string; run: () => Promise<boolean> }[] = [
503
+ {
504
+ name: 'upload',
505
+ run: () =>
506
+ runUpload({ paths: config.paths, client, source, plugins: config.plugins, appKey }, print),
507
+ },
508
+ {
509
+ name: 'push',
510
+ run: () => runPush({ paths: config.paths, client, source, live: true, appKey }, print),
511
+ },
512
+ ]
513
+ if (config.configDefaults.length > 0) {
514
+ steps.push({
515
+ name: 'seed',
516
+ run: () => runConfigSeed(client, config.configDefaults, print, appKey),
517
+ })
518
+ }
519
+ if (config.flowsOn !== undefined) {
520
+ const wanted = config.flowsOn
521
+ steps.push({
522
+ name: 'flows',
523
+ run: async () =>
524
+ runFlowSwitch(
525
+ client,
526
+ wanted === 'all' ? await flowKeysOf(config.paths) : wanted,
527
+ true,
528
+ print,
529
+ appKey,
530
+ ),
531
+ })
532
+ }
533
+ for (const step of steps) {
534
+ print(`== ${step.name}`)
535
+ let ok: boolean
536
+ try {
537
+ ok = await step.run()
538
+ } catch (error) {
539
+ print(`The ${step.name} step failed: ${error instanceof Error ? error.message : error}`)
540
+ return false
541
+ }
542
+ if (!ok) {
543
+ print(`The ${step.name} step failed, so nothing after it was done.`)
544
+ return false
545
+ }
546
+ }
547
+ print(`Deployed ${steps.map((step) => step.name).join(', ')}.`)
548
+ return true
549
+ }
@@ -0,0 +1,107 @@
1
+ import { existsSync } from 'node:fs'
2
+ import { dirname, resolve } from 'node:path'
3
+ import { pathToFileURL } from 'node:url'
4
+ import { configDefaultsRequest, parserOf, s, type SeededValue } from '@greenmind/ext-schema'
5
+ import type { BunPlugin } from 'bun'
6
+
7
+ /**
8
+ * `ext.config.ts`, the file a project keeps in its root so one command (`gm pub deploy`) knows where
9
+ * its definitions are and what its environment needs. It lives in this package rather than in
10
+ * the SDK because only the command reads it, it names Bun build plugins, and the SDK is also
11
+ * bundled into functions that run on Node.
12
+ */
13
+
14
+ export interface ExtConfig {
15
+ /** Modules or directories holding the project's definitions, relative to the config file. */
16
+ readonly paths: readonly string[]
17
+ /**
18
+ * Bun build plugins the functions' sources need to compile (a macro, say). A studio's plain
19
+ * TypeScript needs none.
20
+ */
21
+ readonly plugins?: readonly BunPlugin[]
22
+ /** Config values the functions need, given to an environment that lacks them and never over a retune. */
23
+ readonly configDefaults?: readonly SeededValue[]
24
+ /** Flows `gm pub deploy` switches on: every flow the paths define, or these keys. Left out, none. */
25
+ readonly flowsOn?: 'all' | readonly string[]
26
+ }
27
+
28
+ /** Gives a config file its type, so what it names is checked as it is written. */
29
+ export function defineExtConfig(config: ExtConfig): ExtConfig {
30
+ return config
31
+ }
32
+
33
+ export interface LoadedExtConfig {
34
+ readonly file: string
35
+ /** `paths`, made absolute against the directory the config file is in. */
36
+ readonly paths: readonly string[]
37
+ readonly plugins: readonly BunPlugin[]
38
+ readonly configDefaults: readonly SeededValue[]
39
+ readonly flowsOn: 'all' | readonly string[] | undefined
40
+ }
41
+
42
+ export class ExtConfigError extends Error {
43
+ override readonly name = 'ExtConfigError'
44
+ }
45
+
46
+ const FILE_NAMES = ['ext.config.ts', 'ext.config.mts', 'ext.config.js', 'ext.config.mjs']
47
+
48
+ /** The config file a command was told of, or the one in the working directory. */
49
+ export function findExtConfig(explicit: string | undefined, cwd = process.cwd()): string {
50
+ if (explicit) {
51
+ const file = resolve(cwd, explicit)
52
+ if (!existsSync(file)) throw new ExtConfigError(`${file} does not exist.`)
53
+ return file
54
+ }
55
+ for (const name of FILE_NAMES) {
56
+ const file = resolve(cwd, name)
57
+ if (existsSync(file)) return file
58
+ }
59
+ throw new ExtConfigError(
60
+ `There is no ext.config.ts in ${cwd}. Create one with defineExtConfig, or name it with --config.`,
61
+ )
62
+ }
63
+
64
+ const stringList = parserOf(s.array(s.string({ minLength: 1 }), { maxItems: 1000 }))
65
+
66
+ /** Loads and checks the config file. Its default export is what `defineExtConfig` returned. */
67
+ export async function loadExtConfig(
68
+ explicit?: string,
69
+ cwd = process.cwd(),
70
+ ): Promise<LoadedExtConfig> {
71
+ const file = findExtConfig(explicit, cwd)
72
+ const module: { default?: Partial<ExtConfig> } = await import(pathToFileURL(file).href)
73
+ const config = module.default
74
+ if (!config || !(config instanceof Object)) {
75
+ throw new ExtConfigError(
76
+ `${file} must export a config as its default: export default defineExtConfig({ ... }).`,
77
+ )
78
+ }
79
+ const paths = stringList.safeParse(config.paths)
80
+ if (!paths.success || paths.data.length === 0) {
81
+ throw new ExtConfigError(`${file}: paths must list at least one module or directory.`)
82
+ }
83
+ const plugins = config.plugins ?? []
84
+ if (!Array.isArray(plugins)) throw new ExtConfigError(`${file}: plugins must be a list.`)
85
+ const defaults = parserOf(configDefaultsRequest).safeParse({
86
+ values: config.configDefaults ?? [],
87
+ })
88
+ if (!defaults.success) {
89
+ const issue = defaults.error.issues[0]
90
+ throw new ExtConfigError(
91
+ `${file}: configDefaults is not valid${issue?.path.length ? ` at ${issue.path.join('.')}` : ''}: ${issue?.message ?? 'invalid'}.`,
92
+ )
93
+ }
94
+ const flows = stringList.safeParse(config.flowsOn)
95
+ if (config.flowsOn !== undefined && config.flowsOn !== 'all' && !flows.success) {
96
+ throw new ExtConfigError(`${file}: flowsOn must be 'all' or a list of flow keys.`)
97
+ }
98
+ const flowsOn = flows.success ? flows.data : config.flowsOn
99
+ const root = dirname(file)
100
+ return {
101
+ file,
102
+ paths: paths.data.map((path) => resolve(root, path)),
103
+ plugins,
104
+ configDefaults: defaults.data.values,
105
+ flowsOn,
106
+ }
107
+ }