@prisma/cli-engine 0.1.1 → 0.2.1

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,14 +1,241 @@
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";
6
7
  import { dirname, join, resolve } from "node:path";
7
8
  import { detect } from "package-manager-detector/detect";
9
+ import { fileURLToPath, pathToFileURL } from "node:url";
8
10
  import { createColors } from "colorette";
9
11
  import stringWidth from "string-width";
10
12
  import { Readable, Writable } from "node:stream";
11
- import { Buffer } from "node:buffer";
13
+ //#region src/credential-errors.ts
14
+ const signInAction = {
15
+ kind: "user-choice",
16
+ label: "Sign in, then run the command again."
17
+ };
18
+ const useSessionAction = {
19
+ kind: "run-command",
20
+ label: "Make one of your workspace sessions current",
21
+ command: "prisma auth workspace use"
22
+ };
23
+ /**
24
+ * The single constructor of CLI.CREDENTIALS_REQUIRED. Raised
25
+ * identically by the needs check, ctx.activeCredential, and the
26
+ * engine's request path.
27
+ */
28
+ function credentialsRequiredError(reason = "unauthenticated") {
29
+ switch (reason) {
30
+ case "unauthenticated": return new CliStructuredError("CLI.CREDENTIALS_REQUIRED", "You must be signed in to run this command.", { nextActions: [signInAction] });
31
+ case "expired": return new CliStructuredError("CLI.CREDENTIALS_REQUIRED", "Your session has expired — sign in again.", { nextActions: [signInAction] });
32
+ case "expiring-soon": return new CliStructuredError("CLI.CREDENTIALS_REQUIRED", "Your session expires too soon to run this command — sign in again.", {
33
+ why: "This command hands your credentials to another program, which cannot refresh them while it runs.",
34
+ nextActions: [signInAction]
35
+ });
36
+ case "session-ended": return new CliStructuredError("CLI.CREDENTIALS_REQUIRED", "The workspace session this command was using has ended.", {
37
+ why: "It was ended while the command was running (for example by another prisma process).",
38
+ nextActions: [useSessionAction, signInAction]
39
+ });
40
+ case "sessions-held-none-selected": return new CliStructuredError("CLI.CREDENTIALS_REQUIRED", "No workspace session is current.", {
41
+ why: "You have workspace sessions but none is current.",
42
+ nextActions: [useSessionAction, signInAction]
43
+ });
44
+ }
45
+ }
46
+ /**
47
+ * A refresh attempt failed transiently (the auth service, not the
48
+ * credentials): nothing was cleared, and signing in again is not the
49
+ * fix.
50
+ */
51
+ function authServiceError() {
52
+ return new CliStructuredError("CLI.AUTH_SERVICE_ERROR", "The authentication service could not refresh your session.", {
53
+ why: "The refresh attempt failed transiently; your stored credentials were left untouched.",
54
+ nextActions: [{
55
+ kind: "user-choice",
56
+ label: "Run the command again; sign in again only if the problem persists."
57
+ }]
58
+ });
59
+ }
60
+ /**
61
+ * The credential in force was rejected and could never be renewed — it
62
+ * carries no refresh token. The ONE place wording differs by origin;
63
+ * nothing else compares against `origin.source`.
64
+ */
65
+ function credentialRejectedError(origin, envVar) {
66
+ return origin.source === "environment" ? serviceTokenRejectedError({ envVar }) : credentialsRequiredError("expired");
67
+ }
68
+ /**
69
+ * A credential's workspace_id claim disagrees with the workspace it is
70
+ * being stored under, or a rotated token would re-scope a session.
71
+ * Raised by every CredentialManager, so a test sees what production
72
+ * raises.
73
+ */
74
+ function credentialWorkspaceMismatchError(workspaceId) {
75
+ return new CliStructuredError("AUTH.CREDENTIAL_WORKSPACE_MISMATCH", "That credential belongs to a different workspace.", {
76
+ why: `The token's workspace_id claim does not name workspace '${workspaceId}'.`,
77
+ nextActions: [{
78
+ kind: "run-command",
79
+ label: "Sign in again and pick the workspace you want",
80
+ command: "prisma auth login"
81
+ }]
82
+ });
83
+ }
84
+ /**
85
+ * The env var that supplies a session is set to a blank value. The one
86
+ * structured error for it, raised identically by activeCredential(),
87
+ * the needs check, and the engine's request path.
88
+ */
89
+ function emptyServiceTokenError(spec) {
90
+ return new CliStructuredError("AUTH.SERVICE_TOKEN_EMPTY", `${spec.envVar} is set but empty.`, {
91
+ why: `A blank token authenticates nothing, and ${spec.envVar} overrides your stored workspace sessions while it is set.`,
92
+ nextActions: [{
93
+ kind: "run-command",
94
+ label: `Unset ${spec.envVar}`,
95
+ command: `unset ${spec.envVar}`
96
+ }, {
97
+ kind: "user-choice",
98
+ label: `Or set ${spec.envVar} to a valid service token.`
99
+ }]
100
+ });
101
+ }
102
+ /**
103
+ * No session exists for the named workspace. Sessions are created by
104
+ * `prisma auth login` alone — `workspace use` selects among the ones
105
+ * you have.
106
+ */
107
+ function noSessionForWorkspaceError(workspaceRef) {
108
+ return new CliStructuredError("AUTH.NO_SESSION_FOR_WORKSPACE", `You have no session for workspace '${workspaceRef}'.`, { nextActions: [{
109
+ kind: "run-command",
110
+ label: `Sign in and pick '${workspaceRef}' in the browser`,
111
+ command: "prisma auth login"
112
+ }] });
113
+ }
114
+ /**
115
+ * Module-private on purpose: `credentialRejectedError` is the one place
116
+ * wording differs by origin (§11.1), and exporting this would be a
117
+ * second door into the environment-specific text that bypasses it.
118
+ *
119
+ * The management API rejected the env-supplied service token (401).
120
+ * There is no refresh for it and nothing stored is cleared.
121
+ */
122
+ function serviceTokenRejectedError(spec) {
123
+ return new CliStructuredError("AUTH.SERVICE_TOKEN_REJECTED", `The management API rejected the service token from ${spec.envVar}.`, { nextActions: [{
124
+ kind: "user-choice",
125
+ label: `Replace ${spec.envVar} with a valid service token, or unset it to use your stored sessions.`
126
+ }] });
127
+ }
128
+ //#endregion
129
+ //#region src/token-claims.ts
130
+ /**
131
+ * Reading a credential's own claims. This lives in the engine and is
132
+ * shared rather than reimplemented, because both credential managers
133
+ * need it and the two copies had already drifted: one knew a service
134
+ * token names its workspace through `sub`, the other did not, so a
135
+ * token that worked in production could not be reproduced in a test.
136
+ *
137
+ * Decoding only. Nothing here verifies a signature — the claims are the
138
+ * issuer's word, used for display and for keying, never for authorizing.
139
+ */
140
+ /** A service token's subject is its workspace, not a person. */
141
+ const WORKSPACE_SUBJECT_PREFIX = "workspace:";
142
+ function decodeTokenClaims(token) {
143
+ const payload = token.split(".")[1];
144
+ if (payload === void 0) return void 0;
145
+ try {
146
+ const parsed = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
147
+ return typeof parsed === "object" && parsed !== null ? parsed : void 0;
148
+ } catch {
149
+ return;
150
+ }
151
+ }
152
+ function claimedString(claims, name) {
153
+ const value = claims?.[name];
154
+ return typeof value === "string" && value.length > 0 ? value : void 0;
155
+ }
156
+ /**
157
+ * The workspace a credential names. One derivation, because a token
158
+ * says it one of two ways and every caller wants the same answer: an
159
+ * OAuth token carries `workspace_id`, while a service token names its
160
+ * workspace through `sub` and carries no `workspace_id` at all. Reading
161
+ * only the claim was a second path that happened to work because
162
+ * service tokens reached it by a different route — a split nothing
163
+ * enforced.
164
+ */
165
+ function credentialWorkspaceId(token) {
166
+ const claims = decodeTokenClaims(token);
167
+ const fromClaim = claimedString(claims, "workspace_id");
168
+ if (fromClaim !== void 0) return fromClaim;
169
+ const subject = claimedString(claims, "sub");
170
+ if (subject === void 0 || !subject.startsWith(WORKSPACE_SUBJECT_PREFIX)) return;
171
+ const derived = subject.slice(10).trim();
172
+ return derived.length > 0 ? derived : void 0;
173
+ }
174
+ function claimedExpiresAt(token) {
175
+ const exp = decodeTokenClaims(token)?.exp;
176
+ return typeof exp === "number" ? /* @__PURE__ */ new Date(exp * 1e3) : void 0;
177
+ }
178
+ /**
179
+ * Who a credential belongs to, from its own claims. A service token's
180
+ * subject names a workspace rather than a person, so it yields no user
181
+ * — reporting `workspace:ws_1` as a user id was a real defect.
182
+ */
183
+ function claimedIdentity(token) {
184
+ const claims = decodeTokenClaims(token);
185
+ const subject = claimedString(claims, "sub");
186
+ const userId = subject?.startsWith(WORKSPACE_SUBJECT_PREFIX) ? void 0 : subject;
187
+ const email = claimedString(claims, "email");
188
+ return userId === void 0 && email === void 0 ? void 0 : {
189
+ userId,
190
+ email,
191
+ name: void 0
192
+ };
193
+ }
194
+ //#endregion
195
+ //#region src/active-access-token.ts
196
+ /** Shared implementation used by every CredentialManager. */
197
+ async function readActiveAccessToken(storage, refreshCredential, options) {
198
+ const runLocked = storage.withRefreshLock ?? (async (fn) => fn());
199
+ try {
200
+ return await runLocked(async () => {
201
+ const current = await storage.getTokens();
202
+ if (current === null) return null;
203
+ if (!expiresSoon(current.accessToken, options, current.expiresAt)) return current.accessToken;
204
+ if (!current.refreshToken) throw credentialsRequiredError("expiring-soon");
205
+ if (refreshCredential === void 0) throw new Error("@prisma/cli-engine: delegated OAuth refresh requires Runtime.refreshCredential");
206
+ const refreshed = await refreshCredential({
207
+ refreshToken: current.refreshToken,
208
+ signal: options.signal
209
+ });
210
+ if (refreshed.kind === "invalid") {
211
+ await clearCurrentTokens(storage, current);
212
+ throw credentialsRequiredError("expired");
213
+ }
214
+ await storage.setTokens({
215
+ workspaceId: current.workspaceId,
216
+ accessToken: refreshed.accessToken,
217
+ refreshToken: refreshed.refreshToken
218
+ }, refreshed.expiresAt);
219
+ if (expiresSoon(refreshed.accessToken, options, refreshed.expiresAt)) throw new Error("the OAuth endpoint returned a short-lived token");
220
+ return refreshed.accessToken;
221
+ });
222
+ } catch (cause) {
223
+ if (CliStructuredError.is(cause) || options.signal.aborted) throw cause;
224
+ throw authServiceError();
225
+ }
226
+ }
227
+ function expiresSoon(token, options, fallbackExpiresAt) {
228
+ const expiresAt = claimedExpiresAt(token) ?? fallbackExpiresAt;
229
+ return expiresAt !== void 0 && expiresAt.getTime() - options.now.getTime() <= options.minimumValidityMs;
230
+ }
231
+ async function clearCurrentTokens(storage, current) {
232
+ if (storage.clearTokensIfCurrent !== void 0) {
233
+ await storage.clearTokensIfCurrent(current);
234
+ return;
235
+ }
236
+ await storage.clearTokens();
237
+ }
238
+ //#endregion
12
239
  //#region src/args.ts
