From 4b44fb849dbfc674f2a000cd6572d55532d0bec4 Mon Sep 17 00:00:00 2001 From: rxliuli Date: Wed, 17 Dec 2025 06:58:46 +0800 Subject: [PATCH] fix: Don't return promises from unlisted scripts that do not have an async `main` function (#1907) Co-authored-by: Aaron --- .../__tests__/define-unlisted-script.test.ts | 18 ++++++++++++++ .../src/virtual/unlisted-script-entrypoint.ts | 24 +++++++++++++++++-- 2 files changed, 40 insertions(+), 2 deletions(-) diff --git a/packages/wxt/src/utils/__tests__/define-unlisted-script.test.ts b/packages/wxt/src/utils/__tests__/define-unlisted-script.test.ts index 4d656e51..7e386329 100644 --- a/packages/wxt/src/utils/__tests__/define-unlisted-script.test.ts +++ b/packages/wxt/src/utils/__tests__/define-unlisted-script.test.ts @@ -21,4 +21,22 @@ describe('defineUnlistedScript', () => { expect(actual).toEqual({ main }); }); + + it('should return the result without awaiting for synchronous main functions', () => { + const main = vi.fn(() => 'test'); + + const actual = defineUnlistedScript(main); + + expect(actual).toEqual({ main }); + expect(actual.main()).eq('test'); + }); + + it('should return a promise of a result for async main functions', async () => { + const main = vi.fn(() => Promise.resolve('test')); + + const actual = defineUnlistedScript(main); + + expect(actual).toEqual({ main }); + await expect(actual.main()).resolves.toEqual('test'); + }); }); diff --git a/packages/wxt/src/virtual/unlisted-script-entrypoint.ts b/packages/wxt/src/virtual/unlisted-script-entrypoint.ts index 843d9ac4..40f0b69d 100644 --- a/packages/wxt/src/virtual/unlisted-script-entrypoint.ts +++ b/packages/wxt/src/virtual/unlisted-script-entrypoint.ts @@ -2,10 +2,29 @@ import definition from 'virtual:user-unlisted-script-entrypoint'; import { logger } from '../utils/internal/logger'; import { initPlugins } from 'virtual:wxt-plugins'; -const result = (async () => { +const result = (() => { try { initPlugins(); - return await definition.main(); + } catch (err) { + logger.error( + `Failed to initialize plugins for "${import.meta.env.ENTRYPOINT}"`, + err, + ); + throw err; + } + let result; + try { + result = definition.main(); + + if (result instanceof Promise) { + result = (result as Promise).catch((err) => { + logger.error( + `The unlisted script "${import.meta.env.ENTRYPOINT}" crashed on startup!`, + err, + ); + throw err; + }); + } } catch (err) { logger.error( `The unlisted script "${import.meta.env.ENTRYPOINT}" crashed on startup!`, @@ -13,6 +32,7 @@ const result = (async () => { ); throw err; } + return result; })(); // Return the main function's result to the background when executed via the