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

feat: Support returning values from scripts executed with the scripting API #624

Merged
merged 5 commits into from
May 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 2 additions & 7 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,16 +45,11 @@
"*": "prettier --ignore-unknown --write"
},
"changelog": {
"excludeAuthors": [
"aaronklinker1@gmail.com"
]
"excludeAuthors": ["aaronklinker1@gmail.com"]
},
"pnpm": {
"peerDependencyRules": {
"ignoreMissing": [
"@algolia/client-search",
"search-insights"
]
"ignoreMissing": ["@algolia/client-search", "search-insights"]
}
}
}
3 changes: 3 additions & 0 deletions packages/wxt/e2e/tests/output-structure.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -362,11 +362,13 @@ describe('Output Directory Structure', () => {
function logHello(name) {
console.log(\`Hello \${name}!\`);
}
_background;
const definition = defineBackground({
main() {
logHello("background");
}
});
_background;
chrome;
function print(method, ...args) {
return;
Expand All @@ -389,6 +391,7 @@ describe('Output Directory Structure', () => {
throw err;
}
})();
_background;
"
`);
});
Expand Down
11 changes: 10 additions & 1 deletion packages/wxt/src/core/builders/vite/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import {
} from '~/core/utils/virtual-modules';
import { Hookable } from 'hookable';
import { toArray } from '~/core/utils/arrays';
import { safeVarName } from '~/core/utils/strings';

export async function createViteBuilder(
wxtConfig: ResolvedConfig,
Expand Down Expand Up @@ -87,14 +88,22 @@ export async function createViteBuilder(
plugins.push(wxtPlugins.cssEntrypoints(entrypoint, wxtConfig));
}

const iifeReturnValueName = safeVarName(entrypoint.name);
const libMode: vite.UserConfig = {
mode: wxtConfig.mode,
plugins,
esbuild: {
// Add a footer with the returned value so it can return values to `scripting.executeScript`
// Footer is added apart of esbuild to make sure it's not minified. It
// get's removed if added to `build.rollupOptions.output.footer`
// See https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/scripting/executeScript#return_value
footer: iifeReturnValueName + ';',
},
build: {
lib: {
entry,
formats: ['iife'],
name: '_',
name: iifeReturnValueName,
fileName: entrypoint.name,
},
rollupOptions: {
Expand Down
22 changes: 20 additions & 2 deletions packages/wxt/src/core/utils/__tests__/strings.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ import { describe, expect, it } from 'vitest';
import {
kebabCaseAlphanumeric,
removeImportStatements,
} from '~/core/utils/strings';
safeVarName,
} from '../strings';

describe('String utils', () => {
describe('kebabCaseAlphanumeric', () => {
Expand All @@ -18,6 +19,23 @@ describe('String utils', () => {
});
});

describe('safeVarName', () => {
it.each([
['Hello world!', '_hello_world'],
['123', '_123'],
['abc-123', '_abc_123'],
['', '_'],
[' ', '_'],
['_', '_'],
])(
"should convert '%s' to '%s', which can be used for a variable name",
(input, expected) => {
const actual = safeVarName(input);
expect(actual).toBe(expected);
},
);
});

describe('removeImportStatements', () => {
it('should remove all import formats', () => {
const imports = `
Expand All @@ -30,7 +48,7 @@ import{ registerGithubService, createGithubApi }from "@/utils/github";
import GitHub from "@/utils/github";
import "@/utils/github";
import '@/utils/github';
import"@/utils/github"
import"@/utils/github"
import'@/utils/github';
`;
expect(removeImportStatements(imports).trim()).toEqual('');
Expand Down
8 changes: 8 additions & 0 deletions packages/wxt/src/core/utils/strings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,14 @@ export function kebabCaseAlphanumeric(str: string): string {
.replace(/\s+/g, '-'); // Replace spaces with hyphens
}

/**
* Return a safe variable name for a given string.
*/
export function safeVarName(str: string): string {
// _ prefix to ensure it doesn't start with a number
return '_' + kebabCaseAlphanumeric(str.trim()).replace('-', '_');
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there a possibility that the generated variable name might conflict with an existing variable on the page?

Copy link
Collaborator Author

@aklinker1 aklinker1 Nov 13, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you're running the code in an isolated world, no. Variables are stored in the isolated context.

If you're running the code in the main world... I'm not sure. We could add a prefix or something that makes that less likely. But we should verify that first before making the change.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have two main use cases:

  1. Scripts injected into the main page (to gain access to global objects
  2. Scripts run in Web Worker

For 1, I can see there might be a chance of naming collisions and for 2 it would just produce syntax errors with evaluating undeclared variables generated here by WXT.

Let me see if I can put up a minimal reproduction for this.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It’s a bit late, but I finally had time to look into this (not for name collisions, but for errors occurring with Web Workers):

#1424


/**
* Removes import statements from the top of a file. Keeps import.meta and inline, async `import()`
* calls.
Expand Down
18 changes: 15 additions & 3 deletions packages/wxt/src/types/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -737,16 +737,24 @@ export interface IsolatedWorldContentScriptDefinition
extends IsolatedWorldContentScriptEntrypointOptions {
/**
* Main function executed when the content script is loaded.
*
* When running a content script with `browser.scripting.executeScript`,
* values returned from this function will be returned in the `executeScript`
* result as well. Otherwise returning a value does nothing.
*/
main(ctx: ContentScriptContext): void | Promise<void>;
main(ctx: ContentScriptContext): any | Promise<any>;
}

export interface MainWorldContentScriptDefinition
extends MainWorldContentScriptEntrypointOptions {
/**
* Main function executed when the content script is loaded.
*
* When running a content script with `browser.scripting.executeScript`,
* values returned from this function will be returned in the `executeScript`
* result as well. Otherwise returning a value does nothing.
*/
main(): void | Promise<void>;
main(): any | Promise<any>;
}

export type ContentScriptDefinition =
Expand All @@ -763,8 +771,12 @@ export interface BackgroundDefinition extends BackgroundEntrypointOptions {
export interface UnlistedScriptDefinition extends BaseEntrypointOptions {
/**
* Main function executed when the unlisted script is ran.
*
* When running a content script with `browser.scripting.executeScript`,
* values returned from this function will be returned in the `executeScript`
* result as well. Otherwise returning a value does nothing.
*/
main(): void | Promise<void>;
main(): any | Promise<any>;
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,23 @@
import { logger } from '../sandbox/utils/logger';
import { ContentScriptContext } from 'wxt/client';

(async () => {
const result = (async () => {

Check warning on line 5 in packages/wxt/src/virtual/content-script-isolated-world-entrypoint.ts

View check run for this annotation

Codecov / codecov/patch

packages/wxt/src/virtual/content-script-isolated-world-entrypoint.ts#L5

Added line #L5 was not covered by tests
try {
const { main, ...options } = definition;
const ctx = new ContentScriptContext(import.meta.env.ENTRYPOINT, options);

await main(ctx);
return await main(ctx);

Check warning on line 10 in packages/wxt/src/virtual/content-script-isolated-world-entrypoint.ts

View check run for this annotation

Codecov / codecov/patch

packages/wxt/src/virtual/content-script-isolated-world-entrypoint.ts#L10

Added line #L10 was not covered by tests
} catch (err) {
logger.error(
`The content script "${import.meta.env.ENTRYPOINT}" crashed on startup!`,
err,
);
throw err;

Check warning on line 16 in packages/wxt/src/virtual/content-script-isolated-world-entrypoint.ts

View check run for this annotation

Codecov / codecov/patch

packages/wxt/src/virtual/content-script-isolated-world-entrypoint.ts#L16

Added line #L16 was not covered by tests
}
})();

// Return the main function's result to the background when executed via the
// scripting API. Default export causes the IIFE to return a value.
// https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/scripting/executeScript#return_value
// Tested on both Chrome and Firefox
export default result;

Check warning on line 24 in packages/wxt/src/virtual/content-script-isolated-world-entrypoint.ts

View check run for this annotation

Codecov / codecov/patch

packages/wxt/src/virtual/content-script-isolated-world-entrypoint.ts#L19-L24

Added lines #L19 - L24 were not covered by tests
Original file line number Diff line number Diff line change
@@ -1,14 +1,21 @@
import definition from 'virtual:user-content-script-main-world-entrypoint';
import { logger } from '../sandbox/utils/logger';

(async () => {
const result = (async () => {

Check warning on line 4 in packages/wxt/src/virtual/content-script-main-world-entrypoint.ts

View check run for this annotation

Codecov / codecov/patch

packages/wxt/src/virtual/content-script-main-world-entrypoint.ts#L4

Added line #L4 was not covered by tests
try {
const { main } = definition;
await main();
return await main();

Check warning on line 7 in packages/wxt/src/virtual/content-script-main-world-entrypoint.ts

View check run for this annotation

Codecov / codecov/patch

packages/wxt/src/virtual/content-script-main-world-entrypoint.ts#L7

Added line #L7 was not covered by tests
} catch (err) {
logger.error(
`The content script "${import.meta.env.ENTRYPOINT}" crashed on startup!`,
err,
);
throw err;

Check warning on line 13 in packages/wxt/src/virtual/content-script-main-world-entrypoint.ts

View check run for this annotation

Codecov / codecov/patch

packages/wxt/src/virtual/content-script-main-world-entrypoint.ts#L13

Added line #L13 was not covered by tests
}
})();

// Return the main function's result to the background when executed via the
// scripting API. Default export causes the IIFE to return a value.
// https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/scripting/executeScript#return_value
// Tested on both Chrome and Firefox
export default result;

Check warning on line 21 in packages/wxt/src/virtual/content-script-main-world-entrypoint.ts

View check run for this annotation

Codecov / codecov/patch

packages/wxt/src/virtual/content-script-main-world-entrypoint.ts#L16-L21

Added lines #L16 - L21 were not covered by tests
11 changes: 9 additions & 2 deletions packages/wxt/src/virtual/unlisted-script-entrypoint.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,20 @@
import definition from 'virtual:user-unlisted-script-entrypoint';
import { logger } from '../sandbox/utils/logger';

(async () => {
const result = (async () => {

Check warning on line 4 in packages/wxt/src/virtual/unlisted-script-entrypoint.ts

View check run for this annotation

Codecov / codecov/patch

packages/wxt/src/virtual/unlisted-script-entrypoint.ts#L4

Added line #L4 was not covered by tests
try {
await definition.main();
return await definition.main();

Check warning on line 6 in packages/wxt/src/virtual/unlisted-script-entrypoint.ts

View check run for this annotation

Codecov / codecov/patch

packages/wxt/src/virtual/unlisted-script-entrypoint.ts#L6

Added line #L6 was not covered by tests
} catch (err) {
logger.error(
`The unlisted script "${import.meta.env.ENTRYPOINT}" crashed on startup!`,
err,
);
throw err;

Check warning on line 12 in packages/wxt/src/virtual/unlisted-script-entrypoint.ts

View check run for this annotation

Codecov / codecov/patch

packages/wxt/src/virtual/unlisted-script-entrypoint.ts#L12

Added line #L12 was not covered by tests
}
})();

// Return the main function's result to the background when executed via the
// scripting API. Default export causes the IIFE to return a value.
// https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/scripting/executeScript#return_value
// Tested on both Chrome and Firefox
export default result;

Check warning on line 20 in packages/wxt/src/virtual/unlisted-script-entrypoint.ts

View check run for this annotation

Codecov / codecov/patch

packages/wxt/src/virtual/unlisted-script-entrypoint.ts#L15-L20

Added lines #L15 - L20 were not covered by tests
6 changes: 3 additions & 3 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.