├── .editorconfig
├── .gitattributes
├── .github
└── workflows
│ └── main.yml
├── .gitignore
├── .npmrc
├── code-of-conduct.md
├── contributing.md
├── example.js
├── license
├── media
├── logo-bw.ai
├── logo-bw.png
├── logo-bw.svg
├── logo.ai
├── logo.png
├── logo.svg
├── promo.png
└── promo.psd
├── package.json
├── readme.md
├── source
└── index.ts
├── test
├── _server.ts
├── cookie.ts
├── fixture.html
├── test.ts
└── tsconfig.json
└── tsconfig.json
/.editorconfig:
--------------------------------------------------------------------------------
1 | root = true
2 |
3 | [*]
4 | indent_style = tab
5 | end_of_line = lf
6 | charset = utf-8
7 | trim_trailing_whitespace = true
8 | insert_final_newline = true
9 |
10 | [*.yml]
11 | indent_style = space
12 | indent_size = 2
13 |
--------------------------------------------------------------------------------
/.gitattributes:
--------------------------------------------------------------------------------
1 | * text=auto eol=lf
2 | *.psd binary
3 | *.ai binary
4 |
--------------------------------------------------------------------------------
/.github/workflows/main.yml:
--------------------------------------------------------------------------------
1 | name: CI
2 | on:
3 | - push
4 | - pull_request
5 | jobs:
6 | test:
7 | name: Node.js ${{ matrix.node-version }}
8 | runs-on: ubuntu-latest
9 | strategy:
10 | fail-fast: false
11 | matrix:
12 | node-version:
13 | - 22
14 | - 20
15 | - 18
16 | steps:
17 | - uses: actions/checkout@v4
18 | - uses: actions/setup-node@v4
19 | with:
20 | node-version: ${{ matrix.node-version }}
21 | - run: npm install
22 | - name: Disable AppArmor for unprivileged user namespaces
23 | run: sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0
24 | - run: npm test
25 | - uses: codecov/codecov-action@v3
26 | if: matrix.node-version == 16
27 | with:
28 | fail_ci_if_error: true
29 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules
2 | yarn.lock
3 | .nyc_output
4 | coverage
5 | dist
6 | localhost*.png
7 |
--------------------------------------------------------------------------------
/.npmrc:
--------------------------------------------------------------------------------
1 | package-lock=false
2 |
--------------------------------------------------------------------------------
/code-of-conduct.md:
--------------------------------------------------------------------------------
1 | # Contributor Covenant Code of Conduct
2 |
3 | ## Our Pledge
4 |
5 | We as members, contributors, and leaders pledge to make participation in our
6 | community a harassment-free experience for everyone, regardless of age, body
7 | size, visible or invisible disability, ethnicity, sex characteristics, gender
8 | identity and expression, level of experience, education, socio-economic status,
9 | nationality, personal appearance, race, religion, or sexual identity
10 | and orientation.
11 |
12 | We pledge to act and interact in ways that contribute to an open, welcoming,
13 | diverse, inclusive, and healthy community.
14 |
15 | ## Our Standards
16 |
17 | Examples of behavior that contributes to a positive environment for our
18 | community include:
19 |
20 | * Demonstrating empathy and kindness toward other people
21 | * Being respectful of differing opinions, viewpoints, and experiences
22 | * Giving and gracefully accepting constructive feedback
23 | * Accepting responsibility and apologizing to those affected by our mistakes,
24 | and learning from the experience
25 | * Focusing on what is best not just for us as individuals, but for the
26 | overall community
27 |
28 | Examples of unacceptable behavior include:
29 |
30 | * The use of sexualized language or imagery, and sexual attention or
31 | advances of any kind
32 | * Trolling, insulting or derogatory comments, and personal or political attacks
33 | * Public or private harassment
34 | * Publishing others' private information, such as a physical or email
35 | address, without their explicit permission
36 | * Other conduct which could reasonably be considered inappropriate in a
37 | professional setting
38 |
39 | ## Enforcement Responsibilities
40 |
41 | Community leaders are responsible for clarifying and enforcing our standards of
42 | acceptable behavior and will take appropriate and fair corrective action in
43 | response to any behavior that they deem inappropriate, threatening, offensive,
44 | or harmful.
45 |
46 | Community leaders have the right and responsibility to remove, edit, or reject
47 | comments, commits, code, wiki edits, issues, and other contributions that are
48 | not aligned to this Code of Conduct, and will communicate reasons for moderation
49 | decisions when appropriate.
50 |
51 | ## Scope
52 |
53 | This Code of Conduct applies within all community spaces, and also applies when
54 | an individual is officially representing the community in public spaces.
55 | Examples of representing our community include using an official e-mail address,
56 | posting via an official social media account, or acting as an appointed
57 | representative at an online or offline event.
58 |
59 | ## Enforcement
60 |
61 | Instances of abusive, harassing, or otherwise unacceptable behavior may be
62 | reported to the community leaders responsible for enforcement at
63 | sindresorhus@gmail.com.
64 | All complaints will be reviewed and investigated promptly and fairly.
65 |
66 | All community leaders are obligated to respect the privacy and security of the
67 | reporter of any incident.
68 |
69 | ## Enforcement Guidelines
70 |
71 | Community leaders will follow these Community Impact Guidelines in determining
72 | the consequences for any action they deem in violation of this Code of Conduct:
73 |
74 | ### 1. Correction
75 |
76 | **Community Impact**: Use of inappropriate language or other behavior deemed
77 | unprofessional or unwelcome in the community.
78 |
79 | **Consequence**: A private, written warning from community leaders, providing
80 | clarity around the nature of the violation and an explanation of why the
81 | behavior was inappropriate. A public apology may be requested.
82 |
83 | ### 2. Warning
84 |
85 | **Community Impact**: A violation through a single incident or series
86 | of actions.
87 |
88 | **Consequence**: A warning with consequences for continued behavior. No
89 | interaction with the people involved, including unsolicited interaction with
90 | those enforcing the Code of Conduct, for a specified period of time. This
91 | includes avoiding interactions in community spaces as well as external channels
92 | like social media. Violating these terms may lead to a temporary or
93 | permanent ban.
94 |
95 | ### 3. Temporary Ban
96 |
97 | **Community Impact**: A serious violation of community standards, including
98 | sustained inappropriate behavior.
99 |
100 | **Consequence**: A temporary ban from any sort of interaction or public
101 | communication with the community for a specified period of time. No public or
102 | private interaction with the people involved, including unsolicited interaction
103 | with those enforcing the Code of Conduct, is allowed during this period.
104 | Violating these terms may lead to a permanent ban.
105 |
106 | ### 4. Permanent Ban
107 |
108 | **Community Impact**: Demonstrating a pattern of violation of community
109 | standards, including sustained inappropriate behavior, harassment of an
110 | individual, or aggression toward or disparagement of classes of individuals.
111 |
112 | **Consequence**: A permanent ban from any sort of public interaction within
113 | the community.
114 |
115 | ## Attribution
116 |
117 | This Code of Conduct is adapted from the [Contributor Covenant][homepage],
118 | version 2.0, available at
119 | https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
120 |
121 | Community Impact Guidelines were inspired by [Mozilla's code of conduct
122 | enforcement ladder](https://github.com/mozilla/diversity).
123 |
124 | [homepage]: https://www.contributor-covenant.org
125 |
126 | For answers to common questions about this code of conduct, see the FAQ at
127 | https://www.contributor-covenant.org/faq. Translations are available at
128 | https://www.contributor-covenant.org/translations.
129 |
--------------------------------------------------------------------------------
/contributing.md:
--------------------------------------------------------------------------------
1 | # Contributing to Pageres
2 |
3 | Please note that this project is released with a [Contributor Code of Conduct](code-of-conduct.md). By participating in this project you agree to abide by its terms.
4 |
--------------------------------------------------------------------------------
/example.js:
--------------------------------------------------------------------------------
1 | import Pageres from './dist/index.js';
2 |
3 | await new Pageres({delay: 2})
4 | .source('https://github.com/sindresorhus/pageres', ['480x320', '1024x768'], {crop: true})
5 | .source('https://sindresorhus.com', ['1280x1024', '1920x1080'])
6 | .source('data:text/html,
Awesome!
', ['1024x768'])
7 | .destination('screenshots')
8 | .run();
9 |
10 | console.log('Finished generating screenshots!');
11 |
--------------------------------------------------------------------------------
/license:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) Sindre Sorhus (https://sindresorhus.com)
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6 |
7 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8 |
9 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
10 |
--------------------------------------------------------------------------------
/media/logo-bw.ai:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/sindresorhus/pageres/93d75749e897f2cf7f715cb9ab63327ac0376daf/media/logo-bw.ai
--------------------------------------------------------------------------------
/media/logo-bw.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/sindresorhus/pageres/93d75749e897f2cf7f715cb9ab63327ac0376daf/media/logo-bw.png
--------------------------------------------------------------------------------
/media/logo-bw.svg:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/media/logo.ai:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/sindresorhus/pageres/93d75749e897f2cf7f715cb9ab63327ac0376daf/media/logo.ai
--------------------------------------------------------------------------------
/media/logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/sindresorhus/pageres/93d75749e897f2cf7f715cb9ab63327ac0376daf/media/logo.png
--------------------------------------------------------------------------------
/media/logo.svg:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/media/promo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/sindresorhus/pageres/93d75749e897f2cf7f715cb9ab63327ac0376daf/media/promo.png
--------------------------------------------------------------------------------
/media/promo.psd:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/sindresorhus/pageres/93d75749e897f2cf7f715cb9ab63327ac0376daf/media/promo.psd
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "pageres",
3 | "version": "8.1.0",
4 | "description": "Capture website screenshots",
5 | "license": "MIT",
6 | "repository": "sindresorhus/pageres",
7 | "funding": "https://github.com/sponsors/sindresorhus",
8 | "author": {
9 | "name": "Sindre Sorhus",
10 | "email": "sindresorhus@gmail.com",
11 | "url": "https://sindresorhus.com"
12 | },
13 | "type": "module",
14 | "exports": {
15 | "types": "./dist/index.d.ts",
16 | "default": "./dist/index.js"
17 | },
18 | "sideEffects": false,
19 | "engines": {
20 | "node": ">=18"
21 | },
22 | "scripts": {
23 | "test": "xo && tsc --noEmit && nyc ava --timeout=2m",
24 | "release": "np",
25 | "build": "del-cli dist && tsc",
26 | "prepare": "npm run build"
27 | },
28 | "files": [
29 | "dist"
30 | ],
31 | "keywords": [
32 | "page",
33 | "website",
34 | "site",
35 | "web",
36 | "url",
37 | "resolution",
38 | "size",
39 | "screenshot",
40 | "screenshots",
41 | "screengrab",
42 | "screen",
43 | "snapshot",
44 | "shot",
45 | "responsive",
46 | "gulpfriendly",
47 | "puppeteer",
48 | "chrome",
49 | "image",
50 | "svg",
51 | "render",
52 | "html",
53 | "headless",
54 | "capture",
55 | "pic",
56 | "picture",
57 | "png",
58 | "jpg",
59 | "jpeg"
60 | ],
61 | "dependencies": {
62 | "array-differ": "^4.0.0",
63 | "array-uniq": "^3.0.0",
64 | "capture-website": "^4.1.0",
65 | "date-fns": "^3.6.0",
66 | "filenamify": "^6.0.0",
67 | "filenamify-url": "^3.1.0",
68 | "get-res": "^3.0.0",
69 | "lodash.template": "^4.5.0",
70 | "log-symbols": "^6.0.0",
71 | "make-dir": "^5.0.0",
72 | "p-map": "^7.0.2",
73 | "p-memoize": "^7.1.1",
74 | "plur": "^5.1.0",
75 | "type-fest": "^4.23.0",
76 | "unused-filename": "^4.0.1",
77 | "viewport-list": "^5.1.1"
78 | },
79 | "devDependencies": {
80 | "@sindresorhus/tsconfig": "^6.0.0",
81 | "@types/cookie": "^0.6.0",
82 | "@types/get-res": "^3.0.3",
83 | "@types/lodash.template": "^4.5.3",
84 | "@types/node": "^20.14.12",
85 | "@types/png.js": "^0.2.3",
86 | "@types/sinon": "^17.0.3",
87 | "@types/viewport-list": "^5.1.3",
88 | "ava": "^6.1.3",
89 | "cookie": "^0.6.0",
90 | "del-cli": "^5.1.0",
91 | "file-type": "^19.3.0",
92 | "get-port": "^7.1.0",
93 | "image-dimensions": "^2.3.0",
94 | "nyc": "^17.0.0",
95 | "path-exists": "^5.0.0",
96 | "pify": "^6.1.0",
97 | "png.js": "^0.2.1",
98 | "sinon": "^18.0.0",
99 | "ts-node": "^10.9.2",
100 | "typescript": "^5.5.4",
101 | "xo": "^0.59.2"
102 | },
103 | "ava": {
104 | "workerThreads": false,
105 | "extensions": {
106 | "ts": "module"
107 | },
108 | "nodeArguments": [
109 | "--loader=ts-node/esm"
110 | ]
111 | },
112 | "xo": {
113 | "parserOptions": {
114 | "project": "./test/tsconfig.json"
115 | },
116 | "rules": {
117 | "no-await-in-loop": "off",
118 | "@typescript-eslint/no-unused-vars": "off",
119 | "@typescript-eslint/no-unsafe-assignment": "off",
120 | "@typescript-eslint/no-unsafe-return": "off",
121 | "@typescript-eslint/no-unsafe-call": "off",
122 | "unicorn/prefer-event-target": "off",
123 | "n/file-extension-in-import": "off",
124 | "@typescript-eslint/no-unsafe-argument": "off"
125 | }
126 | },
127 | "nyc": {
128 | "reporter": [
129 | "text",
130 | "lcov"
131 | ],
132 | "extension": [
133 | ".ts"
134 | ]
135 | }
136 | }
137 |
--------------------------------------------------------------------------------
/readme.md:
--------------------------------------------------------------------------------
1 | # 
2 |
3 | [](https://codecov.io/gh/sindresorhus/pageres)
4 | [](https://github.com/xojs/xo)
5 |
6 | Capture screenshots of websites in various resolutions. A good way to make sure your websites are responsive. It's speedy and generates 100 screenshots from 10 different websites in just over a minute. It can also be used to render SVG images.
7 |
8 | *See [pageres-cli](https://github.com/sindresorhus/pageres-cli) for the command-line tool.*
9 |
10 | ## Install
11 |
12 | ```sh
13 | npm install pageres
14 | ```
15 |
16 | Note to Linux users: If you get a "No usable sandbox!" error, you need to enable [system sandboxing](https://github.com/GoogleChrome/puppeteer/blob/master/docs/troubleshooting.md#setting-up-chrome-linux-sandbox).
17 |
18 | ## Usage
19 |
20 | ```js
21 | import Pageres from 'pageres';
22 |
23 | await new Pageres({delay: 2})
24 | .source('https://github.com/sindresorhus/pageres', ['480x320', '1024x768'], {crop: true})
25 | .source('https://sindresorhus.com', ['1280x1024', '1920x1080'])
26 | .source('data:text/html,
Awesome!
', ['1024x768'])
27 | .destination('screenshots')
28 | .run();
29 |
30 | console.log('Finished generating screenshots!');
31 | ```
32 |
33 | ## API
34 |
35 | ### Pageres(options?)
36 |
37 | #### options
38 |
39 | Type: `object`
40 |
41 | ##### delay
42 |
43 | Type: `number` *(Seconds)*\
44 | Default: `0`
45 |
46 | Delay capturing the screenshot.
47 |
48 | Useful when the site does things after load that you want to capture.
49 |
50 | ##### timeout
51 |
52 | Type: `number` *(Seconds)*\
53 | Default: `60`
54 |
55 | Number of seconds after which the request is aborted.
56 |
57 | ##### crop
58 |
59 | Type: `boolean`\
60 | Default: `false`
61 |
62 | Crop to the set height.
63 |
64 | ##### css
65 |
66 | Type: `string`
67 |
68 | Apply custom CSS to the webpage. Specify some CSS or the path to a CSS file.
69 |
70 | ##### script
71 |
72 | Type: `string`
73 |
74 | Apply custom JavaScript to the webpage. Specify some JavaScript or the path to a file.
75 |
76 | ##### cookies
77 |
78 | Type: `Array`
79 |
80 | A string with the same format as a [browser cookie](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies) or [an object](https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#pagesetcookiecookies).
81 |
82 | Tip: Go to the website you want a cookie for and [copy-paste it from DevTools](https://stackoverflow.com/a/24961735/64949).
83 |
84 | ##### filename
85 |
86 | Type: `string`\
87 | Default: `'<%= url %>-<%= size %><%= crop %>'`
88 |
89 | Define a customized filename using [Lo-Dash templates](https://lodash.com/docs#template).\
90 | For example: `<%= date %> - <%= url %>-<%= size %><%= crop %>`.
91 |
92 | Available variables:
93 |
94 | - `url`: The URL in [slugified](https://github.com/sindresorhus/filenamify-url) form, eg. `http://yeoman.io/blog/` becomes `yeoman.io!blog`
95 | - `size`: Specified size, eg. `1024x1000`
96 | - `width`: Width of the specified size, eg. `1024`
97 | - `height`: Height of the specified size, eg. `1000`
98 | - `crop`: Outputs `-cropped` when the crop option is true
99 | - `date`: The current date (YYYY-MM-DD), eg. 2015-05-18
100 | - `time`: The current time (HH-mm-ss), eg. 21-15-11
101 |
102 | ##### incrementalName
103 |
104 | Type: `boolean`\
105 | Default: `false`
106 |
107 | When a file exists, append an incremental number.
108 |
109 | ##### selector
110 |
111 | Type: `string`
112 |
113 | Capture a specific DOM element matching a CSS selector.
114 |
115 | ##### hide
116 |
117 | Type: `string[]`
118 |
119 | Hide an array of DOM elements matching CSS selectors.
120 |
121 | ##### username
122 |
123 | Type: `string`
124 |
125 | Username for authenticating with HTTP auth.
126 |
127 | ##### password
128 |
129 | Type: `string`
130 |
131 | Password for authenticating with HTTP auth.
132 |
133 | ##### scale
134 |
135 | Type: `number`\
136 | Default: `1`
137 |
138 | Scale webpage `n` times.
139 |
140 | ##### format
141 |
142 | Type: `string`\
143 | Default: `png`\
144 | Values: `'png' | 'jpg'`
145 |
146 | Image format.
147 |
148 | ##### userAgent
149 |
150 | Type: `string`
151 |
152 | Custom user agent.
153 |
154 | ##### headers
155 |
156 | Type: `object`
157 |
158 | Custom HTTP request headers.
159 |
160 | ##### transparent
161 |
162 | Type: `boolean`\
163 | Default: `false`
164 |
165 | Set background color to `transparent` instead of `white` if no background is set.
166 |
167 | ##### darkMode
168 |
169 | Type: `boolean`\
170 | Default: `false`
171 |
172 | Emulate preference of dark color scheme.
173 |
174 | ##### launchOptions
175 |
176 | Type: `object`\
177 | Default: `{}`
178 |
179 | Options passed to [`puppeteer.launch()`](https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#puppeteerlaunchoptions).
180 |
181 | ##### beforeScreenshot
182 |
183 | Type: `Function`
184 |
185 | The specified function is called right before the screenshot is captured, as well as before any bounding rectangle is calculated as part of `options.element`. It receives the Puppeteer [`Page` instance](https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#class-page) as the first argument and the [`browser` instance](https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#class-browser) as the second argument. This gives you a lot of power to do custom stuff. The function can be async.
186 |
187 | Note: Make sure to not call `page.close()` or `browser.close()`.
188 |
189 | ```js
190 | import Pageres from 'pageres';
191 |
192 | await new Pageres({
193 | delay: 2,
194 | beforeScreenshot: async (page, browser) => {
195 | await checkSomething();
196 | await page.click('#activate-button');
197 | await page.waitForSelector('.finished');
198 | }
199 | })
200 | .source('https://github.com/sindresorhus/pageres', ['480x320', '1024x768', 'iphone 5s'], {crop: true})
201 | .destination('screenshots')
202 | .run();
203 |
204 | console.log('Finished generating screenshots!');
205 | ```
206 |
207 | ### pageres.source(url, sizes, options?)
208 |
209 | Add a page to screenshot.
210 |
211 | #### url
212 |
213 | *Required*\
214 | Type: `string`
215 |
216 | URL or local path to the website you want to screenshot. You can also use a data URI.
217 |
218 | #### sizes
219 |
220 | *Required*\
221 | Type: `string[]`
222 |
223 | Use a `x` notation or a keyword.
224 |
225 | A keyword is a version of a device from [this list](https://github.com/kevva/viewport-list/blob/master/data.json).
226 |
227 | You can also pass in the `w3counter` keyword to use the ten most popular resolutions from [w3counter](http://www.w3counter.com/globalstats.php).
228 |
229 | #### options
230 |
231 | Type: `object`
232 |
233 | Options set here will take precedence over the ones set in the constructor.
234 |
235 | ### pageres.destination(directory)
236 |
237 | Set the destination directory.
238 |
239 | #### directory
240 |
241 | Type: `string`
242 |
243 | ### pageres.run()
244 |
245 | Run pageres.
246 |
247 | Returns `Promise`.
248 |
249 | ## Task runners
250 |
251 | Check out [grunt-pageres](https://github.com/sindresorhus/grunt-pageres) if you're using Grunt.
252 |
253 | For Gulp and Broccoli, just use the API directly. No need for a wrapper plugin.
254 |
255 | ## Built with Pageres
256 |
257 | - [Break Shot](https://github.com/victorferraz/break-shot) - Desktop app for capturing screenshots of responsive websites.
258 |
259 | ## Related
260 |
261 | - [capture-website](https://github.com/sindresorhus/capture-website) - A different take on screenshotting websites
262 |
--------------------------------------------------------------------------------
/source/index.ts:
--------------------------------------------------------------------------------
1 | import process from 'node:process';
2 | import path from 'node:path';
3 | import {pathToFileURL} from 'node:url';
4 | import fs from 'node:fs';
5 | import fsPromises from 'node:fs/promises';
6 | import os from 'node:os';
7 | import {EventEmitter} from 'node:events';
8 | import captureWebsite, {
9 | type Options as CaptureWebsiteOptions,
10 | type BeforeScreenshot,
11 | type LaunchOptions,
12 | } from 'capture-website';
13 | import pMemoize from 'p-memoize';
14 | import filenamify from 'filenamify';
15 | import {unusedFilename} from 'unused-filename';
16 | import arrayUniq from 'array-uniq';
17 | import arrayDiffer from 'array-differ';
18 | import {format as formatDate} from 'date-fns';
19 | import getResolutions from 'get-res';
20 | import logSymbols from 'log-symbols';
21 | import {makeDirectory} from 'make-dir';
22 | import viewportList from 'viewport-list';
23 | import template from 'lodash.template';
24 | import plur from 'plur';
25 | import filenamifyUrl from 'filenamify-url';
26 | import pMap from 'p-map';
27 | import type {Writable} from 'type-fest';
28 |
29 | const cpuCount = os.cpus().length;
30 |
31 | export type Options = {
32 | /**
33 | Delay capturing the screenshot.
34 |
35 | Useful when the site does things after load that you want to capture.
36 |
37 | @default 0
38 | */
39 | readonly delay?: number;
40 |
41 | /**
42 | Number of seconds after which the request is aborted.
43 |
44 | @default 60
45 | */
46 | readonly timeout?: number;
47 |
48 | /**
49 | Crop to the set height.
50 |
51 | @default false
52 | */
53 | readonly crop?: boolean;
54 |
55 | /**
56 | Apply custom CSS to the webpage. Specify some CSS or the path to a CSS file.
57 | */
58 | readonly css?: string;
59 |
60 | /**
61 | Apply custom JavaScript to the webpage. Specify some JavaScript or the path to a file.
62 | */
63 | readonly script?: string;
64 |
65 | /**
66 | A string with the same format as a [browser cookie](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies) or [an object](https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#pagesetcookiecookies).
67 |
68 | Tip: Go to the website you want a cookie for and [copy-paste it from DevTools](https://stackoverflow.com/a/24961735/64949).
69 |
70 | @default []
71 | */
72 | readonly cookies?: ReadonlyArray>;
73 |
74 | /**
75 | Define a customized filename using [Lo-Dash templates](https://lodash.com/docs#template).\
76 | For example: `<%= date %> - <%= url %>-<%= size %><%= crop %>`.
77 |
78 | Available variables:
79 |
80 | - `url`: The URL in [slugified](https://github.com/sindresorhus/filenamify-url) form, eg. `http://yeoman.io/blog/` becomes `yeoman.io!blog`
81 | - `size`: Specified size, eg. `1024x1000`
82 | - `width`: Width of the specified size, eg. `1024`
83 | - `height`: Height of the specified size, eg. `1000`
84 | - `crop`: Outputs `-cropped` when the crop option is true
85 | - `date`: The current date (YYYY-MM-DD), eg. 2015-05-18
86 | - `time`: The current time (HH-mm-ss), eg. 21-15-11
87 |
88 | @default '<%= url %>-<%= size %><%= crop %>'
89 | */
90 | readonly filename?: string;
91 |
92 | /**
93 | When a file exists, append an incremental number.
94 |
95 | @default false
96 | */
97 | readonly incrementalName?: boolean;
98 |
99 | /**
100 | Capture a specific DOM element matching a CSS selector.
101 | */
102 | readonly selector?: string;
103 |
104 | /**
105 | Hide an array of DOM elements matching CSS selectors.
106 |
107 | @default []
108 | */
109 | readonly hide?: string[];
110 |
111 | /**
112 | Username for authenticating with HTTP auth.
113 | */
114 | readonly username?: string;
115 |
116 | /**
117 | Password for authenticating with HTTP auth.
118 | */
119 | readonly password?: string;
120 |
121 | /**
122 | Scale webpage `n` times.
123 |
124 | @default 1
125 | */
126 | readonly scale?: number;
127 |
128 | /**
129 | Image format.
130 |
131 | @default 'png'
132 | */
133 | readonly format?: 'png' | 'jpg' | 'jpeg';
134 |
135 | /**
136 | Custom user agent.
137 | */
138 | readonly userAgent?: string;
139 |
140 | /**
141 | Custom HTTP request headers.
142 |
143 | @default {}
144 | */
145 | readonly headers?: Record;
146 |
147 | /**
148 | Set background color to `transparent` instead of `white` if no background is set.
149 |
150 | @default false
151 | */
152 | readonly transparent?: boolean;
153 |
154 | /**
155 | Emulate preference of dark color scheme.
156 |
157 | @default false
158 | */
159 | readonly darkMode?: boolean;
160 |
161 | /**
162 | Options passed to [`puppeteer.launch()`](https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#puppeteerlaunchoptions).
163 |
164 | @default {}
165 | */
166 | readonly launchOptions?: LaunchOptions;
167 |
168 | /**
169 | The specified function is called right before the screenshot is captured. It receives the Puppeteer [`Page` instance](https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#class-page) as the first argument and the [`browser` instance](https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#class-browser) as the second argument. This gives you a lot of power to do custom stuff. The function can be async.
170 |
171 | Note: Make sure to not call `page.close()` or `browser.close()`.
172 |
173 | @example
174 | ```
175 | import Pageres from 'pageres';
176 |
177 | await new Pageres({
178 | delay: 2,
179 | beforeScreenshot: async (page, browser) => {
180 | await checkSomething();
181 | await page.click('#activate-button');
182 | await page.waitForSelector('.finished');
183 | }
184 | })
185 | .source('https://github.com/sindresorhus/pageres', ['480x320', '1024x768'], {crop: true})
186 | .destination('screenshots')
187 | .run();
188 |
189 | console.log('Finished generating screenshots!');
190 | ```
191 | */
192 | readonly beforeScreenshot?: BeforeScreenshot;
193 | };
194 |
195 | /**
196 | A page to screenshot added in {@link Pageres.source}.
197 | */
198 | export type Source = {
199 | /**
200 | URL or local path to a website to screenshot. Can also be a data URI.
201 | */
202 | readonly url: string;
203 |
204 | /**
205 | Size of screenshot. Uses `x` notation or a keyword.
206 | */
207 | readonly sizes: string[];
208 |
209 | /**
210 | Options which will take precedence over the ones set in the constructor.
211 | */
212 | readonly options?: Options;
213 | };
214 |
215 | /**
216 | A destination directory set in {@link Pageres.destination}.
217 | */
218 | export type Destination = string;
219 |
220 | export type Viewport = {
221 | readonly url: string;
222 | readonly sizes: string[];
223 | readonly keywords: string[];
224 | };
225 |
226 | type Stats = {
227 | urls: number;
228 | sizes: number;
229 | screenshots: number;
230 | };
231 |
232 | /**
233 | Data representing a screenshot. Includes the filename from the template in {@link Options.filename}.
234 | */
235 | export type Screenshot = Uint8Array & {filename: string};
236 |
237 | const getResolutionsMemoized = pMemoize(getResolutions);
238 | // @ts-expect-error - TS is not very smart.
239 | const viewportListMemoized = pMemoize(viewportList);
240 |
241 | /**
242 | Capture screenshots of websites in various resolutions. A good way to make sure your websites are responsive. It's speedy and generates 100 screenshots from 10 different websites in just over a minute. It can also be used to render SVG images.
243 | */
244 | export default class Pageres extends EventEmitter {
245 | readonly #options: Writable;
246 | readonly #stats: Stats = {} as Stats; // eslint-disable-line @typescript-eslint/consistent-type-assertions
247 | readonly #items: Screenshot[] = [];
248 | readonly #sizes: string[] = [];
249 | readonly #urls: string[] = [];
250 | readonly #_source: Source[] = [];
251 | #_destination: Destination = '';
252 |
253 | constructor(options: Options = {}) {
254 | super();
255 |
256 | // Prevent false-positive `MaxListenersExceededWarning` warnings
257 | this.setMaxListeners(Number.POSITIVE_INFINITY);
258 |
259 | this.#options = {...options};
260 | this.#options.filename ??= '<%= url %>-<%= size %><%= crop %>';
261 | this.#options.format ??= 'png';
262 | this.#options.incrementalName ??= false;
263 | this.#options.launchOptions ??= {};
264 | }
265 |
266 | /**
267 | Retrieve pages to screenshot.
268 |
269 | @returns List of pages that have been already been added.
270 | */
271 | source(): Source[];
272 |
273 | /**
274 | Add a page to screenshot.
275 | @param url - URL or local path to the website you want to screenshot. You can also use a data URI.
276 | @param sizes - Use a `x` notation or a keyword.
277 |
278 | A keyword is a version of a device from [this list](https://github.com/kevva/viewport-list/blob/master/data.json).
279 |
280 | You can also pass in the `w3counter` keyword to use the ten most popular resolutions from [w3counter](http://www.w3counter.com/globalstats.php).
281 | @param options - Options set here will take precedence over the ones set in the constructor.
282 |
283 | @example
284 | ```
285 | import Pageres from 'pageres';
286 |
287 | const pageres = new Pageres({delay: 2})
288 | .source('https://github.com/sindresorhus/pageres', ['480x320', '1024x768'], {crop: true})
289 | .source('https://sindresorhus.com', ['1280x1024', '1920x1080'])
290 | .source('data:text/html,