Skip to content

Commit ffa1b74

Browse files
committed
feat: mv renderingOptions => blockedResourceTypes
BREAKING CHANGE: renames “renderingOptions” to “blockedResourceTypes”. Default is now “None” fix for issue #113
1 parent ae96ced commit ffa1b74

File tree

13 files changed

+97
-49
lines changed

13 files changed

+97
-49
lines changed
Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
1-
import { IRenderingOption } from '@secret-agent/core-interfaces/ITabOptions';
1+
import { IBlockedResourceType } from '@secret-agent/core-interfaces/ITabOptions';
22
import IUserProfile from '@secret-agent/core-interfaces/IUserProfile';
33

44
export default interface IAgentDefaults {
5-
defaultRenderingOptions?: IRenderingOption[];
5+
defaultBlockedResourceTypes?: IBlockedResourceType[];
66
defaultUserProfile?: IUserProfile;
77
}

client/lib/Agent.ts

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
// eslint-disable-next-line max-classes-per-file
2-
import { RenderingOption } from '@secret-agent/core-interfaces/ITabOptions';
2+
import { BlockedResourceType } from '@secret-agent/core-interfaces/ITabOptions';
33
import StateMachine from 'awaited-dom/base/StateMachine';
44
import initializeConstantsAndProperties from 'awaited-dom/base/initializeConstantsAndProperties';
55
import { bindFunctions } from '@secret-agent/commons/utils';
@@ -33,7 +33,7 @@ import createConnection from '../connections/createConnection';
3333
import IAgentConfigureOptions from '../interfaces/IAgentConfigureOptions';
3434

