@prisma/cli-engine 0.0.1 → 0.0.2

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/dist/testing.js CHANGED
@@ -1,4 +1,284 @@
1
- import { t as buildEngine } from "./engine-DXE014TZ.js";
1
+ import { i as credentialsRequiredError, o as noSessionForWorkspaceError, t as buildEngine } from "./engine-vF4FiZqo.js";
2
+ import { Buffer } from "node:buffer";
3
+ //#region src/in-memory-credential-manager.ts
4
+ /**
5
+ * A complete CredentialManager whose state lives in memory rather than
6
+ * in a file. It implements the same rules as the file-backed one — the
7
+ * pinned decision, upsert by workspace, idempotent removal, and the two
8
+ * token storages — and adds a seed and a state read-back. Tests are
9
+ * what it is mostly used for, which is why it ships from the ./testing
10
+ * subpath alongside the JWT minter that produces tokens to seed it, but
11
+ * nothing about it is a stub.
12
+ */
13
+ /** The SDK's Tokens requires a workspace id, so an environment
14
+ * credential whose claims name no workspace is given this instead. It
15
+ * never leaves the manager, and it is never the empty string. */
16
+ const NO_WORKSPACE_CLAIMED = "(no workspace)";
17
+ /** Mints an unsigned JWT whose payload is exactly `claims` — the
18
+ * harness's claim source (`sub`, `workspace_id`, `exp`, `email`). */
19
+ function mintTestJwt(claims) {
20
+ const encode = (value) => Buffer.from(JSON.stringify(value)).toString("base64url");
21
+ return `${encode({
22
+ alg: "none",
23
+ typ: "JWT"
24
+ })}.${encode(claims)}.test-signature`;
25
+ }
26
+ function decodeJwtClaims(token) {
27
+ const parts = token.split(".");
28
+ if (parts.length < 2) return;
29
+ try {
30
+ const parsed = JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8"));
31
+ return typeof parsed === "object" && parsed !== null ? parsed : void 0;
32
+ } catch {
33
+ return;
34
+ }
35
+ }
36
+ function claimedWorkspaceId(token) {
37
+ const workspaceId = decodeJwtClaims(token)?.workspace_id;
38
+ return typeof workspaceId === "string" ? workspaceId : void 0;
39
+ }
40
+ function claimedExpiresAt(token) {
41
+ const exp = decodeJwtClaims(token)?.exp;
42
+ return typeof exp === "number" ? /* @__PURE__ */ new Date(exp * 1e3) : void 0;
43
+ }
44
+ function claimedIdentity(token) {
45
+ const claims = decodeJwtClaims(token);
46
+ const userId = typeof claims?.sub === "string" ? claims.sub : void 0;
47
+ const email = typeof claims?.email === "string" ? claims.email : void 0;
48
+ return userId === void 0 && email === void 0 ? void 0 : {
49
+ userId,
50
+ email,
51
+ name: void 0
52
+ };
53
+ }
54
+ function asSession(record) {
55
+ return {
56
+ workspaceId: record.workspaceId,
57
+ workspaceName: record.workspaceName,
58
+ expiresAt: record.credential.expiresAt
59
+ };
60
+ }
61
+ function storedActiveCredential(record) {
62
+ return {
63
+ workspaceId: record.workspaceId,
64
+ workspaceName: record.workspaceName,
65
+ expiresAt: record.credential.expiresAt,
66
+ identity: claimedIdentity(record.credential.token),
67
+ origin: { source: "stored" }
68
+ };
69
+ }
70
+ function environmentActiveCredential(credential) {
71
+ return {
72
+ workspaceId: claimedWorkspaceId(credential.token),
73
+ workspaceName: void 0,
74
+ expiresAt: claimedExpiresAt(credential.token) ?? credential.expiresAt,
75
+ identity: claimedIdentity(credential.token),
76
+ origin: { source: "environment" }
77
+ };
78
+ }
79
+ /**
80
+ * The memory-backed storage, for a credential with no home record: a
81
+ * free function closing over one local variable, so no method of it —
82
+ * clearTokens included — can reach the stored sessions. An environment
83
+ * credential whose workspace matches a stored session therefore cannot
84
+ * delete that session.
85
+ */
86
+ function memoryBackedStorage(credential) {
87
+ let tokens = {
88
+ workspaceId: claimedWorkspaceId(credential.token) ?? NO_WORKSPACE_CLAIMED,
89
+ accessToken: credential.token,
90
+ refreshToken: credential.refreshToken
91
+ };
92
+ return {
93
+ getTokens: async () => tokens,
94
+ setTokens: async (rotated) => {
95
+ tokens = rotated;
96
+ },
97
+ clearTokens: async () => {
98
+ tokens = null;
99
+ },
100
+ withRefreshLock: (fn) => fn()
101
+ };
102
+ }
103
+ /**
104
+ * The harness's mutable in-memory CredentialManager: the same
105
+ * interface commands see, with the whole stored state readable back
106
+ * after a run, and the design's process pinning — which credential
107
+ * this process acts as is fixed at the first activeCredential() read,
108
+ * while the material behind it is re-read on every call. No
109
+ * persistence, no locking — those belong to the real manager and its
110
+ * own tests.
111
+ */
112
+ var InMemoryCredentialManager = class {
113
+ storedSessions;
114
+ selection;
115
+ environmentCredential;
116
+ pin = { kind: "unresolved" };
117
+ activeStorage;
118
+ constructor(seed) {
119
+ this.storedSessions = [...seed.sessions ?? []];
120
+ this.selection = seed.selectedWorkspaceId;
121
+ this.environmentCredential = seed.environmentCredential;
122
+ if (seed.credential !== void 0) {
123
+ const workspaceId = claimedWorkspaceId(seed.credential.token);
124
+ if (workspaceId === void 0) throw new Error("@prisma/cli-engine/testing: the `credential` seed runs createSession's claims derivation — the token must be a JWT with `workspace_id` (use mintTestJwt)");
125
+ this.applyCreateSession(seed.credential, workspaceId);
126
+ }
127
+ }
128
+ state() {
129
+ return {
130
+ sessions: [...this.storedSessions],
131
+ selectedWorkspaceId: this.selection
132
+ };
133
+ }
134
+ /** Applies a write as ANOTHER process would: the stored state
135
+ * changes, but this process's pinned decision does not move. */
136
+ overwriteStoredState(state) {
137
+ if (state.sessions !== void 0) this.storedSessions = [...state.sessions];
138
+ if ("selectedWorkspaceId" in state) this.selection = state.selectedWorkspaceId;
139
+ }
140
+ async activeCredential() {
141
+ if (this.pin.kind === "unresolved") {
142
+ this.pin = this.resolvePin();
143
+ return this.credentialForPin(true);
144
+ }
145
+ return this.credentialForPin(false);
146
+ }
147
+ async sessions() {
148
+ return {
149
+ sessions: this.storedSessions.map((record) => asSession(record)),
150
+ selectedWorkspaceId: this.resolvedSelection()
151
+ };
152
+ }
153
+ async createSession(credential, workspaceId) {
154
+ return this.applyCreateSession(credential, workspaceId);
155
+ }
156
+ async selectSession(workspaceId) {
157
+ const record = this.storedSessions.find((stored) => stored.workspaceId === workspaceId);
158
+ if (record === void 0) throw noSessionForWorkspaceError(workspaceId);
159
+ this.selection = workspaceId;
160
+ if (this.environmentCredential === void 0) this.pin = {
161
+ kind: "session",
162
+ workspaceId
163
+ };
164
+ return asSession(record);
165
+ }
166
+ async endSession(workspaceId) {
167
+ this.removeRecord(workspaceId);
168
+ if (this.pin.kind === "session" && this.pin.workspaceId === workspaceId) this.pin = { kind: "none" };
169
+ }
170
+ async endAllSessions() {
171
+ this.storedSessions = [];
172
+ this.selection = void 0;
173
+ if (this.environmentCredential === void 0) this.pin = { kind: "none" };
174
+ }
175
+ async activeCredentialStorage() {
176
+ this.activeStorage ??= this.buildActiveStorage();
177
+ return this.activeStorage;
178
+ }
179
+ buildActiveStorage() {
180
+ const pin = this.pin;
181
+ if (pin.kind === "environment") return memoryBackedStorage(this.requireEnvironmentCredential());
182
+ if (pin.kind === "session") return this.storedSessionStorage(pin.workspaceId);
183
+ throw new Error("@prisma/cli-engine/testing: activeCredentialStorage() is only valid once activeCredential() has returned non-null");
184
+ }
185
+ /** The file-backed storage's analogue: the record is read afresh on
186
+ * every call, never snapshotted. */
187
+ storedSessionStorage(workspaceId) {
188
+ const pinnedRecord = () => this.storedSessions.find((record) => record.workspaceId === workspaceId);
189
+ return {
190
+ getTokens: async () => {
191
+ const record = pinnedRecord();
192
+ if (record === void 0) return null;
193
+ return {
194
+ workspaceId,
195
+ accessToken: record.credential.token,
196
+ refreshToken: record.credential.refreshToken
197
+ };
198
+ },
199
+ setTokens: async (tokens) => {
200
+ if (pinnedRecord() === void 0) throw credentialsRequiredError("session-ended");
201
+ const claimed = claimedWorkspaceId(tokens.accessToken);
202
+ if (claimed !== void 0 && claimed !== workspaceId) throw new Error("@prisma/cli-engine/testing: a refreshed token's workspace_id claim disagrees with the pinned workspace — refresh cannot re-scope");
203
+ this.storedSessions = this.storedSessions.map((stored) => stored.workspaceId === workspaceId ? {
204
+ ...stored,
205
+ credential: {
206
+ token: tokens.accessToken,
207
+ refreshToken: tokens.refreshToken,
208
+ expiresAt: claimedExpiresAt(tokens.accessToken)
209
+ }
210
+ } : stored);
211
+ },
212
+ clearTokens: async () => {
213
+ this.removeRecord(workspaceId);
214
+ },
215
+ clearTokensIfCurrent: async (tokens) => {
216
+ const record = pinnedRecord();
217
+ if (record === void 0 || tokens.workspaceId !== workspaceId || tokens.accessToken !== record.credential.token || tokens.refreshToken !== record.credential.refreshToken) return;
218
+ this.removeRecord(workspaceId);
219
+ },
220
+ withRefreshLock: (fn) => fn()
221
+ };
222
+ }
223
+ removeRecord(workspaceId) {
224
+ this.storedSessions = this.storedSessions.filter((stored) => stored.workspaceId !== workspaceId);
225
+ if (this.selection === workspaceId) this.selection = void 0;
226
+ }
227
+ resolvePin() {
228
+ if (this.environmentCredential !== void 0) return { kind: "environment" };
229
+ const selected = this.resolvedSelection();
230
+ return selected === void 0 ? { kind: "none" } : {
231
+ kind: "session",
232
+ workspaceId: selected
233
+ };
234
+ }
235
+ /** The selection the manager will admit to: one that names a stored
236
+ * session, or none. A dangling selection never escapes. */
237
+ resolvedSelection() {
238
+ const selected = this.selection;
239
+ return selected !== void 0 && this.storedSessions.some((record) => record.workspaceId === selected) ? selected : void 0;
240
+ }
241
+ credentialForPin(justResolved) {
242
+ const pin = this.pin;
243
+ if (pin.kind === "environment") return environmentActiveCredential(this.requireEnvironmentCredential());
244
+ if (pin.kind === "session") {
245
+ const record = this.storedSessions.find((stored) => stored.workspaceId === pin.workspaceId);
246
+ if (record === void 0) {
247
+ if (justResolved) throw new Error("@prisma/cli-engine/testing: the pin resolved to a workspace with no record");
248
+ throw credentialsRequiredError("session-ended");
249
+ }
250
+ return storedActiveCredential(record);
251
+ }
252
+ if (this.storedSessions.length > 0) throw credentialsRequiredError("sessions-held-none-selected");
253
+ return null;
254
+ }
255
+ requireEnvironmentCredential() {
256
+ const credential = this.environmentCredential;
257
+ if (credential === void 0) throw new Error("@prisma/cli-engine/testing: no environment credential is seeded");
258
+ return credential;
259
+ }
260
+ applyCreateSession(credential, workspaceId) {
261
+ const claimed = claimedWorkspaceId(credential.token);
262
+ if (claimed !== void 0 && claimed !== workspaceId) throw new Error("@prisma/cli-engine/testing: createSession's workspaceId argument disagrees with the credential's workspace_id claim");
263
+ const record = {
264
+ workspaceId,
265
+ workspaceName: this.storedSessions.find((stored) => stored.workspaceId === workspaceId)?.workspaceName,
266
+ credential: {
267
+ token: credential.token,
268
+ refreshToken: credential.refreshToken,
269
+ expiresAt: claimedExpiresAt(credential.token) ?? credential.expiresAt
270
+ }
271
+ };
272
+ this.storedSessions = [...this.storedSessions.filter((stored) => stored.workspaceId !== workspaceId), record];
273
+ this.selection = workspaceId;
274
+ if (this.environmentCredential === void 0) this.pin = {
275
+ kind: "session",
276
+ workspaceId
277
+ };
278
+ return asSession(record);
279
+ }
280
+ };
281
+ //#endregion
2
282
  //#region src/testing.ts
