Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: allow resources surrogates #4394

Merged
merged 9 commits into from
Oct 30, 2024
12 changes: 11 additions & 1 deletion packages/adblocker/src/resources.ts
Original file line number Diff line number Diff line change
Expand Up @@ -314,7 +314,7 @@ export default class Resources {
const scriptlet = this.getRawScriptlet(name);

if (scriptlet === undefined) {
return undefined;
return this.getSurrogate(name);
}

let script = this.scriptletsCache.get(scriptlet.name);
Expand All @@ -333,6 +333,16 @@ export default class Resources {
return script;
}

private getSurrogate(name: string): string | undefined {
const resource = this.resourcesByName.get(name.endsWith('.js') ? name : `${name}.js`);

if (resource === undefined || resource.contentType !== 'application/javascript') {
return undefined;
}

return resource.body;
}

public getScriptletCanonicalName(name: string): string | undefined {
return this.getRawScriptlet(name)?.name;
}
Expand Down
15 changes: 15 additions & 0 deletions packages/adblocker/test/resources.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,14 @@ describe('#Resources', function () {
requiresTrust: false,
},
],
resources: [
{
name: 'surrogate.js',
aliases: [],
body: '(function resource() {})()',
contentType: 'application/javascript',
},
],
});
});

Expand Down Expand Up @@ -272,6 +280,13 @@ describe('#Resources', function () {
it('includes setup for scritplet globals', function () {
expect(resources.getScriptlet('a')).to.include('var scriptletGlobals = {};');
});

it('allows resources surrogate', function () {
// Also, they don't need to be wrapped with scriptlet suppliments like `scriptletGlobals` to avoid possible conflicts.
expect(resources.getScriptlet('surrogate')).to.be.equal('(function resource() {})()');
// Allow calling surrogate with `.js`.
expect(resources.getScriptlet('surrogate.js')).to.be.equal('(function resource() {})()');
});
});

context('#getResource', function () {
Expand Down