3535
export const DefaultOptions = {
36-
defaultRenderingOptions: [RenderingOption.All],
36+
defaultBlockedResourceTypes: [BlockedResourceType.None],
3737
defaultUserProfile: {},
3838
};
3939
const scriptInstance = new ScriptInstance();
@@ -71,7 +71,8 @@ export default class Agent extends AwaitedEventTarget<{ close: void }> {
7171
initializeConstantsAndProperties(this, [], propertyKeys);
7272
bindFunctions(this);
7373

74-
options.renderingOptions = options.renderingOptions || Agent.options.defaultRenderingOptions;
74+
options.blockedResourceTypes =
75+
options.blockedResourceTypes || Agent.options.defaultBlockedResourceTypes;
7576
options.userProfile = options.userProfile || Agent.options.defaultUserProfile;
7677

7778
const sessionName = scriptInstance.generateSessionName(options.name);

core-interfaces/IConfigureSessionOptions.ts

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,5 +3,10 @@ import ICreateSessionOptions from './ICreateSessionOptions';
33
export default interface IConfigureSessionOptions
44
extends Pick<
55
ICreateSessionOptions,
6-
'userProfile' | 'viewport' | 'timezoneId' | 'locale' | 'upstreamProxyUrl' | 'renderingOptions'
6+
| 'userProfile'
7+
| 'viewport'
8+
| 'timezoneId'
9+
| 'locale'
10+
| 'upstreamProxyUrl'
11+
| 'blockedResourceTypes'
712
> {}

core-interfaces/ITabOptions.ts

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,15 @@
11
export default interface ITabOptions {
2-
renderingOptions?: IRenderingOption[];
2+
blockedResourceTypes?: IBlockedResourceType[];
33
}
44

5-
export enum RenderingOption {
6-
AwaitedDOM = 'AwaitedDOM',
5+
export enum BlockedResourceType {
76
JsRuntime = 'JsRuntime',
8-
LoadJsResources = 'LoadJsResources',
9-
LoadCssResources = 'LoadCssResources',
10-
LoadImages = 'LoadImages',
11-
LoadResources = 'LoadResources',
7+
BlockJsResources = 'BlockJsResources',
8+
BlockCssResources = 'BlockCssResources',
9+
BlockImages = 'BlockImages',
10+
BlockAssets = 'BlockAssets',
1211
All = 'All',
1312
None = 'None',
1413
}
1514

16-
export type IRenderingOption = keyof typeof RenderingOption;
15+
export type IBlockedResourceType = keyof typeof BlockedResourceType;

core/lib/Session.ts

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -88,15 +88,18 @@ export default class Session extends TypedEventEmitter<{
8888
log.warn('BrowserEmulators.PolyfillNotSupported', {
8989
sessionId: this.id,
9090
browserEmulatorId: this.browserEmulatorId,
91-
userAgentString: this.browserEmulator.userAgentString,
91+
userAgentString: this.browserEmulator.userAgentString,
9292
runtimeOs: Os.platform(),
9393
});
9494
}
9595

9696
this.timezoneId = options.timezoneId;
9797
this.viewport = options.viewport;
9898
if (!this.viewport) {
99-
this.viewport = Viewports.getDefault(this.browserEmulator.windowFraming, this.browserEmulator.windowFramingBase);
99+
this.viewport = Viewports.getDefault(
100+
this.browserEmulator.windowFraming,
101+
this.browserEmulator.windowFramingBase,
102+
);
100103
}
101104

102105
this.humanEmulatorId = options.humanEmulatorId || HumanEmulators.getRandomId();
@@ -131,8 +134,8 @@ export default class Session extends TypedEventEmitter<{
131134
this.upstreamProxyUrl = options.upstreamProxyUrl;
132135
this.mitmRequestSession.upstreamProxyUrl = options.upstreamProxyUrl;
133136
}
134-
if (options.renderingOptions !== undefined) {
135-
for (const tab of this.tabs) await tab.setRenderingOptions(options.renderingOptions);
137+
if (options.blockedResourceTypes !== undefined) {
138+
for (const tab of this.tabs) await tab.setBlockedResourceTypes(options.blockedResourceTypes);
136139
}
137140
if (options.viewport !== undefined) this.viewport = options.viewport;
138141
if (options.userProfile !== undefined) {

core/lib/Tab.ts

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { v1 as uuidv1 } from 'uuid';
22
import Log from '@secret-agent/commons/Logger';
3-
import { IRenderingOption } from '@secret-agent/core-interfaces/ITabOptions';
3+
import { IBlockedResourceType } from '@secret-agent/core-interfaces/ITabOptions';
44
import {
55
ILocationStatus,
66
ILocationTrigger,
@@ -143,27 +143,31 @@ export default class Tab extends TypedEventEmitter<ITabEventParams> {
143143
]);
144144
}
145145

146-
public async setRenderingOptions(renderingOptions: IRenderingOption[]): Promise<void> {
146+
public async setBlockedResourceTypes(
147+
blockedResourceTypes: IBlockedResourceType[],
148+
): Promise<void> {
147149
const mitmSession = this.session.mitmRequestSession;
148150
const blockedResources = mitmSession.blockedResources.types;
149151
let enableJs = true;
150152

151-
if (renderingOptions.includes('All')) {
153+
if (blockedResourceTypes.includes('None')) {
152154
blockedResources.length = 0;
153-
} else if (renderingOptions.includes('None')) {
155+
} else if (blockedResourceTypes.includes('All')) {
154156
blockedResources.push('Image', 'Stylesheet', 'Script', 'Font', 'Ico', 'Media');
155157
enableJs = false;
158+
} else if (blockedResourceTypes.includes('BlockAssets')) {
159+
blockedResources.push('Image', 'Stylesheet', 'Script');
156160
} else {
157-
if (!renderingOptions.includes('LoadImages')) {
161+
if (blockedResourceTypes.includes('BlockImages')) {
158162
blockedResources.push('Image');
159163
}
160-
if (!renderingOptions.includes('LoadCssResources')) {
164+
if (blockedResourceTypes.includes('BlockCssResources')) {
161165
blockedResources.push('Stylesheet');
162166
}
163-
if (!renderingOptions.includes('LoadJsResources')) {
167+
if (blockedResourceTypes.includes('BlockJsResources')) {
164168
blockedResources.push('Script');
165169
}
166-
if (!renderingOptions.includes('JsRuntime')) {
170+
if (blockedResourceTypes.includes('JsRuntime')) {
167171
enableJs = false;
168172
}
169173
}
@@ -513,8 +517,8 @@ export default class Tab extends TypedEventEmitter<ITabEventParams> {
513517
}
514518

515519
await this.interactor.initialize();
516-
if (this.session.options?.renderingOptions) {
517-
await this.setRenderingOptions(this.session.options.renderingOptions);
520+
if (this.session.options?.blockedResourceTypes) {
521+
await this.setBlockedResourceTypes(this.session.options.blockedResourceTypes);
518522
}
519523
}
520524

emulate-browsers/base/lib/DomDiffLoader.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,8 @@ function extractFilename(filenames: string[]) {
3030
for (const filename of filenames) {
3131
const matches = filename.match(/^dom-diffs-when-using-([a-z-]+)(-([0-9-]+))?.json$/);
3232
if (!matches) continue;
33-
const [osName, _, osVersion] = matches.slice(1); // eslint-disable-line @typescript-eslint/naming-convention
33+
34+
const [osName, _, osVersion] = matches.slice(1); // eslint-disable-line @typescript-eslint/naming-convention,@typescript-eslint/no-unused-vars
3435
filenameMap[osName] = filenameMap[osName] || {};
3536
filenameMap[osName][osVersion || 'ALL'] = filename;
3637
}

full-client/test/basic.test.ts

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { Helpers } from '@secret-agent/testing';
2+
import Resource from '@secret-agent/client/lib/Resource';
23
import { Handler } from '../index';
34

45
let koaServer;
@@ -22,6 +23,42 @@ describe('basic Full Client tests', () => {
2223
expect(url).toBe(koaServer.baseHost);
2324
});
2425

26+
it('allows you to block resources', async () => {
27+
koaServer.get('/block', ctx => {
28+
ctx.body = `<html>
29+
<head>
30+
<link rel="stylesheet" href="/test.css" />
31+
</head>
32+
<body>
33+
<img src="/img.png" alt="Image"/>
34+
</body>
35+
</html>`;
36+
});
37+
38+
koaServer.get('/img.png', ctx => {
39+
ctx.statusCode = 500;
40+
});
41+
koaServer.get('/test.css', ctx => {
42+
ctx.statusCode = 500;
43+
});
44+
45+
const agent = await handler.createAgent({
46+
blockedResourceTypes: ['BlockAssets'],
47+
});
48+
Helpers.needsClosing.push(agent);
49+
50+
const resources: Resource[] = [];
51+
await agent.activeTab.on('resource', event => resources.push(event));
52+
await agent.goto(`${koaServer.baseUrl}/block`);
53+
await agent.waitForAllContentLoaded();
54+
expect(resources).toHaveLength(3);
55+
for (const resource of resources) {
56+
const status = await resource.response.statusCode;
57+
if (resource.type === 'Document') expect(status).toBe(200);
58+
else expect(status).toBe(404);
59+
}
60+
});
61+
2562
it('should get unreachable proxy errors in the client', async () => {
2663
const agent = await handler.createAgent({
2764
upstreamProxyUrl: koaServer.baseUrl,

puppet-chrome/lib/BrowserContext.ts

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@ import IRegisteredEventListener from '@secret-agent/core-interfaces/IRegisteredE
1717
import { Page } from './Page';
1818
import { Browser } from './Browser';
1919
import { CDPSession } from './CDPSession';
20-
import { Worker } from './Worker';
2120
import Frame from './Frame';
2221
import CookieParam = Protocol.Network.CookieParam;
2322
import TargetInfo = Protocol.Target.TargetInfo;

website/docs/BasicInterfaces/Agent.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ const { Agent } = require('secret-agent');
5959
- timezoneId `string`. Overrides the host timezone. A list of valid ids are available at [unicode.org](https://unicode-org.github.io/cldr-staging/charts/37/supplemental/zone_tzid.html)
6060
- locale `string`. Overrides the host languages settings (eg, en-US). Locale will affect navigator.language value, Accept-Language request header value as well as number and date formatting rules.
6161
- viewport `IViewport`. Sets the emulated screen size, window position in the screen, inner/outer width and height. If not provided, the most popular resolution is used from [statcounter.com](https://gs.statcounter.com/screen-resolution-stats/desktop/united-states-of-america).
62-
- renderingOptions `string[]`. Controls browser functionality.
62+
- blockedResourceTypes `string[]`. Controls browser resource loading.
6363
- userProfile `IUserProfile`. Previous user's cookies, session, etc.
6464
- showReplay `boolean`. Whether or not to show the Replay UI. Can also be set with an env variable: `SA_SHOW_REPLAY=true`.
6565
- upstreamProxyUrl `string`. A socks5 or http proxy url (and optional auth) to use for all HTTP requests in this session. Dns over Tls requests will also use this proxy, if provided. The optional "auth" should be included in the UserInfo section of the url, eg: `http://username:password@proxy.com:80`.
@@ -165,7 +165,7 @@ Update existing configuration settings.
165165
- timezoneId `string`. Overrides the host timezone. A list of valid ids are available at [unicode.org](https://unicode-org.github.io/cldr-staging/charts/37/supplemental/zone_tzid.html)
166166
- locale `string`. Overrides the host languages settings (eg, en-US). Locale will affect navigator.language value, Accept-Language request header value as well as number and date formatting rules.
167167
- viewport `IViewport`. Sets the emulated screen size, window position in the screen, inner/outer width.
168-
- renderingOptions `string[]`. Controls enabled browser rendering features.
168+
- blockedResourceTypes `string[]`. Controls browser resource loading.
169169
- upstreamProxyUrl `string`. A socks5 or http proxy url (and optional auth) to use for all HTTP requests in this session. The optional "auth" should be included in the UserInfo section of the url, eg: `http://username:password@proxy.com:80`.
170170
- coreConnection `options | CoreClientConnection`. An object containing `ICoreConnectionOptions` used to connect, or an already created `CoreClientConnection` instance. Defaults to automatically connecting to a local `Core`.
171171

0 commit comments

Comments
 (0)