@astrale-os/cli 0.4.0-alpha.13
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/.check-workspace.cjs +40 -0
- package/README.md +151 -0
- package/dist/astrale.js +59749 -0
- package/package.json +90 -0
- package/src/command.ts +40 -0
- package/src/commands/__tests__/admin-instance.test.ts +73 -0
- package/src/commands/__tests__/auth-login.test.ts +178 -0
- package/src/commands/__tests__/auth-token.test.ts +223 -0
- package/src/commands/__tests__/call.test.ts +72 -0
- package/src/commands/__tests__/domain-list.test.ts +74 -0
- package/src/commands/__tests__/help-contract.test.ts +136 -0
- package/src/commands/__tests__/install-identity-override.test.ts +65 -0
- package/src/commands/__tests__/instance-bookmark.test.ts +101 -0
- package/src/commands/__tests__/instance-create-hosts.test.ts +29 -0
- package/src/commands/__tests__/instance-list-rows.test.ts +63 -0
- package/src/commands/__tests__/logs.test.ts +117 -0
- package/src/commands/__tests__/ls.test.ts +25 -0
- package/src/commands/__tests__/setup-plan.test.ts +61 -0
- package/src/commands/admin/status.ts +61 -0
- package/src/commands/admin/use.ts +77 -0
- package/src/commands/auth/login.ts +82 -0
- package/src/commands/auth/logout.ts +50 -0
- package/src/commands/auth/status.ts +86 -0
- package/src/commands/auth/token.ts +162 -0
- package/src/commands/browser.ts +207 -0
- package/src/commands/call.ts +300 -0
- package/src/commands/describe.ts +182 -0
- package/src/commands/domain/install.ts +420 -0
- package/src/commands/domain/list.ts +154 -0
- package/src/commands/domain/publish.ts +155 -0
- package/src/commands/get.ts +60 -0
- package/src/commands/identity/create.ts +26 -0
- package/src/commands/identity/delete.ts +18 -0
- package/src/commands/identity/export.ts +66 -0
- package/src/commands/identity/import.ts +101 -0
- package/src/commands/identity/list.ts +56 -0
- package/src/commands/identity/register.ts +170 -0
- package/src/commands/identity/sync.ts +32 -0
- package/src/commands/identity/unsync.ts +24 -0
- package/src/commands/identity/use.ts +18 -0
- package/src/commands/identity/whoami.ts +34 -0
- package/src/commands/idp/add.ts +150 -0
- package/src/commands/idp/list.ts +57 -0
- package/src/commands/idp/refresh.ts +38 -0
- package/src/commands/idp/remove.ts +36 -0
- package/src/commands/idp/show.ts +29 -0
- package/src/commands/instance/active.ts +64 -0
- package/src/commands/instance/bookmark.ts +72 -0
- package/src/commands/instance/create.ts +69 -0
- package/src/commands/instance/delete.ts +72 -0
- package/src/commands/instance/forget.ts +26 -0
- package/src/commands/instance/list.ts +149 -0
- package/src/commands/instance/status.ts +42 -0
- package/src/commands/instance/use.ts +210 -0
- package/src/commands/logs.ts +347 -0
- package/src/commands/ls.ts +229 -0
- package/src/commands/query.ts +32 -0
- package/src/commands/setup.ts +54 -0
- package/src/commands/status.ts +60 -0
- package/src/commands/studio.ts +401 -0
- package/src/commands/token.ts +77 -0
- package/src/commands/update.ts +267 -0
- package/src/commands/use.ts +87 -0
- package/src/errors.ts +65 -0
- package/src/kernel/__tests__/auth.test.ts +77 -0
- package/src/kernel/__tests__/errors.test.ts +43 -0
- package/src/kernel/__tests__/remote-routing.test.ts +70 -0
- package/src/kernel/auth.ts +234 -0
- package/src/kernel/ca-fetch.ts +119 -0
- package/src/kernel/client.ts +191 -0
- package/src/kernel/errors.ts +280 -0
- package/src/kernel/expand.ts +217 -0
- package/src/kernel/index.ts +14 -0
- package/src/kernel/options.ts +22 -0
- package/src/kernel/remote-routing.ts +88 -0
- package/src/kernel/run.ts +63 -0
- package/src/kernel/types.ts +14 -0
- package/src/lib/__tests__/admin-target.test.ts +112 -0
- package/src/lib/__tests__/binary.test.ts +56 -0
- package/src/lib/__tests__/command-dx.test.ts +58 -0
- package/src/lib/__tests__/concurrency.test.ts +62 -0
- package/src/lib/__tests__/config.test.ts +53 -0
- package/src/lib/__tests__/design.test.ts +99 -0
- package/src/lib/__tests__/domain-identity.test.ts +60 -0
- package/src/lib/__tests__/format.test.ts +22 -0
- package/src/lib/__tests__/fs-atomic.test.ts +104 -0
- package/src/lib/__tests__/identity.test.ts +79 -0
- package/src/lib/__tests__/idp-session.driver.ts +53 -0
- package/src/lib/__tests__/idp-session.test.ts +357 -0
- package/src/lib/__tests__/idp.test.ts +385 -0
- package/src/lib/__tests__/instance-candidates.test.ts +73 -0
- package/src/lib/__tests__/instance-target.test.ts +183 -0
- package/src/lib/__tests__/instance.test.ts +136 -0
- package/src/lib/__tests__/keys.test.ts +129 -0
- package/src/lib/__tests__/local-status.test.ts +202 -0
- package/src/lib/__tests__/output.test.ts +150 -0
- package/src/lib/__tests__/panel.test.ts +40 -0
- package/src/lib/__tests__/port.test.ts +44 -0
- package/src/lib/__tests__/prompt.test.ts +25 -0
- package/src/lib/__tests__/sdk-deps.test.ts +68 -0
- package/src/lib/__tests__/self.test.ts +272 -0
- package/src/lib/__tests__/studio-server-deps.test.ts +74 -0
- package/src/lib/__tests__/table.test.ts +53 -0
- package/src/lib/__tests__/update.test.ts +246 -0
- package/src/lib/__tests__/use-target.test.ts +56 -0
- package/src/lib/__tests__/validation.test.ts +34 -0
- package/src/lib/admin-domain.ts +25 -0
- package/src/lib/admin-instance.ts +26 -0
- package/src/lib/admin-target.ts +217 -0
- package/src/lib/binary.ts +131 -0
- package/src/lib/browser.ts +150 -0
- package/src/lib/command-dx.ts +161 -0
- package/src/lib/concurrency.ts +31 -0
- package/src/lib/config.ts +45 -0
- package/src/lib/domain-identity.ts +49 -0
- package/src/lib/env.ts +49 -0
- package/src/lib/format.ts +4 -0
- package/src/lib/fs-atomic.ts +126 -0
- package/src/lib/identity.ts +256 -0
- package/src/lib/idp-session.ts +134 -0
- package/src/lib/idp.ts +876 -0
- package/src/lib/instance-candidates.ts +49 -0
- package/src/lib/instance-target.ts +182 -0
- package/src/lib/instance.ts +395 -0
- package/src/lib/keys.ts +294 -0
- package/src/lib/local-status.ts +152 -0
- package/src/lib/log.ts +116 -0
- package/src/lib/login-flow.ts +164 -0
- package/src/lib/meta.ts +86 -0
- package/src/lib/output.ts +222 -0
- package/src/lib/panel.ts +61 -0
- package/src/lib/paths.ts +11 -0
- package/src/lib/port.ts +41 -0
- package/src/lib/proc.ts +82 -0
- package/src/lib/prompt.ts +136 -0
- package/src/lib/provision-instance.ts +170 -0
- package/src/lib/sdk-deps.ts +104 -0
- package/src/lib/self.ts +166 -0
- package/src/lib/skills.ts +171 -0
- package/src/lib/table.ts +62 -0
- package/src/lib/update.ts +315 -0
- package/src/lib/use-target.ts +24 -0
- package/src/lib/validation.ts +59 -0
- package/src/program.ts +200 -0
- package/src/registry.ts +59 -0
- package/src/setup/__tests__/util.test.ts +29 -0
- package/src/setup/engine.ts +83 -0
- package/src/setup/render.ts +109 -0
- package/src/setup/steps/admin.ts +78 -0
- package/src/setup/steps/agent-browser.ts +81 -0
- package/src/setup/steps/auth.ts +54 -0
- package/src/setup/steps/domain.ts +68 -0
- package/src/setup/steps/index.ts +18 -0
- package/src/setup/steps/instance.ts +119 -0
- package/src/setup/steps/skills-bridge.ts +70 -0
- package/src/setup/steps/skills.ts +59 -0
- package/src/setup/types.ts +61 -0
- package/src/setup/util.ts +34 -0
- package/src/test-utils.ts +18 -0
- package/studio/client/dist/assets/index-DOwzZAEK.css +1 -0
- package/studio/client/dist/assets/index-wtU0Zxhy.js +183 -0
- package/studio/client/dist/index.html +13 -0
- package/studio/package.json +62 -0
- package/studio/server/agent/ask.ts +68 -0
- package/studio/server/agent/bridge-mcp.ts +182 -0
- package/studio/server/agent/bridge.ts +188 -0
- package/studio/server/agent/claude.ts +666 -0
- package/studio/server/agent/mock.ts +186 -0
- package/studio/server/agent/prompt.ts +202 -0
- package/studio/server/agent/registry.ts +29 -0
- package/studio/server/agent/runner.ts +484 -0
- package/studio/server/agent/schema-map.ts +112 -0
- package/studio/server/agent/types.ts +120 -0
- package/studio/server/api.ts +574 -0
- package/studio/server/cache.ts +138 -0
- package/studio/server/detect.ts +81 -0
- package/studio/server/domain.ts +70 -0
- package/studio/server/index.ts +136 -0
- package/studio/server/introspect/anatomy-extras.ts +398 -0
- package/studio/server/introspect/anatomy.ts +108 -0
- package/studio/server/introspect/bundle.ts +57 -0
- package/studio/server/introspect/core-extractor.ts +119 -0
- package/studio/server/introspect/core.ts +44 -0
- package/studio/server/introspect/diff.ts +133 -0
- package/studio/server/introspect/extractor.ts +102 -0
- package/studio/server/introspect/hash.ts +21 -0
- package/studio/server/introspect/overlay-tsmorph.ts +874 -0
- package/studio/server/introspect/overlay.ts +57 -0
- package/studio/server/introspect/runtime.ts +99 -0
- package/studio/server/introspect/schema-refs.ts +46 -0
- package/studio/server/lifecycle.ts +38 -0
- package/studio/server/sse.ts +57 -0
- package/studio/server/state/baseline.ts +211 -0
- package/studio/server/state/catalog.ts +117 -0
- package/studio/server/state/comments.ts +321 -0
- package/studio/server/state/context.ts +167 -0
- package/studio/server/state/copy.ts +156 -0
- package/studio/server/state/create.ts +156 -0
- package/studio/server/state/documents.ts +70 -0
- package/studio/server/state/env.ts +161 -0
- package/studio/server/state/git.ts +75 -0
- package/studio/server/state/handoff.ts +55 -0
- package/studio/server/state/harness-gateway.ts +181 -0
- package/studio/server/state/harness-token.ts +0 -0
- package/studio/server/state/instance.ts +244 -0
- package/studio/server/state/integrations.ts +55 -0
- package/studio/server/state/layout.ts +55 -0
- package/studio/server/state/settings.ts +39 -0
- package/studio/server/state/store.ts +97 -0
- package/studio/server/state/updates.ts +63 -0
- package/studio/server/state/usage.ts +37 -0
- package/studio/server/state/views.ts +138 -0
- package/studio/server/state/visibility.ts +33 -0
- package/studio/server/watch.ts +81 -0
- package/studio/server/workspace-state.ts +26 -0
- package/studio/server/workspace-watch.ts +101 -0
- package/studio/shared/types.ts +873 -0
- package/studio/tsconfig.json +23 -0
- package/tsconfig.json +14 -0
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
import { upsertIdpIdentity } from './identity'
|
|
2
|
+
import {
|
|
3
|
+
decodeTokenClaims,
|
|
4
|
+
exchangeAuthorizationCode,
|
|
5
|
+
identityNameFromClaims,
|
|
6
|
+
issuerFromToken,
|
|
7
|
+
normalizeTokenResponse,
|
|
8
|
+
pollDeviceToken,
|
|
9
|
+
readIdpConfigOrBuiltin,
|
|
10
|
+
readIdpStore,
|
|
11
|
+
requestClientCredentials,
|
|
12
|
+
requestDeviceAuthorization,
|
|
13
|
+
saveIdpSession,
|
|
14
|
+
subjectFromToken,
|
|
15
|
+
tokenAudienceMatches,
|
|
16
|
+
tokenExpiresAt,
|
|
17
|
+
withCachedToken,
|
|
18
|
+
workosClientIdFromEnv,
|
|
19
|
+
type IdpSession,
|
|
20
|
+
type TokenResponse,
|
|
21
|
+
} from './idp'
|
|
22
|
+
import { log } from './log'
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* The IdP login flow, lifted out of the `auth login` command so it can be
|
|
26
|
+
* driven from anywhere (the command renders the result; `astrale setup` runs it
|
|
27
|
+
* as one hand-held step). The side effects — saving the session cache and
|
|
28
|
+
* upserting the IdP-backed identity — live here so every caller gets identical
|
|
29
|
+
* behavior; presentation (the device URL is logged here; success lines are the
|
|
30
|
+
* caller's) does not.
|
|
31
|
+
*/
|
|
32
|
+
export type LoginFlowOpts = {
|
|
33
|
+
idp?: string
|
|
34
|
+
name?: string
|
|
35
|
+
scope?: string
|
|
36
|
+
audience?: string
|
|
37
|
+
clientId?: string
|
|
38
|
+
clientSecretEnv?: string
|
|
39
|
+
clientCredentials?: boolean
|
|
40
|
+
code?: string
|
|
41
|
+
redirectUri?: string
|
|
42
|
+
codeVerifier?: string
|
|
43
|
+
/** Switch the default identity to the one we just logged in (default true). */
|
|
44
|
+
use?: boolean
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export type LoginResult = {
|
|
48
|
+
session: IdpSession
|
|
49
|
+
identityName: string
|
|
50
|
+
idpName: string
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Authenticate against an IdP and persist the result. Throws on any failure
|
|
55
|
+
* (no session is written) — notably BEFORE saving when an explicit `--audience`
|
|
56
|
+
* does not match the minted access token, so a wrong-audience login never
|
|
57
|
+
* leaves a half-written cache.
|
|
58
|
+
*/
|
|
59
|
+
export async function loginViaIdp(opts: LoginFlowOpts): Promise<LoginResult> {
|
|
60
|
+
const idpName = await resolveIdpName(opts.idp)
|
|
61
|
+
const idp = await readIdpConfigOrBuiltin(idpName, { clientId: opts.clientId, persist: true })
|
|
62
|
+
const scope = opts.scope ?? idp.client.scope ?? 'openid profile email offline_access'
|
|
63
|
+
|
|
64
|
+
const token = normalizeTokenResponse(await obtainToken(idp, opts, scope))
|
|
65
|
+
if (!token.access_token) throw new Error('IdP response did not include access_token')
|
|
66
|
+
if (opts.audience && !tokenAudienceMatches(token.access_token, opts.audience)) {
|
|
67
|
+
throw new Error(
|
|
68
|
+
`IdP response access_token was not minted for requested audience ${opts.audience}`,
|
|
69
|
+
)
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const claims = decodeTokenClaims(token.id_token ?? token.access_token)
|
|
73
|
+
const subject = subjectFromToken(token, opts.clientId ?? idp.client.client_id ?? idpName)
|
|
74
|
+
const issuer = issuerFromToken(token, idp.metadata.issuer)
|
|
75
|
+
const identityName = opts.name ?? identityNameFromClaims(claims, idpName)
|
|
76
|
+
const session: IdpSession = {
|
|
77
|
+
identity: identityName,
|
|
78
|
+
idp: idpName,
|
|
79
|
+
issuer,
|
|
80
|
+
subject,
|
|
81
|
+
audience: opts.audience,
|
|
82
|
+
access_token: token.access_token,
|
|
83
|
+
id_token: token.id_token,
|
|
84
|
+
refresh_token: token.refresh_token,
|
|
85
|
+
token_type: token.token_type,
|
|
86
|
+
scope: token.scope ?? scope,
|
|
87
|
+
expires_at: tokenExpiresAt(token),
|
|
88
|
+
tokens: withCachedToken(undefined, token.access_token, tokenExpiresAt(token)),
|
|
89
|
+
claims: claims ? (claims as Record<string, unknown>) : undefined,
|
|
90
|
+
updatedAt: new Date().toISOString(),
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
await saveIdpSession(session)
|
|
94
|
+
await upsertIdpIdentity(identityName, {
|
|
95
|
+
subject,
|
|
96
|
+
idp: idpName,
|
|
97
|
+
issuer,
|
|
98
|
+
audience: opts.audience,
|
|
99
|
+
claims: session.claims,
|
|
100
|
+
use: opts.use,
|
|
101
|
+
})
|
|
102
|
+
|
|
103
|
+
return { session, identityName, idpName }
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** Resolve which IdP to use: explicit name, the sole configured one, or WorkOS. */
|
|
107
|
+
export async function resolveIdpName(name: string | undefined): Promise<string> {
|
|
108
|
+
if (name) return name
|
|
109
|
+
const store = await readIdpStore()
|
|
110
|
+
const names = Object.keys(store.idps)
|
|
111
|
+
if (names.length === 1) return names[0]
|
|
112
|
+
if (names.length === 0 && workosClientIdFromEnv()) return 'workos'
|
|
113
|
+
if (names.length === 0)
|
|
114
|
+
throw new Error('No IdPs configured. Run: astrale idp add <name> --issuer <url>')
|
|
115
|
+
throw new Error(`Multiple IdPs configured. Choose one with --idp: ${names.join(', ')}`)
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
async function obtainToken(
|
|
119
|
+
idp: Awaited<ReturnType<typeof readIdpConfigOrBuiltin>>,
|
|
120
|
+
opts: LoginFlowOpts,
|
|
121
|
+
scope: string,
|
|
122
|
+
): Promise<TokenResponse> {
|
|
123
|
+
if (opts.clientCredentials) {
|
|
124
|
+
return requestClientCredentials({
|
|
125
|
+
idp,
|
|
126
|
+
clientId: opts.clientId,
|
|
127
|
+
clientSecretEnv: opts.clientSecretEnv,
|
|
128
|
+
scope,
|
|
129
|
+
audience: opts.audience,
|
|
130
|
+
})
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
if (opts.code) {
|
|
134
|
+
if (!opts.redirectUri) throw new Error('--redirect-uri is required with --code')
|
|
135
|
+
return exchangeAuthorizationCode({
|
|
136
|
+
idp,
|
|
137
|
+
code: opts.code,
|
|
138
|
+
redirectUri: opts.redirectUri,
|
|
139
|
+
codeVerifier: opts.codeVerifier,
|
|
140
|
+
clientId: opts.clientId,
|
|
141
|
+
clientSecretEnv: opts.clientSecretEnv,
|
|
142
|
+
})
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
const device = await requestDeviceAuthorization({
|
|
146
|
+
idp,
|
|
147
|
+
clientId: opts.clientId,
|
|
148
|
+
scope,
|
|
149
|
+
audience: opts.audience,
|
|
150
|
+
})
|
|
151
|
+
if (device.verification_uri_complete) log.info(`Open: ${device.verification_uri_complete}`)
|
|
152
|
+
else if (device.verification_uri) log.info(`Open: ${device.verification_uri}`)
|
|
153
|
+
if (device.user_code) log.info(`Code: ${device.user_code}`)
|
|
154
|
+
if (device.message) log.dim(` ${device.message}`)
|
|
155
|
+
|
|
156
|
+
return pollDeviceToken({
|
|
157
|
+
idp,
|
|
158
|
+
deviceCode: device.device_code,
|
|
159
|
+
clientId: opts.clientId,
|
|
160
|
+
clientSecretEnv: opts.clientSecretEnv,
|
|
161
|
+
intervalSec: device.interval,
|
|
162
|
+
expiresInSec: device.expires_in,
|
|
163
|
+
})
|
|
164
|
+
}
|
package/src/lib/meta.ts
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Issuer reachability helpers — OIDC discovery + JWKS.
|
|
3
|
+
*
|
|
4
|
+
* Kernels don't expose `/meta`. They expose OIDC discovery at
|
|
5
|
+
* `/.well-known/openid-configuration` (standard, returns `issuer` and
|
|
6
|
+
* `jwks_uri`) and JWKS at `/.well-known/jwks.json`. These helpers probe
|
|
7
|
+
* both to verify the issuer is alive and publishes at least one key.
|
|
8
|
+
*
|
|
9
|
+
* Domain workers may expose `/meta` for deployment drift detection; that is
|
|
10
|
+
* outside this connect-only CLI surface.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { IssuerUnreachableError } from '../errors'
|
|
14
|
+
|
|
15
|
+
export type DiscoveryDocument = {
|
|
16
|
+
/** OIDC issuer URL. */
|
|
17
|
+
issuer: string
|
|
18
|
+
/** JWKS URI (defaults to `<issuer>/.well-known/jwks.json`). */
|
|
19
|
+
jwksUri: string
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export async function fetchDiscovery(
|
|
23
|
+
url: string,
|
|
24
|
+
timeoutMs = 5_000,
|
|
25
|
+
fetchImpl: typeof fetch = globalThis.fetch,
|
|
26
|
+
): Promise<DiscoveryDocument> {
|
|
27
|
+
const discoveryUrl = url.replace(/\/+$/, '') + '/.well-known/openid-configuration'
|
|
28
|
+
try {
|
|
29
|
+
const r = await fetchImpl(discoveryUrl, { signal: AbortSignal.timeout(timeoutMs) })
|
|
30
|
+
if (!r.ok) throw new Error(`HTTP ${r.status}`)
|
|
31
|
+
const body = (await r.json()) as { issuer?: string; jwks_uri?: string }
|
|
32
|
+
if (!body.issuer) throw new Error('discovery missing "issuer"')
|
|
33
|
+
const issuer = body.issuer
|
|
34
|
+
const jwksUri = body.jwks_uri ?? `${issuer.replace(/\/+$/, '')}/.well-known/jwks.json`
|
|
35
|
+
return { issuer, jwksUri }
|
|
36
|
+
} catch (e) {
|
|
37
|
+
throw new IssuerUnreachableError(discoveryUrl, (e as Error).message)
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export async function fetchJwks(
|
|
42
|
+
jwksUri: string,
|
|
43
|
+
timeoutMs = 5_000,
|
|
44
|
+
fetchImpl: typeof fetch = globalThis.fetch,
|
|
45
|
+
): Promise<{ keys: Array<{ kid?: string }> }> {
|
|
46
|
+
try {
|
|
47
|
+
const r = await fetchImpl(jwksUri, { signal: AbortSignal.timeout(timeoutMs) })
|
|
48
|
+
if (!r.ok) throw new Error(`HTTP ${r.status}`)
|
|
49
|
+
return (await r.json()) as { keys: Array<{ kid?: string }> }
|
|
50
|
+
} catch (e) {
|
|
51
|
+
throw new IssuerUnreachableError(jwksUri, (e as Error).message)
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Discover the WorkOS organization an instance host pins
|
|
57
|
+
*/
|
|
58
|
+
export async function fetchOrgHint(url: string, timeoutMs = 5_000): Promise<string | undefined> {
|
|
59
|
+
try {
|
|
60
|
+
const origin = new URL(url).origin
|
|
61
|
+
const r = await fetch(`${origin}/auth/org`, { signal: AbortSignal.timeout(timeoutMs) })
|
|
62
|
+
if (!r.ok) return undefined
|
|
63
|
+
const body = (await r.json()) as { organizationId?: unknown }
|
|
64
|
+
return typeof body.organizationId === 'string' ? body.organizationId : undefined
|
|
65
|
+
} catch {
|
|
66
|
+
return undefined
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Verify the issuer at `url` publishes OIDC discovery and a non-empty JWKS.
|
|
72
|
+
* `issuerOverride` forces a specific expected issuer when discovery URL and
|
|
73
|
+
* declared issuer differ.
|
|
74
|
+
*/
|
|
75
|
+
export async function checkIssuerReachability(
|
|
76
|
+
url: string,
|
|
77
|
+
issuerOverride?: string,
|
|
78
|
+
fetchImpl?: typeof fetch,
|
|
79
|
+
): Promise<{ issuer: string; keys: Array<{ kid?: string }> }> {
|
|
80
|
+
const discovery = await fetchDiscovery(url, 5_000, fetchImpl)
|
|
81
|
+
const issuer = issuerOverride ?? discovery.issuer
|
|
82
|
+
const jwks = await fetchJwks(discovery.jwksUri, 5_000, fetchImpl)
|
|
83
|
+
if (jwks.keys.length === 0)
|
|
84
|
+
throw new IssuerUnreachableError(discovery.jwksUri, 'no keys published')
|
|
85
|
+
return { issuer, keys: jwks.keys }
|
|
86
|
+
}
|
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
import chalk from 'chalk'
|
|
2
|
+
import { stringify as yamlStringify } from 'yaml'
|
|
3
|
+
|
|
4
|
+
import { renderTable, type Column } from './table'
|
|
5
|
+
|
|
6
|
+
export type { Column } from './table'
|
|
7
|
+
|
|
8
|
+
export type OutputOpts = {
|
|
9
|
+
raw?: boolean
|
|
10
|
+
json?: boolean
|
|
11
|
+
format?: 'yaml' | 'json'
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export type RawOutputOpts = Pick<OutputOpts, 'raw' | 'json'>
|
|
15
|
+
|
|
16
|
+
export const RAW_OUTPUT_OPTIONS = [
|
|
17
|
+
{ flags: '--json', description: 'Always-valid JSON (for jq)' },
|
|
18
|
+
{ flags: '--raw', description: 'Unwrapped: bare scalar / raw bytes / JSON for objects' },
|
|
19
|
+
] as const
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Is the consumer a machine (emit structured data, not a pretty view)?
|
|
23
|
+
* True for `--json`, `--raw`, or any non-TTY stdout (pipe, redirect, CI, agent).
|
|
24
|
+
*/
|
|
25
|
+
export function isMachine(opts?: RawOutputOpts): boolean {
|
|
26
|
+
return !!(opts?.raw || opts?.json) || !(process.stdout.isTTY ?? false)
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* `--raw` = the *unwrapped* value (bare scalar, raw bytes). The raw-vs-json
|
|
31
|
+
* distinction only manifests for scalars and binary; objects/arrays fall back
|
|
32
|
+
* to JSON under either flag.
|
|
33
|
+
*/
|
|
34
|
+
export function isUnwrapped(opts?: RawOutputOpts): boolean {
|
|
35
|
+
return !!opts?.raw
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Write structured data to stdout in the appropriate format.
|
|
40
|
+
*
|
|
41
|
+
* Precedence:
|
|
42
|
+
* - `--raw` / `--json` → plain JSON, no colors (machine-readable)
|
|
43
|
+
* - explicit `--format yaml|json` → honor regardless of TTY, colors only on TTY
|
|
44
|
+
* - default on TTY → highlighted YAML
|
|
45
|
+
* - default on non-TTY → plain JSON
|
|
46
|
+
*
|
|
47
|
+
* Void-returning syscalls surface as `undefined` here; `JSON.stringify(undefined)`
|
|
48
|
+
* itself returns `undefined`, which would print the bare string `undefined` and
|
|
49
|
+
* break any caller doing `JSON.parse(stdout)`. Normalize to `null` (parseable
|
|
50
|
+
* JSON, valid YAML) at the entry so every formatter branch is consistent.
|
|
51
|
+
*/
|
|
52
|
+
export function output(data: unknown, opts: OutputOpts): void {
|
|
53
|
+
if (data === undefined) data = null
|
|
54
|
+
|
|
55
|
+
if (opts.raw || opts.json) {
|
|
56
|
+
process.stdout.write(JSON.stringify(data, null, 2) + '\n')
|
|
57
|
+
return
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const isTTY = process.stdout.isTTY ?? false
|
|
61
|
+
|
|
62
|
+
if (opts.format === 'json') {
|
|
63
|
+
const rendered = isTTY ? highlightJson(data) : JSON.stringify(data, null, 2)
|
|
64
|
+
process.stdout.write(rendered + '\n')
|
|
65
|
+
return
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
if (opts.format === 'yaml') {
|
|
69
|
+
const rendered = isTTY
|
|
70
|
+
? highlightYaml(data)
|
|
71
|
+
: yamlStringify(data, { indent: 2, lineWidth: 120 }).trimEnd()
|
|
72
|
+
process.stdout.write(rendered + '\n')
|
|
73
|
+
return
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// Default: TTY → highlighted YAML, non-TTY → plain JSON
|
|
77
|
+
if (isTTY) {
|
|
78
|
+
process.stdout.write(highlightYaml(data) + '\n')
|
|
79
|
+
} else {
|
|
80
|
+
process.stdout.write(JSON.stringify(data, null, 2) + '\n')
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// ── YAML ───────────────────────────────────────────────────
|
|
85
|
+
|
|
86
|
+
function highlightYaml(data: unknown): string {
|
|
87
|
+
const raw = yamlStringify(data, { indent: 2, lineWidth: 120 })
|
|
88
|
+
return raw
|
|
89
|
+
.replace(
|
|
90
|
+
/^(\s*-?\s*)([\w.-]+)(:)\s*(.*)/gm,
|
|
91
|
+
(_, indent: string, key: string, colon: string, value: string) =>
|
|
92
|
+
`${indent}${chalk.cyan(key)}${colon} ${colorYamlValue(value)}`,
|
|
93
|
+
)
|
|
94
|
+
.trimEnd()
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function colorYamlValue(value: string): string {
|
|
98
|
+
if (value === 'null' || value === '~') return chalk.dim('null')
|
|
99
|
+
if (value === 'true' || value === 'false') return chalk.magenta(value)
|
|
100
|
+
if (/^-?\d+(\.\d+)?$/.test(value)) return chalk.yellow(value)
|
|
101
|
+
return chalk.green(value)
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// ── JSON ───────────────────────────────────────────────────
|
|
105
|
+
|
|
106
|
+
function highlightJson(data: unknown): string {
|
|
107
|
+
const json = JSON.stringify(data, null, 2)
|
|
108
|
+
return json
|
|
109
|
+
.replace(/"([^"]+)"(?=\s*:)/g, (_, key: string) => chalk.cyan(`"${key}"`))
|
|
110
|
+
.replace(/: "([^"]*)"(?=[,\n\r\]}])/g, (_, val: string) => `: ${chalk.green(`"${val}"`)}`)
|
|
111
|
+
.replace(/: (-?\d+\.?\d*(?:e[+-]?\d+)?)\b/gi, (_, num: string) => `: ${chalk.yellow(num)}`)
|
|
112
|
+
.replace(/: (true|false)\b/g, (_, bool: string) => `: ${chalk.magenta(bool)}`)
|
|
113
|
+
.replace(/: (null)\b/g, () => `: ${chalk.dim('null')}`)
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// ── present: shape-aware rendering ──────────────────────────
|
|
117
|
+
|
|
118
|
+
export type PresentOpts = OutputOpts & { denoise?: boolean }
|
|
119
|
+
|
|
120
|
+
/** One display row per item plus the columns and (optional) `-q` paths. */
|
|
121
|
+
export type ListProjection = {
|
|
122
|
+
columns: Column[]
|
|
123
|
+
rows: Array<Record<string, string>>
|
|
124
|
+
paths?: string[]
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
export type ListOpts = OutputOpts & {
|
|
128
|
+
quiet?: boolean
|
|
129
|
+
count?: boolean
|
|
130
|
+
long?: boolean
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const NOISE_KEYS = new Set(['schema', 'icon', 'code', 'inputSchema', 'outputSchema'])
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* Strip heavy, low-signal keys (serialized schema blobs, SVG icons, code) at any
|
|
137
|
+
* depth — so machine output is the kernel's data minus the noise, never a wall.
|
|
138
|
+
*/
|
|
139
|
+
export function denoise(value: unknown): unknown {
|
|
140
|
+
if (Array.isArray(value)) return value.map(denoise)
|
|
141
|
+
if (value && typeof value === 'object') {
|
|
142
|
+
const out: Record<string, unknown> = {}
|
|
143
|
+
for (const [k, v] of Object.entries(value)) {
|
|
144
|
+
if (NOISE_KEYS.has(k)) continue
|
|
145
|
+
out[k] = v && typeof v === 'object' ? denoise(v) : v
|
|
146
|
+
}
|
|
147
|
+
return out
|
|
148
|
+
}
|
|
149
|
+
return value
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function isBareScalar(v: unknown): v is string | number | boolean {
|
|
153
|
+
return typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean'
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* Present a single kernel value, shape- and audience-aware.
|
|
158
|
+
*
|
|
159
|
+
* - scalar → `--raw` bare (no quotes, for `X=$(…)`) · `--json`/pipe JSON · TTY bare
|
|
160
|
+
* - object → YAML on a TTY, JSON for machines (delegates to {@link output})
|
|
161
|
+
* - array → YAML/JSON fallback (use {@link presentList} for a table)
|
|
162
|
+
*
|
|
163
|
+
* `null`/`undefined` normalize to `null` (via `output`) so `JSON.parse(stdout)`
|
|
164
|
+
* never breaks.
|
|
165
|
+
*/
|
|
166
|
+
export function present(value: unknown, opts: PresentOpts = {}): void {
|
|
167
|
+
const data = opts.denoise ? denoise(value) : value
|
|
168
|
+
|
|
169
|
+
if (isBareScalar(data)) {
|
|
170
|
+
if (opts.raw) {
|
|
171
|
+
process.stdout.write(String(data) + '\n')
|
|
172
|
+
return
|
|
173
|
+
}
|
|
174
|
+
if (!opts.json && (process.stdout.isTTY ?? false)) {
|
|
175
|
+
process.stdout.write(String(data) + '\n')
|
|
176
|
+
return
|
|
177
|
+
}
|
|
178
|
+
// `--json` or non-TTY machine → JSON (quoted string / bare number).
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
output(data, opts)
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* Present an array of objects.
|
|
186
|
+
*
|
|
187
|
+
* - `--count` → just the number
|
|
188
|
+
* - `-q/--quiet` → one path per line (unix-pipeable)
|
|
189
|
+
* - machine → denoised JSON of the raw items (`-l` keeps full items)
|
|
190
|
+
* - TTY → an aligned table + a dim count footer
|
|
191
|
+
*
|
|
192
|
+
* Projection (columns/rows/paths) is for the human table and `-q` only; the
|
|
193
|
+
* machine surface stays the kernel's own item fields.
|
|
194
|
+
*/
|
|
195
|
+
export function presentList<T>(
|
|
196
|
+
items: T[],
|
|
197
|
+
opts: ListOpts,
|
|
198
|
+
project: (items: T[]) => ListProjection,
|
|
199
|
+
): void {
|
|
200
|
+
if (opts.count) {
|
|
201
|
+
process.stdout.write(String(items.length) + '\n')
|
|
202
|
+
return
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
if (opts.quiet) {
|
|
206
|
+
const proj = project(items)
|
|
207
|
+
const paths = proj.paths ?? proj.rows.map((r) => r[proj.columns[0]?.key ?? ''] ?? '')
|
|
208
|
+
for (const p of paths) process.stdout.write(p + '\n')
|
|
209
|
+
return
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
if (isMachine(opts) || opts.format) {
|
|
213
|
+
output(opts.long ? items : denoise(items), opts)
|
|
214
|
+
return
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
const proj = project(items)
|
|
218
|
+
const table = renderTable(proj.rows, { columns: proj.columns })
|
|
219
|
+
const footer =
|
|
220
|
+
items.length > 0 ? chalk.dim(`\n ${items.length} item${items.length === 1 ? '' : 's'}`) : ''
|
|
221
|
+
process.stdout.write(table + footer + '\n')
|
|
222
|
+
}
|
package/src/lib/panel.ts
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import chalk from 'chalk'
|
|
2
|
+
|
|
3
|
+
// ESC[…m — built without a control char in the source so no lint disable is needed.
|
|
4
|
+
const ANSI = new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*m`, 'g')
|
|
5
|
+
|
|
6
|
+
/** Printable width of a string, ignoring ANSI color codes. */
|
|
7
|
+
function visibleWidth(s: string): number {
|
|
8
|
+
return s.replace(ANSI, '').length
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
const BOX = { tl: '╭', tr: '╮', bl: '╰', br: '╯', h: '─', v: '│' } as const
|
|
12
|
+
|
|
13
|
+
export type PanelOpts = {
|
|
14
|
+
/** Colorize the box border (default: cyan). */
|
|
15
|
+
borderColor?: (s: string) => string
|
|
16
|
+
/** Horizontal padding inside the box (default: 3). */
|
|
17
|
+
padX?: number
|
|
18
|
+
/** Left margin in spaces for the whole box (default: 2). */
|
|
19
|
+
margin?: number
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Draw a rounded box around pre-styled lines. Widths are computed on *visible*
|
|
24
|
+
* length so embedded ANSI (bold/color/underline) never breaks alignment. The
|
|
25
|
+
* lines are passed in already colored — `panel` only frames them.
|
|
26
|
+
*/
|
|
27
|
+
export function panel(lines: string[], opts: PanelOpts = {}): string {
|
|
28
|
+
const padX = opts.padX ?? 3
|
|
29
|
+
const margin = ' '.repeat(opts.margin ?? 2)
|
|
30
|
+
const border = opts.borderColor ?? chalk.cyan
|
|
31
|
+
const inner = Math.max(0, ...lines.map(visibleWidth))
|
|
32
|
+
const span = inner + padX * 2
|
|
33
|
+
|
|
34
|
+
const top = margin + border(BOX.tl + BOX.h.repeat(span) + BOX.tr)
|
|
35
|
+
const bottom = margin + border(BOX.bl + BOX.h.repeat(span) + BOX.br)
|
|
36
|
+
const body = lines.map((line) => {
|
|
37
|
+
const fill = ' '.repeat(inner - visibleWidth(line))
|
|
38
|
+
return (
|
|
39
|
+
margin + border(BOX.v) + ' '.repeat(padX) + line + fill + ' '.repeat(padX) + border(BOX.v)
|
|
40
|
+
)
|
|
41
|
+
})
|
|
42
|
+
return [top, ...body, bottom].join('\n')
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* The provisioned-instance hero: a bright, click-inviting panel that puts the
|
|
47
|
+
* fresh instance URL front and center. Rendered only in interactive (human)
|
|
48
|
+
* mode — machine output carries the URL in its JSON instead.
|
|
49
|
+
*/
|
|
50
|
+
export function renderInstanceHero(slug: string, url: string): string {
|
|
51
|
+
return panel(
|
|
52
|
+
[
|
|
53
|
+
`${chalk.green('✦')} ${chalk.bold('Your instance is live')}`,
|
|
54
|
+
'',
|
|
55
|
+
` ${chalk.bold.cyan.underline(url)}`,
|
|
56
|
+
'',
|
|
57
|
+
chalk.dim(` ${slug} · ⌘-click the link or paste it into your browser`),
|
|
58
|
+
],
|
|
59
|
+
{ borderColor: chalk.cyan },
|
|
60
|
+
)
|
|
61
|
+
}
|
package/src/lib/paths.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { paths } from './env'
|
|
2
|
+
|
|
3
|
+
export const ASTRALE_HOME = paths.home
|
|
4
|
+
export const KEYS_DIR = paths.keys
|
|
5
|
+
export const DATA_DIR = paths.data
|
|
6
|
+
export const CONFIG_PATH = paths.config
|
|
7
|
+
export const INSTALL_PATH = paths.install
|
|
8
|
+
export const IDENTITIES_PATH = paths.identities
|
|
9
|
+
export const INSTANCES_PATH = paths.instances
|
|
10
|
+
export const IDPS_PATH = paths.idps
|
|
11
|
+
export const IDP_SESSIONS_DIR = paths.idpSessionsDir
|
package/src/lib/port.ts
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import net from 'node:net'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Loopback port helpers for launching local servers (e.g. `astrale studio`).
|
|
5
|
+
*
|
|
6
|
+
* We probe by ACTUALLY trying to bind, not by connecting — a connect-probe to
|
|
7
|
+
* 127.0.0.1 is racy and can falsely pass on a half-open socket. Whatever port
|
|
8
|
+
* the OS lets us bind is, by definition, free for us right now. We bind on the
|
|
9
|
+
* loopback interface specifically (matching the studio's 127.0.0.1 bind) with
|
|
10
|
+
* `exclusive: true` so the probe never "succeeds" on a port another process
|
|
11
|
+
* holds via SO_REUSEADDR/REUSEPORT.
|
|
12
|
+
*/
|
|
13
|
+
const LOOPBACK = '127.0.0.1'
|
|
14
|
+
|
|
15
|
+
/** Resolves true if [port] can be bound on loopback right now, false otherwise. */
|
|
16
|
+
export function portFree(port: number, host = LOOPBACK): Promise<boolean> {
|
|
17
|
+
return new Promise((resolve) => {
|
|
18
|
+
const srv = net.createServer()
|
|
19
|
+
srv.once('error', () => resolve(false))
|
|
20
|
+
srv.once('listening', () => srv.close(() => resolve(true)))
|
|
21
|
+
srv.listen({ port, host, exclusive: true })
|
|
22
|
+
})
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* First free port in [start, start + span) on loopback, or null if the whole
|
|
27
|
+
* window is taken. We deliberately scan a small band in the IANA Registered
|
|
28
|
+
* range (well below the OS ephemeral range, which starts at 49152 on
|
|
29
|
+
* macOS/BSD and 32768 on Linux) so a probe can't collide with a short-lived
|
|
30
|
+
* outbound socket the OS hands out a microsecond later.
|
|
31
|
+
*/
|
|
32
|
+
export async function findFreePort(
|
|
33
|
+
start: number,
|
|
34
|
+
span = 20,
|
|
35
|
+
host = LOOPBACK,
|
|
36
|
+
): Promise<number | null> {
|
|
37
|
+
for (let p = start; p < start + span; p++) {
|
|
38
|
+
if (await portFree(p, host)) return p
|
|
39
|
+
}
|
|
40
|
+
return null
|
|
41
|
+
}
|
package/src/lib/proc.ts
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { spawn, type ChildProcess, type StdioOptions } from 'node:child_process'
|
|
2
|
+
|
|
3
|
+
export type RunResult = {
|
|
4
|
+
/** Exit code, or -1 when the process was killed by a signal. */
|
|
5
|
+
code: number
|
|
6
|
+
stdout: string
|
|
7
|
+
stderr: string
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Spawn a child process and capture stdout/stderr as UTF-8 text.
|
|
12
|
+
*
|
|
13
|
+
* Uses `node:child_process` rather than `Bun.spawn` so the exact same code runs
|
|
14
|
+
* under both the Bun-compiled standalone binary (Linux/macOS) and the Node/npm
|
|
15
|
+
* build (Windows and any Node user). The promise rejects only when the process
|
|
16
|
+
* fails to spawn (e.g. ENOENT); a non-zero exit resolves with that `code` so
|
|
17
|
+
* callers can branch on it.
|
|
18
|
+
*/
|
|
19
|
+
export function run(
|
|
20
|
+
file: string,
|
|
21
|
+
args: string[] = [],
|
|
22
|
+
opts: { cwd?: string } = {},
|
|
23
|
+
): Promise<RunResult> {
|
|
24
|
+
return new Promise((resolve, reject) => {
|
|
25
|
+
const child = spawn(file, args, { cwd: opts.cwd, stdio: ['ignore', 'pipe', 'pipe'] })
|
|
26
|
+
let stdout = ''
|
|
27
|
+
let stderr = ''
|
|
28
|
+
child.stdout?.setEncoding('utf8')
|
|
29
|
+
child.stderr?.setEncoding('utf8')
|
|
30
|
+
child.stdout?.on('data', (chunk: string) => {
|
|
31
|
+
stdout += chunk
|
|
32
|
+
})
|
|
33
|
+
child.stderr?.on('data', (chunk: string) => {
|
|
34
|
+
stderr += chunk
|
|
35
|
+
})
|
|
36
|
+
child.on('error', reject)
|
|
37
|
+
child.on('close', (code) => resolve({ code: code ?? -1, stdout, stderr }))
|
|
38
|
+
})
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Spawn a child process with inherited stdio so its output streams live to the
|
|
43
|
+
* user's terminal. Used for hand-held installs (npm / npx) where progress
|
|
44
|
+
* matters and the output is for the human, not for parsing. Resolves with the
|
|
45
|
+
* exit code; rejects only when the process fails to spawn (e.g. ENOENT).
|
|
46
|
+
*/
|
|
47
|
+
export function runInherit(
|
|
48
|
+
file: string,
|
|
49
|
+
args: string[] = [],
|
|
50
|
+
opts: { cwd?: string } = {},
|
|
51
|
+
): Promise<number> {
|
|
52
|
+
return new Promise((resolve, reject) => {
|
|
53
|
+
const child = spawn(file, args, { cwd: opts.cwd, stdio: 'inherit' })
|
|
54
|
+
child.on('error', reject)
|
|
55
|
+
child.on('close', (code) => resolve(code ?? -1))
|
|
56
|
+
})
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Spawn a LONG-LIVED child and return the handle immediately so the caller can
|
|
61
|
+
* supervise it (wait for exit, forward signals, tear down siblings). Unlike
|
|
62
|
+
* run()/runInherit() — which resolve only once the child closes — this is for
|
|
63
|
+
* servers the command keeps attached to (e.g. `astrale studio`'s Bun server and
|
|
64
|
+
* Vite dev process). Same node:child_process basis (cross-runtime) and bare
|
|
65
|
+
* PATH-name lookup convention. Default stdio streams stdout/stderr live but
|
|
66
|
+
* ignores stdin, so two supervised children never contend for the TTY.
|
|
67
|
+
*/
|
|
68
|
+
export function spawnHandle(
|
|
69
|
+
file: string,
|
|
70
|
+
args: string[] = [],
|
|
71
|
+
opts: { cwd?: string; env?: NodeJS.ProcessEnv; stdio?: StdioOptions; detached?: boolean } = {},
|
|
72
|
+
): ChildProcess {
|
|
73
|
+
return spawn(file, args, {
|
|
74
|
+
cwd: opts.cwd,
|
|
75
|
+
env: opts.env,
|
|
76
|
+
// `detached` makes the child its own process-group leader so the caller can
|
|
77
|
+
// tear down the whole tree (the child AND its grandchildren) with a single
|
|
78
|
+
// group signal — `process.kill(-child.pid, …)`.
|
|
79
|
+
detached: opts.detached,
|
|
80
|
+
stdio: opts.stdio ?? ['ignore', 'inherit', 'inherit'],
|
|
81
|
+
})
|
|
82
|
+
}
|