3
283
  function inputStreamFromString(text) {
4
284
  const bytes = new TextEncoder().encode(text);
@@ -14,83 +294,113 @@ function inputStreamFromString(text) {
14
294
  * proven by construction.
15
295
  */
16
296
  function createTestCli(spec) {
17
- const engine = buildEngine({
18
- name: "prisma-test",
19
- version: "0.0.0",
20
- commandFamilies: spec.commandFamilies ?? [],
21
- groups: spec.groups ?? {},
22
- commands: spec.commands
23
- }, { now: spec.now });
24
- return { async run(argv, opts) {
25
- let stdoutText = "";
26
- let stderrText = "";
27
- const frames = [];
28
- const events = [];
29
- let presented;
30
- const signalListeners = /* @__PURE__ */ new Set();
31
- const deliverSignal = (reason) => {
32
- const signal = reason === "SIGTERM" ? "SIGTERM" : "SIGINT";
33
- for (const listener of [...signalListeners]) listener(signal);
34
- };
35
- const runtime = {
36
- stdout: { write: (text) => {
37
- stdoutText += text;
38
- } },
39
- stderr: { write: (text) => {
40
- stderrText += text;
41
- } },
42
- stdin: inputStreamFromString(opts?.stdin ?? ""),
43
- cwd: opts?.cwd ?? "/",
44
- env: opts?.env ?? {},
45
- isTty: {
46
- stdin: opts?.isTty?.stdin ?? false,
47
- stdout: opts?.isTty?.stdout ?? false,
48
- stderr: opts?.isTty?.stderr ?? false
49
- },
50
- exit: (code) => {
51
- throw new Error(`@prisma/cli-engine: runtime.exit(${code}) reached the test harness`);
52
- },
53
- onSignal: (cb) => {
54
- signalListeners.add(cb);
55
- return () => {
56
- signalListeners.delete(cb);
57
- };
58
- },
59
- config: {
60
- sections: spec.config ?? {},
61
- diagnostics: []
62
- },
63
- getCredentials: async () => spec.credentials,
64
- managementApi: { baseUrl: spec.managementApi?.baseUrl ?? "https://test.invalid" },
65
- packageManager: spec.packageManager ?? "unknown"
66
- };
67
- const running = engine.execute(argv, runtime, {
68
- onEvent: (event) => {
69
- events.push(event);
70
- opts?.onEvent?.(event);
71
- },
72
- onPresented: (value) => {
73
- presented = value;
74
- },
75
- onStreamEvent: (frame) => {
76
- frames.push(frame);
77
- },
78
- onSettled: opts?.onSettled,
79
- answers: opts?.answers,
80
- managementApi: spec.managementApi?.client === void 0 ? void 0 : { client: spec.managementApi.client }
81
- });
82
- const abort = opts?.abort;
83
- if (abort !== void 0) if (abort.aborted) deliverSignal(abort.reason);
84
- else abort.addEventListener("abort", () => deliverSignal(abort.reason), { once: true });
85
- return {
86
- exitCode: await running,
87
- stdout: stdoutText,
88
- stderr: stderrText,
89
- json: frames,
90
- events,
91
- presented
92
- };
93
- } };
297
+ const credentialManager = new InMemoryCredentialManager({
298
+ sessions: spec.sessions,
299
+ selectedWorkspaceId: spec.selectedWorkspaceId,
300
+ credential: spec.credential,
301
+ environmentCredential: spec.environmentCredential
302
+ });
303
+ const managementApiClientConfig = spec.managementApiClientConfig ?? {
304
+ clientId: "test-client-id",
305
+ redirectUri: "https://test.invalid/auth/callback",
306
+ apiBaseUrl: spec.managementApi?.baseUrl ?? "https://test.invalid",
307
+ authBaseUrl: "https://auth.test.invalid"
308
+ };
309
+ const engine = buildEngine(
310
+ {
311
+ name: "prisma-test",
312
+ version: "0.0.0",
313
+ commandFamilies: spec.commandFamilies ?? [],
314
+ groups: spec.groups ?? {},
315
+ commands: spec.commands
316
+ },
317
+ /** Waiting is instant under test: browserWait's polling is driven
318
+ * by the seeded clock, never by real time. */
319
+ {
320
+ now: spec.now,
321
+ delay: async (ms, signal) => {
322
+ await spec.delay?.(ms, signal);
323
+ }
324
+ }
325
+ );
326
+ return {
327
+ credentialManager,
328
+ async run(argv, opts) {
329
+ let stdoutText = "";
330
+ let stderrText = "";
331
+ const frames = [];
332
+ const events = [];
333
+ let presented;
334
+ const signalListeners = /* @__PURE__ */ new Set();
335
+ const deliverSignal = (reason) => {
336
+ const signal = reason === "SIGTERM" ? "SIGTERM" : "SIGINT";
337
+ for (const listener of [...signalListeners]) listener(signal);
338
+ };
339
+ const runtime = {
340
+ stdout: { write: (text) => {
341
+ stdoutText += text;
342
+ } },
343
+ stderr: { write: (text) => {
344
+ stderrText += text;
345
+ } },
346
+ stdin: inputStreamFromString(opts?.stdin ?? ""),
347
+ cwd: opts?.cwd ?? "/",
348
+ env: spec.environmentCredential === void 0 ? opts?.env ?? {} : {
349
+ PRISMA_SERVICE_TOKEN: spec.environmentCredential.token,
350
+ ...opts?.env
351
+ },
352
+ isTty: {
353
+ stdin: opts?.isTty?.stdin ?? false,
354
+ stdout: opts?.isTty?.stdout ?? false,
355
+ stderr: opts?.isTty?.stderr ?? false
356
+ },
357
+ exit: (code) => {
358
+ throw new Error(`@prisma/cli-engine: runtime.exit(${code}) reached the test harness`);
359
+ },
360
+ onSignal: (cb) => {
361
+ signalListeners.add(cb);
362
+ return () => {
363
+ signalListeners.delete(cb);
364
+ };
365
+ },
366
+ config: {
367
+ sections: spec.config ?? {},
368
+ diagnostics: []
369
+ },
370
+ credentialManager,
371
+ managementApiClientConfig,
372
+ openUrl: spec.openUrl ?? (() => {}),
373
+ managementApi: { baseUrl: spec.managementApi?.baseUrl ?? "https://test.invalid" },
374
+ packageManager: spec.packageManager ?? "unknown"
375
+ };
376
+ const running = engine.execute(argv, runtime, {
377
+ onEvent: (event) => {
378
+ events.push(event);
379
+ opts?.onEvent?.(event);
380
+ },
381
+ onPresented: (value) => {
382
+ presented = value;
383
+ },
384
+ onStreamEvent: (frame) => {
385
+ frames.push(frame);
386
+ },
387
+ onSettled: opts?.onSettled,
388
+ answers: opts?.answers,
389
+ managementApi: spec.managementApi?.client === void 0 ? void 0 : { client: spec.managementApi.client }
390
+ });
391
+ const abort = opts?.abort;
392
+ if (abort !== void 0) if (abort.aborted) deliverSignal(abort.reason);
393
+ else abort.addEventListener("abort", () => deliverSignal(abort.reason), { once: true });
394
+ return {
395
+ exitCode: await running,
396
+ stdout: stdoutText,
397
+ stderr: stderrText,
398
+ json: frames,
399
+ events,
400
+ presented
401
+ };
402
+ }
403
+ };
94
404
  }
95
405
  //#endregion
96
- export { createTestCli };
406
+ export { InMemoryCredentialManager, createTestCli, mintTestJwt };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@prisma/cli-engine",
3
- "version": "0.0.1",
3
+ "version": "0.0.2",
4
4
  "description": "The execution engine of the unified Prisma CLI.",
5
5
  "type": "module",
6
6
  "exports": {