13
240
  function flagRuntime(spec) {
14
241
  return spec;
@@ -1004,122 +1231,6 @@ function runCommand(manager, request) {
1004
1231
  //#region src/presentation.ts
1005
1232
  const PRESENTED = Symbol.for("prisma.cli-engine.presented");
1006
1233
  //#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
1234
  //#region src/credential-manager.ts
1124
1235
  /** The environment variables that supply a credential to a process: a
1125
1236
  * service token, plus the workspace it acts in when the token's own
@@ -1244,7 +1355,7 @@ function observedTokenStorage(storage, active, debug, probe) {
1244
1355
  };
1245
1356
  return {
1246
1357
  getTokens: () => storage.getTokens(),
1247
- setTokens: (tokens) => storage.setTokens(tokens),
1358
+ setTokens: (tokens, expiresAt) => storage.setTokens(tokens, expiresAt),
1248
1359
  clearTokens: () => storage.clearTokens(),
1249
1360
  ...storage.clearTokensIfCurrent === void 0 ? {} : { clearTokensIfCurrent: (tokens) => storage.clearTokensIfCurrent(tokens) },
1250
1361
  withRefreshLock: (fn) => storage.withRefreshLock === void 0 ? observedRefresh(fn) : storage.withRefreshLock(() => observedRefresh(fn))
@@ -1537,7 +1648,7 @@ const EVALUATE_ONE_FILE_ONLY = {
1537
1648
  * exact path and must not answer with another.
1538
1649
  */
1539
1650
  async function evaluateConfigFile(path) {
1540
- const result = await (await import("c12")).loadConfig({
1651
+ const result = await (await import(pathToFileURL(realpathSync(fileURLToPath(import.meta.resolve("c12")))).href)).loadConfig({
1541
1652
  name: "prisma",
1542
1653
  configFile: path,
1543
1654
  cwd: dirname(path),
@@ -2337,7 +2448,7 @@ function reportEvent(invocation, event) {
2337
2448
  return;
2338
2449
  }
2339
2450
  const terminal = state.delegatedTerminal;
2340
- if (terminal !== void 0) {
2451
+ if (terminal !== void 0 && state.format !== "json") {
2341
2452
  if (terminal.buffered.length >= 1e3) {
2342
2453
  terminal.dropped += 1;
2343
2454
  return;
@@ -2439,11 +2550,11 @@ async function checkDependencies(needs, invocation) {
2439
2550
  * ctx.api raise identically. A host with no manager wired has no
2440
2551
  * credentials at all.
2441
2552
  *
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.
2553
+ * The `"child"` form resolves the same credential ONCE and prepares an
2554
+ * access-token snapshot before the handler runs. A refreshable stored
2555
+ * OAuth session inside the near-expiry window is rotated and persisted;
2556
+ * an unrefreshable credential is refused. This happens before the
2557
+ * handler because work preceding a spawn may create platform resources.
2447
2558
  */
2448
2559
  async function checkCredentials(needs, invocation) {
2449
2560
  if (needs.credentials === false) return {};
@@ -2458,13 +2569,17 @@ async function checkCredentials(needs, invocation) {
2458
2569
  }
2459
2570
  if (credential === null) return { failure: needsErrored(credentialsRequiredError()) };
2460
2571
  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"));
2572
+ try {
2573
+ if (await manager.activeAccessToken({
2574
+ minimumValidityMs: 3e5,
2575
+ now: invocation.now(),
2576
+ signal: invocation.signal
2577
+ }) === null) return { failure: needsErrored(credentialsRequiredError("session-ended")) };
2578
+ return { spawnCredential: credential };
2579
+ } catch (cause) {
2580
+ if (CliStructuredError.is(cause)) return { failure: needsErrored(cause) };
2581
+ throw cause;
2582
+ }
2468
2583
  }
2469
2584
  /**
2470
2585
  * A top-level key in the config file that is not one of the sections
@@ -3233,7 +3348,8 @@ async function runDelegated(invocation, def, terminal, spawnChild, options) {
3233
3348
  command: options.command,
3234
3349
  args: options.args ?? [],
3235
3350
  cwd: options.cwd ?? invocation.runtime.cwd,
3236
- env: await composeChildEnv(invocation, def, options.env)
3351
+ env: await composeChildEnv(invocation, def, options.env),
3352
+ output: state.format === "json" ? "diagnostic" : "inherit"
3237
3353
  };
3238
3354
  debug(`spawn: ${request.command} ${request.args.join(" ")} (cwd ${request.cwd})`);
3239
3355
  const result = await runChild(invocation, terminal, spawnChild, request);
@@ -3344,13 +3460,21 @@ async function composeChildEnv(invocation, def, additions) {
3344
3460
  }
3345
3461
  /**
3346
3462
  * 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.
3463
+ * operation, read fresh at spawn time. The near-expiry policy already ran
3464
+ * at preflight, before the handler; the spawn-time read refuses only a
3465
+ * token that is already expired, so a still-valid credential can never be
3466
+ * refused after the handler's pre-spawn work has created resources. The
3467
+ * refresh token is never injected: the child runs on a snapshot it cannot
3468
+ * refresh.
3349
3469
  */
3350
3470
  async function spawnToken(invocation) {
3351
3471
  const manager = invocation.runtime.credentialManager;
3352
3472
  if (manager === void 0) throw credentialsRequiredError();
3353
- const accessToken = await manager.activeAccessToken();
3473
+ const accessToken = await manager.activeAccessToken({
3474
+ minimumValidityMs: 0,
3475
+ now: invocation.now(),
3476
+ signal: invocation.signal
3477
+ });
3354
3478
  if (accessToken === null) throw credentialsRequiredError("session-ended");
3355
3479
  return accessToken;
3356
3480
  }
@@ -3682,27 +3806,19 @@ function commandParameters(def) {
3682
3806
  function resolveExample(example, cliName) {
3683
3807
  return example.includes("{bin}") ? example.replaceAll("{bin}", cliName) : `${cliName} ${example}`;
3684
3808
  }
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
3809
  function commandDocs(def, cliName) {
3689
3810
  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 {
3811
+ if (examples.length === 0) return {
3692
3812
  brief: def.help.summary,
3693
3813
  fullDescription: def.help.description
3694
3814
  };
3695
3815
  return {
3696
3816
  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")
3817
+ fullDescription: [def.help.description ?? def.help.summary, ...examples.length === 0 ? [] : [
3818
+ "",
3819
+ "Examples:",
3820
+ ...examples.map((example) => ` ${example}`)
3821
+ ]].join("\n")
3706
3822
  };
3707
3823
  }
3708
3824
  function toStricliCommand(entry, cliName, runEntry) {
@@ -4036,10 +4152,6 @@ function renderLeafHelp(spec, entry, path, paint, lines) {
4036
4152
  lines.push(rail(paint));
4037
4153
  proseLines(def.help.description, paint, lines);
4038
4154
  }
4039
- if (def.maySpawn) {
4040
- lines.push(rail(paint));
4041
- lines.push(rail(paint, paint("muted", NO_JSON_NOTE)));
4042
- }
4043
4155
  const positionalEntries = Object.values(def.args.positionals).map((spec) => positionalRuntime(spec));
4044
4156
  if (positionalEntries.length > 0) {
4045
4157
  lines.push(rail(paint));
@@ -4195,9 +4307,8 @@ function settleVerbatimExitCode(invocation, exitCode) {
4195
4307
  * The status comes from the engine's own record of the child, never
4196
4308
  * from the handler, so there is nothing here for a handler to state.
4197
4309
  * 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.
4310
+ * declare that it can hand execution to another program, and a child must
4311
+ * actually have run.
4201
4312
  *
4202
4313
  * A signal-killed child overrules whatever the handler asked for. The
4203
4314
  * user stopped the run: it settles 128 + the signal number, with no
@@ -4207,8 +4318,50 @@ function settleChildStatus(invocation, def, settlement) {
4207
4318
  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
4319
  const child = invocation.state.lastChild;
4209
4320
  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`);
4321
+ const exitCode = childExitCode(child);
4322
+ if (invocation.state.format === "json") {
4323
+ settleStructuredChildStatus(invocation, settlement, child, exitCode);
4324
+ return;
4325
+ }
4210
4326
  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));
4327
+ settleVerbatimExitCode(invocation, exitCode);
4328
+ }
4329
+ function settleStructuredChildStatus(invocation, settlement, child, exitCode) {
4330
+ settleVerbatimExitCode(invocation, exitCode);
4331
+ const nextActions = child.signal === null ? settlement.nextActions : [];
4332
+ if (exitCode === 0) {
4333
+ emitFrame(invocation, {
4334
+ kind: "result",
4335
+ envelope: {
4336
+ ok: true,
4337
+ commandId: invocation.state.commandId,
4338
+ result: null,
4339
+ exitCode,
4340
+ diagnostics: [],
4341
+ nextActions
4342
+ },
4343
+ commandId: invocation.state.commandId,
4344
+ timestamp: invocation.now().toISOString()
4345
+ });
4346
+ return;
4347
+ }
4348
+ const how = child.signal === null ? `exited with code ${String(child.exitCode ?? "unknown")}` : `was terminated by ${child.signal}`;
4349
+ emitErrored(invocation, {
4350
+ ok: false,
4351
+ commandId: invocation.state.commandId,
4352
+ error: {
4353
+ code: "CLI.CHILD_PROCESS_FAILED",
4354
+ severity: "error",
4355
+ summary: `The delegated process ${how}.`,
4356
+ nextActions,
4357
+ meta: {
4358
+ exitCode: child.exitCode,
4359
+ signal: child.signal
4360
+ }
4361
+ },
4362
+ diagnostics: [],
4363
+ nextActions
4364
+ });
4212
4365
  }
4213
4366
  /** A session command that returned ok shut down cleanly: no
4214
4367
  * presentation, and exit 0 — unless a signal ended the run, which
@@ -4599,18 +4752,11 @@ var EngineImpl = class {
4599
4752
  hooks.onSettled(summary);
4600
4753
  } catch {}
4601
4754
  }
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. */
4755
+ /** A host that mounts a maySpawn command without a spawn adapter is
4756
+ * misconfigured. Refuse before needs or handler side effects. */
4606
4757
  refuseUnspawnable(invocation, entry) {
4607
4758
  const state = invocation.state;
4608
4759
  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
4760
  if (invocation.runtime.spawn === void 0) {
4615
4761
  state.format = "human";
4616
4762
  settleBug(invocation, /* @__PURE__ */ new Error(`@prisma/cli-engine: command '${entry.id}' declares maySpawn but the Runtime supplies no spawn adapter`));
@@ -4667,10 +4813,9 @@ var EngineImpl = class {
4667
4813
  let needsOutcome;
4668
4814
  try {
4669
4815
  applySharedFlags(state, rawFlags, invocation.runtime);
4670
- if (entry.def.maySpawn) state.format = "human";
4671
4816
  needsOutcome = await checkNeeds(entry.def, invocation);
4672
4817
  } catch (cause) {
4673
- settleBug(invocation, cause);
4818
+ settleThrown(invocation, cause);
4674
4819
  return;
4675
4820
  }
4676
4821
  if (needsOutcome.kind === "errored") {
@@ -4718,7 +4863,7 @@ var EngineImpl = class {
4718
4863
  try {
4719
4864
  needsOutcome = await checkNeeds(entry.def, invocation);
4720
4865
  } catch (cause) {
4721
- settleBug(invocation, cause);
4866
+ settleThrown(invocation, cause);
4722
4867
  return;
4723
4868
  }
4724
4869
  if (needsOutcome.kind === "errored") {
@@ -4774,18 +4919,6 @@ function attemptedPath(argv) {
4774
4919
  function declaredConfigSections(spec) {
4775
4920
  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
4921
  }
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
4922
  function declaredCapabilities(def) {
4790
4923
  if (def.kind !== "result-command") return {
4791
4924
  managesCredentials: false,
@@ -4814,70 +4947,4 @@ function distributePositionals(def, values) {
4814
4947
  return positionals;
4815
4948
  }
4816
4949
  //#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 };
4950
+ 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 };