@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/package.json +40 -4
- package/src/bin.ts +15 -0
- package/src/bundle.ts +100 -0
- package/src/client.ts +549 -0
- package/src/command.ts +1054 -0
- package/src/commands.ts +274 -0
- package/src/constants.ts +39 -0
- package/src/credentials.ts +159 -0
- package/src/environment-commands.ts +470 -0
- package/src/ext-config.ts +107 -0
- package/src/identity.ts +287 -0
- package/src/index.ts +58 -0
- package/src/json-read.ts +29 -0
- package/src/load.ts +127 -0
- package/src/org-commands.ts +579 -0
- package/src/protocol.ts +28 -0
- package/src/runner-command.ts +118 -0
- package/src/session.ts +278 -0
- package/README.md +0 -3
package/src/identity.ts
ADDED
|
@@ -0,0 +1,287 @@
|
|
|
1
|
+
import type { Json } from '@greenmind/ext-schema'
|
|
2
|
+
import { DISCOVERY_PATH } from './constants'
|
|
3
|
+
import { readLogin, type StoredLogin, withLock, writeLogin } from './credentials'
|
|
4
|
+
import { numberField as number, textField as text } from './json-read'
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* The OAuth 2.0 device authorisation grant (RFC 8628) against the identity server, written to the
|
|
8
|
+
* standard so the server's own endpoints are discovered rather than assumed: sign in, spend a
|
|
9
|
+
* refresh token, revoke one. Nothing here knows which server it is.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
export class IdentityError extends Error {
|
|
13
|
+
override readonly name = 'IdentityError'
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export interface IdentityOptions {
|
|
17
|
+
readonly fetch?: typeof fetch
|
|
18
|
+
/** Replaced in tests, so a poll's wait costs nothing. */
|
|
19
|
+
readonly sleep?: (ms: number) => Promise<void>
|
|
20
|
+
readonly now?: () => number
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface IdentityEndpoints {
|
|
24
|
+
readonly deviceAuthorization: string
|
|
25
|
+
readonly token: string
|
|
26
|
+
/** Absent where the server offers none, so a sign-out can only forget the tokens. */
|
|
27
|
+
readonly revocation?: string
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const defaultSleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms))
|
|
31
|
+
|
|
32
|
+
/** The most a token request may take; nothing here runs unattended for longer. */
|
|
33
|
+
const REQUEST_TIMEOUT_MS = 20_000
|
|
34
|
+
|
|
35
|
+
/** A token endpoint's polling interval is this many seconds when the server names none (RFC 8628). */
|
|
36
|
+
const DEFAULT_INTERVAL_SECONDS = 5
|
|
37
|
+
const SLOW_DOWN_SECONDS = 5
|
|
38
|
+
|
|
39
|
+
async function readJson(response: Response): Promise<Json | undefined> {
|
|
40
|
+
const body = await response.text()
|
|
41
|
+
try {
|
|
42
|
+
return JSON.parse(body)
|
|
43
|
+
} catch {
|
|
44
|
+
return undefined
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function form(fields: Record<string, string>): RequestInit {
|
|
49
|
+
return {
|
|
50
|
+
method: 'POST',
|
|
51
|
+
headers: { 'content-type': 'application/x-www-form-urlencoded', accept: 'application/json' },
|
|
52
|
+
body: new URLSearchParams(fields).toString(),
|
|
53
|
+
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Reads the issuer's discovery document for the three endpoints the flow needs. */
|
|
58
|
+
export async function discover(
|
|
59
|
+
issuer: string,
|
|
60
|
+
options: IdentityOptions = {},
|
|
61
|
+
): Promise<IdentityEndpoints> {
|
|
62
|
+
const send = options.fetch ?? fetch
|
|
63
|
+
const url = `${issuer.replace(/\/+$/, '')}${DISCOVERY_PATH}`
|
|
64
|
+
let response: Response
|
|
65
|
+
try {
|
|
66
|
+
response = await send(url, {
|
|
67
|
+
headers: { accept: 'application/json' },
|
|
68
|
+
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
|
69
|
+
})
|
|
70
|
+
} catch (error) {
|
|
71
|
+
throw new IdentityError(
|
|
72
|
+
`Could not reach the identity server at ${issuer}: ${error instanceof Error ? error.message : error}.`,
|
|
73
|
+
)
|
|
74
|
+
}
|
|
75
|
+
const body = await readJson(response)
|
|
76
|
+
const deviceAuthorization = text(body, 'device_authorization_endpoint')
|
|
77
|
+
const token = text(body, 'token_endpoint')
|
|
78
|
+
if (!response.ok || !deviceAuthorization || !token) {
|
|
79
|
+
throw new IdentityError(
|
|
80
|
+
`${url} does not describe a server that supports signing in from a terminal (it needs device_authorization_endpoint and token_endpoint).`,
|
|
81
|
+
)
|
|
82
|
+
}
|
|
83
|
+
return { deviceAuthorization, token, revocation: text(body, 'revocation_endpoint') }
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** What a token endpoint answered, with its expiry made absolute. */
|
|
87
|
+
interface Issued {
|
|
88
|
+
readonly accessToken: string
|
|
89
|
+
readonly refreshToken?: string
|
|
90
|
+
readonly expiresAt: string
|
|
91
|
+
readonly scope?: string
|
|
92
|
+
readonly idToken?: string
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function issuedFrom(body: Json | undefined, now: number): Issued | undefined {
|
|
96
|
+
const accessToken = text(body, 'access_token')
|
|
97
|
+
if (!accessToken) return undefined
|
|
98
|
+
// A server that names no lifetime gets the shortest a client can safely assume.
|
|
99
|
+
const lifetime = number(body, 'expires_in') ?? 300
|
|
100
|
+
return {
|
|
101
|
+
accessToken,
|
|
102
|
+
refreshToken: text(body, 'refresh_token'),
|
|
103
|
+
expiresAt: new Date(now + lifetime * 1000).toISOString(),
|
|
104
|
+
scope: text(body, 'scope'),
|
|
105
|
+
idToken: text(body, 'id_token'),
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Who an ID token names, for display; it is not verified, since nothing here trusts it for access. */
|
|
110
|
+
function userOf(idToken: string | undefined): StoredLogin['user'] {
|
|
111
|
+
const payload = idToken?.split('.')[1]
|
|
112
|
+
if (!payload) return {}
|
|
113
|
+
try {
|
|
114
|
+
const claims: Json = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8'))
|
|
115
|
+
return {
|
|
116
|
+
subject: text(claims, 'sub'),
|
|
117
|
+
name: text(claims, 'name') ?? text(claims, 'preferred_username'),
|
|
118
|
+
email: text(claims, 'email'),
|
|
119
|
+
}
|
|
120
|
+
} catch {
|
|
121
|
+
return {}
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export interface DeviceLoginOptions extends IdentityOptions {
|
|
126
|
+
readonly issuer: string
|
|
127
|
+
readonly clientId: string
|
|
128
|
+
readonly scopes: readonly string[]
|
|
129
|
+
/** Called once with where to go and what to type. */
|
|
130
|
+
readonly prompt: (instructions: { url: string; code: string; completeUrl?: string }) => void
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* Asks for a code, tells the person where to enter it, and polls until they have, with the
|
|
135
|
+
* server's interval, waiting longer when told to slow down.
|
|
136
|
+
*/
|
|
137
|
+
export async function deviceLogin(options: DeviceLoginOptions): Promise<StoredLogin> {
|
|
138
|
+
const send = options.fetch ?? fetch
|
|
139
|
+
const sleep = options.sleep ?? defaultSleep
|
|
140
|
+
const now = options.now ?? Date.now
|
|
141
|
+
const endpoints = await discover(options.issuer, options)
|
|
142
|
+
|
|
143
|
+
const started = await send(
|
|
144
|
+
endpoints.deviceAuthorization,
|
|
145
|
+
form({ client_id: options.clientId, scope: options.scopes.join(' ') }),
|
|
146
|
+
)
|
|
147
|
+
const grant = await readJson(started)
|
|
148
|
+
const deviceCode = text(grant, 'device_code')
|
|
149
|
+
const userCode = text(grant, 'user_code')
|
|
150
|
+
const url = text(grant, 'verification_uri') ?? text(grant, 'verification_url')
|
|
151
|
+
if (!started.ok || !deviceCode || !userCode || !url) {
|
|
152
|
+
const why =
|
|
153
|
+
text(grant, 'error_description') ?? text(grant, 'error') ?? `status ${started.status}`
|
|
154
|
+
throw new IdentityError(`The identity server did not start a sign-in: ${why}.`)
|
|
155
|
+
}
|
|
156
|
+
options.prompt({ url, code: userCode, completeUrl: text(grant, 'verification_uri_complete') })
|
|
157
|
+
|
|
158
|
+
const giveUpAt = now() + (number(grant, 'expires_in') ?? 600) * 1000
|
|
159
|
+
let interval = number(grant, 'interval') ?? DEFAULT_INTERVAL_SECONDS
|
|
160
|
+
for (;;) {
|
|
161
|
+
await sleep(interval * 1000)
|
|
162
|
+
if (now() > giveUpAt) {
|
|
163
|
+
throw new IdentityError('The code expired before it was entered. Run `gm login` again.')
|
|
164
|
+
}
|
|
165
|
+
const answer = await send(
|
|
166
|
+
endpoints.token,
|
|
167
|
+
form({
|
|
168
|
+
grant_type: 'urn:ietf:params:oauth:grant-type:device_code',
|
|
169
|
+
device_code: deviceCode,
|
|
170
|
+
client_id: options.clientId,
|
|
171
|
+
}),
|
|
172
|
+
)
|
|
173
|
+
const body = await readJson(answer)
|
|
174
|
+
if (answer.ok) {
|
|
175
|
+
const issued = issuedFrom(body, now())
|
|
176
|
+
if (!issued) throw new IdentityError('The identity server answered without an access token.')
|
|
177
|
+
return {
|
|
178
|
+
issuer: options.issuer,
|
|
179
|
+
clientId: options.clientId,
|
|
180
|
+
accessToken: issued.accessToken,
|
|
181
|
+
refreshToken: issued.refreshToken,
|
|
182
|
+
expiresAt: issued.expiresAt,
|
|
183
|
+
scope: issued.scope ?? options.scopes.join(' '),
|
|
184
|
+
user: userOf(issued.idToken),
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
const code = text(body, 'error')
|
|
188
|
+
if (code === 'authorization_pending') continue
|
|
189
|
+
if (code === 'slow_down') {
|
|
190
|
+
interval += SLOW_DOWN_SECONDS
|
|
191
|
+
continue
|
|
192
|
+
}
|
|
193
|
+
if (code === 'access_denied') {
|
|
194
|
+
throw new IdentityError('The sign-in was denied on the consent page.')
|
|
195
|
+
}
|
|
196
|
+
if (code === 'expired_token') {
|
|
197
|
+
throw new IdentityError('The code expired before it was entered. Run `gm login` again.')
|
|
198
|
+
}
|
|
199
|
+
const why = text(body, 'error_description') ?? code ?? `status ${answer.status}`
|
|
200
|
+
throw new IdentityError(`The identity server refused the sign-in: ${why}.`)
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* Spends the stored refresh token for a new pair, holding the lock so two `gm` processes cannot
|
|
206
|
+
* both spend it. Where another process already rotated the tokens while this one waited, theirs
|
|
207
|
+
* are returned and nothing is spent. `undefined` means there is nothing to refresh with or the
|
|
208
|
+
* server no longer accepts it: the person has to sign in again.
|
|
209
|
+
*/
|
|
210
|
+
export async function refreshLogin(
|
|
211
|
+
dir: string,
|
|
212
|
+
platformUrl: string,
|
|
213
|
+
rejectedAccessToken: string | undefined,
|
|
214
|
+
options: IdentityOptions = {},
|
|
215
|
+
): Promise<StoredLogin | undefined> {
|
|
216
|
+
const send = options.fetch ?? fetch
|
|
217
|
+
const now = options.now ?? Date.now
|
|
218
|
+
return withLock(dir, async () => {
|
|
219
|
+
const held = readLogin(dir, platformUrl)
|
|
220
|
+
if (!held) return undefined
|
|
221
|
+
const usable = Date.parse(held.expiresAt) - now() > 10_000
|
|
222
|
+
if (rejectedAccessToken !== undefined && held.accessToken !== rejectedAccessToken && usable) {
|
|
223
|
+
return held
|
|
224
|
+
}
|
|
225
|
+
if (rejectedAccessToken === undefined && usable) return held
|
|
226
|
+
if (!held.refreshToken) return undefined
|
|
227
|
+
const endpoints = await discover(held.issuer, options)
|
|
228
|
+
const answer = await send(
|
|
229
|
+
endpoints.token,
|
|
230
|
+
form({
|
|
231
|
+
grant_type: 'refresh_token',
|
|
232
|
+
refresh_token: held.refreshToken,
|
|
233
|
+
client_id: held.clientId,
|
|
234
|
+
}),
|
|
235
|
+
)
|
|
236
|
+
const body = await readJson(answer)
|
|
237
|
+
const issued = answer.ok ? issuedFrom(body, now()) : undefined
|
|
238
|
+
if (!issued) {
|
|
239
|
+
if (answer.status >= 500) {
|
|
240
|
+
throw new IdentityError(`The identity server answered ${answer.status} to a refresh.`)
|
|
241
|
+
}
|
|
242
|
+
return undefined
|
|
243
|
+
}
|
|
244
|
+
const next: StoredLogin = {
|
|
245
|
+
...held,
|
|
246
|
+
accessToken: issued.accessToken,
|
|
247
|
+
// A server that does not rotate keeps the token it issued; one that does names the new one.
|
|
248
|
+
refreshToken: issued.refreshToken ?? held.refreshToken,
|
|
249
|
+
expiresAt: issued.expiresAt,
|
|
250
|
+
scope: issued.scope ?? held.scope,
|
|
251
|
+
}
|
|
252
|
+
writeLogin(dir, platformUrl, next)
|
|
253
|
+
return next
|
|
254
|
+
})
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/**
|
|
258
|
+
* Revokes a login's tokens at the server, refresh token first since it is the one that can mint
|
|
259
|
+
* more. Answers the reason it could not, if so; the caller forgets the tokens either way.
|
|
260
|
+
*/
|
|
261
|
+
export async function revokeLogin(
|
|
262
|
+
login: StoredLogin,
|
|
263
|
+
options: IdentityOptions = {},
|
|
264
|
+
): Promise<string | undefined> {
|
|
265
|
+
const send = options.fetch ?? fetch
|
|
266
|
+
let endpoints: IdentityEndpoints
|
|
267
|
+
try {
|
|
268
|
+
endpoints = await discover(login.issuer, options)
|
|
269
|
+
} catch (error) {
|
|
270
|
+
return error instanceof Error ? error.message : String(error)
|
|
271
|
+
}
|
|
272
|
+
if (!endpoints.revocation) return 'The identity server offers no revocation endpoint.'
|
|
273
|
+
const tokens: [string, string][] = [['access_token', login.accessToken]]
|
|
274
|
+
if (login.refreshToken) tokens.unshift(['refresh_token', login.refreshToken])
|
|
275
|
+
for (const [hint, token] of tokens) {
|
|
276
|
+
try {
|
|
277
|
+
const answer = await send(
|
|
278
|
+
endpoints.revocation,
|
|
279
|
+
form({ token, token_type_hint: hint, client_id: login.clientId }),
|
|
280
|
+
)
|
|
281
|
+
if (!answer.ok) return `The identity server answered ${answer.status} to a revocation.`
|
|
282
|
+
} catch (error) {
|
|
283
|
+
return error instanceof Error ? error.message : String(error)
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
return undefined
|
|
287
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* GreenMind's command line, `gm` (published as `@greenmind/cli`): one sign-in, then a group of
|
|
3
|
+
* commands per product. Today that is `gm pub`, the publishing platform: environments and keys,
|
|
4
|
+
* and the project's definitions (check them against an environment, push them to a test
|
|
5
|
+
* environment, upload function bundles, run a function on a recorded event).
|
|
6
|
+
*
|
|
7
|
+
* A build of the command line can carry more than the published one through `GmCommandContext`:
|
|
8
|
+
* more commands under a product, and more `gm login` switches asking for further scopes.
|
|
9
|
+
*
|
|
10
|
+
* What it says to the tooling API is in `protocol.ts` and `client.ts`.
|
|
11
|
+
*/
|
|
12
|
+
export {
|
|
13
|
+
PlatformClient,
|
|
14
|
+
type PlatformClientOptions,
|
|
15
|
+
PlatformError,
|
|
16
|
+
readToolDiscovery,
|
|
17
|
+
type RequestBody,
|
|
18
|
+
type TokenSource,
|
|
19
|
+
UpgradeRequiredError,
|
|
20
|
+
} from './client'
|
|
21
|
+
export { credentialsDir, readLogin, type StoredLogin, writeLogin } from './credentials'
|
|
22
|
+
export {
|
|
23
|
+
buildGmCommand,
|
|
24
|
+
COMMAND_GROUPS,
|
|
25
|
+
type CommandBuilder,
|
|
26
|
+
type GmCommandContext,
|
|
27
|
+
gmCommand,
|
|
28
|
+
guarded,
|
|
29
|
+
type LoginScopeOption,
|
|
30
|
+
type ProductGroup,
|
|
31
|
+
PUBLISHING,
|
|
32
|
+
} from './command'
|
|
33
|
+
export { connect, type SessionOptions, SessionError, signedInAs } from './session'
|
|
34
|
+
export {
|
|
35
|
+
defineExtConfig,
|
|
36
|
+
type ExtConfig,
|
|
37
|
+
ExtConfigError,
|
|
38
|
+
findExtConfig,
|
|
39
|
+
type LoadedExtConfig,
|
|
40
|
+
loadExtConfig,
|
|
41
|
+
} from './ext-config'
|
|
42
|
+
export { columns, runDeploy } from './environment-commands'
|
|
43
|
+
export {
|
|
44
|
+
type CheckOptions,
|
|
45
|
+
type Print,
|
|
46
|
+
type PushOptions,
|
|
47
|
+
requestFor,
|
|
48
|
+
type RunOptions,
|
|
49
|
+
runCheck,
|
|
50
|
+
runCompile,
|
|
51
|
+
runFunction,
|
|
52
|
+
runPush,
|
|
53
|
+
runUpload,
|
|
54
|
+
type UploadOptions,
|
|
55
|
+
} from './commands'
|
|
56
|
+
export { type Bundle, buildBundle, RUNTIME, sha256Hex } from './bundle'
|
|
57
|
+
export { filesUnder, kindOfStored, LoadError, loadDefinitions, loadModule } from './load'
|
|
58
|
+
export * from './protocol'
|
package/src/json-read.ts
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { type Json, parserOf, s } from '@greenmind/ext-schema'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Reading single fields out of a body this tool does not own (an identity server's answer, whose
|
|
5
|
+
* extra fields are none of its business), each checked against the schema of what it should be.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
const text = parserOf(s.string({ minLength: 1 }))
|
|
9
|
+
const count = parserOf(s.number())
|
|
10
|
+
|
|
11
|
+
function isObject(value: Json | undefined): value is { readonly [key: string]: Json } {
|
|
12
|
+
return value !== null && value !== undefined && value instanceof Object && !Array.isArray(value)
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export function fieldOf(body: Json | undefined, name: string): Json | undefined {
|
|
16
|
+
return isObject(body) ? body[name] : undefined
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** A field that is non-empty text, or nothing. */
|
|
20
|
+
export function textField(body: Json | undefined, name: string): string | undefined {
|
|
21
|
+
const parsed = text.safeParse(fieldOf(body, name))
|
|
22
|
+
return parsed.success ? parsed.data : undefined
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** A field that is a number, or nothing. */
|
|
26
|
+
export function numberField(body: Json | undefined, name: string): number | undefined {
|
|
27
|
+
const parsed = count.safeParse(fieldOf(body, name))
|
|
28
|
+
return parsed.success ? parsed.data : undefined
|
|
29
|
+
}
|
package/src/load.ts
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import { readdirSync, readFileSync, statSync } from 'node:fs'
|
|
2
|
+
import { extname, join, resolve } from 'node:path'
|
|
3
|
+
import { pathToFileURL } from 'node:url'
|
|
4
|
+
import type { Json, JsonObject } from '@greenmind/ext-schema'
|
|
5
|
+
import {
|
|
6
|
+
type CompiledDefinition,
|
|
7
|
+
compileProject,
|
|
8
|
+
DEFINITION_KINDS,
|
|
9
|
+
type DefinitionBase,
|
|
10
|
+
type DefinitionKind,
|
|
11
|
+
definitionsOf,
|
|
12
|
+
type ModuleExports,
|
|
13
|
+
SdkError,
|
|
14
|
+
storedDefinition,
|
|
15
|
+
} from '@greenmind/ext-sdk'
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Reading definitions from files: TypeScript or JavaScript modules, whose exported definitions are
|
|
19
|
+
* compiled by the SDK, and JSON files already in the stored form. Our own are TypeScript; a JSON
|
|
20
|
+
* file is for what a program wrote.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
const MODULES = new Set(['.ts', '.mts', '.js', '.mjs'])
|
|
24
|
+
const SKIPPED = /(\.d\.ts|\.test\.tsx?|\.check\.ts)$/
|
|
25
|
+
|
|
26
|
+
export class LoadError extends Error {
|
|
27
|
+
override readonly name = 'LoadError'
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function isObject(value: Json): value is JsonObject {
|
|
31
|
+
return value !== null && value instanceof Object && !Array.isArray(value)
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** The kind of definition a stored JSON object is, by the fields only that kind has. */
|
|
35
|
+
export function kindOfStored(body: Json): DefinitionKind | undefined {
|
|
36
|
+
if (!isObject(body)) return undefined
|
|
37
|
+
if ('steps' in body && 'trigger' in body) return 'flow'
|
|
38
|
+
if ('sentBy' in body) return 'event'
|
|
39
|
+
if ('scope' in body && 'fields' in body) return 'collection'
|
|
40
|
+
if ('reads' in body) return 'function'
|
|
41
|
+
if ('in' in body && 'out' in body) return 'socket'
|
|
42
|
+
if ('guard' in body && 'flow' in body) return 'webhook'
|
|
43
|
+
if ('label' in body) return 'permission'
|
|
44
|
+
if ('cron' in body && 'target' in body) return 'schedule'
|
|
45
|
+
if ('input' in body && 'key' in body) return 'job'
|
|
46
|
+
return undefined
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** The files a path names: the file itself, or every module and JSON file under a directory. */
|
|
50
|
+
export function filesUnder(path: string): string[] {
|
|
51
|
+
const absolute = resolve(path)
|
|
52
|
+
if (!statSync(absolute).isDirectory()) return [absolute]
|
|
53
|
+
return readdirSync(absolute, { withFileTypes: true })
|
|
54
|
+
.filter((entry) => entry.name !== 'node_modules' && !entry.name.startsWith('.'))
|
|
55
|
+
.flatMap((entry) => {
|
|
56
|
+
const full = join(absolute, entry.name)
|
|
57
|
+
if (entry.isDirectory()) return filesUnder(full)
|
|
58
|
+
const extension = extname(entry.name)
|
|
59
|
+
return (MODULES.has(extension) || extension === '.json') && !SKIPPED.test(entry.name)
|
|
60
|
+
? [full]
|
|
61
|
+
: []
|
|
62
|
+
})
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export async function loadModule(file: string): Promise<DefinitionBase[]> {
|
|
66
|
+
const exported: ModuleExports = await import(pathToFileURL(file).href)
|
|
67
|
+
return definitionsOf(exported)
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function loadStored(file: string): CompiledDefinition {
|
|
71
|
+
let body: Json
|
|
72
|
+
try {
|
|
73
|
+
body = JSON.parse(readFileSync(file, 'utf8'))
|
|
74
|
+
} catch (error) {
|
|
75
|
+
throw new LoadError(
|
|
76
|
+
`${file} is not valid JSON: ${error instanceof Error ? error.message : error}.`,
|
|
77
|
+
)
|
|
78
|
+
}
|
|
79
|
+
const kind = kindOfStored(body)
|
|
80
|
+
if (!kind) {
|
|
81
|
+
throw new LoadError(
|
|
82
|
+
`${file} is not a stored definition: expected a flow (trigger and steps), event (sentBy), collection (scope and fields), function (reads), socket (in and out), webhook (guard and flow) or permission (label).`,
|
|
83
|
+
)
|
|
84
|
+
}
|
|
85
|
+
try {
|
|
86
|
+
return storedDefinition(kind, body)
|
|
87
|
+
} catch (error) {
|
|
88
|
+
if (error instanceof SdkError) throw new LoadError(`${file}: ${error.message}`)
|
|
89
|
+
throw error
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Every definition in the given files and directories, compiled, each once. A key two files both
|
|
95
|
+
* define must define it the same way.
|
|
96
|
+
*/
|
|
97
|
+
export async function loadDefinitions(paths: readonly string[]): Promise<CompiledDefinition[]> {
|
|
98
|
+
const files = paths.flatMap(filesUnder)
|
|
99
|
+
if (files.length === 0) throw new LoadError('There are no .ts, .js or .json files to read.')
|
|
100
|
+
const fromCode: DefinitionBase[] = []
|
|
101
|
+
const stored: CompiledDefinition[] = []
|
|
102
|
+
for (const file of files) {
|
|
103
|
+
if (extname(file) === '.json') stored.push(loadStored(file))
|
|
104
|
+
else if (MODULES.has(extname(file))) fromCode.push(...(await loadModule(file)))
|
|
105
|
+
else throw new LoadError(`${file}: expected a .ts, .mts, .js, .mjs or .json file.`)
|
|
106
|
+
}
|
|
107
|
+
const merged = new Map<string, CompiledDefinition>()
|
|
108
|
+
for (const definition of [...compileProject(fromCode), ...stored]) {
|
|
109
|
+
const id = `${definition.kind}:${definition.key}`
|
|
110
|
+
const earlier = merged.get(id)
|
|
111
|
+
if (earlier && earlier.contentHash !== definition.contentHash) {
|
|
112
|
+
throw new LoadError(`Two files define ${definition.kind} "${definition.key}" differently.`)
|
|
113
|
+
}
|
|
114
|
+
merged.set(id, definition)
|
|
115
|
+
}
|
|
116
|
+
// Checking or pushing nothing must never read as success. It is also what modules look like
|
|
117
|
+
// whose definitions were made by an SDK that marks them differently from this one.
|
|
118
|
+
if (merged.size === 0) {
|
|
119
|
+
throw new LoadError(
|
|
120
|
+
`No flow, function, event, collection, socket, webhook or permission is defined in ${paths.join(', ')}. Export each definition from its module, made with defineFlow, defineFunction and the rest of the SDK.`,
|
|
121
|
+
)
|
|
122
|
+
}
|
|
123
|
+
const order = (kind: DefinitionKind) => DEFINITION_KINDS.indexOf(kind)
|
|
124
|
+
return [...merged.values()].sort(
|
|
125
|
+
(a, b) => order(a.kind) - order(b.kind) || (a.key < b.key ? -1 : a.key > b.key ? 1 : 0),
|
|
126
|
+
)
|
|
127
|
+
}
|