diff --git a/README.md b/README.md
index e6aefe9..8dbda83 100644
--- a/README.md
+++ b/README.md
@@ -37,8 +37,8 @@ You can set `window.paceOptions` before bringing in the file:
```javascript
paceOptions = {
- // Disable the 'elements' source
- elements: false,
+ // Don't wait for any elements to appear
+ waitFor: [],
// Only show the progress on regular and ajax-y page navigation,
// not every request
@@ -46,14 +46,44 @@ paceOptions = {
}
```
-You can also put options on the script tag (the value must be valid JSON):
+You can also put options on Pace's own script tag (the value must be valid JSON). They apply after `window.paceOptions`:
```html
-
+
```
-Pace reads its options once, when pace.js loads, so set them before including it.
-Assigning `Pace.options` afterwards has no effect.
+To change settings later, call `Pace.configure({ ... })`; `Pace.start({ ... })` does the same, then starts. Settings
+about requests and navigation (`restartOnNavigation`, `restartOnRequestAfter`, `trackXHR`, `trackFetch`,
+`trackWebSockets`, `requestMethods`, `ignoreRequests` and `maxWait`) apply from the next request or navigation; the
+others from the next time the bar starts, so a bar that is showing doesn't change halfway. `Pace.getOptions()` returns a
+copy of the settings in use.
+
+A wrong value or an unknown name is ignored, and the console shows a warning (once) that says what Pace expected. Pace
+never throws because of a wrong value.
+
+| Setting | Default | What it does |
+|---|---|---|
+| `startOnPageLoad` | `true` | Show the bar while the page loads. With a bundler, call `Pace.start()` instead. |
+| `restartOnNavigation` | `true` | Restart when the page calls `history.pushState` or `replaceState`. |
+| `restartOnRequestAfter` | `500` | Restart for a tracked request still running after this many milliseconds; `false` to never. |
+| `target` | `'body'` | A selector for the element the bar is added to. |
+| `className` | `''` | Class names added to the bar's `.pace-progress` element. |
+| `trackDocument` | `true` | Wait for the document to load. |
+| `trackEventLag` | `true` | Wait until the page's scripts stop keeping it busy. |
+| `waitFor` | `['body']` | Selectors that must each match an element; `[]` to not wait for any. |
+| `trackXHR` | `true` | Track `XMLHttpRequest` requests. |
+| `trackFetch` | `true` | Track `fetch()` requests. |
+| `trackWebSockets` | `true` | Track WebSocket connections until they open. |
+| `requestMethods` | `['GET']` | The methods of the requests to track, in any case. |
+| `ignoreRequests` | `[]` | URL patterns (non-empty strings and regular expressions) of requests not to track. |
+| `maxWait` | `15000` | The longest Pace waits for one request, in milliseconds; `false` for no limit. |
+| `minVisible` | `250` | The shortest time the bar is shown, in milliseconds. |
+| `hideDelay` | `100` | How long the full bar stays before it's hidden, in milliseconds. |
+| `catchupTime` | `100` | About how many milliseconds the bar takes to catch up when the progress jumps. |
+| `initialRate` | `0.03` | How fast the bar moves before any progress is known, in percent per millisecond. |
+| `maxProgressPerFrame` | `20` | The most the bar moves in one frame, in percent. |
+| `easeFactor` | `1.25` | How the bar slows down as it fills; higher values slow it later. |
+| `extraSources` | `[]` | Your own progress sources, see Collectors below. |
If you load pace with a bundler or module loader (AMD or CommonJS), it doesn't start on its own:
set `window.paceOptions` before pace loads, then call `Pace.start()`. `import` statements run
@@ -62,7 +92,7 @@ before the rest of a file, so put the options in their own file and import it fi
```javascript
// pace-options.js
window.paceOptions = {
- document: false
+ trackDocument: false
};
```
@@ -113,16 +143,16 @@ Collectors are the bits of code which gather progress information. Pace includes
Checks for event loop lag signaling that javascript is being executed
-They can each be configured or disabled through configuration options of the same name.
+They can each be configured or disabled through settings:
```javascript
paceOptions = {
- ajax: false, // disabled
- document: false, // disabled
- eventLag: false, // disabled
- elements: {
- selectors: ['.my-page']
- }
+ trackXHR: false, // disabled
+ trackFetch: false, // disabled
+ trackWebSockets: false, // disabled
+ trackDocument: false, // disabled
+ trackEventLag: false, // disabled
+ waitFor: ['.my-page']
};
```
@@ -142,13 +172,11 @@ may never appear:
```javascript
paceOptions = {
- elements: {
- selectors: ['.timeline, .timeline-error', '.user-profile, .profile-error']
- }
+ waitFor: ['.timeline, .timeline-error', '.user-profile, .profile-error']
}
```
-Pace will consider the elements test successful when each selector matches something. For
+Pace will consider the elements test successful when each selector matches something (it checks every 100 ms). For
this example, when either `.timeline` or `.timeline-error` exist, and either `.user-profile`
or `.profile-error` exist.
@@ -160,7 +188,7 @@ Most users want the progress bar to automatically restart when a pushState event
```javascript
paceOptions = {
- restartOnPushState: false
+ restartOnNavigation: false
}
```
@@ -179,15 +207,18 @@ paceOptions = {
You can always trigger a restart manually by calling `Pace.restart()`
-See [the source](https://github.com/CodeByZach/pace/blob/master/pace.js) for a full list of options.
-
API
---
Pace exposes the following methods:
- `Pace.start`: Show the progress bar and start updating. Called automatically if you don't use AMD or CommonJS.
-While a run is in progress (not yet `done`), it only stores the options for the next run.
+While a run is in progress (not yet `done`), it doesn't restart it; the options it's given apply as described in
+Configuration above.
+
+- `Pace.configure`: Change settings without starting the bar, see Configuration above.
+
+- `Pace.getOptions`: A copy of the settings in use.
- `Pace.restart`: Show the progress bar if it's hidden and start reporting the progress from scratch. Called automatically
whenever `pushState` or `replaceState` is called by default.
@@ -208,7 +239,7 @@ Pace fires the following events:
- `restart`: When pace is restarted (manually, or by a new AJAX request)
- `progress`: On every frame while the bar is running, with the current progress (0–100)
- `done`: When pace is finished
-- `hide`: When the pace is hidden (can be later than `done`, based on `ghostTime` and `minTime`)
+- `hide`: When the pace is hidden (can be later than `done`, based on `hideDelay` and `minVisible`)
You can bind onto events using the `on`, `off` and `once` methods:
@@ -229,32 +260,30 @@ Only `GET` requests are tracked by default. To also show the bar for other metho
```javascript
paceOptions = {
- ajax: {
- trackMethods: ['GET', 'POST']
- }
+ requestMethods: ['GET', 'POST']
}
```
`fetch()` requests are tracked the same way, until their response arrives: Pace can't see a response's body load
-without reading it. To stop tracking them, set `trackFetch: false` inside `ajax`.
+without reading it. To stop tracking them, set `trackFetch: false`.
Pace waits for each request at most `maxWait` milliseconds after it's sent (15000 by default), so a request that never
-finishes can't hold the bar forever. The request itself keeps going. Set a different number, or `false` to wait for
-every request until it ends (anything other than a number from 0 to 2147483647, about 24 days, means the same):
+finishes can't hold the bar forever. The request itself keeps going. Set a different number (up to 2147483647, about 24
+days), or `false` to wait for every request until it ends:
```javascript
paceOptions = {
- ajax: {
- maxWait: 30000
- }
+ maxWait: 30000
}
```
-You can disable all ajax tracking by setting `ajax` to false:
+You can disable all ajax tracking by turning off each kind of request:
```javascript
paceOptions = {
- ajax: false
+ trackXHR: false,
+ trackFetch: false,
+ trackWebSockets: false
}
```
@@ -288,9 +317,7 @@ You can also ignore URLs based on a pattern:
```javascript
paceOptions = {
- ajax: {
- ignoreURLs: ['some-substring', /some-regexp/]
- }
+ ignoreRequests: ['some-substring', /some-regexp/]
}
```
@@ -302,11 +329,11 @@ resources on the page.
Requests a page keeps open on purpose, such as long polling for chat or live updates, show the bar each time one
starts, and so do slow requests a page makes in the background, such as prefetching links. Add their URLs to
-`ignoreURLs`.
+`ignoreRequests`.
-WebSocket connections are tracked too. To stop that, set `trackWebSockets: false` inside `ajax`. When `trackFetch` or
-`trackWebSockets` is false the first time Pace starts, Pace leaves `fetch` or `WebSocket` alone, so `Pace.track` can't
-track them either.
+WebSocket connections are tracked too. To stop that, set `trackWebSockets: false`. While `trackXHR`, `trackFetch` or
+`trackWebSockets` is false, Pace doesn't track that kind of request, not even inside `Pace.track`, and until Pace has started
+with it on, Pace leaves `XMLHttpRequest`, `fetch` or `WebSocket` alone.
A few things Pace can't track:
@@ -320,7 +347,7 @@ A few things Pace can't track:
Avoid calling `Pace.restart()` for every request, for example from jQuery's `ajaxStart`. It restarts the bar even for
ignored requests, and parallel requests restart it several times. To show the bar for `POST` requests, add `POST` to
-`trackMethods` as shown above.
+`requestMethods` as shown above.
Dependencies
------------
diff --git a/pace.js b/pace.js
index c20e418..4a923e3 100644
--- a/pace.js
+++ b/pace.js
@@ -4,35 +4,164 @@
* Licensed MIT © HubSpot, Inc. and Zachary Miller
*/
(function () {
- const defaultOptions = {
- className: '',
- catchupTime: 100,
- initialRate: 0.03,
- minTime: 250,
- ghostTime: 100,
- maxProgressPerFrame: 20,
- easeFactor: 1.25,
- startOnPageLoad: true,
- restartOnPushState: true,
- restartOnRequestAfter: 500,
- target: 'body',
- elements: {
- checkInterval: 100,
- selectors: ['body'],
- },
- eventLag: {
- minSamples: 10,
- sampleCount: 3,
- lagThreshold: 3,
- },
- ajax: {
- trackMethods: ['GET'],
- trackWebSockets: true,
- trackFetch: true,
- ignoreURLs: [],
- maxWait: 15000,
+ // The longest delay a timer can wait: setTimeout treats more, and Infinity, as 0.
+ const MAX_DELAY = 2147483647;
+
+ const isNumber = (value) => typeof value === 'number' && Number.isFinite(value);
+ const isMilliseconds = (value) => isNumber(value) && value >= 0 && value <= MAX_DELAY;
+
+ // querySelector throws on anything that isn't a valid selector.
+ const isSelector = (value) => {
+ if (typeof value !== 'string') {
+ return false;
+ }
+ try {
+ document.createDocumentFragment().querySelector(value);
+ return true;
+ } catch {
+ return false;
+ }
+ };
+
+ // RegExp.prototype's source getter throws for anything that isn't a RegExp,
+ // so this also accepts a RegExp made in another frame, which instanceof
+ // wouldn't, and rejects an object that only claims to be one.
+ const regExpSource = Object.getOwnPropertyDescriptor(RegExp.prototype, 'source').get;
+ const isRegExp = (value) => {
+ try {
+ regExpSource.call(value);
+ return value !== RegExp.prototype;
+ } catch {
+ return false;
+ }
+ };
+
+ // Whether `new value()` works, without calling or reading anything from it:
+ // Reflect.construct checks that its target is a constructor before it reads
+ // the arguments, which throw here.
+ const notArguments = {
+ get length() {
+ throw notArguments;
},
};
+ const isConstructor = (value) => {
+ try {
+ Reflect.construct(value, notArguments);
+ } catch (error) {
+ return error === notArguments;
+ }
+ };
+
+ const BOOLEAN = { expected: 'true or false', test: (value) => typeof value === 'boolean' };
+ const MILLISECONDS = { expected: `a number of milliseconds from 0 to ${MAX_DELAY}`, test: isMilliseconds };
+ const MILLISECONDS_OR_FALSE = { expected: `false or ${MILLISECONDS.expected}`, test: (value) => value === false || isMilliseconds(value) };
+ const ABOVE_ZERO = { expected: 'a number greater than 0', test: (value) => isNumber(value) && value > 0 };
+ const listOf = (expected, test) => ({ expected: `an array of ${expected}`, test: Array.isArray, item: test });
+
+ // Each setting with its default and the values it accepts.
+ const SETTINGS = new Map([
+ ['startOnPageLoad', [true, BOOLEAN]],
+ ['restartOnNavigation', [true, BOOLEAN]],
+ ['restartOnRequestAfter', [500, MILLISECONDS_OR_FALSE]],
+ ['target', ['body', { expected: 'a valid CSS selector', test: isSelector }]],
+ ['className', ['', { expected: 'a string', test: (value) => typeof value === 'string' }]],
+ ['trackDocument', [true, BOOLEAN]],
+ ['trackEventLag', [true, BOOLEAN]],
+ ['waitFor', [['body'], listOf('valid CSS selectors', isSelector)]],
+ ['trackXHR', [true, BOOLEAN]],
+ ['trackFetch', [true, BOOLEAN]],
+ ['trackWebSockets', [true, BOOLEAN]],
+ ['requestMethods', [['GET'], listOf('strings', (item) => typeof item === 'string')]],
+ ['ignoreRequests', [[], listOf('non-empty strings and RegExps', (item) => (typeof item === 'string' && item !== '') || isRegExp(item))]],
+ ['maxWait', [15000, MILLISECONDS_OR_FALSE]],
+ ['minVisible', [250, MILLISECONDS]],
+ ['hideDelay', [100, MILLISECONDS]],
+ ['catchupTime', [100, ABOVE_ZERO]],
+ ['initialRate', [0.03, { expected: 'a number of 0 or more', test: (value) => isNumber(value) && value >= 0 }]],
+ ['maxProgressPerFrame', [20, ABOVE_ZERO]],
+ ['easeFactor', [1.25, ABOVE_ZERO]],
+ ['extraSources', [[], listOf('constructors', isConstructor)]],
+ ]);
+
+ // Version 1 settings, and what replaced them.
+ const RENAMED = new Map([
+ ['ajax', 'trackXHR, trackFetch, trackWebSockets, requestMethods, ignoreRequests and maxWait'],
+ ['document', 'trackDocument'],
+ ['elements', 'waitFor'],
+ ['eventLag', 'trackEventLag'],
+ ['ghostTime', 'hideDelay'],
+ ['minTime', 'minVisible'],
+ ['restartOnPushState', 'restartOnNavigation'],
+ ]);
+
+ // A copy of a setting's value that shares nothing that can change: a list
+ // becomes a plain array, read once, and its RegExps (whose lastIndex changes,
+ // and which the page could freeze) are copied.
+ const copyValue = (value) => {
+ if (!Array.isArray(value)) {
+ return value;
+ }
+ const copy = [];
+ for (let i = 0, n = value.length; i < n; i++) {
+ const item = value[i];
+ copy.push(isRegExp(item) ? new RegExp(item) : item);
+ }
+ return copy;
+ };
+
+ const copyOptions = (settings) => {
+ const copy = {};
+ for (const name of SETTINGS.keys()) {
+ copy[name] = copyValue(settings[name]);
+ }
+ return copy;
+ };
+
+ const options = copyOptions(Object.fromEntries([...SETTINGS].map(([name, [value]]) => [name, value])));
+
+ // A value as a warning shows it: its type, and the value itself when that is short.
+ const describe = (value) => {
+ if (value == null) {
+ return String(value);
+ }
+ if (Array.isArray(value)) {
+ return 'array';
+ }
+ switch (typeof value) {
+ case 'string': {
+ const json = JSON.stringify(value);
+ return `string ${json.length > 50 ? json.slice(0, 48) + '…"' : json}`;
+ }
+ case 'object':
+ return Object.prototype.toString.call(value).slice(8, -1);
+ case 'function':
+ return 'function';
+ default:
+ return `${typeof value} ${String(value)}`;
+ }
+ };
+
+ const warned = new Set();
+
+ // Logs each distinct warning once.
+ const warn = (message) => {
+ message = `Pace: ${message}`;
+ if (!warned.has(message)) {
+ warned.add(message);
+ console.warn(message);
+ }
+ };
+
+ // What is wrong with `value` for a setting that accepts `check`, or undefined.
+ const problemWith = (check, value) => {
+ if (!check.test(value)) {
+ return describe(value);
+ }
+ const index = check.item ? value.findIndex((item) => !check.item(item)) : -1;
+ if (index !== -1) {
+ return `array containing ${describe(value[index])}`;
+ }
+ };
const now = () => performance.now();
@@ -46,25 +175,6 @@
return obj[key];
};
- const extend = (out, ...sources) => {
- for (const source of sources) {
- if (!source) {
- continue;
- }
- for (const key in source) {
- if (!Object.prototype.hasOwnProperty.call(source, key)) continue;
- if (key === '__proto__' || key === 'constructor' || key === 'prototype') continue;
- const val = source[key];
- if (out[key] != null && typeof out[key] === 'object' && val != null && typeof val === 'object') {
- extend(out[key], val);
- } else {
- out[key] = val;
- }
- }
- }
- return out;
- };
-
const avgAmplitude = (arr) => {
let sum = 0;
let count = 0;
@@ -75,22 +185,6 @@
return sum / count;
};
- const getFromDOM = (key = 'options', json = true) => {
- const el = document.querySelector(`script[data-pace-${key}]`);
- if (!el) {
- return;
- }
- const data = el.getAttribute(`data-pace-${key}`);
- if (!json) {
- return data;
- }
- try {
- return JSON.parse(data);
- } catch (e) {
- console.error('Error parsing inline pace options', e);
- }
- };
-
const Pace = window.Pace || {};
window.Pace = Pace;
@@ -166,21 +260,74 @@
},
});
- const options = (Pace.options = extend({}, defaultOptions, window.paceOptions, getFromDOM()));
-
- // `true` turns a collector on with its default settings.
- const normalizeOptions = () => {
- for (const key of ['ajax', 'document', 'eventLag', 'elements']) {
- if (options[key] === true) {
- options[key] = defaultOptions[key];
+ // Applies the settings in `given`, from `channel` (named in warnings). A wrong
+ // value or an unknown name is ignored with a warning; undefined means not given.
+ // Each value is copied, then the copy is checked and kept, so changing the
+ // page's own list later changes nothing. An error from reading a setting (a
+ // getter that throws, say) is reported, and the other settings still apply.
+ const applyOptions = (given, channel) => {
+ if (given === undefined) {
+ return;
+ }
+ try {
+ if (Object.prototype.toString.call(given) !== '[object Object]') {
+ warn(`ignored the options from ${channel}: expected an object, got ${describe(given)}.`);
+ return;
}
+ for (const name of Object.keys(given)) {
+ try {
+ const value = copyValue(given[name]);
+ if (value === undefined) {
+ continue;
+ }
+ if (SETTINGS.has(name)) {
+ const [, check] = SETTINGS.get(name);
+ const problem = problemWith(check, value);
+ if (problem) {
+ warn(`ignored the ${name} option from ${channel}: expected ${check.expected}, got ${problem}.`);
+ } else {
+ options[name] = value;
+ }
+ } else if (RENAMED.has(name)) {
+ warn(`ignored the ${name} option from ${channel}: use ${RENAMED.get(name)} instead.`);
+ } else {
+ const match = [...SETTINGS.keys()].find((known) => known.toLowerCase() === name.toLowerCase());
+ warn(`ignored the unknown option ${name} from ${channel}.${match ? ` Did you mean ${match}?` : ''}`);
+ }
+ } catch (error) {
+ reportException(error);
+ }
+ }
+ } catch (error) {
+ reportException(error);
+ }
+ };
+
+ // Pace's own " });
+ test(`${api}: ignoreRequests patterns see the full URL`, async ({ page, open }) => {
+ await open({ head: "" });
await idle(page);
await clearEvents(page);
await request(page, { ms: 900, api }); // a relative URL
expect(await page.evaluate(() => events)).toEqual([]);
});
- test(`${api}: ajax.ignoreURLs patterns also see the path and query of a request to the page's origin, not another's`, async ({ page, open }) => {
+ test(`${api}: ignoreRequests patterns also see the path and query of a request to the page's origin, not another's`, async ({ page, open }) => {
await page.route('http://other.test/**', async (route) => {
await new Promise((resolve) => setTimeout(resolve, 900));
await route.fulfill({ headers: { 'access-control-allow-origin': '*' }, body: 'ok' });
});
- await open({ head: "" });
+ await open({ head: "" });
await idle(page);
await clearEvents(page);
await request(page, { ms: 900, api, origin: 'http://pace.test', query: '#part' }); // an absolute URL
@@ -28,8 +28,8 @@ for (const api of ['XMLHttpRequest', 'fetch']) {
expect(await page.evaluate(() => events)).toEqual(RESTARTED);
});
- test(`${api}: ajax.ignoreURLs patterns also see the URL as the page wrote it`, async ({ page, open }) => {
- await open({ head: "" });
+ test(`${api}: ignoreRequests patterns also see the URL as the page wrote it`, async ({ page, open }) => {
+ await open({ head: "" });
await idle(page);
await clearEvents(page);
// Neither appears in the full URL, which has %20 for the space and a lowercase domain.
@@ -38,8 +38,8 @@ for (const api of ['XMLHttpRequest', 'fetch']) {
expect(await page.evaluate(() => events)).toEqual([]);
});
- test(`${api}: ajax.ignoreURLs patterns see the full URL resolved against ',
+ });
+ await idle(page);
+ const [doneAt, loadedAt] = await page.evaluate(() => [eventTimes.done, window.loadedAt]);
+ expect(doneAt).toBeLessThan(loadedAt - 1000);
+});
+
+test('trackEventLag: false does not wait for the page to stop being busy', async ({ page, open }) => {
+ // Measuring event lag takes at least 500 ms (ten samples, 50 ms apart).
+ await open({ head: options('{ trackEventLag: false, trackDocument: false }') });
+ await idle(page);
+ expect(await page.evaluate(() => eventTimes.done - eventTimes.start)).toBeLessThan(400);
+});
+
+test.describe('wrong values and unknown names', () => {
+ test('a wrong value is ignored with a warning, and the setting keeps its value', async ({ page, open }) => {
+ const logged = warnings(page);
+ await open({ head: options("{ minVisible: 'slow', hideDelay: -1, maxWait: Infinity, trackXHR: 'no', target: 5, requestMethods: ['GET', 7], catchupTime: 0 }") });
+ expect(logged).toEqual([
+ 'Pace: ignored the minVisible option from window.paceOptions: expected a number of milliseconds from 0 to 2147483647, got string "slow".',
+ 'Pace: ignored the hideDelay option from window.paceOptions: expected a number of milliseconds from 0 to 2147483647, got number -1.',
+ 'Pace: ignored the maxWait option from window.paceOptions: expected false or a number of milliseconds from 0 to 2147483647, got number Infinity.',
+ 'Pace: ignored the trackXHR option from window.paceOptions: expected true or false, got string "no".',
+ 'Pace: ignored the target option from window.paceOptions: expected a valid CSS selector, got number 5.',
+ 'Pace: ignored the requestMethods option from window.paceOptions: expected an array of strings, got array containing number 7.',
+ 'Pace: ignored the catchupTime option from window.paceOptions: expected a number greater than 0, got number 0.',
+ ]);
+ expect(await page.evaluate(() => Pace.getOptions())).toEqual(DEFAULTS);
+ });
+
+ test('an unknown name is ignored with a warning, which suggests the name that differs only in case', async ({ page, open }) => {
+ const logged = warnings(page);
+ await open({ head: options("{ classname: 'a', colour: 'red' }") });
+ expect(logged).toEqual([
+ 'Pace: ignored the unknown option classname from window.paceOptions. Did you mean className?',
+ 'Pace: ignored the unknown option colour from window.paceOptions.',
+ ]);
+ await expect(page.locator('.pace-progress')).toHaveClass('pace-progress');
+ });
+
+ test('a version 1 name is ignored with a warning that names what replaced it', async ({ page, open }) => {
+ const logged = warnings(page);
+ await open({ head: options("{ ajax: { trackMethods: ['POST'] }, eventLag: false, elements: { selectors: ['#x'] }, document: false, restartOnPushState: false, minTime: 0, ghostTime: 0 }") });
+ expect(logged).toEqual([
+ 'Pace: ignored the ajax option from window.paceOptions: use trackXHR, trackFetch, trackWebSockets, requestMethods, ignoreRequests and maxWait instead.',
+ 'Pace: ignored the eventLag option from window.paceOptions: use trackEventLag instead.',
+ 'Pace: ignored the elements option from window.paceOptions: use waitFor instead.',
+ 'Pace: ignored the document option from window.paceOptions: use trackDocument instead.',
+ 'Pace: ignored the restartOnPushState option from window.paceOptions: use restartOnNavigation instead.',
+ 'Pace: ignored the minTime option from window.paceOptions: use minVisible instead.',
+ 'Pace: ignored the ghostTime option from window.paceOptions: use hideDelay instead.',
+ ]);
+ expect(await page.evaluate(() => Pace.getOptions())).toEqual(DEFAULTS);
+ });
+
+ test('each problem is warned about once', async ({ page, open }) => {
+ const logged = warnings(page);
+ await open({ head: options('{ startOnPageLoad: false }') });
+ await page.evaluate(() => {
+ Pace.configure({ minVisible: 'slow' });
+ Pace.configure({ minVisible: 'slow' });
+ Pace.start({ minVisible: 'slow' });
+ });
+ expect(logged).toEqual([
+ 'Pace: ignored the minVisible option from Pace.configure(): expected a number of milliseconds from 0 to 2147483647, got string "slow".',
+ 'Pace: ignored the minVisible option from Pace.start(): expected a number of milliseconds from 0 to 2147483647, got string "slow".',
+ ]);
+ });
+
+ test('an invalid selector in target or waitFor is ignored with a warning, and pace keeps working', async ({ page, open }) => {
+ const logged = warnings(page);
+ await open({ head: options("{ trackEventLag: false, target: '#a[', waitFor: ['body', '#b['] }") });
+ await idle(page);
+ expect(logged).toEqual([
+ 'Pace: ignored the target option from window.paceOptions: expected a valid CSS selector, got string "#a[".',
+ 'Pace: ignored the waitFor option from window.paceOptions: expected an array of valid CSS selectors, got array containing string "#b[".',
+ ]);
+ });
+
+ test('Pace.start() and Pace.configure() never throw, whatever they are given', async ({ page, open }) => {
+ const logged = warnings(page);
+ await open({ head: options('{ trackEventLag: false }') });
+ await idle(page);
+ const status = await page.evaluate(() => {
+ Pace.configure(5);
+ Pace.configure({ requestMethods: null, waitFor: '.x' });
+ Pace.start(null);
+ // A misconfiguration must not break the page's own requests either.
+ const xhr = new XMLHttpRequest();
+ xhr.open('GET', '/delay?ms=0');
+ return new Promise((resolve) => {
+ xhr.onload = () => resolve(xhr.status);
+ xhr.send();
+ });
+ });
+ expect(status).toBe(200);
+ expect(logged).toEqual([
+ 'Pace: ignored the options from Pace.configure(): expected an object, got number 5.',
+ 'Pace: ignored the requestMethods option from Pace.configure(): expected an array of strings, got null.',
+ 'Pace: ignored the waitFor option from Pace.configure(): expected an array of valid CSS selectors, got string ".x".',
+ 'Pace: ignored the options from Pace.start(): expected an object, got null.',
+ ]);
+ });
+
+ test('an error from reading the options is reported, not thrown', async ({ page, open }) => {
+ const errors = [];
+ page.on('pageerror', (error) => errors.push(error.message));
+ await open({ head: options('{ startOnPageLoad: false }') });
+ const threw = await page.evaluate(() => {
+ try {
+ Pace.configure({ className: 'before', get target() { throw new Error('getter'); }, hideDelay: 50 });
+ return false;
+ } catch {
+ return true;
+ }
+ });
+ expect(threw).toBe(false);
+ await expect.poll(() => errors).toEqual(['getter']);
+ // The other settings still apply.
+ expect(await page.evaluate(() => [Pace.getOptions().className, Pace.getOptions().hideDelay])).toEqual(['before', 50]);
+ });
+
+ test('a value is checked as it is stored: a list is read once, and an error while checking one setting skips only that one', async ({ page, open }) => {
+ const errors = [];
+ page.on('pageerror', (error) => errors.push(error.message));
+ await open({ head: options('{ startOnPageLoad: false }') });
+ const result = await page.evaluate(() => {
+ // A list whose first item is 'GET' when checked and 7 afterwards.
+ let reads = 0;
+ const methods = [];
+ Object.defineProperty(methods, 0, { get: () => (reads++ ? 7 : 'GET'), enumerable: true });
+ const revoked = Proxy.revocable({}, {});
+ revoked.revoke();
+ Pace.configure({ requestMethods: methods, className: 'a', target: revoked.proxy, hideDelay: 50 });
+ Pace.start();
+ const xhr = new XMLHttpRequest();
+ xhr.open('GET', '/delay?ms=0');
+ return [Pace.getOptions().requestMethods, Pace.getOptions().className, Pace.getOptions().hideDelay];
+ });
+ expect(result).toEqual([['GET'], 'a', 50]);
+ await expect.poll(() => errors.length).toBe(1); // the revoked proxy
+ });
+
+ test('ignoreRequests rejects an empty string, which would match every URL, and an object that only claims to be a RegExp', async ({ page, open }) => {
+ const logged = warnings(page);
+ await open({ head: options("{ startOnPageLoad: false }") });
+ await page.evaluate(() => {
+ Pace.configure({ ignoreRequests: [''] });
+ Pace.configure({ ignoreRequests: [{ [Symbol.toStringTag]: 'RegExp' }] });
+ });
+ expect(logged).toEqual([
+ 'Pace: ignored the ignoreRequests option from Pace.configure(): expected an array of non-empty strings and RegExps, got array containing string "".',
+ 'Pace: ignored the ignoreRequests option from Pace.configure(): expected an array of non-empty strings and RegExps, got array containing RegExp.',
+ ]);
+ expect(await page.evaluate(() => Pace.getOptions().ignoreRequests)).toEqual([]);
+ });
+
+ test('an extra source is checked without reading anything from it', async ({ page, open }) => {
+ await open({ head: options('{ startOnPageLoad: false }') });
+ const [reads, accepted] = await page.evaluate(() => {
+ const reads = [];
+ const source = new Proxy(class {}, { get: (target, key) => { reads.push(String(key)); return target[key]; } });
+ Pace.configure({ extraSources: [source] });
+ return [reads, Pace.getOptions().extraSources.length];
+ });
+ expect([reads, accepted]).toEqual([[], 1]);
+ });
+
+ test('an extra source that can\'t be constructed with new is ignored with a warning', async ({ page, open }) => {
+ const logged = warnings(page);
+ const errors = [];
+ page.on('pageerror', (error) => errors.push(error.message));
+ await open({ head: options('{ trackEventLag: false, extraSources: [() => {}] }') });
+ await idle(page);
+ expect(errors).toEqual([]);
+ expect(logged).toEqual(['Pace: ignored the extraSources option from window.paceOptions: expected an array of constructors, got array containing function.']);
+ });
+
+ test('page markup that takes the name paceOptions is ignored with a warning', async ({ page, open }) => {
+ // A form with id="paceOptions" becomes window.paceOptions, and an input named target
+ // becomes its target property.
+ const logged = warnings(page);
+ await open({ head: '