@prisma/cli-engine 0.1.1 → 0.2.0

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.
@@ -1,5 +1,6 @@
1
- import { a as okVoid, r as notOk, t as CliStructuredError } from "./protocol-D1CRNkhv.js";
1
+ import { a as okVoid, r as notOk, t as CliStructuredError } from "./protocol-TtNVkeVS.js";
2
2
  import { createRequire } from "node:module";
3
+ import { Buffer } from "node:buffer";
3
4
  import { FlagNotFoundError, buildApplication, buildCommand, buildRouteMap, run, text_en } from "@stricli/core";
4
5
  import { randomUUID } from "node:crypto";
5
6
  import { existsSync, mkdirSync, readFileSync, realpathSync, renameSync, writeFileSync } from "node:fs";
@@ -8,7 +9,232 @@ import { detect } from "package-manager-detector/detect";
8
9
  import { createColors } from "colorette";
9
10
  import stringWidth from "string-width";
10
11
  import { Readable, Writable } from "node:stream";
11
- import { Buffer } from "node:buffer";
12
+ //#region src/credential-errors.ts
13
+ const signInAction = {
14
+ kind: "user-choice",
15
+ label: "Sign in, then run the command again."
16
+ };
17
+ const useSessionAction = {
18
+ kind: "run-command",
19
+ label: "Make one of your workspace sessions current",
20
+ command: "prisma auth workspace use"
21
+ };
22
+ /**
23
+ * The single constructor of CLI.CREDENTIALS_REQUIRED. Raised
24
+ * identically by the needs check, ctx.activeCredential, and the
25
+ * engine's request path.
26
+ */
27
+ function credentialsRequiredError(reason = "unauthenticated") {
28
+ switch (reason) {
29
+ case "unauthenticated": return new CliStructuredError("CLI.CREDENTIALS_REQUIRED", "You must be signed in to run this command.", { nextActions: [signInAction] });
30
+ case "expired": return new CliStructuredError("CLI.CREDENTIALS_REQUIRED", "Your session has expired — sign in again.", { nextActions: [signInAction] });
31
+ case "expiring-soon": return new CliStructuredError("CLI.CREDENTIALS_REQUIRED", "Your session expires too soon to run this command — sign in again.", {
32
+ why: "This command hands your credentials to another program, which cannot refresh them while it runs.",
33
+ nextActions: [signInAction]
34
+ });
35
+ case "session-ended": return new CliStructuredError("CLI.CREDENTIALS_REQUIRED", "The workspace session this command was using has ended.", {
36
+ why: "It was ended while the command was running (for example by another prisma process).",
37
+ nextActions: [useSessionAction, signInAction]
38
+ });
39
+ case "sessions-held-none-selected": return new CliStructuredError("CLI.CREDENTIALS_REQUIRED", "No workspace session is current.", {
40
+ why: "You have workspace sessions but none is current.",
41
+ nextActions: [useSessionAction, signInAction]
42
+ });
43
+ }
44
+ }
45
+ /**
46
+ * A refresh attempt failed transiently (the auth service, not the
47
+ * credentials): nothing was cleared, and signing in again is not the
48
+ * fix.
49
+ */
50
+ function authServiceError() {
51
+ return new CliStructuredError("CLI.AUTH_SERVICE_ERROR", "The authentication service could not refresh your session.", {
52
+ why: "The refresh attempt failed transiently; your stored credentials were left untouched.",
53
+ nextActions: [{
54
+ kind: "user-choice",
55
+ label: "Run the command again; sign in again only if the problem persists."
56
+ }]
57
+ });
58
+ }
59
+ /**
60
+ * The credential in force was rejected and could never be renewed — it
61
+ * carries no refresh token. The ONE place wording differs by origin;
62
+ * nothing else compares against `origin.source`.
63
+ */
64
+ function credentialRejectedError(origin, envVar) {
65
+ return origin.source === "environment" ? serviceTokenRejectedError({ envVar }) : credentialsRequiredError("expired");
66
+ }
67
+ /**
68
+ * A credential's workspace_id claim disagrees with the workspace it is
69
+ * being stored under, or a rotated token would re-scope a session.
70
+ * Raised by every CredentialManager, so a test sees what production
71
+ * raises.
72
+ */
73
+ function credentialWorkspaceMismatchError(workspaceId) {
74
+ return new CliStructuredError("AUTH.CREDENTIAL_WORKSPACE_MISMATCH", "That credential belongs to a different workspace.", {
75
+ why: `The token's workspace_id claim does not name workspace '${workspaceId}'.`,
76
+ nextActions: [{
77
+ kind: "run-command",
78
+ label: "Sign in again and pick the workspace you want",
79
+ command: "prisma auth login"
80
+ }]
81
+ });
82
+ }
83
+ /**
84
+ * The env var that supplies a session is set to a blank value. The one
85
+ * structured error for it, raised identically by activeCredential(),
86
+ * the needs check, and the engine's request path.
87
+ */
88
+ function emptyServiceTokenError(spec) {
89
+ return new CliStructuredError("AUTH.SERVICE_TOKEN_EMPTY", `${spec.envVar} is set but empty.`, {
90
+ why: `A blank token authenticates nothing, and ${spec.envVar} overrides your stored workspace sessions while it is set.`,
91
+ nextActions: [{
92
+ kind: "run-command",
93
+ label: `Unset ${spec.envVar}`,
94
+ command: `unset ${spec.envVar}`
95
+ }, {
96
+ kind: "user-choice",
97
+ label: `Or set ${spec.envVar} to a valid service token.`
98
+ }]
99
+ });
100
+ }
101
+ /**
102
+ * No session exists for the named workspace. Sessions are created by
103
+ * `prisma auth login` alone — `workspace use` selects among the ones
104
+ * you have.
105
+ */
106
+ function noSessionForWorkspaceError(workspaceRef) {
107
+ return new CliStructuredError("AUTH.NO_SESSION_FOR_WORKSPACE", `You have no session for workspace '${workspaceRef}'.`, { nextActions: [{
108
+ kind: "run-command",
109
+ label: `Sign in and pick '${workspaceRef}' in the browser`,
110
+ command: "prisma auth login"
111
+ }] });
112
+ }
113
+ /**
114
+ * Module-private on purpose: `credentialRejectedError` is the one place
115
+ * wording differs by origin (§11.1), and exporting this would be a
116
+ * second door into the environment-specific text that bypasses it.
117
+ *
118
+ * The management API rejected the env-supplied service token (401).
119
+ * There is no refresh for it and nothing stored is cleared.
120
+ */
121
+ function serviceTokenRejectedError(spec) {
122
+ return new CliStructuredError("AUTH.SERVICE_TOKEN_REJECTED", `The management API rejected the service token from ${spec.envVar}.`, { nextActions: [{
123
+ kind: "user-choice",
124
+ label: `Replace ${spec.envVar} with a valid service token, or unset it to use your stored sessions.`
125
+ }] });
126
+ }
127
+ //#endregion
128
+ //#region src/token-claims.ts
129
+ /**
130
+ * Reading a credential's own claims. This lives in the engine and is
131
+ * shared rather than reimplemented, because both credential managers
132
+ * need it and the two copies had already drifted: one knew a service
133
+ * token names its workspace through `sub`, the other did not, so a
134
+ * token that worked in production could not be reproduced in a test.
135
+ *
136
+ * Decoding only. Nothing here verifies a signature — the claims are the
137
+ * issuer's word, used for display and for keying, never for authorizing.
138
+ */
139
+ /** A service token's subject is its workspace, not a person. */
140
+ const WORKSPACE_SUBJECT_PREFIX = "workspace:";
141
+ function decodeTokenClaims(token) {
142
+ const payload = token.split(".")[1];
143
+ if (payload === void 0) return void 0;
144
+ try {
145
+ const parsed = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
146
+ return typeof parsed === "object" && parsed !== null ? parsed : void 0;
147
+ } catch {
148
+ return;
149
+ }
150
+ }
151
+ function claimedString(claims, name) {
152
+ const value = claims?.[name];
153
+ return typeof value === "string" && value.length > 0 ? value : void 0;
154
+ }
155
+ /**
156
+ * The workspace a credential names. One derivation, because a token
157
+ * says it one of two ways and every caller wants the same answer: an
158
+ * OAuth token carries `workspace_id`, while a service token names its
159
+ * workspace through `sub` and carries no `workspace_id` at all. Reading
160
+ * only the claim was a second path that happened to work because
161
+ * service tokens reached it by a different route — a split nothing
162
+ * enforced.
163
+ */
164
+ function credentialWorkspaceId(token) {
165
+ const claims = decodeTokenClaims(token);
166
+ const fromClaim = claimedString(claims, "workspace_id");
167
+ if (fromClaim !== void 0) return fromClaim;
168
+ const subject = claimedString(claims, "sub");
169
+ if (subject === void 0 || !subject.startsWith(WORKSPACE_SUBJECT_PREFIX)) return;
170
+ const derived = subject.slice(10).trim();
171
+ return derived.length > 0 ? derived : void 0;
172
+ }
173
+ function claimedExpiresAt(token) {
174
+ const exp = decodeTokenClaims(token)?.exp;
175
+ return typeof exp === "number" ? /* @__PURE__ */ new Date(exp * 1e3) : void 0;
176
+ }
177
+ /**
178
+ * Who a credential belongs to, from its own claims. A service token's
179
+ * subject names a workspace rather than a person, so it yields no user
180
+ * — reporting `workspace:ws_1` as a user id was a real defect.
181
+ */
182
+ function claimedIdentity(token) {
183
+ const claims = decodeTokenClaims(token);
184
+ const subject = claimedString(claims, "sub");
185
+ const userId = subject?.startsWith(WORKSPACE_SUBJECT_PREFIX) ? void 0 : subject;
186
+ const email = claimedString(claims, "email");
187
+ return userId === void 0 && email === void 0 ? void 0 : {
188
+ userId,
189
+ email,
190
+ name: void 0
191
+ };
192
+ }
193
+ //#endregion
194
+ //#region src/active-access-token.ts
195
+ /** Shared implementation used by every CredentialManager. */
196
+ async function readActiveAccessToken(storage, refreshCredential, options) {
197
+ const runLocked = storage.withRefreshLock ?? (async (fn) => fn());
198
+ try {
199
+ return await runLocked(async () => {
200
+ const current = await storage.getTokens();
201
+ if (current === null) return null;
202
+ if (!expiresSoon(current.accessToken, options, current.expiresAt)) return current.accessToken;
203
+ if (!current.refreshToken) throw credentialsRequiredError("expiring-soon");
204
+ if (refreshCredential === void 0) throw new Error("@prisma/cli-engine: delegated OAuth refresh requires Runtime.refreshCredential");
205
+ const refreshed = await refreshCredential({
206
+ refreshToken: current.refreshToken,
207
+ signal: options.signal
208
+ });
209
+ if (refreshed.kind === "invalid") {
210
+ await clearCurrentTokens(storage, current);
211
+ throw credentialsRequiredError("expired");
212
+ }
213
+ await storage.setTokens({
214
+ workspaceId: current.workspaceId,
215
+ accessToken: refreshed.accessToken,
216
+ refreshToken: refreshed.refreshToken
217
+ }, refreshed.expiresAt);
218
+ if (expiresSoon(refreshed.accessToken, options, refreshed.expiresAt)) throw new Error("the OAuth endpoint returned a short-lived token");
219
+ return refreshed.accessToken;
220
+ });
221
+ } catch (cause) {
222
+ if (CliStructuredError.is(cause) || options.signal.aborted) throw cause;
223
+ throw authServiceError();
224
+ }
225
+ }
226
+ function expiresSoon(token, options, fallbackExpiresAt) {
227
+ const expiresAt = claimedExpiresAt(token) ?? fallbackExpiresAt;
228
+ return expiresAt !== void 0 && expiresAt.getTime() - options.now.getTime() <= options.minimumValidityMs;
229
+ }
230
+ async function clearCurrentTokens(storage, current) {
231
+ if (storage.clearTokensIfCurrent !== void 0) {
232
+ await storage.clearTokensIfCurrent(current);
233
+ return;
234
+ }
235
+ await storage.clearTokens();
236
+ }
237
+ //#endregion
12
238
  //#region src/args.ts
