@darbotlabs/darbot-browser-mcp 0.1.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.
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Copyright (c) Microsoft Corporation.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ import { fork } from 'child_process';
17
+ import path from 'path';
18
+ import { z } from 'zod';
19
+ import { defineTool } from './tool.js';
20
+ import { fileURLToPath } from 'node:url';
21
+ const install = defineTool({
22
+ capability: 'install',
23
+ schema: {
24
+ name: 'browser_install',
25
+ title: 'Install the browser specified in the config',
26
+ description: 'Install the browser specified in the config. Call this if you get an error about the browser not being installed.',
27
+ inputSchema: z.object({}),
28
+ type: 'destructive',
29
+ },
30
+ handle: async (context) => {
31
+ const channel = context.config.browser?.launchOptions?.channel ?? context.config.browser?.browserName ?? 'msedge';
32
+ const cliUrl = import.meta.resolve('playwright/package.json');
33
+ const cliPath = path.join(fileURLToPath(cliUrl), '..', 'cli.js');
34
+ const child = fork(cliPath, ['install', channel], {
35
+ stdio: 'pipe',
36
+ });
37
+ const output = [];
38
+ child.stdout?.on('data', data => output.push(data.toString()));
39
+ child.stderr?.on('data', data => output.push(data.toString()));
40
+ await new Promise((resolve, reject) => {
41
+ child.on('close', code => {
42
+ if (code === 0)
43
+ resolve();
44
+ else
45
+ reject(new Error(`Failed to install browser: ${output.join('')}`));
46
+ });
47
+ });
48
+ return {
49
+ code: [`// Browser ${channel} installed`],
50
+ captureSnapshot: false,
51
+ waitForNetwork: false,
52
+ };
53
+ },
54
+ });
55
+ export default [
56
+ install,
57
+ ];
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Copyright (c) Microsoft Corporation.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ import { z } from 'zod';
17
+ import { defineTool } from './tool.js';
18
+ const pressKey = captureSnapshot => defineTool({
19
+ capability: 'core',
20
+ schema: {
21
+ name: 'browser_press_key',
22
+ title: 'Press a key',
23
+ description: 'Press a key on the keyboard',
24
+ inputSchema: z.object({
25
+ key: z.string().describe('Name of the key to press or a character to generate, such as `ArrowLeft` or `a`'),
26
+ }),
27
+ type: 'destructive',
28
+ },
29
+ handle: async (context, params) => {
30
+ const tab = context.currentTabOrDie();
31
+ const code = [
32
+ `// Press ${params.key}`,
33
+ `await page.keyboard.press('${params.key}');`,
34
+ ];
35
+ const action = () => tab.page.keyboard.press(params.key);
36
+ return {
37
+ code,
38
+ action,
39
+ captureSnapshot,
40
+ waitForNetwork: true
41
+ };
42
+ },
43
+ });
44
+ export default (captureSnapshot) => [
45
+ pressKey(captureSnapshot),
46
+ ];
@@ -0,0 +1,93 @@
1
+ /**
2
+ * Copyright (c) Microsoft Corporation.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ import { z } from 'zod';
17
+ import { defineTool } from './tool.js';
18
+ const navigate = captureSnapshot => defineTool({
19
+ capability: 'core',
20
+ schema: {
21
+ name: 'browser_navigate',
22
+ title: 'Navigate to a URL',
23
+ description: 'Navigate to a URL',
24
+ inputSchema: z.object({
25
+ url: z.string().describe('The URL to navigate to'),
26
+ }),
27
+ type: 'destructive',
28
+ },
29
+ handle: async (context, params) => {
30
+ const tab = await context.ensureTab();
31
+ await tab.navigate(params.url);
32
+ const code = [
33
+ `// Navigate to ${params.url}`,
34
+ `await page.goto('${params.url}');`,
35
+ ];
36
+ return {
37
+ code,
38
+ captureSnapshot,
39
+ waitForNetwork: false,
40
+ };
41
+ },
42
+ });
43
+ const goBack = captureSnapshot => defineTool({
44
+ capability: 'history',
45
+ schema: {
46
+ name: 'browser_navigate_back',
47
+ title: 'Go back',
48
+ description: 'Go back to the previous page',
49
+ inputSchema: z.object({}),
50
+ type: 'readOnly',
51
+ },
52
+ handle: async (context) => {
53
+ const tab = await context.ensureTab();
54
+ await tab.page.goBack();
55
+ const code = [
56
+ `// Navigate back`,
57
+ `await page.goBack();`,
58
+ ];
59
+ return {
60
+ code,
61
+ captureSnapshot,
62
+ waitForNetwork: false,
63
+ };
64
+ },
65
+ });
66
+ const goForward = captureSnapshot => defineTool({
67
+ capability: 'history',
68
+ schema: {
69
+ name: 'browser_navigate_forward',
70
+ title: 'Go forward',
71
+ description: 'Go forward to the next page',
72
+ inputSchema: z.object({}),
73
+ type: 'readOnly',
74
+ },
75
+ handle: async (context) => {
76
+ const tab = context.currentTabOrDie();
77
+ await tab.page.goForward();
78
+ const code = [
79
+ `// Navigate forward`,
80
+ `await page.goForward();`,
81
+ ];
82
+ return {
83
+ code,
84
+ captureSnapshot,
85
+ waitForNetwork: false,
86
+ };
87
+ },
88
+ });
89
+ export default (captureSnapshot) => [
90
+ navigate(captureSnapshot),
91
+ goBack(captureSnapshot),
92
+ goForward(captureSnapshot),
93
+ ];
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Copyright (c) Microsoft Corporation.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ import { z } from 'zod';
17
+ import { defineTool } from './tool.js';
18
+ const requests = defineTool({
19
+ capability: 'core',
20
+ schema: {
21
+ name: 'browser_network_requests',
22
+ title: 'List network requests',
23
+ description: 'Returns all network requests since loading the page',
24
+ inputSchema: z.object({}),
25
+ type: 'readOnly',
26
+ },
27
+ handle: async (context) => {
28
+ const requests = context.currentTabOrDie().requests();
29
+ const log = [...requests.entries()].map(([request, response]) => renderRequest(request, response)).join('\n');
30
+ return {
31
+ code: [`// <internal code to list network requests>`],
32
+ action: async () => {
33
+ return {
34
+ content: [{ type: 'text', text: log }]
35
+ };
36
+ },
37
+ captureSnapshot: false,
38
+ waitForNetwork: false,
39
+ };
40
+ },
41
+ });
42
+ function renderRequest(request, response) {
43
+ const result = [];
44
+ result.push(`[${request.method().toUpperCase()}] ${request.url()}`);
45
+ if (response)
46
+ result.push(`=> [${response.status()}] ${response.statusText()}`);
47
+ return result.join(' ');
48
+ }
49
+ export default [
50
+ requests,
51
+ ];
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Copyright (c) Microsoft Corporation.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ import { z } from 'zod';
17
+ import { defineTool } from './tool.js';
18
+ import * as javascript from '../javascript.js';
19
+ import { outputFile } from '../config.js';
20
+ const pdfSchema = z.object({
21
+ filename: z.string().optional().describe('File name to save the pdf to. Defaults to `page-{timestamp}.pdf` if not specified.'),
22
+ });
23
+ const pdf = defineTool({
24
+ capability: 'pdf',
25
+ schema: {
26
+ name: 'browser_pdf_save',
27
+ title: 'Save as PDF',
28
+ description: 'Save page as PDF',
29
+ inputSchema: pdfSchema,
30
+ type: 'readOnly',
31
+ },
32
+ handle: async (context, params) => {
33
+ const tab = context.currentTabOrDie();
34
+ const fileName = await outputFile(context.config, params.filename ?? `page-${new Date().toISOString()}.pdf`);
35
+ const code = [
36
+ `// Save page as ${fileName}`,
37
+ `await page.pdf(${javascript.formatObject({ path: fileName })});`,
38
+ ];
39
+ return {
40
+ code,
41
+ action: async () => tab.page.pdf({ path: fileName }).then(() => { }),
42
+ captureSnapshot: false,
43
+ waitForNetwork: false,
44
+ };
45
+ },
46
+ });
47
+ export default [
48
+ pdf,
49
+ ];
@@ -0,0 +1,271 @@
1
+ /**
2
+ * Copyright (c) Microsoft Corporation.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ import fs from 'fs';
17
+ import path from 'path';
18
+ import os from 'os';
19
+ import { z } from 'zod';
20
+ import { defineTool } from './tool.js';
21
+ import { sanitizeForFilePath } from './utils.js';
22
+ const saveProfileSchema = z.object({
23
+ name: z.string().describe('Name for the work profile'),
24
+ description: z.string().optional().describe('Optional description for the work profile'),
25
+ });
26
+ const switchProfileSchema = z.object({
27
+ name: z.string().describe('Name of the work profile to switch to'),
28
+ });
29
+ const listProfilesSchema = z.object({});
30
+ const deleteProfileSchema = z.object({
31
+ name: z.string().describe('Name of the work profile to delete'),
32
+ });
33
+ async function getProfilesDir() {
34
+ let profilesDir;
35
+ if (process.platform === 'linux')
36
+ profilesDir = process.env.XDG_DATA_HOME || path.join(os.homedir(), '.local', 'share');
37
+ else if (process.platform === 'darwin')
38
+ profilesDir = path.join(os.homedir(), 'Library', 'Application Support');
39
+ else if (process.platform === 'win32')
40
+ profilesDir = process.env.APPDATA || path.join(os.homedir(), 'AppData', 'Roaming');
41
+ else
42
+ throw new Error('Unsupported platform: ' + process.platform);
43
+ const result = path.join(profilesDir, 'darbot-browser-mcp', 'work-profiles');
44
+ await fs.promises.mkdir(result, { recursive: true });
45
+ return result;
46
+ }
47
+ async function saveCurrentProfile(context, profileName, description) {
48
+ const profilesDir = await getProfilesDir();
49
+ const sanitizedName = sanitizeForFilePath(profileName);
50
+ const profileDir = path.join(profilesDir, sanitizedName);
51
+ await fs.promises.mkdir(profileDir, { recursive: true });
52
+ // Get current browser state
53
+ const tab = context.currentTabOrDie();
54
+ const url = tab.page.url();
55
+ const title = await tab.title();
56
+ // Save profile metadata
57
+ const profileData = {
58
+ name: profileName,
59
+ description: description || '',
60
+ created: new Date().toISOString(),
61
+ url,
62
+ title,
63
+ };
64
+ await fs.promises.writeFile(path.join(profileDir, 'profile.json'), JSON.stringify(profileData, null, 2));
65
+ // Save storage state (cookies, localStorage, etc.)
66
+ try {
67
+ const storageState = await tab.page.context().storageState();
68
+ await fs.promises.writeFile(path.join(profileDir, 'storage-state.json'), JSON.stringify(storageState, null, 2));
69
+ }
70
+ catch (error) {
71
+ // Storage state save failed, but we can still save the profile
72
+ // eslint-disable-next-line no-console
73
+ console.warn('Failed to save storage state:', error);
74
+ }
75
+ return profileData;
76
+ }
77
+ async function loadProfile(context, profileName) {
78
+ const profilesDir = await getProfilesDir();
79
+ const sanitizedName = sanitizeForFilePath(profileName);
80
+ const profileDir = path.join(profilesDir, sanitizedName);
81
+ try {
82
+ await fs.promises.access(profileDir);
83
+ }
84
+ catch {
85
+ throw new Error(`Work profile "${profileName}" not found`);
86
+ }
87
+ // Load profile metadata
88
+ const profileDataPath = path.join(profileDir, 'profile.json');
89
+ const profileData = JSON.parse(await fs.promises.readFile(profileDataPath, 'utf8'));
90
+ // Load storage state if available
91
+ const storageStatePath = path.join(profileDir, 'storage-state.json');
92
+ try {
93
+ await fs.promises.access(storageStatePath);
94
+ const storageState = JSON.parse(await fs.promises.readFile(storageStatePath, 'utf8'));
95
+ // Create new context with the stored state
96
+ const tab = await context.ensureTab();
97
+ const currentContext = tab.page.context();
98
+ if (currentContext) {
99
+ await currentContext.close();
100
+ }
101
+ const newContext = await tab.page.context().browser()?.newContext({
102
+ storageState,
103
+ viewport: null,
104
+ });
105
+ if (newContext) {
106
+ const newPage = await newContext.newPage();
107
+ await newPage.goto(profileData.url);
108
+ return { profileData, restored: true };
109
+ }
110
+ }
111
+ catch {
112
+ // Storage state not available or failed to load, fall through to fallback
113
+ }
114
+ // Fallback: just navigate to the URL
115
+ const tab = await context.ensureTab();
116
+ await tab.page.goto(profileData.url);
117
+ return { profileData, restored: false };
118
+ }
119
+ async function listProfiles() {
120
+ const profilesDir = await getProfilesDir();
121
+ const profiles = [];
122
+ try {
123
+ const entries = await fs.promises.readdir(profilesDir);
124
+ for (const entry of entries) {
125
+ const profileDir = path.join(profilesDir, entry);
126
+ const stat = await fs.promises.stat(profileDir);
127
+ if (stat.isDirectory()) {
128
+ const profileDataPath = path.join(profileDir, 'profile.json');
129
+ try {
130
+ await fs.promises.access(profileDataPath);
131
+ const profileData = JSON.parse(await fs.promises.readFile(profileDataPath, 'utf8'));
132
+ profiles.push(profileData);
133
+ }
134
+ catch {
135
+ // File does not exist, skip this entry
136
+ }
137
+ }
138
+ }
139
+ }
140
+ catch (error) {
141
+ // Profiles directory doesn't exist yet
142
+ return [];
143
+ }
144
+ return profiles;
145
+ }
146
+ async function deleteProfile(profileName) {
147
+ const profilesDir = await getProfilesDir();
148
+ const sanitizedName = sanitizeForFilePath(profileName);
149
+ const profileDir = path.join(profilesDir, sanitizedName);
150
+ try {
151
+ await fs.promises.access(profileDir);
152
+ }
153
+ catch {
154
+ throw new Error(`Work profile "${profileName}" not found`);
155
+ }
156
+ await fs.promises.rm(profileDir, { recursive: true, force: true });
157
+ }
158
+ export const browserSaveProfile = defineTool({
159
+ capability: 'core',
160
+ schema: {
161
+ name: 'browser_save_profile',
162
+ title: 'Save Work Profile',
163
+ description: 'Save the current browser state as a work profile',
164
+ inputSchema: saveProfileSchema,
165
+ type: 'destructive',
166
+ },
167
+ handle: async (context, { name, description }) => {
168
+ const profileData = await saveCurrentProfile(context, name, description);
169
+ return {
170
+ code: [`await browser_save_profile({ name: '${name}', description: '${description || ''}' })`],
171
+ action: async () => ({ content: [] }),
172
+ captureSnapshot: false,
173
+ waitForNetwork: false,
174
+ resultOverride: {
175
+ content: [{
176
+ type: 'text',
177
+ text: `Work profile "${name}" saved successfully.\n\nProfile details:\n- Name: ${profileData.name}\n- Description: ${profileData.description}\n- URL: ${profileData.url}\n- Title: ${profileData.title}\n- Created: ${profileData.created}`,
178
+ }],
179
+ },
180
+ };
181
+ },
182
+ });
183
+ export const browserSwitchProfile = defineTool({
184
+ capability: 'core',
185
+ schema: {
186
+ name: 'browser_switch_profile',
187
+ title: 'Switch Work Profile',
188
+ description: 'Switch to a saved work profile',
189
+ inputSchema: switchProfileSchema,
190
+ type: 'destructive',
191
+ },
192
+ handle: async (context, { name }) => {
193
+ const result = await loadProfile(context, name);
194
+ return {
195
+ code: [`await browser_switch_profile({ name: '${name}' })`],
196
+ action: async () => ({ content: [] }),
197
+ captureSnapshot: true,
198
+ waitForNetwork: false,
199
+ resultOverride: {
200
+ content: [{
201
+ type: 'text',
202
+ text: `Switched to work profile "${name}".\n\nProfile details:\n- Name: ${result.profileData.name}\n- Description: ${result.profileData.description}\n- URL: ${result.profileData.url}\n- Title: ${result.profileData.title}\n- Storage state ${result.restored ? 'restored' : 'not available'}`,
203
+ }],
204
+ },
205
+ };
206
+ },
207
+ });
208
+ export const browserListProfiles = defineTool({
209
+ capability: 'core',
210
+ schema: {
211
+ name: 'browser_list_profiles',
212
+ title: 'List Work Profiles',
213
+ description: 'List all saved work profiles',
214
+ inputSchema: listProfilesSchema,
215
+ type: 'readOnly',
216
+ },
217
+ handle: async (context, {}) => {
218
+ const profiles = await listProfiles();
219
+ let text = '### Saved Work Profiles\n\n';
220
+ if (profiles.length === 0) {
221
+ text += 'No work profiles saved yet. Use the "browser_save_profile" tool to save your current browser state as a work profile.';
222
+ }
223
+ else {
224
+ for (const profile of profiles) {
225
+ text += `**${profile.name}**\n`;
226
+ if (profile.description)
227
+ text += `- Description: ${profile.description}\n`;
228
+ text += `- URL: ${profile.url}\n`;
229
+ text += `- Title: ${profile.title}\n`;
230
+ text += `- Created: ${new Date(profile.created).toLocaleString()}\n\n`;
231
+ }
232
+ }
233
+ return {
234
+ code: ['await browser_list_profiles()'],
235
+ action: async () => ({ content: [] }),
236
+ captureSnapshot: false,
237
+ waitForNetwork: false,
238
+ resultOverride: {
239
+ content: [{
240
+ type: 'text',
241
+ text,
242
+ }],
243
+ },
244
+ };
245
+ },
246
+ });
247
+ export const browserDeleteProfile = defineTool({
248
+ capability: 'core',
249
+ schema: {
250
+ name: 'browser_delete_profile',
251
+ title: 'Delete Work Profile',
252
+ description: 'Delete a saved work profile',
253
+ inputSchema: deleteProfileSchema,
254
+ type: 'destructive',
255
+ },
256
+ handle: async (context, { name }) => {
257
+ await deleteProfile(name);
258
+ return {
259
+ code: [`await browser_delete_profile({ name: '${name}' })`],
260
+ action: async () => ({ content: [] }),
261
+ captureSnapshot: false,
262
+ waitForNetwork: false,
263
+ resultOverride: {
264
+ content: [{
265
+ type: 'text',
266
+ text: `Work profile "${name}" deleted successfully.`,
267
+ }],
268
+ },
269
+ };
270
+ },
271
+ });
@@ -0,0 +1,77 @@
1
+ /**
2
+ * Copyright (c) Microsoft Corporation.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ import { z } from 'zod';
17
+ import { defineTool } from './tool.js';
18
+ import * as javascript from '../javascript.js';
19
+ import { outputFile } from '../config.js';
20
+ import { generateLocator } from './utils.js';
21
+ const screenshotSchema = z.object({
22
+ raw: z.boolean().optional().describe('Whether to return without compression (in PNG format). Default is false, which returns a JPEG image.'),
23
+ filename: z.string().optional().describe('File name to save the screenshot to. Defaults to `page-{timestamp}.{png|jpeg}` if not specified.'),
24
+ element: z.string().optional().describe('Human-readable element description used to obtain permission to screenshot the element. If not provided, the screenshot will be taken of viewport. If element is provided, ref must be provided too.'),
25
+ ref: z.string().optional().describe('Exact target element reference from the page snapshot. If not provided, the screenshot will be taken of viewport. If ref is provided, element must be provided too.'),
26
+ }).refine(data => {
27
+ return !!data.element === !!data.ref;
28
+ }, {
29
+ message: 'Both element and ref must be provided or neither.',
30
+ path: ['ref', 'element']
31
+ });
32
+ const screenshot = defineTool({
33
+ capability: 'core',
34
+ schema: {
35
+ name: 'browser_take_screenshot',
36
+ title: 'Take a screenshot',
37
+ description: `Take a screenshot of the current page. You can't perform actions based on the screenshot, use browser_snapshot for actions.`,
38
+ inputSchema: screenshotSchema,
39
+ type: 'readOnly',
40
+ },
41
+ handle: async (context, params) => {
42
+ const tab = context.currentTabOrDie();
43
+ const snapshot = tab.snapshotOrDie();
44
+ const fileType = params.raw ? 'png' : 'jpeg';
45
+ const fileName = await outputFile(context.config, params.filename ?? `page-${new Date().toISOString()}.${fileType}`);
46
+ const options = { type: fileType, quality: fileType === 'png' ? undefined : 50, scale: 'css', path: fileName };
47
+ const isElementScreenshot = params.element && params.ref;
48
+ const code = [
49
+ `// Screenshot ${isElementScreenshot ? params.element : 'viewport'} and save it as ${fileName}`,
50
+ ];
51
+ const locator = params.ref ? snapshot.refLocator({ element: params.element || '', ref: params.ref }) : null;
52
+ if (locator)
53
+ code.push(`await page.${await generateLocator(locator)}.screenshot(${javascript.formatObject(options)});`);
54
+ else
55
+ code.push(`await page.screenshot(${javascript.formatObject(options)});`);
56
+ const includeBase64 = context.clientSupportsImages();
57
+ const action = async () => {
58
+ const screenshot = locator ? await locator.screenshot(options) : await tab.page.screenshot(options);
59
+ return {
60
+ content: includeBase64 ? [{
61
+ type: 'image',
62
+ data: screenshot.toString('base64'),
63
+ mimeType: fileType === 'png' ? 'image/png' : 'image/jpeg',
64
+ }] : []
65
+ };
66
+ };
67
+ return {
68
+ code,
69
+ action,
70
+ captureSnapshot: true,
71
+ waitForNetwork: false,
72
+ };
73
+ }
74
+ });
75
+ export default [
76
+ screenshot,
77
+ ];