@prisma/cli-engine 0.0.1 → 0.0.3

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