13
239
  function flagRuntime(spec) {
14
240
  return spec;
@@ -1004,122 +1230,6 @@ function runCommand(manager, request) {
1004
1230
  //#region src/presentation.ts
1005
1231
  const PRESENTED = Symbol.for("prisma.cli-engine.presented");
1006
1232
  //#endregion
1007
- //#region src/credential-errors.ts
1008
- const signInAction = {
1009
- kind: "user-choice",
1010
- label: "Sign in, then run the command again."
1011
- };
1012
- const useSessionAction = {
1013
- kind: "run-command",
1014
- label: "Make one of your workspace sessions current",
1015
- command: "prisma auth workspace use"
1016
- };
1017
- /**
1018
- * The single constructor of CLI.CREDENTIALS_REQUIRED. Raised
1019
- * identically by the needs check, ctx.activeCredential, and the
1020
- * engine's request path.
1021
- */
1022
- function credentialsRequiredError(reason = "unauthenticated") {
1023
- switch (reason) {
1024
- case "unauthenticated": return new CliStructuredError("CLI.CREDENTIALS_REQUIRED", "You must be signed in to run this command.", { nextActions: [signInAction] });
1025
- case "expired": return new CliStructuredError("CLI.CREDENTIALS_REQUIRED", "Your session has expired — sign in again.", { nextActions: [signInAction] });
1026
- case "expiring-soon": return new CliStructuredError("CLI.CREDENTIALS_REQUIRED", "Your session expires too soon to run this command — sign in again.", {
1027
- why: "This command hands your credentials to another program, which cannot refresh them while it runs.",
1028
- nextActions: [signInAction]
1029
- });
1030
- case "session-ended": return new CliStructuredError("CLI.CREDENTIALS_REQUIRED", "The workspace session this command was using has ended.", {
1031
- why: "It was ended while the command was running (for example by another prisma process).",
1032
- nextActions: [useSessionAction, signInAction]
1033
- });
1034
- case "sessions-held-none-selected": return new CliStructuredError("CLI.CREDENTIALS_REQUIRED", "No workspace session is current.", {
1035
- why: "You have workspace sessions but none is current.",
1036
- nextActions: [useSessionAction, signInAction]
1037
- });
1038
- }
1039
- }
1040
- /**
1041
- * A refresh attempt failed transiently (the auth service, not the
1042
- * credentials): nothing was cleared, and signing in again is not the
1043
- * fix.
1044
- */
1045
- function authServiceError() {
1046
- return new CliStructuredError("CLI.AUTH_SERVICE_ERROR", "The authentication service could not refresh your session.", {
1047
- why: "The refresh attempt failed transiently; your stored credentials were left untouched.",
1048
- nextActions: [{
1049
- kind: "user-choice",
1050
- label: "Run the command again; sign in again only if the problem persists."
1051
- }]
1052
- });
1053
- }
1054
- /**
1055
- * The credential in force was rejected and could never be renewed — it
1056
- * carries no refresh token. The ONE place wording differs by origin;
1057
- * nothing else compares against `origin.source`.
1058
- */
1059
- function credentialRejectedError(origin, envVar) {
1060
- return origin.source === "environment" ? serviceTokenRejectedError({ envVar }) : credentialsRequiredError("expired");
1061
- }
1062
- /**
1063
- * A credential's workspace_id claim disagrees with the workspace it is
1064
- * being stored under, or a rotated token would re-scope a session.
1065
- * Raised by every CredentialManager, so a test sees what production
1066
- * raises.
1067
- */
1068
- function credentialWorkspaceMismatchError(workspaceId) {
1069
- return new CliStructuredError("AUTH.CREDENTIAL_WORKSPACE_MISMATCH", "That credential belongs to a different workspace.", {
1070
- why: `The token's workspace_id claim does not name workspace '${workspaceId}'.`,
1071
- nextActions: [{
1072
- kind: "run-command",
1073
- label: "Sign in again and pick the workspace you want",
1074
- command: "prisma auth login"
1075
- }]
1076
- });
1077
- }
1078
- /**
1079
- * The env var that supplies a session is set to a blank value. The one
1080
- * structured error for it, raised identically by activeCredential(),
1081
- * the needs check, and the engine's request path.
1082
- */
1083
- function emptyServiceTokenError(spec) {
1084
- return new CliStructuredError("AUTH.SERVICE_TOKEN_EMPTY", `${spec.envVar} is set but empty.`, {
1085
- why: `A blank token authenticates nothing, and ${spec.envVar} overrides your stored workspace sessions while it is set.`,
1086
- nextActions: [{
1087
- kind: "run-command",
1088
- label: `Unset ${spec.envVar}`,
1089
- command: `unset ${spec.envVar}`
1090
- }, {
1091
- kind: "user-choice",
1092
- label: `Or set ${spec.envVar} to a valid service token.`
1093
- }]
1094
- });
1095
- }
1096
- /**
1097
- * No session exists for the named workspace. Sessions are created by
1098
- * `prisma auth login` alone — `workspace use` selects among the ones
1099
- * you have.
1100
- */
1101
- function noSessionForWorkspaceError(workspaceRef) {
1102
- return new CliStructuredError("AUTH.NO_SESSION_FOR_WORKSPACE", `You have no session for workspace '${workspaceRef}'.`, { nextActions: [{
1103
- kind: "run-command",
1104
- label: `Sign in and pick '${workspaceRef}' in the browser`,
1105
- command: "prisma auth login"
1106
- }] });
1107
- }
1108
- /**
1109
- * Module-private on purpose: `credentialRejectedError` is the one place
1110
- * wording differs by origin (§11.1), and exporting this would be a
1111
- * second door into the environment-specific text that bypasses it.
1112
- *
1113
- * The management API rejected the env-supplied service token (401).
1114
- * There is no refresh for it and nothing stored is cleared.
1115
- */
1116
- function serviceTokenRejectedError(spec) {
1117
- return new CliStructuredError("AUTH.SERVICE_TOKEN_REJECTED", `The management API rejected the service token from ${spec.envVar}.`, { nextActions: [{
1118
- kind: "user-choice",
1119
- label: `Replace ${spec.envVar} with a valid service token, or unset it to use your stored sessions.`
1120
- }] });
1121
- }
1122
- //#endregion
1123
1233
  //#region src/credential-manager.ts
1124
1234
  /** The environment variables that supply a credential to a process: a
1125
1235
  * service token, plus the workspace it acts in when the token's own
@@ -1244,7 +1354,7 @@ function observedTokenStorage(storage, active, debug, probe) {
1244
1354
  };
1245
1355
  return {
1246
1356
  getTokens: () => storage.getTokens(),
1247
- setTokens: (tokens) => storage.setTokens(tokens),
1357
+ setTokens: (tokens, expiresAt) => storage.setTokens(tokens, expiresAt),
1248
1358
  clearTokens: () => storage.clearTokens(),
1249
1359
  ...storage.clearTokensIfCurrent === void 0 ? {} : { clearTokensIfCurrent: (tokens) => storage.clearTokensIfCurrent(tokens) },
1250
1360
  withRefreshLock: (fn) => storage.withRefreshLock === void 0 ? observedRefresh(fn) : storage.withRefreshLock(() => observedRefresh(fn))
@@ -2337,7 +2447,7 @@ function reportEvent(invocation, event) {
2337
2447
  return;
2338
2448
  }
2339
2449
  const terminal = state.delegatedTerminal;
2340
- if (terminal !== void 0) {
2450
+ if (terminal !== void 0 && state.format !== "json") {
2341
2451
  if (terminal.buffered.length >= 1e3) {
2342
2452
  terminal.dropped += 1;
2343
2453
  return;
@@ -2439,11 +2549,11 @@ async function checkDependencies(needs, invocation) {
2439
2549
  * ctx.api raise identically. A host with no manager wired has no
2440
2550
  * credentials at all.
2441
2551
  *
2442
- * The `"child"` form resolves the same credential ONCE, additionally
2443
- * refuses a session about to expire — before the handler runs, not
2444
- * before the spawn: the work that precedes a spawn creates real
2445
- * platform resources, and the child cannot refresh the snapshot it is
2446
- * given — and carries the credential forward for the spawn path.
2552
+ * The `"child"` form resolves the same credential ONCE and prepares an
2553
+ * access-token snapshot before the handler runs. A refreshable stored
2554
+ * OAuth session inside the near-expiry window is rotated and persisted;
2555
+ * an unrefreshable credential is refused. This happens before the
2556
+ * handler because work preceding a spawn may create platform resources.
2447
2557
  */
2448
2558
  async function checkCredentials(needs, invocation) {
2449
2559
  if (needs.credentials === false) return {};
@@ -2458,13 +2568,17 @@ async function checkCredentials(needs, invocation) {
2458
2568
  }
2459
2569
  if (credential === null) return { failure: needsErrored(credentialsRequiredError()) };
2460
2570
  if (needs.credentials !== "child") return {};
2461
- const expiry = nearExpiryFailure(credential, invocation);
2462
- return expiry === void 0 ? { spawnCredential: credential } : { failure: expiry };
2463
- }
2464
- function nearExpiryFailure(credential, invocation) {
2465
- if (credential.expiresAt === void 0) return;
2466
- if (credential.expiresAt.getTime() - invocation.now().getTime() > 3e5) return;
2467
- return needsErrored(credentialsRequiredError("expiring-soon"));
2571
+ try {
2572
+ if (await manager.activeAccessToken({
2573
+ minimumValidityMs: 3e5,
2574
+ now: invocation.now(),
2575
+ signal: invocation.signal
2576
+ }) === null) return { failure: needsErrored(credentialsRequiredError("session-ended")) };
2577
+ return { spawnCredential: credential };
2578
+ } catch (cause) {
2579
+ if (CliStructuredError.is(cause)) return { failure: needsErrored(cause) };
2580
+ throw cause;
2581
+ }
2468
2582
  }
2469
2583
  /**
2470
2584
  * A top-level key in the config file that is not one of the sections
@@ -3233,7 +3347,8 @@ async function runDelegated(invocation, def, terminal, spawnChild, options) {
3233
3347
  command: options.command,
3234
3348
  args: options.args ?? [],
3235
3349
  cwd: options.cwd ?? invocation.runtime.cwd,
3236
- env: await composeChildEnv(invocation, def, options.env)
3350
+ env: await composeChildEnv(invocation, def, options.env),
3351
+ output: state.format === "json" ? "diagnostic" : "inherit"
3237
3352
  };
3238
3353
  debug(`spawn: ${request.command} ${request.args.join(" ")} (cwd ${request.cwd})`);
3239
3354
  const result = await runChild(invocation, terminal, spawnChild, request);
@@ -3344,13 +3459,21 @@ async function composeChildEnv(invocation, def, additions) {
3344
3459
  }
3345
3460
  /**
3346
3461
  * The child's copy of the credential: the manager's activeAccessToken()
3347
- * operation, read at spawn time. The refresh token is never injected:
3348
- * the child runs on a snapshot it cannot refresh.
3462
+ * operation, read fresh at spawn time. The near-expiry policy already ran
3463
+ * at preflight, before the handler; the spawn-time read refuses only a
3464
+ * token that is already expired, so a still-valid credential can never be
3465
+ * refused after the handler's pre-spawn work has created resources. The
3466
+ * refresh token is never injected: the child runs on a snapshot it cannot
3467
+ * refresh.
3349
3468
  */
3350
3469
  async function spawnToken(invocation) {
3351
3470
  const manager = invocation.runtime.credentialManager;
3352
3471
  if (manager === void 0) throw credentialsRequiredError();
3353
- const accessToken = await manager.activeAccessToken();
3472
+ const accessToken = await manager.activeAccessToken({
3473
+ minimumValidityMs: 0,
3474
+ now: invocation.now(),
3475
+ signal: invocation.signal
3476
+ });
3354
3477
  if (accessToken === null) throw credentialsRequiredError("session-ended");
3355
3478
  return accessToken;
3356
3479
  }
@@ -3682,27 +3805,19 @@ function commandParameters(def) {
3682
3805
  function resolveExample(example, cliName) {
3683
3806
  return example.includes("{bin}") ? example.replaceAll("{bin}", cliName) : `${cliName} ${example}`;
3684
3807
  }
3685
- /** The --json refusal is stated in help, so a machine consumer learns
3686
- * it without running the command. */
3687
- const NO_JSON_NOTE = "This command hands the terminal to another program and does not support --json.";
3688
3808
  function commandDocs(def, cliName) {
3689
3809
  const examples = def.help.examples.map((example) => resolveExample(example, cliName));
3690
- const notes = def.maySpawn ? ["", NO_JSON_NOTE] : [];
3691
- if (examples.length === 0 && notes.length === 0) return {
3810
+ if (examples.length === 0) return {
3692
3811
  brief: def.help.summary,
3693
3812
  fullDescription: def.help.description
3694
3813
  };
3695
3814
  return {
3696
3815
  brief: def.help.summary,
3697
- fullDescription: [
3698
- def.help.description ?? def.help.summary,
3699
- ...notes,
3700
- ...examples.length === 0 ? [] : [
3701
- "",
3702
- "Examples:",
3703
- ...examples.map((example) => ` ${example}`)
3704
- ]
3705
- ].join("\n")
3816
+ fullDescription: [def.help.description ?? def.help.summary, ...examples.length === 0 ? [] : [
3817
+ "",
3818
+ "Examples:",
3819
+ ...examples.map((example) => ` ${example}`)
3820
+ ]].join("\n")
3706
3821
  };
3707
3822
  }
3708
3823
  function toStricliCommand(entry, cliName, runEntry) {
@@ -4036,10 +4151,6 @@ function renderLeafHelp(spec, entry, path, paint, lines) {
4036
4151
  lines.push(rail(paint));
4037
4152
  proseLines(def.help.description, paint, lines);
4038
4153
  }
4039
- if (def.maySpawn) {
4040
- lines.push(rail(paint));
4041
- lines.push(rail(paint, paint("muted", NO_JSON_NOTE)));
4042
- }
4043
4154
  const positionalEntries = Object.values(def.args.positionals).map((spec) => positionalRuntime(spec));
4044
4155
  if (positionalEntries.length > 0) {
4045
4156
  lines.push(rail(paint));
@@ -4195,9 +4306,8 @@ function settleVerbatimExitCode(invocation, exitCode) {
4195
4306
  * The status comes from the engine's own record of the child, never
4196
4307
  * from the handler, so there is nothing here for a handler to state.
4197
4308
  * Two conditions fence it, both construction errors: the command must
4198
- * hand the terminal to another program — reachable from a
4199
- * non-declaring handler this would also end a json stream without its
4200
- * terminal result frame — and a child must actually have run.
4309
+ * declare that it can hand execution to another program, and a child must
4310
+ * actually have run.
4201
4311
  *
4202
4312
  * A signal-killed child overrules whatever the handler asked for. The
4203
4313
  * user stopped the run: it settles 128 + the signal number, with no
@@ -4207,8 +4317,50 @@ function settleChildStatus(invocation, def, settlement) {
4207
4317
  if (!def.maySpawn) throw new Error(`@prisma/cli-engine: command '${invocation.state.commandId}' returned exitWithChildStatus without declaring maySpawn — only a command that hands the terminal to another program may settle with that program's status`);
4208
4318
  const child = invocation.state.lastChild;
4209
4319
  if (child === void 0) throw new Error(`@prisma/cli-engine: command '${invocation.state.commandId}' returned exitWithChildStatus without a child having run — that settlement reports the status of a child ctx.spawn started, and this run started none`);
4320
+ const exitCode = childExitCode(child);
4321
+ if (invocation.state.format === "json") {
4322
+ settleStructuredChildStatus(invocation, settlement, child, exitCode);
4323
+ return;
4324
+ }
4210
4325
  if (child.signal === null) for (const action of settlement.nextActions) invocation.runtime.stderr.write(`${renderNextAction(action, makePaint(invocation.state.colorEnabled))}\n`);
4211
- settleVerbatimExitCode(invocation, childExitCode(child));
4326
+ settleVerbatimExitCode(invocation, exitCode);
4327
+ }
4328
+ function settleStructuredChildStatus(invocation, settlement, child, exitCode) {
4329
+ settleVerbatimExitCode(invocation, exitCode);
4330
+ const nextActions = child.signal === null ? settlement.nextActions : [];
4331
+ if (exitCode === 0) {
4332
+ emitFrame(invocation, {
4333
+ kind: "result",
4334
+ envelope: {
4335
+ ok: true,
4336
+ commandId: invocation.state.commandId,
4337
+ result: null,
4338
+ exitCode,
4339
+ diagnostics: [],
4340
+ nextActions
4341
+ },
4342
+ commandId: invocation.state.commandId,
4343
+ timestamp: invocation.now().toISOString()
4344
+ });
4345
+ return;
4346
+ }
4347
+ const how = child.signal === null ? `exited with code ${String(child.exitCode ?? "unknown")}` : `was terminated by ${child.signal}`;
4348
+ emitErrored(invocation, {
4349
+ ok: false,
4350
+ commandId: invocation.state.commandId,
4351
+ error: {
4352
+ code: "CLI.CHILD_PROCESS_FAILED",
4353
+ severity: "error",
4354
+ summary: `The delegated process ${how}.`,
4355
+ nextActions,
4356
+ meta: {
4357
+ exitCode: child.exitCode,
4358
+ signal: child.signal
4359
+ }
4360
+ },
4361
+ diagnostics: [],
4362
+ nextActions
4363
+ });
4212
4364
  }
4213
4365
  /** A session command that returned ok shut down cleanly: no
4214
4366
  * presentation, and exit 0 — unless a signal ended the run, which
@@ -4599,18 +4751,11 @@ var EngineImpl = class {
4599
4751
  hooks.onSettled(summary);
4600
4752
  } catch {}
4601
4753
  }
4602
- /** The refusals a maySpawn command can hit before anything runs: a
4603
- * child's terminal output cannot be framed as a json stream, and a
4604
- * host that mounts the command without a spawn adapter is
4605
- * misconfigured. Returns whether the run was settled here. */
4754
+ /** A host that mounts a maySpawn command without a spawn adapter is
4755
+ * misconfigured. Refuse before needs or handler side effects. */
4606
4756
  refuseUnspawnable(invocation, entry) {
4607
4757
  const state = invocation.state;
4608
4758
  if (!entry.def.maySpawn) return false;
4609
- if (formatFlagGiven(state.argv) === "json") {
4610
- state.format = "human";
4611
- settleErrored(invocation, jsonUnsupportedError(entry.id));
4612
- return true;
4613
- }
4614
4759
  if (invocation.runtime.spawn === void 0) {
4615
4760
  state.format = "human";
4616
4761
  settleBug(invocation, /* @__PURE__ */ new Error(`@prisma/cli-engine: command '${entry.id}' declares maySpawn but the Runtime supplies no spawn adapter`));
@@ -4667,10 +4812,9 @@ var EngineImpl = class {
4667
4812
  let needsOutcome;
4668
4813
  try {
4669
4814
  applySharedFlags(state, rawFlags, invocation.runtime);
4670
- if (entry.def.maySpawn) state.format = "human";
4671
4815
  needsOutcome = await checkNeeds(entry.def, invocation);
4672
4816
  } catch (cause) {
4673
- settleBug(invocation, cause);
4817
+ settleThrown(invocation, cause);
4674
4818
  return;
4675
4819
  }
4676
4820
  if (needsOutcome.kind === "errored") {
@@ -4718,7 +4862,7 @@ var EngineImpl = class {
4718
4862
  try {
4719
4863
  needsOutcome = await checkNeeds(entry.def, invocation);
4720
4864
  } catch (cause) {
4721
- settleBug(invocation, cause);
4865
+ settleThrown(invocation, cause);
4722
4866
  return;
4723
4867
  }
4724
4868
  if (needsOutcome.kind === "errored") {
@@ -4774,18 +4918,6 @@ function attemptedPath(argv) {
4774
4918
  function declaredConfigSections(spec) {
4775
4919
  return [...new Set([...spec.commandFamilies.map((commandFamily) => commandFamily.configSection?.name), ...Object.values(spec.commands).map((def) => def.needs.config?.name)].filter((name) => name !== void 0))];
4776
4920
  }
4777
- /** A command that may hand the terminal to a child cannot frame its
4778
- * output, so json is refused as soon as the command is known — before
4779
- * the needs check and before anything runs. */
4780
- function jsonUnsupportedError(commandId) {
4781
- return new CliStructuredError("CLI.JSON_UNSUPPORTED", `The '${commandId.replaceAll(".", " ")}' command does not support json output.`, {
4782
- why: "It hands the terminal to another program, whose output cannot be framed as a json stream.",
4783
- nextActions: [{
4784
- kind: "user-choice",
4785
- label: "Run it without --json or --format json."
4786
- }]
4787
- });
4788
- }
4789
4921
  function declaredCapabilities(def) {
4790
4922
  if (def.kind !== "result-command") return {
4791
4923
  managesCredentials: false,
@@ -4814,70 +4946,4 @@ function distributePositionals(def, values) {
4814
4946
  return positionals;
4815
4947
  }
4816
4948
  //#endregion
4817
- //#region src/token-claims.ts
4818
- /**
4819
- * Reading a credential's own claims. This lives in the engine and is
4820
- * shared rather than reimplemented, because both credential managers
4821
- * need it and the two copies had already drifted: one knew a service
4822
- * token names its workspace through `sub`, the other did not, so a
4823
- * token that worked in production could not be reproduced in a test.
4824
- *
4825
- * Decoding only. Nothing here verifies a signature — the claims are the
4826
- * issuer's word, used for display and for keying, never for authorizing.
4827
- */
4828
- /** A service token's subject is its workspace, not a person. */
4829
- const WORKSPACE_SUBJECT_PREFIX = "workspace:";
4830
- function decodeTokenClaims(token) {
4831
- const payload = token.split(".")[1];
4832
- if (payload === void 0) return void 0;
4833
- try {
4834
- const parsed = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
4835
- return typeof parsed === "object" && parsed !== null ? parsed : void 0;
4836
- } catch {
4837
- return;
4838
- }
4839
- }
4840
- function claimedString(claims, name) {
4841
- const value = claims?.[name];
4842
- return typeof value === "string" && value.length > 0 ? value : void 0;
4843
- }
4844
- /**
4845
- * The workspace a credential names. One derivation, because a token
4846
- * says it one of two ways and every caller wants the same answer: an
4847
- * OAuth token carries `workspace_id`, while a service token names its
4848
- * workspace through `sub` and carries no `workspace_id` at all. Reading
4849
- * only the claim was a second path that happened to work because
4850
- * service tokens reached it by a different route — a split nothing
4851
- * enforced.
4852
- */
4853
- function credentialWorkspaceId(token) {
4854
- const claims = decodeTokenClaims(token);
4855
- const fromClaim = claimedString(claims, "workspace_id");
4856
- if (fromClaim !== void 0) return fromClaim;
4857
- const subject = claimedString(claims, "sub");
4858
- if (subject === void 0 || !subject.startsWith(WORKSPACE_SUBJECT_PREFIX)) return;
4859
- const derived = subject.slice(10).trim();
4860
- return derived.length > 0 ? derived : void 0;
4861
- }
4862
- function claimedExpiresAt(token) {
4863
- const exp = decodeTokenClaims(token)?.exp;
4864
- return typeof exp === "number" ? /* @__PURE__ */ new Date(exp * 1e3) : void 0;
4865
- }
4866
- /**
4867
- * Who a credential belongs to, from its own claims. A service token's
4868
- * subject names a workspace rather than a person, so it yields no user
4869
- * — reporting `workspace:ws_1` as a user id was a real defect.
4870
- */
4871
- function claimedIdentity(token) {
4872
- const claims = decodeTokenClaims(token);
4873
- const subject = claimedString(claims, "sub");
4874
- const userId = subject?.startsWith(WORKSPACE_SUBJECT_PREFIX) ? void 0 : subject;
4875
- const email = claimedString(claims, "email");
4876
- return userId === void 0 && email === void 0 ? void 0 : {
4877
- userId,
4878
- email,
4879
- name: void 0
4880
- };
4881
- }
4882
- //#endregion
4883
- export { exitWithChildStatus as C, resolveGating as S, positional as T, noSessionForWorkspaceError as _, CONFIG_FILE_NAME as a, userConfigPath as b, loadConfig as c, WORKSPACE_ID_ENV_VAR as d, authServiceError as f, emptyServiceTokenError as g, credentialsRequiredError as h, buildEngine as i, PRISMA_CONFIG_VERSION as l, credentialWorkspaceMismatchError as m, claimedIdentity as n, defineConfig as o, credentialRejectedError as p, credentialWorkspaceId as r, definePrismaConfig as s, claimedExpiresAt as t, SERVICE_TOKEN_ENV_VAR as u, PRESENTED as v, flag as w, writeUserConfig as x, readUserConfig as y };
4949
+ export { credentialWorkspaceMismatchError as C, noSessionForWorkspaceError as E, credentialRejectedError as S, emptyServiceTokenError as T, readActiveAccessToken as _, loadConfig as a, credentialWorkspaceId as b, WORKSPACE_ID_ENV_VAR as c, userConfigPath as d, writeUserConfig as f, positional as g, flag as h, definePrismaConfig as i, PRESENTED as l, exitWithChildStatus as m, CONFIG_FILE_NAME as n, PRISMA_CONFIG_VERSION as o, resolveGating as p, defineConfig as r, SERVICE_TOKEN_ENV_VAR as s, buildEngine as t, readUserConfig as u, claimedExpiresAt as v, credentialsRequiredError as w, authServiceError as x, claimedIdentity as y };