deepspace 0.19.5 → 0.21.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.
- package/CHANGELOG.md +24 -0
- package/dist/{chunk-A7UFIOWO.js → chunk-KDCDRHBA.js} +7 -2
- package/dist/chunk-KDCDRHBA.js.map +1 -0
- package/dist/cli.js +219 -94
- package/dist/cli.js.map +1 -1
- package/dist/documentation-client-core.d.ts +3 -2
- package/dist/documentation-client-core.js +1 -1
- package/dist/documentation-default-renderer.cjs +48 -48
- package/dist/documentation-react.d.ts +2 -1
- package/dist/documentation-react.js +1 -1
- package/dist/documentation-runtime.js +7 -7
- package/dist/documentation-server-core.d.ts +3 -2
- package/dist/documentation-server-core.js +1 -1
- package/dist/documentation.d.ts +40 -12
- package/dist/documentation.js +40 -7
- package/dist/documentation.js.map +1 -1
- package/dist/index.d.ts +225 -21
- package/dist/index.js +262 -112
- package/dist/index.js.map +1 -1
- package/dist/{public-CFAj1hL2.d.ts → public-DenQ1TsZ.d.ts} +36 -11
- package/dist/server.d.ts +46 -29
- package/dist/server.js +1041 -254
- package/dist/server.js.map +1 -1
- package/dist/testing-mcp.d.ts +69 -0
- package/dist/testing-mcp.js +99 -0
- package/dist/testing-mcp.js.map +1 -0
- package/dist/testing.d.ts +17 -20
- package/dist/testing.js +47 -25
- package/dist/testing.js.map +1 -1
- package/dist/worker.d.ts +73 -32
- package/dist/worker.js +1094 -244
- package/dist/worker.js.map +1 -1
- package/features/ai-chat/feature.json +2 -2
- package/features/ai-chat/src/AiChatPage.tsx +56 -21
- package/features/ai-chat/src/ChatPanel.tsx +33 -10
- package/features/ai-chat/src/__tests__/ChatPanel.lifecycle.test.tsx +156 -0
- package/features/cron/src/CronLogPage.tsx +107 -69
- package/features/file-attachments/feature.json +2 -1
- package/features/file-manager/feature.json +2 -1
- package/features/file-manager/src/FileManagerPage.tsx +227 -194
- package/features/integration-test/src/IntegrationTestPage.tsx +54 -34
- package/package.json +5 -1
- package/dist/chunk-A7UFIOWO.js.map +0 -1
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `deepspace/testing/mcp` — dependency-free JSON-RPC client for exercising
|
|
3
|
+
* the documentation MCP endpoint over its real HTTP wire contract.
|
|
4
|
+
*
|
|
5
|
+
* The endpoint is JSON-only (never SSE), stateless (no session ids), and
|
|
6
|
+
* unauthenticated, so the client is plain `fetch`: incrementing request ids,
|
|
7
|
+
* the negotiated `MCP-Protocol-Version` echoed after `initialize`, JSON-RPC
|
|
8
|
+
* error objects surfaced as typed throws, and notifications resolved on the
|
|
9
|
+
* wire's 202 + null body. It must stay importable without `@playwright/test`,
|
|
10
|
+
* so it lives beside — never inside — `./index.ts`.
|
|
11
|
+
*/
|
|
12
|
+
interface McpTestClientOptions {
|
|
13
|
+
/** Endpoint path resolved against the base URL. */
|
|
14
|
+
endpoint?: string;
|
|
15
|
+
/** Fetch implementation, e.g. one bound to an in-process worker. */
|
|
16
|
+
fetch?: typeof fetch;
|
|
17
|
+
}
|
|
18
|
+
interface McpInitializeResult {
|
|
19
|
+
protocolVersion: string;
|
|
20
|
+
capabilities: Record<string, unknown>;
|
|
21
|
+
serverInfo: {
|
|
22
|
+
name: string;
|
|
23
|
+
version: string;
|
|
24
|
+
title?: string;
|
|
25
|
+
};
|
|
26
|
+
instructions?: string;
|
|
27
|
+
}
|
|
28
|
+
interface McpTool {
|
|
29
|
+
name: string;
|
|
30
|
+
title?: string;
|
|
31
|
+
description?: string;
|
|
32
|
+
inputSchema: Record<string, unknown>;
|
|
33
|
+
}
|
|
34
|
+
interface McpToolCallResult {
|
|
35
|
+
content: Array<{
|
|
36
|
+
type: string;
|
|
37
|
+
text?: string;
|
|
38
|
+
}>;
|
|
39
|
+
structuredContent?: Record<string, unknown>;
|
|
40
|
+
isError?: boolean;
|
|
41
|
+
}
|
|
42
|
+
interface McpTestClient {
|
|
43
|
+
/** Negotiated at `initialize`; writable so suites can force a wire mismatch. */
|
|
44
|
+
protocolVersion: string | undefined;
|
|
45
|
+
initialize(params?: Record<string, unknown>): Promise<McpInitializeResult>;
|
|
46
|
+
listTools(): Promise<McpTool[]>;
|
|
47
|
+
callTool(name: string, args?: Record<string, unknown>): Promise<McpToolCallResult>;
|
|
48
|
+
notify(method: string, params?: Record<string, unknown>): Promise<void>;
|
|
49
|
+
}
|
|
50
|
+
/** A JSON-RPC `error` object answered by the endpoint. */
|
|
51
|
+
declare class McpRpcError extends Error {
|
|
52
|
+
readonly code: number;
|
|
53
|
+
readonly data: unknown;
|
|
54
|
+
readonly status: number;
|
|
55
|
+
constructor(status: number, error: {
|
|
56
|
+
code: number;
|
|
57
|
+
message: string;
|
|
58
|
+
data?: unknown;
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
/** A response outside the JSON-RPC contract, e.g. an unpublished surface's 404 page. */
|
|
62
|
+
declare class McpTransportError extends Error {
|
|
63
|
+
readonly status: number;
|
|
64
|
+
readonly bodyHead: string;
|
|
65
|
+
constructor(status: number, body: string);
|
|
66
|
+
}
|
|
67
|
+
declare function createMcpTestClient(baseUrl: string, options?: McpTestClientOptions): McpTestClient;
|
|
68
|
+
|
|
69
|
+
export { type McpInitializeResult, McpRpcError, type McpTestClient, type McpTestClientOptions, type McpTool, type McpToolCallResult, McpTransportError, createMcpTestClient };
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
// src/testing/mcp.ts
|
|
2
|
+
var McpRpcError = class extends Error {
|
|
3
|
+
code;
|
|
4
|
+
data;
|
|
5
|
+
status;
|
|
6
|
+
constructor(status, error) {
|
|
7
|
+
super(error.message);
|
|
8
|
+
this.name = "McpRpcError";
|
|
9
|
+
this.code = error.code;
|
|
10
|
+
this.data = error.data;
|
|
11
|
+
this.status = status;
|
|
12
|
+
}
|
|
13
|
+
};
|
|
14
|
+
var McpTransportError = class extends Error {
|
|
15
|
+
status;
|
|
16
|
+
bodyHead;
|
|
17
|
+
constructor(status, body) {
|
|
18
|
+
const bodyHead = body.slice(0, 200);
|
|
19
|
+
super(`Unexpected MCP response (HTTP ${status}): ${bodyHead || "<empty body>"}`);
|
|
20
|
+
this.name = "McpTransportError";
|
|
21
|
+
this.status = status;
|
|
22
|
+
this.bodyHead = bodyHead;
|
|
23
|
+
}
|
|
24
|
+
};
|
|
25
|
+
function createMcpTestClient(baseUrl, options = {}) {
|
|
26
|
+
const endpoint = new URL(options.endpoint ?? "/mcp", baseUrl).toString();
|
|
27
|
+
const fetchImpl = options.fetch ?? fetch;
|
|
28
|
+
let nextId = 1;
|
|
29
|
+
let protocolVersion;
|
|
30
|
+
const post = (payload) => fetchImpl(endpoint, {
|
|
31
|
+
method: "POST",
|
|
32
|
+
headers: {
|
|
33
|
+
"Content-Type": "application/json",
|
|
34
|
+
Accept: "application/json",
|
|
35
|
+
// The header exists only after negotiation, so `initialize` never carries it.
|
|
36
|
+
...protocolVersion !== void 0 && payload.method !== "initialize" ? { "MCP-Protocol-Version": protocolVersion } : {}
|
|
37
|
+
},
|
|
38
|
+
body: JSON.stringify(payload)
|
|
39
|
+
});
|
|
40
|
+
const parseMessage = async (response) => {
|
|
41
|
+
const body = await response.text();
|
|
42
|
+
let message;
|
|
43
|
+
try {
|
|
44
|
+
message = JSON.parse(body);
|
|
45
|
+
} catch {
|
|
46
|
+
throw new McpTransportError(response.status, body);
|
|
47
|
+
}
|
|
48
|
+
if (!message || typeof message !== "object" || Array.isArray(message)) {
|
|
49
|
+
throw new McpTransportError(response.status, body);
|
|
50
|
+
}
|
|
51
|
+
const { error } = message;
|
|
52
|
+
if (error) throw new McpRpcError(response.status, error);
|
|
53
|
+
return { body, message };
|
|
54
|
+
};
|
|
55
|
+
const request = async (method, params) => {
|
|
56
|
+
const response = await post({
|
|
57
|
+
jsonrpc: "2.0",
|
|
58
|
+
id: nextId++,
|
|
59
|
+
method,
|
|
60
|
+
...params !== void 0 ? { params } : {}
|
|
61
|
+
});
|
|
62
|
+
return (await parseMessage(response)).message.result;
|
|
63
|
+
};
|
|
64
|
+
return {
|
|
65
|
+
get protocolVersion() {
|
|
66
|
+
return protocolVersion;
|
|
67
|
+
},
|
|
68
|
+
set protocolVersion(value) {
|
|
69
|
+
protocolVersion = value;
|
|
70
|
+
},
|
|
71
|
+
async initialize(params) {
|
|
72
|
+
const result = await request("initialize", params);
|
|
73
|
+
protocolVersion = typeof result?.protocolVersion === "string" ? result.protocolVersion : void 0;
|
|
74
|
+
return result;
|
|
75
|
+
},
|
|
76
|
+
async listTools() {
|
|
77
|
+
return (await request("tools/list")).tools;
|
|
78
|
+
},
|
|
79
|
+
async callTool(name, args = {}) {
|
|
80
|
+
return request("tools/call", { name, arguments: args });
|
|
81
|
+
},
|
|
82
|
+
async notify(method, params) {
|
|
83
|
+
const response = await post({
|
|
84
|
+
jsonrpc: "2.0",
|
|
85
|
+
method,
|
|
86
|
+
...params !== void 0 ? { params } : {}
|
|
87
|
+
});
|
|
88
|
+
if (response.status === 202) return;
|
|
89
|
+
const { body } = await parseMessage(response);
|
|
90
|
+
throw new McpTransportError(response.status, body);
|
|
91
|
+
}
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
export {
|
|
95
|
+
McpRpcError,
|
|
96
|
+
McpTransportError,
|
|
97
|
+
createMcpTestClient
|
|
98
|
+
};
|
|
99
|
+
//# sourceMappingURL=testing-mcp.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/testing/mcp.ts"],"sourcesContent":["/**\n * `deepspace/testing/mcp` — dependency-free JSON-RPC client for exercising\n * the documentation MCP endpoint over its real HTTP wire contract.\n *\n * The endpoint is JSON-only (never SSE), stateless (no session ids), and\n * unauthenticated, so the client is plain `fetch`: incrementing request ids,\n * the negotiated `MCP-Protocol-Version` echoed after `initialize`, JSON-RPC\n * error objects surfaced as typed throws, and notifications resolved on the\n * wire's 202 + null body. It must stay importable without `@playwright/test`,\n * so it lives beside — never inside — `./index.ts`.\n */\n\nexport interface McpTestClientOptions {\n /** Endpoint path resolved against the base URL. */\n endpoint?: string\n /** Fetch implementation, e.g. one bound to an in-process worker. */\n fetch?: typeof fetch\n}\n\nexport interface McpInitializeResult {\n protocolVersion: string\n capabilities: Record<string, unknown>\n serverInfo: { name: string; version: string; title?: string }\n instructions?: string\n}\n\nexport interface McpTool {\n name: string\n title?: string\n description?: string\n inputSchema: Record<string, unknown>\n}\n\nexport interface McpToolCallResult {\n content: Array<{ type: string; text?: string }>\n structuredContent?: Record<string, unknown>\n isError?: boolean\n}\n\nexport interface McpTestClient {\n /** Negotiated at `initialize`; writable so suites can force a wire mismatch. */\n protocolVersion: string | undefined\n initialize(params?: Record<string, unknown>): Promise<McpInitializeResult>\n listTools(): Promise<McpTool[]>\n callTool(name: string, args?: Record<string, unknown>): Promise<McpToolCallResult>\n notify(method: string, params?: Record<string, unknown>): Promise<void>\n}\n\n/** A JSON-RPC `error` object answered by the endpoint. */\nexport class McpRpcError extends Error {\n readonly code: number\n readonly data: unknown\n readonly status: number\n constructor(status: number, error: { code: number; message: string; data?: unknown }) {\n super(error.message)\n this.name = 'McpRpcError'\n this.code = error.code\n this.data = error.data\n this.status = status\n }\n}\n\n/** A response outside the JSON-RPC contract, e.g. an unpublished surface's 404 page. */\nexport class McpTransportError extends Error {\n readonly status: number\n readonly bodyHead: string\n constructor(status: number, body: string) {\n const bodyHead = body.slice(0, 200)\n super(`Unexpected MCP response (HTTP ${status}): ${bodyHead || '<empty body>'}`)\n this.name = 'McpTransportError'\n this.status = status\n this.bodyHead = bodyHead\n }\n}\n\nexport function createMcpTestClient(\n baseUrl: string,\n options: McpTestClientOptions = {},\n): McpTestClient {\n const endpoint = new URL(options.endpoint ?? '/mcp', baseUrl).toString()\n const fetchImpl = options.fetch ?? fetch\n let nextId = 1\n let protocolVersion: string | undefined\n\n const post = (payload: Record<string, unknown>): Promise<Response> =>\n fetchImpl(endpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n // The header exists only after negotiation, so `initialize` never carries it.\n ...(protocolVersion !== undefined && payload.method !== 'initialize'\n ? { 'MCP-Protocol-Version': protocolVersion }\n : {}),\n },\n body: JSON.stringify(payload),\n })\n\n const parseMessage = async (\n response: Response,\n ): Promise<{ body: string; message: Record<string, unknown> }> => {\n const body = await response.text()\n let message: unknown\n try {\n message = JSON.parse(body)\n } catch {\n throw new McpTransportError(response.status, body)\n }\n if (!message || typeof message !== 'object' || Array.isArray(message)) {\n throw new McpTransportError(response.status, body)\n }\n const { error } = message as { error?: { code: number; message: string; data?: unknown } }\n if (error) throw new McpRpcError(response.status, error)\n return { body, message: message as Record<string, unknown> }\n }\n\n const request = async <Result>(method: string, params?: unknown): Promise<Result> => {\n const response = await post({\n jsonrpc: '2.0',\n id: nextId++,\n method,\n ...(params !== undefined ? { params } : {}),\n })\n return (await parseMessage(response)).message.result as Result\n }\n\n return {\n get protocolVersion() {\n return protocolVersion\n },\n set protocolVersion(value) {\n protocolVersion = value\n },\n async initialize(params) {\n const result = await request<McpInitializeResult>('initialize', params)\n protocolVersion =\n typeof result?.protocolVersion === 'string' ? result.protocolVersion : undefined\n return result\n },\n async listTools() {\n return (await request<{ tools: McpTool[] }>('tools/list')).tools\n },\n async callTool(name, args = {}) {\n return request<McpToolCallResult>('tools/call', { name, arguments: args })\n },\n async notify(method, params) {\n const response = await post({\n jsonrpc: '2.0',\n method,\n ...(params !== undefined ? { params } : {}),\n })\n if (response.status === 202) return\n // Anything else breaches the notification contract: a JSON-RPC error\n // throws typed above, and a stray result is itself a transport fault.\n const { body } = await parseMessage(response)\n throw new McpTransportError(response.status, body)\n },\n }\n}\n"],"mappings":";AAiDO,IAAM,cAAN,cAA0B,MAAM;AAAA,EAC5B;AAAA,EACA;AAAA,EACA;AAAA,EACT,YAAY,QAAgB,OAA0D;AACpF,UAAM,MAAM,OAAO;AACnB,SAAK,OAAO;AACZ,SAAK,OAAO,MAAM;AAClB,SAAK,OAAO,MAAM;AAClB,SAAK,SAAS;AAAA,EAChB;AACF;AAGO,IAAM,oBAAN,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AA,MACJ;AAAA,MACA,GAAI,WAAW,SAAY,EAAE,OAAO,IAAI,CAAC;AAAA,IAC3C,CAAC;AACD,YAAQ,MAAM,aAAa,QAAQ,GAAG,QAAQ;AAAA,EAChD;AAEA,SAAO;AAAA,IACL,IAAI,kBAAkB;AACpB,aAAO;AAAA,IACT;AAAA,IACA,IAAI,gBAAgB,OAAO;AACzB,wBAAkB;AAAA,IACpB;AAAA,IACA,MAAM,WAAW,QAAQ;AACvB,YAAM,SAAS,MAAM,QAA6B,cAAc,MAAM;AACtE,wBACE,OAAO,QAAQ,oBAAoB,WAAW,OAAO,kBAAkB;AACzE,aAAO;AAAA,IACT;AAAA,IACA,MAAM,YAAY;AAChB,cAAQ,MAAM,QAA8B,YAAY,GAAG;AAAA,IAC7D;AAAA,IACA,MAAM,SAAS,MAAM,OAAO,CAAC,GAAG;AAC9B,aAAO,QAA2B,cAAc,EAAE,MAAM,WAAW,KAAK,CAAC;AAAA,IAC3E;AAAA,IACA,MAAM,OAAO,QAAQ,QAAQ;AAC3B,YAAM,WAAW,MAAM,KAAK;AAAA,QAC1B,SAAS;AAAA,QACT;AAAA,QACA,GAAI,WAAW,SAAY,EAAE,OAAO,IAAI,CAAC;AAAA,MAC3C,CAAC;AACD,UAAI,SAAS,WAAW,IAAK;AAG7B,YAAM,EAAE,KAAK,IAAI,MAAM,aAAa,QAAQ;AAC5C,YAAM,IAAI,kBAAkB,SAAS,QAAQ,IAAI;AAAA,IACnD;AAAA,EACF;AACF;","names":[]}
|
package/dist/testing.d.ts
CHANGED
|
@@ -72,7 +72,7 @@ declare function findTestAccountByName(name: string): TestAccount;
|
|
|
72
72
|
* subsequent runs.
|
|
73
73
|
*
|
|
74
74
|
* Cache layout:
|
|
75
|
-
* ~/.deepspace/playwright-states/<sha256(email)>.json
|
|
75
|
+
* ~/.deepspace/playwright-states/<sha256(authScope, appOrigin, email)>.json
|
|
76
76
|
*
|
|
77
77
|
* Validity: a cached file is reused if Playwright successfully loads it
|
|
78
78
|
* AND the resulting context produces a non-anonymous session on the
|
|
@@ -80,33 +80,30 @@ declare function findTestAccountByName(name: string): TestAccount;
|
|
|
80
80
|
* overwrite the cache.
|
|
81
81
|
*/
|
|
82
82
|
|
|
83
|
+
interface StorageStateAccount {
|
|
84
|
+
email: string;
|
|
85
|
+
password: string;
|
|
86
|
+
/** Remote user id, when the local registry knows it. */
|
|
87
|
+
userId?: string;
|
|
88
|
+
}
|
|
89
|
+
/** Where the cache for `email` against `baseURL`'s origin lives. */
|
|
90
|
+
declare function getStatePathForEmail(email: string, baseURL: string): string;
|
|
83
91
|
interface EnsureStorageStateOptions {
|
|
84
|
-
/**
|
|
85
|
-
maxAgeMs?: number;
|
|
86
|
-
/** Force a fresh sign-in even if the cache is fresh. */
|
|
92
|
+
/** Force a fresh sign-in even if a cached state validates. */
|
|
87
93
|
force?: boolean;
|
|
88
94
|
}
|
|
89
95
|
/**
|
|
90
|
-
* Ensure a Playwright `storageState` file exists for `account`
|
|
91
|
-
* return its path.
|
|
92
|
-
*
|
|
96
|
+
* Ensure a validated Playwright `storageState` file exists for `account`
|
|
97
|
+
* and return its path. A cached file is probed against the app before
|
|
98
|
+
* reuse (once per worker process); a missing, expired, or wrong-account
|
|
99
|
+
* state triggers one fresh sign-in that overwrites it.
|
|
93
100
|
*/
|
|
94
|
-
declare function ensureStorageState(browser: Browser, account:
|
|
95
|
-
email: string;
|
|
96
|
-
password: string;
|
|
97
|
-
}, baseURL: string, options?: EnsureStorageStateOptions): Promise<string>;
|
|
101
|
+
declare function ensureStorageState(browser: Browser, account: StorageStateAccount, baseURL: string, options?: EnsureStorageStateOptions): Promise<string>;
|
|
98
102
|
/**
|
|
99
103
|
* Convenience: open a fresh `BrowserContext` for `account` using the
|
|
100
104
|
* cached storage state (signing in if needed). The caller is responsible
|
|
101
105
|
* for closing the context.
|
|
102
106
|
*/
|
|
103
|
-
declare function newSignedInContext(browser: Browser, account:
|
|
104
|
-
email: string;
|
|
105
|
-
password: string;
|
|
106
|
-
}, baseURL: string, options?: EnsureStorageStateOptions): Promise<BrowserContext>;
|
|
107
|
-
/** Read a cached storageState file (mostly for debugging). */
|
|
108
|
-
declare function readCachedState(email: string): unknown | null;
|
|
109
|
-
/** Where the cache for `email` lives. Useful for diagnostics. */
|
|
110
|
-
declare function getStatePathForEmail(email: string): string;
|
|
107
|
+
declare function newSignedInContext(browser: Browser, account: StorageStateAccount, baseURL: string, options?: EnsureStorageStateOptions): Promise<BrowserContext>;
|
|
111
108
|
|
|
112
|
-
export { type EnsureStorageStateOptions, type MultiplayerUser, type TestAccount, type UsersFixture, ensureStorageState, findTestAccountByName, getStatePathForEmail, loadAllTestAccounts, newSignedInContext, pickTestAccounts,
|
|
109
|
+
export { type EnsureStorageStateOptions, type MultiplayerUser, type TestAccount, type UsersFixture, ensureStorageState, findTestAccountByName, getStatePathForEmail, loadAllTestAccounts, newSignedInContext, pickTestAccounts, test };
|
package/dist/testing.js
CHANGED
|
@@ -73,23 +73,49 @@ function findTestAccountByName(name) {
|
|
|
73
73
|
|
|
74
74
|
// src/testing/storage-state.ts
|
|
75
75
|
import { createHash } from "crypto";
|
|
76
|
-
import { existsSync as existsSync2, mkdirSync as mkdirSync2
|
|
76
|
+
import { existsSync as existsSync2, mkdirSync as mkdirSync2 } from "fs";
|
|
77
77
|
import { homedir as homedir2 } from "os";
|
|
78
78
|
import { join as join2 } from "path";
|
|
79
|
+
import { request } from "@playwright/test";
|
|
80
|
+
|
|
81
|
+
// src/shared/jwt.ts
|
|
82
|
+
function decodeJwtPayload(token) {
|
|
83
|
+
const payloadSegment = token.split(".")[1];
|
|
84
|
+
if (!payloadSegment) {
|
|
85
|
+
throw new Error("JWT payload is missing");
|
|
86
|
+
}
|
|
87
|
+
return JSON.parse(Buffer.from(payloadSegment, "base64url").toString("utf8"));
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// src/testing/storage-state.ts
|
|
79
91
|
var STATES_DIR = join2(homedir2(), ".deepspace", "playwright-states");
|
|
80
|
-
var
|
|
81
|
-
function
|
|
82
|
-
const
|
|
92
|
+
var stateValidations = /* @__PURE__ */ new Map();
|
|
93
|
+
function getStatePathForEmail(email, baseURL) {
|
|
94
|
+
const key = `${currentTestAccountScope()}
|
|
95
|
+
${new URL(baseURL).origin}
|
|
96
|
+
${email.trim().toLowerCase()}`;
|
|
97
|
+
const hash = createHash("sha256").update(key).digest("hex").slice(0, 24);
|
|
83
98
|
return join2(STATES_DIR, `${hash}.json`);
|
|
84
99
|
}
|
|
85
100
|
function ensureStatesDir() {
|
|
86
101
|
if (!existsSync2(STATES_DIR)) mkdirSync2(STATES_DIR, { recursive: true });
|
|
87
102
|
}
|
|
88
|
-
function
|
|
89
|
-
if (
|
|
103
|
+
function tokenClaimsMatchAccount(claims, account) {
|
|
104
|
+
if (account.userId && claims.sub === account.userId) return true;
|
|
105
|
+
return typeof claims.email === "string" && claims.email.trim().toLowerCase() === account.email.trim().toLowerCase();
|
|
106
|
+
}
|
|
107
|
+
async function probeStoredSession(path, baseURL, account) {
|
|
90
108
|
try {
|
|
91
|
-
const
|
|
92
|
-
|
|
109
|
+
const ctx = await request.newContext({ storageState: path, baseURL });
|
|
110
|
+
try {
|
|
111
|
+
const res = await ctx.post("/api/auth/token");
|
|
112
|
+
if (!res.ok()) return false;
|
|
113
|
+
const { token } = await res.json();
|
|
114
|
+
if (typeof token !== "string") return false;
|
|
115
|
+
return tokenClaimsMatchAccount(decodeJwtPayload(token), account);
|
|
116
|
+
} finally {
|
|
117
|
+
await ctx.dispose();
|
|
118
|
+
}
|
|
93
119
|
} catch {
|
|
94
120
|
return false;
|
|
95
121
|
}
|
|
@@ -116,7 +142,7 @@ async function signInAndSaveState(browser, account, baseURL, outPath) {
|
|
|
116
142
|
message: typeof error?.message === "string" ? error.message : null
|
|
117
143
|
};
|
|
118
144
|
},
|
|
119
|
-
account
|
|
145
|
+
{ email: account.email, password: account.password }
|
|
120
146
|
);
|
|
121
147
|
if (!result.ok) throw new Error(formatSignInFailure(account.email, result));
|
|
122
148
|
await ctx.storageState({ path: outPath });
|
|
@@ -132,9 +158,18 @@ function formatSignInFailure(email, failure) {
|
|
|
132
158
|
return `Sign-in failed for ${email} (HTTP ${failure.status}${code})${detail}. ${nextStep}`;
|
|
133
159
|
}
|
|
134
160
|
async function ensureStorageState(browser, account, baseURL, options = {}) {
|
|
135
|
-
const path =
|
|
136
|
-
|
|
137
|
-
|
|
161
|
+
const path = getStatePathForEmail(account.email, baseURL);
|
|
162
|
+
if (options.force) stateValidations.delete(path);
|
|
163
|
+
let pending = stateValidations.get(path);
|
|
164
|
+
if (!pending) {
|
|
165
|
+
pending = validateOrSignIn(browser, account, baseURL, path, options.force === true);
|
|
166
|
+
stateValidations.set(path, pending);
|
|
167
|
+
pending.catch(() => stateValidations.delete(path));
|
|
168
|
+
}
|
|
169
|
+
return pending;
|
|
170
|
+
}
|
|
171
|
+
async function validateOrSignIn(browser, account, baseURL, path, force) {
|
|
172
|
+
if (!force && existsSync2(path) && await probeStoredSession(path, baseURL, account)) {
|
|
138
173
|
return path;
|
|
139
174
|
}
|
|
140
175
|
return signInAndSaveState(browser, account, baseURL, path);
|
|
@@ -143,18 +178,6 @@ async function newSignedInContext(browser, account, baseURL, options = {}) {
|
|
|
143
178
|
const statePath = await ensureStorageState(browser, account, baseURL, options);
|
|
144
179
|
return browser.newContext({ storageState: statePath, baseURL });
|
|
145
180
|
}
|
|
146
|
-
function readCachedState(email) {
|
|
147
|
-
const path = statePathForEmail(email);
|
|
148
|
-
if (!existsSync2(path)) return null;
|
|
149
|
-
try {
|
|
150
|
-
return JSON.parse(readFileSync2(path, "utf-8"));
|
|
151
|
-
} catch {
|
|
152
|
-
return null;
|
|
153
|
-
}
|
|
154
|
-
}
|
|
155
|
-
function getStatePathForEmail(email) {
|
|
156
|
-
return statePathForEmail(email);
|
|
157
|
-
}
|
|
158
181
|
|
|
159
182
|
// src/testing/fixtures.ts
|
|
160
183
|
import { expect } from "@playwright/test";
|
|
@@ -206,7 +229,6 @@ export {
|
|
|
206
229
|
loadAllTestAccounts,
|
|
207
230
|
newSignedInContext,
|
|
208
231
|
pickTestAccounts,
|
|
209
|
-
readCachedState,
|
|
210
232
|
test
|
|
211
233
|
};
|
|
212
234
|
//# sourceMappingURL=testing.js.map
|
package/dist/testing.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/testing/fixtures.ts","../src/testing/accounts.ts","../src/testing/storage-state.ts"],"sourcesContent":["/**\n * Multi-user Playwright fixture for DeepSpace apps.\n *\n * Usage:\n *\n * import { test, expect } from 'deepspace/testing'\n *\n * test('A sends, B sees', async ({ users }) => {\n * const [a, b] = await users(2)\n * await a.page.goto('/chat')\n * await b.page.goto('/chat')\n * await a.page.getByTestId('message-input').fill('hi')\n * await a.page.getByTestId('send-message-btn').click()\n * await expect(b.page.getByText('hi')).toBeVisible()\n * })\n *\n * `users(N)` picks the first N test accounts from\n * `~/.deepspace/test-accounts.json` (created via\n * `deepspace test accounts create`). `users(['Alice', 'Bob'])` picks\n * specific accounts by name.\n *\n * Each user gets a separate browser context with cached storageState\n * (per-account JSON in `~/.deepspace/playwright-states/`). Sign-in\n * happens once per account, not once per test, sidestepping Better\n * Auth's per-IP rate limit on `/api/auth/sign-in/email`.\n *\n * Contexts are auto-closed when the test finishes.\n */\n\nimport { test as baseTest, type Browser, type BrowserContext, type Page } from '@playwright/test'\nimport {\n type TestAccount,\n pickTestAccounts,\n findTestAccountByName,\n} from './accounts'\nimport { ensureStorageState } from './storage-state'\n\nexport interface MultiplayerUser {\n context: BrowserContext\n page: Page\n email: string\n name: string\n /** Test account user ID, if known from the accounts registry. */\n userId?: string\n}\n\n/**\n * Fixture function signature. Pass either a count (`users(2)`) or an\n * array of account names (`users(['Alice', 'Bob'])`). Returns one entry\n * per requested user.\n */\nexport type UsersFixture = (\n selector: number | string[],\n options?: { label?: string },\n) => Promise<MultiplayerUser[]>\n\ninterface MultiplayerFixtures {\n users: UsersFixture\n}\n\nasync function buildUser(\n browser: Browser,\n account: TestAccount,\n baseURL: string,\n): Promise<{ user: MultiplayerUser; cleanup: () => Promise<void> }> {\n const statePath = await ensureStorageState(browser, account, baseURL)\n const context = await browser.newContext({ storageState: statePath, baseURL })\n const page = await context.newPage()\n return {\n user: {\n context,\n page,\n email: account.email,\n name: account.name ?? account.email.split('@')[0],\n userId: account.userId,\n },\n cleanup: async () => {\n await context.close()\n },\n }\n}\n\nexport const test = baseTest.extend<MultiplayerFixtures>({\n users: async ({ browser, baseURL }, use) => {\n if (!baseURL) {\n throw new Error(\n '`users` fixture requires a baseURL. Set it on your Playwright config ' +\n '(e.g. `use: { baseURL: \"http://localhost:5173\" }`) or via the ' +\n 'webServer.url shortcut.',\n )\n }\n\n const cleanups: Array<() => Promise<void>> = []\n\n const usersFn: UsersFixture = async (selector, options) => {\n const accounts: TestAccount[] = Array.isArray(selector)\n ? selector.map((name) => findTestAccountByName(name))\n : pickTestAccounts(selector, options)\n\n const built = await Promise.all(\n accounts.map((acct) => buildUser(browser, acct, baseURL)),\n )\n for (const b of built) cleanups.push(b.cleanup)\n return built.map((b) => b.user)\n }\n\n await use(usersFn)\n\n // Tear down any contexts we created. Errors are swallowed — a test\n // failure shouldn't be masked by a cleanup error.\n for (const cleanup of cleanups) {\n await cleanup().catch(() => {})\n }\n },\n})\n\nexport { expect } from '@playwright/test'\n","/**\n * Account-credential plumbing for the testing module.\n *\n * Reads test accounts from the auth-origin-scoped registry at\n * `~/.deepspace/test-accounts.json` (the same file\n * `deepspace test accounts create` writes). Persisted accounts are bound to a\n * remote account id; `name` and `label` are optional.\n *\n * Used by the multi-user Playwright fixture in `./fixtures.ts` and is\n * also exported standalone in case suites want to do their own\n * orchestration.\n */\n\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { join } from 'node:path'\n\nexport interface TestAccount {\n email: string\n password: string\n name?: string\n label?: string | null\n id?: string\n userId?: string\n createdAt?: number\n}\n\nexport const TEST_ACCOUNTS_PATH = join(homedir(), '.deepspace', 'test-accounts.json')\n\nconst PRODUCTION_AUTH_ORIGIN = 'https://auth.deep.space'\nconst STAGING_AUTH_ORIGIN = 'https://auth.deepspacesites.com'\n\nexport interface TestAccountCredentialStore {\n version: 2\n scopes: Record<string, TestAccount[]>\n}\n\nexport interface RemoteTestAccount {\n id: string\n email: string\n userId: string\n label: string | null\n createdAt: number\n}\n\n/**\n * Load all test accounts the developer has created. Returns an empty\n * array if the file doesn't exist yet.\n */\nexport function currentTestAccountScope(env: NodeJS.ProcessEnv = process.env): string {\n const selected = env.DEEPSPACE_AUTH_URL ??\n (env.DEEPSPACE_ENV === 'staging' ? STAGING_AUTH_ORIGIN : PRODUCTION_AUTH_ORIGIN)\n return normalizeTestAccountScope(selected)\n}\n\nexport function normalizeTestAccountScope(value: string): string {\n try {\n return new URL(value).origin\n } catch {\n return value\n }\n}\n\nexport function loadAllTestAccounts(scope = currentTestAccountScope()): TestAccount[] {\n const store = readTestAccountStore()\n return store.scopes[scope] ?? []\n}\n\n/**\n * Replace the local credential registry with the subset that still exists\n * remotely. Passwords and display names remain local-only; a recreated email\n * with a different id is deliberately treated as a different account.\n */\nexport function reconcileTestAccountStore(\n remote: RemoteTestAccount[],\n scope = currentTestAccountScope(),\n): {\n accounts: TestAccount[]\n removed: number\n} {\n const result = reconcileTestAccountScopes(readTestAccountStore(), remote, scope)\n saveTestAccountStore(result.store)\n return { accounts: result.accounts, removed: result.removed }\n}\n\nexport function reconcileTestAccountScopes(\n store: TestAccountCredentialStore,\n remote: RemoteTestAccount[],\n scope: string,\n): { store: TestAccountCredentialStore; accounts: TestAccount[]; removed: number } {\n const scoped = store.scopes[scope] ?? []\n const accounts = reconcileTestAccounts(scoped, remote)\n return {\n accounts,\n removed: Math.max(0, scoped.length - accounts.length),\n store: {\n version: 2,\n scopes: { ...store.scopes, [scope]: accounts },\n },\n }\n}\n\nexport function reconcileTestAccounts(\n local: TestAccount[],\n remote: RemoteTestAccount[],\n): TestAccount[] {\n const localById = new Map(local.filter((account) => account.id).map((account) => [account.id, account]))\n return remote.flatMap((account) => {\n const stored = localById.get(account.id)\n return stored ? [{ ...stored, ...account }] : []\n })\n}\n\n/** Add or replace one locally stored credential without creating duplicates. */\nexport function upsertTestAccount(account: TestAccount, scope = currentTestAccountScope()): void {\n const store = readTestAccountStore()\n const accounts = (store.scopes[scope] ?? []).filter(\n (stored) => stored.id !== account.id && stored.email !== account.email,\n )\n saveTestAccountStore({\n version: 2,\n scopes: { ...store.scopes, [scope]: [...accounts, account] },\n })\n}\n\n/** Remove credentials after the corresponding remote delete succeeds. */\nexport function removeTestAccounts(\n ids: string[],\n emails: string[] = [],\n scope = currentTestAccountScope(),\n): void {\n const idSet = new Set(ids)\n const emailSet = new Set(emails)\n const keep = (account: TestAccount): boolean =>\n !idSet.has(account.id ?? '') && !emailSet.has(account.email)\n const store = readTestAccountStore()\n saveTestAccountStore({\n version: 2,\n scopes: { ...store.scopes, [scope]: (store.scopes[scope] ?? []).filter(keep) },\n })\n}\n\nfunction readTestAccountStore(): TestAccountCredentialStore {\n if (!existsSync(TEST_ACCOUNTS_PATH)) return { version: 2, scopes: {} }\n try {\n const raw: unknown = JSON.parse(readFileSync(TEST_ACCOUNTS_PATH, 'utf-8'))\n if (Array.isArray(raw)) return { version: 2, scopes: {} }\n if (!raw || typeof raw !== 'object') {\n return { version: 2, scopes: {} }\n }\n const candidate = raw as { scopes?: unknown }\n const scopes = candidate.scopes && typeof candidate.scopes === 'object' && !Array.isArray(candidate.scopes)\n ? Object.fromEntries(Object.entries(candidate.scopes).map(([key, value]) => [key, validTestAccounts(value)]))\n : {}\n return { version: 2, scopes }\n } catch {\n return { version: 2, scopes: {} }\n }\n}\n\nfunction validTestAccounts(value: unknown): TestAccount[] {\n if (!Array.isArray(value)) return []\n return value.filter((item): item is TestAccount =>\n Boolean(\n item &&\n typeof item === 'object' &&\n typeof (item as TestAccount).id === 'string' &&\n typeof (item as TestAccount).email === 'string' &&\n typeof (item as TestAccount).password === 'string',\n ),\n )\n}\n\nfunction saveTestAccountStore(store: TestAccountCredentialStore): void {\n mkdirSync(join(homedir(), '.deepspace'), { recursive: true })\n writeFileSync(TEST_ACCOUNTS_PATH, JSON.stringify(store, null, 2), { mode: 0o600 })\n}\n\n/**\n * Pick `count` test accounts from the local registry, optionally\n * filtered by `label`. Order-stable: sorted by `createdAt` ascending so\n * the first test account you created is always the first one returned.\n *\n * Throws with a helpful message if not enough accounts exist.\n */\nexport function pickTestAccounts(\n count: number,\n options?: { label?: string },\n): TestAccount[] {\n const all = loadAllTestAccounts()\n const filtered = options?.label\n ? all.filter((a) => a.label === options.label)\n : all\n const sorted = filtered.slice().sort((a, b) => (a.createdAt ?? 0) - (b.createdAt ?? 0))\n\n if (sorted.length < count) {\n const labelHint = options?.label ? ` (label=\"${options.label}\")` : ''\n throw new Error(\n `Multiplayer test needs ${count} test accounts${labelHint}, but only ${sorted.length} ` +\n `are present in ${TEST_ACCOUNTS_PATH}. Create more with:\\n` +\n ` deepspace test accounts create --email <name>@deepspace.test --password <pw> --name \"<name>\"${\n options?.label ? ` --label ${options.label}` : ''\n }`,\n )\n }\n\n return sorted.slice(0, count)\n}\n\n/**\n * Find a single account by name. Used by `users(['Alice', 'Bob'])`.\n * Throws if not found.\n */\nexport function findTestAccountByName(name: string): TestAccount {\n const all = loadAllTestAccounts()\n const match = all.find((a) => a.name === name)\n if (!match) {\n throw new Error(\n `No test account named \"${name}\" in ${TEST_ACCOUNTS_PATH}. Create with:\\n` +\n ` deepspace test accounts create --email ${name.toLowerCase()}@deepspace.test --password <pw> --name \"${name}\"`,\n )\n }\n return match\n}\n","/**\n * Per-account `storageState` cache for Playwright.\n *\n * Better Auth applies a per-IP rate limit on `/api/auth/sign-in/email`\n * (~5 sign-ins / 60s / endpoint). A multiplayer suite that spins up\n * 5+ users per spec would hit the limit and start failing in non-obvious\n * ways. This module signs each account in *once*, persists the\n * resulting browser cookies + storage to disk, and reuses the file on\n * subsequent runs.\n *\n * Cache layout:\n * ~/.deepspace/playwright-states/<sha256(email)>.json\n *\n * Validity: a cached file is reused if Playwright successfully loads it\n * AND the resulting context produces a non-anonymous session on the\n * target app. If validation fails, we fall back to a fresh sign-in and\n * overwrite the cache.\n */\n\nimport { createHash } from 'node:crypto'\nimport { existsSync, mkdirSync, readFileSync, statSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { join } from 'node:path'\nimport type { Browser, BrowserContext } from '@playwright/test'\n\nconst STATES_DIR = join(homedir(), '.deepspace', 'playwright-states')\n\n/** Default freshness window — re-sign-in if the cache is older than this. */\nconst DEFAULT_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000 // 7 days\n\nfunction statePathForEmail(email: string): string {\n const hash = createHash('sha256').update(email.trim().toLowerCase()).digest('hex').slice(0, 24)\n return join(STATES_DIR, `${hash}.json`)\n}\n\nfunction ensureStatesDir() {\n if (!existsSync(STATES_DIR)) mkdirSync(STATES_DIR, { recursive: true })\n}\n\n/** Returns true if a cache file exists and is younger than `maxAgeMs`. */\nfunction isCacheFresh(path: string, maxAgeMs: number): boolean {\n if (!existsSync(path)) return false\n try {\n const age = Date.now() - statSync(path).mtimeMs\n return age < maxAgeMs\n } catch {\n return false\n }\n}\n\n/**\n * Sign `account` in by POSTing `/api/auth/sign-in/email` against\n * `baseURL` and capturing the resulting cookies. Returns the path to the\n * Playwright `storageState` JSON file.\n *\n * The browser-driven approach is intentional: we want the cookies set\n * on the same origin Playwright contexts will load from, otherwise the\n * Set-Cookie domain attribute won't match.\n */\nasync function signInAndSaveState(\n browser: Browser,\n account: { email: string; password: string },\n baseURL: string,\n outPath: string,\n): Promise<string> {\n ensureStatesDir()\n const ctx = await browser.newContext({ baseURL })\n try {\n const page = await ctx.newPage()\n // Hit the app first so the origin is established (some auth plugins\n // require a same-origin Origin header on sign-in).\n await page.goto('/')\n const result = await page.evaluate(\n async ({ email, password }: { email: string; password: string }) => {\n const res = await fetch('/api/auth/sign-in/email', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ email, password }),\n })\n const body: unknown = await res.json().catch(() => null)\n const error = body && typeof body === 'object' ? (body as Record<string, unknown>) : null\n return {\n ok: res.ok,\n status: res.status,\n code: typeof error?.code === 'string' ? error.code : null,\n message: typeof error?.message === 'string' ? error.message : null,\n }\n },\n account,\n )\n if (!result.ok) throw new Error(formatSignInFailure(account.email, result))\n await ctx.storageState({ path: outPath })\n return outPath\n } finally {\n await ctx.close()\n }\n}\n\ninterface SignInFailure {\n status: number\n code: string | null\n message: string | null\n}\n\n/** Keep the server's safe status/code so auth failures remain actionable. */\nexport function formatSignInFailure(email: string, failure: SignInFailure): string {\n const code = failure.code ? ` ${failure.code}` : ''\n const detail = failure.message ? `: ${failure.message}` : ''\n const nextStep =\n failure.code === 'INVALID_ORIGIN'\n ? 'Add this app origin to the auth allowlist, then retry.'\n : 'Check the stored credential or recreate the account with `deepspace test accounts create`.'\n return `Sign-in failed for ${email} (HTTP ${failure.status}${code})${detail}. ${nextStep}`\n}\n\nexport interface EnsureStorageStateOptions {\n /** Max age of a cached state file before we re-sign-in. Default 7 days. */\n maxAgeMs?: number\n /** Force a fresh sign-in even if the cache is fresh. */\n force?: boolean\n}\n\n/**\n * Ensure a Playwright `storageState` file exists for `account` and\n * return its path. Signs in once if the cache is missing, stale, or\n * `force: true`.\n */\nexport async function ensureStorageState(\n browser: Browser,\n account: { email: string; password: string },\n baseURL: string,\n options: EnsureStorageStateOptions = {},\n): Promise<string> {\n const path = statePathForEmail(account.email)\n const maxAgeMs = options.maxAgeMs ?? DEFAULT_MAX_AGE_MS\n\n if (!options.force && isCacheFresh(path, maxAgeMs)) {\n return path\n }\n\n return signInAndSaveState(browser, account, baseURL, path)\n}\n\n/**\n * Convenience: open a fresh `BrowserContext` for `account` using the\n * cached storage state (signing in if needed). The caller is responsible\n * for closing the context.\n */\nexport async function newSignedInContext(\n browser: Browser,\n account: { email: string; password: string },\n baseURL: string,\n options: EnsureStorageStateOptions = {},\n): Promise<BrowserContext> {\n const statePath = await ensureStorageState(browser, account, baseURL, options)\n return browser.newContext({ storageState: statePath, baseURL })\n}\n\n/** Read a cached storageState file (mostly for debugging). */\nexport function readCachedState(email: string): unknown | null {\n const path = statePathForEmail(email)\n if (!existsSync(path)) return null\n try {\n return JSON.parse(readFileSync(path, 'utf-8'))\n } catch {\n return null\n }\n}\n\n/** Where the cache for `email` lives. Useful for diagnostics. */\nexport function getStatePathForEmail(email: string): string {\n return statePathForEmail(email)\n}\n"],"mappings":";AA6BA,SAAS,QAAQ,gBAA8D;;;AChB/E,SAAS,YAAY,WAAW,cAAc,qBAAqB;AACnE,SAAS,eAAe;AACxB,SAAS,YAAY;AAYd,IAAM,qBAAqB,KAAK,QAAQ,GAAG,cAAc,oBAAoB;AAEpF,IAAM,yBAAyB;AAC/B,IAAM,sBAAsB;AAmBrB,SAAS,wBAAwB,MAAyB,QAAQ,KAAa;AACpF,QAAM,WAAW,IAAI,uBAClB,IAAI,kBAAkB,YAAY,sBAAsB;AAC3D,SAAO,0BAA0B,QAAQ;AAC3C;AAEO,SAAS,0BAA0B,OAAuB;AAC/D,MAAI;AACF,WAAO,IAAI,IAAI,KAAK,EAAE;AAAA,EACxB,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEO,SAAS,oBAAoB,QAAQ,wBAAwB,GAAkB;AACpF,QAAM,QAAQ,qBAAqB;AACnC,SAAO,MAAM,OAAO,KAAK,KAAK,CAAC;AACjC;AA4EA,SAAS,uBAAmD;AAC1D,MAAI,CAAC,WAAW,kBAAkB,EAAG,QAAO,EAAE,SAAS,GAAG,QAAQ,CAAC,EAAE;AACrE,MAAI;AACF,UAAM,MAAe,KAAK,MAAM,aAAa,oBAAoB,OAAO,CAAC;AACzE,QAAI,MAAM,QAAQ,GAAG,EAAG,QAAO,EAAE,SAAS,GAAG,QAAQ,CAAC,EAAE;AACxD,QAAI,CAAC,OAAO,OAAO,QAAQ,UAAU;AACnC,aAAO,EAAE,S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S,IAAI,CAAC,SAAS,sBAAsB,IAAI,CAAC,IAClD,iBAAiB,UAAU,OAAO;AAEtC,YAAM,QAAQ,MAAM,QAAQ;AAAA,QAC1B,SAAS,IAAI,CAAC,SAAS,UAAU,SAAS,MAAM,OAAO,CAAC;AAAA,MAC1D;AACA,iBAAW,KAAK,MAAO,UAAS,KAAK,EAAE,OAAO;AAC9C,aAAO,MAAM,IAAI,CAAC,MAAM,EAAE,IAAI;AAAA,IAChC;AAEA,UAAM,IAAI,OAAO;AAIjB,eAAW,WAAW,UAAU;AAC9B,YAAM,QAAQ,EAAE,MAAM,MAAM;AAAA,MAAC,CAAC;AAAA,IAChC;AAAA,EACF;AACF,CAAC;","names":["existsSync","mkdirSync","readFileSync","homedir","join"]}
|
|
1
|
+
{"version":3,"sources":["../src/testing/fixtures.ts","../src/testing/accounts.ts","../src/testing/storage-state.ts","../src/shared/jwt.ts"],"sourcesContent":["/**\n * Multi-user Playwright fixture for DeepSpace apps.\n *\n * Usage:\n *\n * import { test, expect } from 'deepspace/testing'\n *\n * test('A sends, B sees', async ({ users }) => {\n * const [a, b] = await users(2)\n * await a.page.goto('/chat')\n * await b.page.goto('/chat')\n * await a.page.getByTestId('message-input').fill('hi')\n * await a.page.getByTestId('send-message-btn').click()\n * await expect(b.page.getByText('hi')).toBeVisible()\n * })\n *\n * `users(N)` picks the first N test accounts from\n * `~/.deepspace/test-accounts.json` (created via\n * `deepspace test accounts create`). `users(['Alice', 'Bob'])` picks\n * specific accounts by name.\n *\n * Each user gets a separate browser context with cached storageState\n * (per-account JSON in `~/.deepspace/playwright-states/`). Sign-in\n * happens once per account, not once per test, sidestepping Better\n * Auth's per-IP rate limit on `/api/auth/sign-in/email`.\n *\n * Contexts are auto-closed when the test finishes.\n */\n\nimport { test as baseTest, type Browser, type BrowserContext, type Page } from '@playwright/test'\nimport {\n type TestAccount,\n pickTestAccounts,\n findTestAccountByName,\n} from './accounts'\nimport { ensureStorageState } from './storage-state'\n\nexport interface MultiplayerUser {\n context: BrowserContext\n page: Page\n email: string\n name: string\n /** Test account user ID, if known from the accounts registry. */\n userId?: string\n}\n\n/**\n * Fixture function signature. Pass either a count (`users(2)`) or an\n * array of account names (`users(['Alice', 'Bob'])`). Returns one entry\n * per requested user.\n */\nexport type UsersFixture = (\n selector: number | string[],\n options?: { label?: string },\n) => Promise<MultiplayerUser[]>\n\ninterface MultiplayerFixtures {\n users: UsersFixture\n}\n\nasync function buildUser(\n browser: Browser,\n account: TestAccount,\n baseURL: string,\n): Promise<{ user: MultiplayerUser; cleanup: () => Promise<void> }> {\n const statePath = await ensureStorageState(browser, account, baseURL)\n const context = await browser.newContext({ storageState: statePath, baseURL })\n const page = await context.newPage()\n return {\n user: {\n context,\n page,\n email: account.email,\n name: account.name ?? account.email.split('@')[0],\n userId: account.userId,\n },\n cleanup: async () => {\n await context.close()\n },\n }\n}\n\nexport const test = baseTest.extend<MultiplayerFixtures>({\n users: async ({ browser, baseURL }, use) => {\n if (!baseURL) {\n throw new Error(\n '`users` fixture requires a baseURL. Set it on your Playwright config ' +\n '(e.g. `use: { baseURL: \"http://localhost:5173\" }`) or via the ' +\n 'webServer.url shortcut.',\n )\n }\n\n const cleanups: Array<() => Promise<void>> = []\n\n const usersFn: UsersFixture = async (selector, options) => {\n const accounts: TestAccount[] = Array.isArray(selector)\n ? selector.map((name) => findTestAccountByName(name))\n : pickTestAccounts(selector, options)\n\n const built = await Promise.all(\n accounts.map((acct) => buildUser(browser, acct, baseURL)),\n )\n for (const b of built) cleanups.push(b.cleanup)\n return built.map((b) => b.user)\n }\n\n await use(usersFn)\n\n // Tear down any contexts we created. Errors are swallowed — a test\n // failure shouldn't be masked by a cleanup error.\n for (const cleanup of cleanups) {\n await cleanup().catch(() => {})\n }\n },\n})\n\nexport { expect } from '@playwright/test'\n","/**\n * Account-credential plumbing for the testing module.\n *\n * Reads test accounts from the auth-origin-scoped registry at\n * `~/.deepspace/test-accounts.json` (the same file\n * `deepspace test accounts create` writes). Persisted accounts are bound to a\n * remote account id; `name` and `label` are optional.\n *\n * Used by the multi-user Playwright fixture in `./fixtures.ts` and is\n * also exported standalone in case suites want to do their own\n * orchestration.\n */\n\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { join } from 'node:path'\n\nexport interface TestAccount {\n email: string\n password: string\n name?: string\n label?: string | null\n id?: string\n userId?: string\n createdAt?: number\n}\n\nexport const TEST_ACCOUNTS_PATH = join(homedir(), '.deepspace', 'test-accounts.json')\n\nconst PRODUCTION_AUTH_ORIGIN = 'https://auth.deep.space'\nconst STAGING_AUTH_ORIGIN = 'https://auth.deepspacesites.com'\n\nexport interface TestAccountCredentialStore {\n version: 2\n scopes: Record<string, TestAccount[]>\n}\n\nexport interface RemoteTestAccount {\n id: string\n email: string\n userId: string\n label: string | null\n createdAt: number\n}\n\n/**\n * Load all test accounts the developer has created. Returns an empty\n * array if the file doesn't exist yet.\n */\nexport function currentTestAccountScope(env: NodeJS.ProcessEnv = process.env): string {\n const selected = env.DEEPSPACE_AUTH_URL ??\n (env.DEEPSPACE_ENV === 'staging' ? STAGING_AUTH_ORIGIN : PRODUCTION_AUTH_ORIGIN)\n return normalizeTestAccountScope(selected)\n}\n\nexport function normalizeTestAccountScope(value: string): string {\n try {\n return new URL(value).origin\n } catch {\n return value\n }\n}\n\nexport function loadAllTestAccounts(scope = currentTestAccountScope()): TestAccount[] {\n const store = readTestAccountStore()\n return store.scopes[scope] ?? []\n}\n\n/**\n * Replace the local credential registry with the subset that still exists\n * remotely. Passwords and display names remain local-only; a recreated email\n * with a different id is deliberately treated as a different account.\n */\nexport function reconcileTestAccountStore(\n remote: RemoteTestAccount[],\n scope = currentTestAccountScope(),\n): {\n accounts: TestAccount[]\n removed: number\n} {\n const result = reconcileTestAccountScopes(readTestAccountStore(), remote, scope)\n saveTestAccountStore(result.store)\n return { accounts: result.accounts, removed: result.removed }\n}\n\nexport function reconcileTestAccountScopes(\n store: TestAccountCredentialStore,\n remote: RemoteTestAccount[],\n scope: string,\n): { store: TestAccountCredentialStore; accounts: TestAccount[]; removed: number } {\n const scoped = store.scopes[scope] ?? []\n const accounts = reconcileTestAccounts(scoped, remote)\n return {\n accounts,\n removed: Math.max(0, scoped.length - accounts.length),\n store: {\n version: 2,\n scopes: { ...store.scopes, [scope]: accounts },\n },\n }\n}\n\nexport function reconcileTestAccounts(\n local: TestAccount[],\n remote: RemoteTestAccount[],\n): TestAccount[] {\n const localById = new Map(local.filter((account) => account.id).map((account) => [account.id, account]))\n return remote.flatMap((account) => {\n const stored = localById.get(account.id)\n return stored ? [{ ...stored, ...account }] : []\n })\n}\n\n/** Add or replace one locally stored credential without creating duplicates. */\nexport function upsertTestAccount(account: TestAccount, scope = currentTestAccountScope()): void {\n const store = readTestAccountStore()\n const accounts = (store.scopes[scope] ?? []).filter(\n (stored) => stored.id !== account.id && stored.email !== account.email,\n )\n saveTestAccountStore({\n version: 2,\n scopes: { ...store.scopes, [scope]: [...accounts, account] },\n })\n}\n\n/** Remove credentials after the corresponding remote delete succeeds. */\nexport function removeTestAccounts(\n ids: string[],\n emails: string[] = [],\n scope = currentTestAccountScope(),\n): void {\n const idSet = new Set(ids)\n const emailSet = new Set(emails)\n const keep = (account: TestAccount): boolean =>\n !idSet.has(account.id ?? '') && !emailSet.has(account.email)\n const store = readTestAccountStore()\n saveTestAccountStore({\n version: 2,\n scopes: { ...store.scopes, [scope]: (store.scopes[scope] ?? []).filter(keep) },\n })\n}\n\nfunction readTestAccountStore(): TestAccountCredentialStore {\n if (!existsSync(TEST_ACCOUNTS_PATH)) return { version: 2, scopes: {} }\n try {\n const raw: unknown = JSON.parse(readFileSync(TEST_ACCOUNTS_PATH, 'utf-8'))\n if (Array.isArray(raw)) return { version: 2, scopes: {} }\n if (!raw || typeof raw !== 'object') {\n return { version: 2, scopes: {} }\n }\n const candidate = raw as { scopes?: unknown }\n const scopes = candidate.scopes && typeof candidate.scopes === 'object' && !Array.isArray(candidate.scopes)\n ? Object.fromEntries(Object.entries(candidate.scopes).map(([key, value]) => [key, validTestAccounts(value)]))\n : {}\n return { version: 2, scopes }\n } catch {\n return { version: 2, scopes: {} }\n }\n}\n\nfunction validTestAccounts(value: unknown): TestAccount[] {\n if (!Array.isArray(value)) return []\n return value.filter((item): item is TestAccount =>\n Boolean(\n item &&\n typeof item === 'object' &&\n typeof (item as TestAccount).id === 'string' &&\n typeof (item as TestAccount).email === 'string' &&\n typeof (item as TestAccount).password === 'string',\n ),\n )\n}\n\nfunction saveTestAccountStore(store: TestAccountCredentialStore): void {\n mkdirSync(join(homedir(), '.deepspace'), { recursive: true })\n writeFileSync(TEST_ACCOUNTS_PATH, JSON.stringify(store, null, 2), { mode: 0o600 })\n}\n\n/**\n * Pick `count` test accounts from the local registry, optionally\n * filtered by `label`. Order-stable: sorted by `createdAt` ascending so\n * the first test account you created is always the first one returned.\n *\n * Throws with a helpful message if not enough accounts exist.\n */\nexport function pickTestAccounts(\n count: number,\n options?: { label?: string },\n): TestAccount[] {\n const all = loadAllTestAccounts()\n const filtered = options?.label\n ? all.filter((a) => a.label === options.label)\n : all\n const sorted = filtered.slice().sort((a, b) => (a.createdAt ?? 0) - (b.createdAt ?? 0))\n\n if (sorted.length < count) {\n const labelHint = options?.label ? ` (label=\"${options.label}\")` : ''\n throw new Error(\n `Multiplayer test needs ${count} test accounts${labelHint}, but only ${sorted.length} ` +\n `are present in ${TEST_ACCOUNTS_PATH}. Create more with:\\n` +\n ` deepspace test accounts create --email <name>@deepspace.test --password <pw> --name \"<name>\"${\n options?.label ? ` --label ${options.label}` : ''\n }`,\n )\n }\n\n return sorted.slice(0, count)\n}\n\n/**\n * Find a single account by name. Used by `users(['Alice', 'Bob'])`.\n * Throws if not found.\n */\nexport function findTestAccountByName(name: string): TestAccount {\n const all = loadAllTestAccounts()\n const match = all.find((a) => a.name === name)\n if (!match) {\n throw new Error(\n `No test account named \"${name}\" in ${TEST_ACCOUNTS_PATH}. Create with:\\n` +\n ` deepspace test accounts create --email ${name.toLowerCase()}@deepspace.test --password <pw> --name \"${name}\"`,\n )\n }\n return match\n}\n","/**\n * Per-account `storageState` cache for Playwright.\n *\n * Better Auth applies a per-IP rate limit on `/api/auth/sign-in/email`\n * (~5 sign-ins / 60s / endpoint). A multiplayer suite that spins up\n * 5+ users per spec would hit the limit and start failing in non-obvious\n * ways. This module signs each account in *once*, persists the\n * resulting browser cookies + storage to disk, and reuses the file on\n * subsequent runs.\n *\n * Cache layout:\n * ~/.deepspace/playwright-states/<sha256(authScope, appOrigin, email)>.json\n *\n * Validity: a cached file is reused if Playwright successfully loads it\n * AND the resulting context produces a non-anonymous session on the\n * target app. If validation fails, we fall back to a fresh sign-in and\n * overwrite the cache.\n */\n\nimport { createHash } from 'node:crypto'\nimport { existsSync, mkdirSync } from 'node:fs'\nimport { homedir } from 'node:os'\nimport { join } from 'node:path'\nimport { request, type Browser, type BrowserContext } from '@playwright/test'\nimport { decodeJwtPayload } from '../shared/jwt'\nimport { currentTestAccountScope } from './accounts'\n\nconst STATES_DIR = join(homedir(), '.deepspace', 'playwright-states')\n\n/**\n * Validation/sign-in per state path, in flight or settled. Memoizing the\n * promise — rather than flagging a Set after the await — makes concurrent\n * callers for the same account share one probe/sign-in instead of racing\n * duplicate sign-ins into the rate limit. A rejected attempt is evicted so\n * a later call can retry.\n */\nconst stateValidations = new Map<string, Promise<string>>()\n\ninterface StorageStateAccount {\n email: string\n password: string\n /** Remote user id, when the local registry knows it. */\n userId?: string\n}\n\n/** Where the cache for `email` against `baseURL`'s origin lives. */\nexport function getStatePathForEmail(email: string, baseURL: string): string {\n // Keyed by auth scope + app origin + email: one email signed into two\n // apps (or two auth environments) must never serve the wrong session.\n const key = `${currentTestAccountScope()}\\n${new URL(baseURL).origin}\\n${email.trim().toLowerCase()}`\n const hash = createHash('sha256').update(key).digest('hex').slice(0, 24)\n return join(STATES_DIR, `${hash}.json`)\n}\n\nfunction ensureStatesDir() {\n if (!existsSync(STATES_DIR)) mkdirSync(STATES_DIR, { recursive: true })\n}\n\n/**\n * Does a token minted from a cached session belong to `account`? `sub` is\n * authoritative when the registry knows the remote user id; the `email`\n * claim covers states recorded before the id was known.\n */\nexport function tokenClaimsMatchAccount(\n claims: Record<string, unknown>,\n account: { email: string; userId?: string },\n): boolean {\n if (account.userId && claims.sub === account.userId) return true\n return (\n typeof claims.email === 'string' &&\n claims.email.trim().toLowerCase() === account.email.trim().toLowerCase()\n )\n}\n\n/**\n * Live-validate a cached state: load it into a request context and ask the\n * app to mint a token. Only a token for this account counts — a transport\n * failure, an anonymous session, or another user's session all report\n * false, so the caller signs in fresh (where a real outage surfaces as an\n * actionable sign-in error instead of silent reuse of a dead session).\n */\nasync function probeStoredSession(\n path: string,\n baseURL: string,\n account: { email: string; userId?: string },\n): Promise<boolean> {\n try {\n const ctx = await request.newContext({ storageState: path, baseURL })\n try {\n const res = await ctx.post('/api/auth/token')\n if (!res.ok()) return false\n const { token } = (await res.json()) as { token?: unknown }\n if (typeof token !== 'string') return false\n return tokenClaimsMatchAccount(decodeJwtPayload(token), account)\n } finally {\n await ctx.dispose()\n }\n } catch {\n return false\n }\n}\n\n/**\n * Sign `account` in by POSTing `/api/auth/sign-in/email` against\n * `baseURL` and capturing the resulting cookies. Returns the path to the\n * Playwright `storageState` JSON file.\n *\n * The browser-driven approach is intentional: we want the cookies set\n * on the same origin Playwright contexts will load from, otherwise the\n * Set-Cookie domain attribute won't match.\n */\nasync function signInAndSaveState(\n browser: Browser,\n account: { email: string; password: string },\n baseURL: string,\n outPath: string,\n): Promise<string> {\n ensureStatesDir()\n const ctx = await browser.newContext({ baseURL })\n try {\n const page = await ctx.newPage()\n // Hit the app first so the origin is established (some auth plugins\n // require a same-origin Origin header on sign-in).\n await page.goto('/')\n const result = await page.evaluate(\n async ({ email, password }: { email: string; password: string }) => {\n const res = await fetch('/api/auth/sign-in/email', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ email, password }),\n })\n const body: unknown = await res.json().catch(() => null)\n const error = body && typeof body === 'object' ? (body as Record<string, unknown>) : null\n return {\n ok: res.ok,\n status: res.status,\n code: typeof error?.code === 'string' ? error.code : null,\n message: typeof error?.message === 'string' ? error.message : null,\n }\n },\n { email: account.email, password: account.password },\n )\n if (!result.ok) throw new Error(formatSignInFailure(account.email, result))\n await ctx.storageState({ path: outPath })\n return outPath\n } finally {\n await ctx.close()\n }\n}\n\ninterface SignInFailure {\n status: number\n code: string | null\n message: string | null\n}\n\n/** Keep the server's safe status/code so auth failures remain actionable. */\nexport function formatSignInFailure(email: string, failure: SignInFailure): string {\n const code = failure.code ? ` ${failure.code}` : ''\n const detail = failure.message ? `: ${failure.message}` : ''\n const nextStep =\n failure.code === 'INVALID_ORIGIN'\n ? 'Add this app origin to the auth allowlist, then retry.'\n : 'Check the stored credential or recreate the account with `deepspace test accounts create`.'\n return `Sign-in failed for ${email} (HTTP ${failure.status}${code})${detail}. ${nextStep}`\n}\n\nexport interface EnsureStorageStateOptions {\n /** Force a fresh sign-in even if a cached state validates. */\n force?: boolean\n}\n\n/**\n * Ensure a validated Playwright `storageState` file exists for `account`\n * and return its path. A cached file is probed against the app before\n * reuse (once per worker process); a missing, expired, or wrong-account\n * state triggers one fresh sign-in that overwrites it.\n */\nexport async function ensureStorageState(\n browser: Browser,\n account: StorageStateAccount,\n baseURL: string,\n options: EnsureStorageStateOptions = {},\n): Promise<string> {\n const path = getStatePathForEmail(account.email, baseURL)\n if (options.force) stateValidations.delete(path)\n let pending = stateValidations.get(path)\n if (!pending) {\n pending = validateOrSignIn(browser, account, baseURL, path, options.force === true)\n stateValidations.set(path, pending)\n pending.catch(() => stateValidations.delete(path))\n }\n return pending\n}\n\nasync function validateOrSignIn(\n browser: Browser,\n account: StorageStateAccount,\n baseURL: string,\n path: string,\n force: boolean,\n): Promise<string> {\n if (!force && existsSync(path) && (await probeStoredSession(path, baseURL, account))) {\n return path\n }\n return signInAndSaveState(browser, account, baseURL, path)\n}\n\n/**\n * Convenience: open a fresh `BrowserContext` for `account` using the\n * cached storage state (signing in if needed). The caller is responsible\n * for closing the context.\n */\nexport async function newSignedInContext(\n browser: Browser,\n account: StorageStateAccount,\n baseURL: string,\n options: EnsureStorageStateOptions = {},\n): Promise<BrowserContext> {\n const statePath = await ensureStorageState(browser, account, baseURL, options)\n return browser.newContext({ storageState: statePath, baseURL })\n}\n","export function decodeJwtPayload<T = Record<string, unknown>>(token: string): T {\n const payloadSegment = token.split('.')[1]\n if (!payloadSegment) {\n throw new Error('JWT payload is missing')\n }\n return JSON.parse(Buffer.from(payloadSegment, 'base64url').toString('utf8')) as T\n}\n"],"mappings":";AA6BA,SAAS,QAAQ,gBAA8D;;;AChB/E,SAAS,YAAY,WAAW,cAAc,qBAAqB;AACnE,SAAS,eAAe;AACxB,SAAS,YAAY;AAYd,IAAM,qBAAqB,KAAK,QAAQ,GAAG,cAAc,oBAAoB;AAEpF,IAAM,yBAAyB;AAC/B,IAAM,sBAAsB;AAmBrB,SAAS,wBAAwB,MAAyB,QAAQ,KAAa;AACpF,QAAM,WAAW,IAAI,uBAClB,IAAI,kBAAkB,YAAY,sBAAsB;AAC3D,SAAO,0BAA0B,QAAQ;AAC3C;AAEO,SAAS,0BAA0B,OAAuB;AAC/D,MAAI;AACF,WAAO,IAAI,IAAI,KAAK,EAAE;AAAA,EACxB,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEO,SAAS,oBAAoB,QAAQ,wBAAwB,GAAkB;AACpF,QAAM,QAAQ,qBAAqB;AACnC,SAAO,MAAM,OAAO,KAAK,KAAK,CAAC;AACjC;AA4EA,SAAS,uBAAmD;AAC1D,MAAI,CAAC,WAAW,kBAAkB,EAAG,QAAO,EAAE,SAAS,GAAG,QAAQ,CAAC,EAAE;AACrE,MAAI;AACF,UAAM,MAAe,KAAK,MAAM,aAAa,oBAAoB,OAAO,CAAC;AACzE,QAAI,MAAM,QAAQ,GAAG,EAAG,QAAO,EAAE,SAAS,GAAG,QAAQ,CAAC,EAAE;AACxD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