@thinkrun/mcp 0.3.14 → 0.3.16
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 +26 -0
- package/README.md +34 -2
- package/dist/bin/thinkrun-mcp.js +51 -11
- package/dist/bin/thinkrun-mcp.js.map +1 -1
- package/dist/shared/analysis-plans.d.ts +10 -0
- package/dist/shared/analysis-plans.js +12 -0
- package/dist/shared/batch-steps.d.ts +49 -0
- package/dist/shared/batch-steps.js +171 -0
- package/dist/shared/batch-steps.test.js +127 -0
- package/dist/shared/group-binding-key.d.ts +5 -0
- package/dist/shared/group-binding-key.js +15 -0
- package/dist/shared/group-binding-key.test.js +50 -0
- package/dist/shared/issue-report.d.ts +10 -0
- package/dist/shared/issue-report.js +126 -0
- package/dist/shared/issue-report.test.ts +110 -0
- package/dist/shared/native-type-budget.d.ts +16 -0
- package/dist/shared/native-type-budget.js +28 -0
- package/dist/shared/navigation-retry.d.ts +2 -0
- package/dist/shared/navigation-retry.js +26 -0
- package/dist/shared/navigation-retry.test.js +25 -0
- package/dist/shared/onboarding-drips.d.ts +13 -0
- package/dist/shared/onboarding-drips.js +100 -0
- package/dist/shared/onboarding-metrics.d.ts +4 -0
- package/dist/shared/onboarding-metrics.js +53 -0
- package/dist/shared/onboarding-public-consent.cjs +3 -0
- package/dist/shared/onboarding-public-consent.d.ts +1 -0
- package/dist/shared/onboarding-public-consent.js +3 -0
- package/dist/shared/onboarding-public-consent.json +3 -0
- package/dist/shared/recording-upload.js +11 -4
- package/dist/shared/recording-upload.test.js +16 -0
- package/dist/shared/selector-hints.d.ts +1 -0
- package/dist/shared/selector-hints.js +43 -0
- package/dist/shared/selector-hints.test.js +31 -0
- package/dist/shared/slack-report.d.ts +21 -0
- package/dist/shared/slack-report.js +381 -0
- package/dist/src/account-connection.d.ts +7 -0
- package/dist/src/account-connection.d.ts.map +1 -0
- package/dist/src/account-connection.js +37 -0
- package/dist/src/account-connection.js.map +1 -0
- package/dist/src/client.d.ts +14 -0
- package/dist/src/client.d.ts.map +1 -1
- package/dist/src/cloud-client.d.ts +2 -0
- package/dist/src/cloud-client.d.ts.map +1 -1
- package/dist/src/cloud-client.js +8 -0
- package/dist/src/cloud-client.js.map +1 -1
- package/dist/src/local-client.d.ts +23 -4
- package/dist/src/local-client.d.ts.map +1 -1
- package/dist/src/local-client.js +148 -49
- package/dist/src/local-client.js.map +1 -1
- package/dist/src/local-saving.d.ts +51 -0
- package/dist/src/local-saving.d.ts.map +1 -0
- package/dist/src/local-saving.js +150 -0
- package/dist/src/local-saving.js.map +1 -0
- package/dist/src/onboarding.d.ts +1 -1
- package/dist/src/onboarding.js +1 -1
- package/dist/src/recordings.d.ts +29 -0
- package/dist/src/recordings.d.ts.map +1 -0
- package/dist/src/recordings.js +68 -0
- package/dist/src/recordings.js.map +1 -0
- package/dist/src/server.d.ts +25 -1
- package/dist/src/server.d.ts.map +1 -1
- package/dist/src/server.js +182 -43
- package/dist/src/server.js.map +1 -1
- package/package.json +6 -5
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
// Specialized delivery ledger for this one onboarding sequence. No runtime DDL.
|
|
2
|
+
export const LEDGER_DDL = `CREATE TABLE circleinbox_onboarding (
|
|
3
|
+
subject_id TEXT PRIMARY KEY, email TEXT NOT NULL,
|
|
4
|
+
enrollment_id TEXT, enrolled_at TIMESTAMPTZ, activated_at TIMESTAMPTZ, finished_at TIMESTAMPTZ,
|
|
5
|
+
checked_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
|
|
6
|
+
)`;
|
|
7
|
+
|
|
8
|
+
export function onboardingConfig(env) {
|
|
9
|
+
if (env.CIRCLEINBOX_ONBOARDING_ENABLED !== 'true') return null;
|
|
10
|
+
const since = new Date(env.CIRCLEINBOX_ONBOARDING_SINCE || '');
|
|
11
|
+
if (!Number.isFinite(since.getTime()) || env.CIRCLEINBOX_ONBOARDING_CONSENT !== 'true') {
|
|
12
|
+
throw new Error('Onboarding requires an explicit enable timestamp and consent assertion');
|
|
13
|
+
}
|
|
14
|
+
if (!env.CIRCLEINBOX_API_KEY || !Number.isSafeInteger(Number(env.CIRCLEINBOX_ONBOARDING_SEQUENCE_VERSION)) || Number(env.CIRCLEINBOX_ONBOARDING_SEQUENCE_VERSION) < 1) {
|
|
15
|
+
throw new Error('Onboarding requires credentials and a published sequence version');
|
|
16
|
+
}
|
|
17
|
+
const allowAll = env.CIRCLEINBOX_ONBOARDING_ALLOW_ALL_NEW_USERS === 'true';
|
|
18
|
+
const raw = env.CIRCLEINBOX_ONBOARDING_RECIPIENT_ALLOWLIST?.trim() || '';
|
|
19
|
+
if (allowAll === Boolean(raw) || raw.length > 5100) throw new Error('Onboarding requires exactly one recipient scope');
|
|
20
|
+
const recipients = raw ? [...new Set(raw.split(',').map((email) => email.trim().toLowerCase()))] : null;
|
|
21
|
+
if (recipients && (recipients.length > 20 || recipients.some((email) => email.length > 254 || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)))) {
|
|
22
|
+
throw new Error('Onboarding recipient allowlist must contain 1 to 20 valid emails');
|
|
23
|
+
}
|
|
24
|
+
return { since: since.toISOString(), sequenceId: 'thinkrun-onboarding', version: Number(env.CIRCLEINBOX_ONBOARDING_SEQUENCE_VERSION), recipients };
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function onboardingSql(env, createMechKysely) {
|
|
28
|
+
const db = createMechKysely({ appId: env.MECH_APP_ID || env.MECH_BROWSE_APP_ID || '', apiKey: env.MECH_API_KEY });
|
|
29
|
+
return async (sql, parameters = []) => {
|
|
30
|
+
// executeQuery accepts this CompiledQuery directly; SQL is already compiled and bound.
|
|
31
|
+
const result = await db.executeQuery({ sql, parameters, query: { kind: 'RawNode', sqlFragments: [sql], parameters: [] } });
|
|
32
|
+
return result.rows;
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export async function queueVerifiedSignup(env, subjectId, execute) {
|
|
37
|
+
const config = onboardingConfig(env);
|
|
38
|
+
if (!config) return;
|
|
39
|
+
const sql = execute(env);
|
|
40
|
+
// A successful verification is the source of truth; do not trust request email.
|
|
41
|
+
await sql(`INSERT INTO circleinbox_onboarding (subject_id,email)
|
|
42
|
+
SELECT id::text,email FROM users WHERE id=$1 AND email_verified=true AND created_at >= $2::timestamptz
|
|
43
|
+
AND ($3::text[] IS NULL OR lower(email)=ANY($3::text[]))
|
|
44
|
+
ON CONFLICT (subject_id) DO NOTHING`, [subjectId, config.since, config.recipients]);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export async function pumpOnboarding({ env, sql, sdk, completedTask, limit = 25 }) {
|
|
48
|
+
const config = onboardingConfig(env);
|
|
49
|
+
if (!config) return { enrolled: 0, activated: 0, failed: 0 };
|
|
50
|
+
// Commit queued ledger rows BEFORE any remote SDK call, even during an outage.
|
|
51
|
+
// Exclude every queued subject (including enrolled_at=null); the next pass can
|
|
52
|
+
// discover users beyond this batch while earlier deliveries remain pending.
|
|
53
|
+
// This closes the post-auth enqueue gap for newly created verified accounts.
|
|
54
|
+
await sql(`INSERT INTO circleinbox_onboarding (subject_id,email)
|
|
55
|
+
SELECT u.id::text,u.email FROM users u WHERE u.email_verified=true AND u.created_at >= $1::timestamptz
|
|
56
|
+
AND ($2::text[] IS NULL OR lower(u.email)=ANY($2::text[]))
|
|
57
|
+
AND NOT EXISTS (SELECT 1 FROM circleinbox_onboarding o WHERE o.subject_id=u.id::text)
|
|
58
|
+
ORDER BY u.created_at,u.id LIMIT 100 ON CONFLICT (subject_id) DO NOTHING`, [config.since, config.recipients]);
|
|
59
|
+
const rows = await sql(`SELECT subject_id,email,enrolled_at,enrollment_id FROM circleinbox_onboarding
|
|
60
|
+
WHERE activated_at IS NULL AND finished_at IS NULL
|
|
61
|
+
AND ($2::text[] IS NULL OR lower(email)=ANY($2::text[]))
|
|
62
|
+
ORDER BY checked_at,subject_id LIMIT $1`, [limit, config.recipients]);
|
|
63
|
+
const result = { enrolled: 0, activated: 0, failed: 0 };
|
|
64
|
+
for (const row of rows) {
|
|
65
|
+
let failed = false;
|
|
66
|
+
try {
|
|
67
|
+
let enrollmentId = row.enrollment_id;
|
|
68
|
+
if (!row.enrolled_at || !enrollmentId) {
|
|
69
|
+
// API contract: UNIQUE(org,sequenceId,subjectId) across versions. Identical
|
|
70
|
+
// enroll replays return the same resource; changed payloads return409.
|
|
71
|
+
// Replaying after a lost ledger acknowledgment cannot create another workflow.
|
|
72
|
+
const enrollment = await sdk.enroll({ sequenceId: config.sequenceId, version: config.version, subjectId: row.subject_id, email: row.email, consent: true });
|
|
73
|
+
enrollmentId = enrollment?.data?.id;
|
|
74
|
+
if (typeof enrollmentId !== 'string' || !enrollmentId) throw new Error('InvalidEnrollmentResponse');
|
|
75
|
+
await sql('UPDATE circleinbox_onboarding SET enrolled_at=CURRENT_TIMESTAMP,enrollment_id=$2 WHERE subject_id=$1', [row.subject_id, enrollmentId]);
|
|
76
|
+
result.enrolled++;
|
|
77
|
+
}
|
|
78
|
+
const remote = await sdk.getEnrollment(enrollmentId);
|
|
79
|
+
if (['completed', 'cancelled', 'suppressed', 'failed', 'unknown'].includes(remote?.data?.status)) {
|
|
80
|
+
await sql('UPDATE circleinbox_onboarding SET finished_at=CURRENT_TIMESTAMP WHERE subject_id=$1', [row.subject_id]);
|
|
81
|
+
continue;
|
|
82
|
+
}
|
|
83
|
+
if (!['active', 'waiting', 'sending'].includes(remote?.data?.status)) throw new Error('InvalidEnrollmentResponse');
|
|
84
|
+
if (await completedTask(row.subject_id, config.since)) {
|
|
85
|
+
await sdk.track({ id: `thinkrun:activated:${row.subject_id}`, subjectId: row.subject_id, name: 'thinkrun.task_completed' });
|
|
86
|
+
await sql('UPDATE circleinbox_onboarding SET activated_at=CURRENT_TIMESTAMP WHERE subject_id=$1', [row.subject_id]);
|
|
87
|
+
result.activated++;
|
|
88
|
+
}
|
|
89
|
+
} catch {
|
|
90
|
+
// Status remains pending; retry uses stable enrollment/event identifiers.
|
|
91
|
+
failed = true;
|
|
92
|
+
result.failed++;
|
|
93
|
+
} finally {
|
|
94
|
+
try { await sql('UPDATE circleinbox_onboarding SET checked_at=CURRENT_TIMESTAMP WHERE subject_id=$1', [row.subject_id]); }
|
|
95
|
+
catch { if (!failed) result.failed++; }
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
return result;
|
|
99
|
+
}
|
|
100
|
+
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
type Source = 'cli' | 'mcp';
|
|
2
|
+
type Step = 'local_connected' | 'account_connected' | 'session_saved';
|
|
3
|
+
export function onboardingReviewLink(source: Source, sessionId: string): string;
|
|
4
|
+
export function recordOnboardingStep(source: Source, step: Step, sessionId?: string): Promise<void>;
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
// Opt-in only. A missing receipt or unavailable collector must never interrupt browser control.
|
|
2
|
+
import { createHmac, randomUUID } from 'node:crypto';
|
|
3
|
+
import { homedir } from 'node:os';
|
|
4
|
+
import { join } from 'node:path';
|
|
5
|
+
import { mkdirSync, readFileSync, writeFileSync, existsSync } from 'node:fs';
|
|
6
|
+
|
|
7
|
+
const endpoint = 'https://thinkrun.ai/api/onboarding-metrics';
|
|
8
|
+
const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
|
|
9
|
+
const enabled = () => process.env.THINKRUN_ONBOARDING_METRICS === '1' && !process.env.DO_NOT_TRACK;
|
|
10
|
+
|
|
11
|
+
function install(source) {
|
|
12
|
+
if (!enabled() || !['cli', 'mcp'].includes(source)) return;
|
|
13
|
+
const base = join(process.env.THINKRUN_LOCK_DIR || join(homedir(), '.thinkrun'), 'onboarding-metrics');
|
|
14
|
+
const directory = join(base, source);
|
|
15
|
+
mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
16
|
+
const file = join(base, 'installation');
|
|
17
|
+
if (!existsSync(file)) {
|
|
18
|
+
try { writeFileSync(file, randomUUID(), { flag: 'wx', mode: 0o600 }); }
|
|
19
|
+
catch (err) { if (err?.code !== 'EEXIST') throw err; }
|
|
20
|
+
}
|
|
21
|
+
const id = readFileSync(file, 'utf8');
|
|
22
|
+
if (uuid.test(id)) return { id, directory };
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function reviewMarker(id, sessionId) {
|
|
26
|
+
return createHmac('sha256', id).update('review:' + sessionId).digest('hex').slice(0, 32);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function onboardingReviewLink(source, sessionId) {
|
|
30
|
+
const url = new URL('/sessions/' + encodeURIComponent(sessionId), 'https://thinkrun.ai');
|
|
31
|
+
try {
|
|
32
|
+
const installation = install(source);
|
|
33
|
+
if (installation) url.hash = 'tr-review=' + source + '.' + reviewMarker(installation.id, sessionId);
|
|
34
|
+
} catch { /* Prefer a clean dashboard link if metrics are unavailable. */ }
|
|
35
|
+
return url.href;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export async function recordOnboardingStep(source, step, sessionId) {
|
|
39
|
+
if (!['local_connected', 'account_connected', 'session_saved'].includes(step)) return;
|
|
40
|
+
try {
|
|
41
|
+
const installation = install(source);
|
|
42
|
+
if (!installation) return;
|
|
43
|
+
const review = step === 'session_saved' && sessionId ? reviewMarker(installation.id, sessionId) : undefined;
|
|
44
|
+
const receipt = join(installation.directory, review || step);
|
|
45
|
+
if (existsSync(receipt)) return;
|
|
46
|
+
const response = await fetch(endpoint, {
|
|
47
|
+
method: 'POST', redirect: 'error', credentials: 'omit', signal: AbortSignal.timeout(800),
|
|
48
|
+
headers: { 'Content-Type': 'application/json' },
|
|
49
|
+
body: JSON.stringify({ source, step, installation: installation.id, review }),
|
|
50
|
+
});
|
|
51
|
+
if (response.ok) writeFileSync(receipt, '', { mode: 0o600 });
|
|
52
|
+
} catch { /* Optional metrics are best effort. */ }
|
|
53
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const ONBOARDING_PUBLIC_DEFAULT_CONSENT_VERSION: string;
|
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
* never media bytes supplied by an API caller, and talks to the recording API
|
|
4
4
|
* directly (not through the browser extension/native bridge).
|
|
5
5
|
*/
|
|
6
|
+
import { createHash } from 'node:crypto';
|
|
6
7
|
import { createReadStream } from 'node:fs';
|
|
7
8
|
import { access, lstat, open } from 'node:fs/promises';
|
|
8
9
|
import { constants } from 'node:fs';
|
|
@@ -105,10 +106,13 @@ export async function uploadRecordingFile(options) {
|
|
|
105
106
|
handle = await open(file.path, constants.O_RDONLY | (constants.O_NOFOLLOW || 0));
|
|
106
107
|
const opened = await handle.stat();
|
|
107
108
|
if (!opened.isFile() || opened.size !== file.sizeBytes || opened.dev !== file.device || opened.ino !== file.inode) throw new RecordingUploadError('FILE_CHANGED', 'Recording file changed during validation');
|
|
108
|
-
const stream = () => createReadStream(file.path, { fd: handle.fd, autoClose: false });
|
|
109
|
+
const stream = () => createReadStream(file.path, { fd: handle.fd, autoClose: false, start: 0 });
|
|
110
|
+
const digest = createHash('sha256');
|
|
111
|
+
for await (const chunk of stream()) digest.update(chunk);
|
|
112
|
+
const videoChecksumSha256 = digest.digest('hex');
|
|
109
113
|
const created = requireSuccess(await request(fetchImpl, `${baseUrl}/api/feedback/recordings`, {
|
|
110
114
|
method: 'POST', headers: headers(options.apiKey), body: JSON.stringify({
|
|
111
|
-
source: 'cli', videoContentType: file.contentType,
|
|
115
|
+
source: 'cli', videoContentType: file.contentType, videoBytes: file.sizeBytes, videoChecksumSha256,
|
|
112
116
|
metadata: { version: '1.0', duration: 0, url, title, profile: 'simple', intent, features: { audio: false, console: false, network: false, dom: false } },
|
|
113
117
|
actions: [], browserState: { consoleLogs: [], networkRequests: [] }, elements: [],
|
|
114
118
|
}),
|
|
@@ -127,11 +131,14 @@ export async function uploadRecordingFile(options) {
|
|
|
127
131
|
uploadStarted = true;
|
|
128
132
|
// Axios preserves Content-Length for Node file streams; fetch sends these
|
|
129
133
|
// as chunked bodies and R2's presigned endpoint rejects them with HTTP 411.
|
|
134
|
+
const directHeaders = new Headers(created.presignedVideoHeaders);
|
|
135
|
+
directHeaders.set('Content-Type', created.presignedVideoContentType || file.contentType);
|
|
136
|
+
directHeaders.set('Content-Length', String(file.sizeBytes));
|
|
130
137
|
let direct;
|
|
131
138
|
try {
|
|
132
139
|
direct = options.fetchImpl
|
|
133
|
-
? await fetchImpl(created.uploadUrl, { method: 'PUT', headers:
|
|
134
|
-
: await axios.put(created.uploadUrl, stream(), { headers: { 'Content-Type': created.presignedVideoContentType || file.contentType, 'Content-Length': String(file.sizeBytes) }, maxBodyLength: MAX_RECORDING_UPLOAD_BYTES, timeout: UPLOAD_TIMEOUT_MS, validateStatus: () => true });
|
|
140
|
+
? await fetchImpl(created.uploadUrl, { method: 'PUT', headers: directHeaders, body: stream(), duplex: 'half', signal: AbortSignal.timeout(UPLOAD_TIMEOUT_MS) })
|
|
141
|
+
: await axios.put(created.uploadUrl, stream(), { headers: { ...created.presignedVideoHeaders, 'Content-Type': created.presignedVideoContentType || file.contentType, 'Content-Length': String(file.sizeBytes) }, maxBodyLength: MAX_RECORDING_UPLOAD_BYTES, timeout: UPLOAD_TIMEOUT_MS, validateStatus: () => true });
|
|
135
142
|
} catch (error) {
|
|
136
143
|
if (isDefinitivePreTransferError(error)) uploadStarted = false;
|
|
137
144
|
throw error;
|
|
@@ -34,6 +34,22 @@ describe('agent recording upload', () => {
|
|
|
34
34
|
expect(calls).toHaveLength(3);
|
|
35
35
|
});
|
|
36
36
|
|
|
37
|
+
test('normalizes supplied direct-upload header names without comma-joining values', async () => {
|
|
38
|
+
const path = await fixture(); let checked = false;
|
|
39
|
+
const fetchImpl = async (url, init = {}) => {
|
|
40
|
+
if (String(url).endsWith('/recordings')) return Response.json({ success: true, recordingId: 'rec-12345678', uploadUrl: 'https://signed.example.test/token', uploadToken: 'token', presignedVideoObjectId: 'object-1', presignedVideoContentType: 'video/webm', presignedVideoHeaders: { 'content-type': 'video/webm', 'content-length': '5' } });
|
|
41
|
+
if (String(url).startsWith('https://signed.')) {
|
|
42
|
+
const headers = new Headers(init.headers);
|
|
43
|
+
expect(headers.get('content-type')).toBe('video/webm');
|
|
44
|
+
expect(headers.get('content-length')).toBe('5');
|
|
45
|
+
checked = true; return new Response('', { status: 200 });
|
|
46
|
+
}
|
|
47
|
+
return Response.json({ success: true, analysisEnqueued: false });
|
|
48
|
+
};
|
|
49
|
+
await uploadRecordingFile({ path, apiBase: 'https://api.example.test', fetchImpl });
|
|
50
|
+
expect(checked).toBe(true);
|
|
51
|
+
});
|
|
52
|
+
|
|
37
53
|
test('falls back to the authenticated streaming endpoint when no presign is offered', async () => {
|
|
38
54
|
const path = await fixture('capture.mov'); const calls = [];
|
|
39
55
|
const fetchImpl = async (url, init = {}) => {
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function explainUnsupportedSelector(selector: string, action: string): string | null;
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Local mode resolves CSS plus Playwright's :has-text(), :text(), :text-is() and text=.
|
|
3
|
+
* Models also write other Playwright forms, so explain the fix before any round trip.
|
|
4
|
+
* Cloud mode runs real Playwright and should not use this check.
|
|
5
|
+
*/
|
|
6
|
+
const QUOTED = /"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'/g;
|
|
7
|
+
|
|
8
|
+
function roleNameText(selector) {
|
|
9
|
+
const match = selector.match(/^\s*[a-z]+\s+("(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')\s*$/i);
|
|
10
|
+
return match ? match[1].slice(1, -1).replace(/\\(.)/g, '$1') : null;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
function usesUnsupportedSyntax(selector) {
|
|
14
|
+
// Remove quoted text first, so a CSS attribute value such as [title=":visible"] is not flagged.
|
|
15
|
+
const unquoted = selector.replace(QUOTED, '""');
|
|
16
|
+
const textPseudos = unquoted.match(/:(?:has-text|text-is|text)\(/g) ?? [];
|
|
17
|
+
return /^\s*text=\/.*\/[a-z]*\s*$/i.test(selector)
|
|
18
|
+
|| textPseudos.length > 1
|
|
19
|
+
|| /:(?:has-text|text-is|text)\(\s*[^"\s)]/.test(unquoted)
|
|
20
|
+
|| /:(?:has-text|text-is|text)\(\s*""\s*\)[^\s>]/.test(unquoted)
|
|
21
|
+
|| (textPseudos.length > 0 && /,/.test(unquoted.replace(/\([^()]*\)/g, '').replace(/\[[^\]]*\]/g, '')))
|
|
22
|
+
|| /:(?:text-matches|nth-match)\(/.test(unquoted)
|
|
23
|
+
|| /:visible\b/.test(unquoted)
|
|
24
|
+
|| /\s>>\s/.test(unquoted)
|
|
25
|
+
|| /\bgetBy[A-Z]\w*\(/.test(unquoted)
|
|
26
|
+
|| /:(?:right-of|left-of|above|below|near)\(/.test(unquoted)
|
|
27
|
+
|| /^\s*(?:role|css|xpath|id|data-testid|nth|internal:[\w-]+)=/i.test(unquoted)
|
|
28
|
+
|| /^\s*\(?\/\//.test(unquoted)
|
|
29
|
+
|| /^\s*[a-z]+\s+""\s*$/i.test(unquoted);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* @param {string} selector
|
|
34
|
+
* @param {string} _action
|
|
35
|
+
* @returns {string | null} Guidance when the selector cannot work in local mode.
|
|
36
|
+
*/
|
|
37
|
+
export function explainUnsupportedSelector(selector, _action) {
|
|
38
|
+
if (typeof selector !== 'string') return null;
|
|
39
|
+
const trimmed = selector.trim();
|
|
40
|
+
if (!usesUnsupportedSyntax(trimmed)) return null;
|
|
41
|
+
const example = `:has-text("${roleNameText(trimmed) ?? 'Visible text'}")`;
|
|
42
|
+
return `Selector ${JSON.stringify(selector)} uses Playwright syntax that local mode does not support. Use a CSS selector, or match by text with ${example}.`;
|
|
43
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { describe, expect, test } from 'bun:test';
|
|
2
|
+
import { explainUnsupportedSelector as explain } from './selector-hints.js';
|
|
3
|
+
|
|
4
|
+
describe('explainUnsupportedSelector', () => {
|
|
5
|
+
test.each([
|
|
6
|
+
'input[name=quantity]', 'form button[type=submit]', 'a[href="/product/2"]', 'div > a', 'li:nth-child(2)', 'a:not(.x)', 'input:checked',
|
|
7
|
+
'[title=":visible"]', '[data-x="a >> b"]', 'button:has(svg)',
|
|
8
|
+
'button:has-text("Add to cart")', "button:has-text('Add')", 'a:text("Next")', 'a:text-is("Next")', 'text=Add to cart', 'text="Add"',
|
|
9
|
+
'li:has-text("Speaker") a', 'li:has-text("Speaker") > a', ':is(a, button):has-text("x")', 'a, button',
|
|
10
|
+
])('allows %s', (selector) => {
|
|
11
|
+
expect(explain(selector, 'click')).toBeNull();
|
|
12
|
+
expect(explain(selector, 'fill')).toBeNull();
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
test.each([
|
|
16
|
+
'textbox "Search"', 'button:visible', 'a:visible', 'div >> a', 'getByRole("button")', 'role=button[name="Add"]', 'xpath=//a', 'css=a', 'id=main',
|
|
17
|
+
'data-testid=save', '//a[@href]', 'a:near(.x)', 'text=/add/i', 'a:has-text("x"):has-text("y")', 'a:has-text("x").y', 'a:has-text(x)', 'li:has-text("x") a, .other', 'li, .notice:has-text("x")',
|
|
18
|
+
])('explains %s', (selector) => {
|
|
19
|
+
const hint = explain(selector, 'fill');
|
|
20
|
+
expect(hint).toContain('Playwright syntax');
|
|
21
|
+
expect(hint).toContain(':has-text');
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
test('uses the name from a role-style selector', () => {
|
|
25
|
+
expect(explain('button "Search"', 'click')).toContain(':has-text("Search")');
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
test('ignores missing selectors', () => {
|
|
29
|
+
expect(explain(undefined, 'click')).toBeNull();
|
|
30
|
+
});
|
|
31
|
+
});
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
export const SLACK_REPORT_TITLE_LIMIT: 256;
|
|
2
|
+
export const SLACK_REPORT_BODY_LIMIT: 12000;
|
|
3
|
+
export type SlackReportMode = 'compact' | 'full';
|
|
4
|
+
export const SLACK_REPORT_MODES: SlackReportMode[];
|
|
5
|
+
export type SlackTextStyle = { bold?: boolean; italic?: boolean; code?: boolean };
|
|
6
|
+
export type SlackInline = { type: 'text'; text: string; style?: SlackTextStyle } | { type: 'link'; url: string; text: string; style?: SlackTextStyle };
|
|
7
|
+
export interface SlackRichSection { type: 'rich_text_section'; elements: SlackInline[] }
|
|
8
|
+
export type SlackRichElement = SlackRichSection
|
|
9
|
+
| { type: 'rich_text_list'; style: 'bullet' | 'ordered'; indent: number; offset?: number; elements: SlackRichSection[] }
|
|
10
|
+
| { type: 'rich_text_preformatted'; elements: SlackInline[] }
|
|
11
|
+
| { type: 'rich_text_quote'; elements: SlackInline[] };
|
|
12
|
+
export type SlackBlock = { type: 'header'; text: { type: 'plain_text'; text: string; emoji: false } }
|
|
13
|
+
| { type: 'rich_text'; elements: SlackRichElement[] }
|
|
14
|
+
| { type: 'divider' };
|
|
15
|
+
export interface SlackReportMessage { text: string; blocks: SlackBlock[]; mrkdwn: false; parse: 'none'; link_names: false; unfurl_links: false; unfurl_media: false }
|
|
16
|
+
export class SlackReportError extends Error { code: 'INVALID_MODE' | 'REPORT_TOO_LARGE'; constructor(code: string, message: string) }
|
|
17
|
+
export function safeSlackLinkUrl(value: unknown): string | undefined;
|
|
18
|
+
/** A projector's `message` is the exact chat.postMessage content; `notices` are preview-only disclosures. */
|
|
19
|
+
export type SlackReportProjector = (title: string, body: string, mode: SlackReportMode) => { message: SlackReportMessage; notices: string[] };
|
|
20
|
+
/** Pass `fromMarkdown` from `mdast-util-from-markdown`; consumers pin the same version for preview/delivery parity. */
|
|
21
|
+
export function createSlackReportProjector(fromMarkdown: (markdown: string) => unknown): SlackReportProjector;
|