Compare commits

...

31 Commits

Author SHA1 Message Date
GitHub Actions b5a9d8082d chore(release): v0.1.5 2023-07-13 22:53:25 +00:00
Aaron Klinker 371be99770 fix: Include vite/client types 2023-07-13 17:36:52 -05:00
GitHub Actions 09928e8a15 chore(release): v0.1.4 2023-07-13 21:46:50 +00:00
Aaron Klinker 0a26673172 docs: Update CLI screenshot 2023-07-13 16:40:06 -05:00
Aaron Klinker 68611ae944 chore: Update prettier ignore 2023-07-13 16:37:15 -05:00
Aaron Klinker 49965e7786 fix: Fix config hook implementations for vite plugins
Turns out the returned config is merged with the user config, so we don't have to do that ourselves.
2023-07-13 16:36:39 -05:00
Aaron Klinker fa2b6566d8 fix: Fix regression where manifest was not listed first in build summary 2023-07-13 16:09:23 -05:00
Aaron 2d1c41eff1 Fix broken link in README.md 2023-07-11 17:59:01 -05:00
GitHub Actions 10fba3de49 chore(release): v0.1.3 2023-07-11 22:54:00 +00:00
Aaron aa16014650 feat: Add tsconfig path aliases (#32) 2023-07-11 17:39:13 -05:00
Aaron Klinker 0ce7c9d183 chore: Upgrade to pnpm 8 2023-07-11 17:35:45 -05:00
Aaron Klinker ac0b28e608 fix: Cleanup build summary with sourcemaps 2023-07-11 17:18:22 -05:00
Aaron 80fed4a451 docs: Create documentation site (#31) 2023-07-11 14:22:47 -05:00
Aaron Klinker 05ca9985d5 fix: Merge manifest option from both inline and user config 2023-07-11 10:24:55 -05:00
GitHub Actions 145038c6a2 chore(release): v0.1.2 2023-07-11 14:45:39 +00:00
Aaron Klinker 6e7184d98d fix: Generate valid type for EntrypointPath when there are no entrypoints 2023-07-11 09:42:08 -05:00
Aaron Klinker ee49837804 feat: Accept a function for config.manifest 2023-07-11 09:41:43 -05:00
Aaron Klinker 67f972eab8 Remove milestone warning from README 2023-07-10 23:19:27 -05:00
Aaron Klinker b29c3c6fdd fix: Only add imports to JS files 2023-07-10 23:19:13 -05:00
Aaron Klinker ef6001e0c0 types: Change config.vite to UserConfig 2023-07-10 23:00:30 -05:00
Aaron Klinker 636aa48e95 fix: Add missing types for webextension-polyfill and the manifest option 2023-07-10 22:55:40 -05:00
Aaron Klinker ec66b6172c Update changelog after release 2023-07-10 22:22:31 -05:00
GitHub Actions 1edd94e8f4 chore(release): v0.1.1 2023-07-11 03:21:27 +00:00
Aaron 2efc193b45 fix: Unable to read entrypoint options (#28) 2023-07-10 22:18:20 -05:00
Aaron Klinker 2e51e7349d fix: Allow dashes in entrypoint names 2023-07-10 22:16:08 -05:00
Aaron Klinker 28733df5f9 chore: Update changelog after release 2023-07-10 18:34:55 -05:00
GitHub Actions 0110a2bd4e chore(release): v0.1.0 2023-07-10 23:24:09 +00:00
Aaron Klinker afe838a348 feat!: Initial release 2023-07-10 18:21:01 -05:00
Aaron Klinker 0255028ce2 docs: Update feature list 2023-07-10 18:03:27 -05:00
Aaron 249aa5eccc feat: Content scripts reloading (#25) 2023-07-10 17:47:52 -05:00
Aaron Klinker b7c078f4e4 ci: Create github release 2023-07-03 17:43:10 -05:00
52 changed files with 3441 additions and 1379 deletions
Binary file not shown.

Before

Width:  |  Height:  |  Size: 150 KiB

+2 -2
View File
@@ -19,7 +19,7 @@ jobs:
- name: Setup PNPM
uses: pnpm/action-setup@v2
with:
version: 7
version: 8
- name: Setup NodeJS
uses: actions/setup-node@v3
@@ -47,4 +47,4 @@ jobs:
pnpm publish
- name: GitHub Release
run: pnpx changelogen@latest gh release
run: pnpx changelogen@latest gh release --token ${{ secrets.GITHUB_TOKEN }}
+1 -1
View File
@@ -16,7 +16,7 @@ jobs:
- name: Setup PNPM
uses: pnpm/action-setup@v2
with:
version: 7
version: 8
- name: Setup NodeJS
uses: actions/setup-node@v3
-1
View File
@@ -1,2 +1 @@
ignore-workspace-root-check=true
use-node-version=18.16.0
+3
View File
@@ -1,3 +1,6 @@
.output
coverage
dist
e2e/project
.wxt
docs/.vitepress/cache
+121 -2
View File
@@ -1,5 +1,126 @@
# Changelog
## v0.1.5
[compare changes](https://github.com/aklinker1/wxt/compare/v0.1.4...v0.1.5)
### 🩹 Fixes
- Include `vite/client` types ([371be99](https://github.com/aklinker1/wxt/commit/371be99))
### ❤️ Contributors
- Aaron Klinker
## v0.1.4
[compare changes](https://github.com/aklinker1/wxt/compare/v0.1.3...v0.1.4)
### 🩹 Fixes
- Fix regression where manifest was not listed first in build summary ([fa2b656](https://github.com/aklinker1/wxt/commit/fa2b656))
- Fix config hook implementations for vite plugins ([49965e7](https://github.com/aklinker1/wxt/commit/49965e7))
### 📖 Documentation
- Update CLI screenshot ([0a26673](https://github.com/aklinker1/wxt/commit/0a26673))
### 🏡 Chore
- Update prettier ignore ([68611ae](https://github.com/aklinker1/wxt/commit/68611ae))
### ❤️ Contributors
- Aaron Klinker
## v0.1.3
[compare changes](https://github.com/aklinker1/wxt/compare/v0.1.2...v0.1.3)
### 🚀 Enhancements
- Add tsconfig path aliases ([#32](https://github.com/aklinker1/wxt/pull/32))
### 🩹 Fixes
- Merge `manifest` option from both inline and user config ([05ca998](https://github.com/aklinker1/wxt/commit/05ca998))
- Cleanup build summary with sourcemaps ([ac0b28e](https://github.com/aklinker1/wxt/commit/ac0b28e))
### 📖 Documentation
- Create documentation site ([#31](https://github.com/aklinker1/wxt/pull/31))
### 🏡 Chore
- Upgrade to pnpm 8 ([0ce7c9d](https://github.com/aklinker1/wxt/commit/0ce7c9d))
### ❤️ Contributors
- Aaron
- Aaron Klinker
## v0.1.2
[compare changes](https://github.com/aklinker1/wxt/compare/v0.1.1...v0.1.2)
### 🚀 Enhancements
- Accept a function for `config.manifest` ([ee49837](https://github.com/aklinker1/wxt/commit/ee49837))
### 🩹 Fixes
- Add missing types for `webextension-polyfill` and the `manifest` option ([636aa48](https://github.com/aklinker1/wxt/commit/636aa48))
- Only add imports to JS files ([b29c3c6](https://github.com/aklinker1/wxt/commit/b29c3c6))
- Generate valid type for `EntrypointPath` when there are no entrypoints ([6e7184d](https://github.com/aklinker1/wxt/commit/6e7184d))
### 🌊 Types
- Change `config.vite` to `UserConfig` ([ef6001e](https://github.com/aklinker1/wxt/commit/ef6001e))
### ❤️ Contributors
- Aaron Klinker
## v0.1.1
[compare changes](https://github.com/aklinker1/wxt/compare/v0.1.0...v0.1.1)
### 🩹 Fixes
- Allow dashes in entrypoint names ([2e51e73](https://github.com/aklinker1/wxt/commit/2e51e73))
- Unable to read entrypoint options ([#28](https://github.com/aklinker1/wxt/pull/28))
### ❤️ Contributors
- Aaron Klinker
## v0.1.0
Initial release of WXT. Full support for production builds and initial toolkit for development:
- HMR support when HTML page dependencies change
- Reload extension when background changes
- Reload HTML pages when saving them directly
- Re-register and reload tabs when content scripts change
[compare changes](https://github.com/aklinker1/wxt/compare/v0.0.2...v0.1.0)
### 🚀 Enhancements
- Content scripts reloading ([#25](https://github.com/aklinker1/wxt/pull/25))
### 📖 Documentation
- Update feature list ([0255028](https://github.com/aklinker1/wxt/commit/0255028))
### 🤖 CI
- Create github release ([b7c078f](https://github.com/aklinker1/wxt/commit/b7c078f))
### ❤️ Contributors
- Aaron Klinker
## v0.0.2
[compare changes](https://github.com/aklinker1/wxt/compare/v0.0.1...v0.0.2)
@@ -25,7 +146,6 @@
### 🏡 Chore
- Update changelog ([a9af4d3](https://github.com/aklinker1/wxt/commit/a9af4d3))
- Refactor build output type ([#19](https://github.com/aklinker1/wxt/pull/19))
- Refactor build outputs to support transpiled templates ([a78aada](https://github.com/aklinker1/wxt/commit/a78aada))
- Rename `templates` to `virtual-modules` ([#24](https://github.com/aklinker1/wxt/pull/24))
@@ -34,7 +154,6 @@
### ❤️ Contributors
- Aaron Klinker
- Aaron
## v0.0.1
+5 -14
View File
@@ -2,37 +2,28 @@
<p align="center"><i>Next gen framework for developing web extensions.<br/>Powered by <a href="https://vitejs.dev/" target="_blank">Vite</a>. Inspired by <a href="https://nuxt.com/" target="_blank">Nuxt</a>.</i></p>
![Example CLI Output](./.github/assets/cli-output.png)
> **Warning**
>
> [![GitHub milestone](https://img.shields.io/github/milestones/progress-percent/aklinker1/wxt/1)](https://github.com/aklinker1/wxt/milestone/1)
>
> WXT is not ready for use yet. Production builds work, but dev mode is incomplete.
>
> See the [Initial Release Candidate](https://github.com/aklinker1/wxt/milestone/1) milestone for more details.
![Example CLI Output](./docs/assets/cli-output.png)
## Features
- 🌐 Supports all browsers
- ✅ Supports both MV2 and MV3
- 📂 Directory based entrypoints
- Dev mode with HMR & auto-reload
- 📂 File based entrypoints
- 🚔 TypeScript
- 🦾 Auto-imports
- ⚡ Dev mode with HMR
- ⬇️ Download and bundle remote URL imports
- 🎨 Frontend framework agnostic: works with Vue, React, Svelte, etc
### Todo
- 🤖 Automated publishing
- 🖍️ Quickly bootstrap a new project
- 📏 Bundle analysis
- ⚡ Dev mode with HMR and **_auto-reload_**
- 🤖 Automated publishing
## Get Started
Checkout the [installation guide](https://wxtjs.dev/get-started) to get started with WXT.
Checkout the [installation guide](https://wxt.dev/get-started/installation.html) to get started with WXT.
## Contributors
+35
View File
@@ -0,0 +1,35 @@
import { defineConfig } from 'vitepress';
// https://vitepress.dev/reference/site-config
export default defineConfig({
title: 'WXT',
description: 'Next gen framework for developing web extensions',
themeConfig: {
// https://vitepress.dev/reference/default-theme-config
nav: [
{ text: 'Get Started', link: '/get-started/installation.md' },
{ text: 'Guide', link: '/guide.md' },
{ text: 'API', link: '/api.md' },
],
sidebar: {
'/get-started/': [
{
text: 'Guide',
items: [
{ text: 'Introduction', link: '/get-started/introduction.md' },
{ text: 'Installation', link: '/get-started/installation.md' },
{ text: 'Configuration', link: '/get-started/configuration.md' },
{ text: 'Entrypoints', link: '/get-started/entrypoints.md' },
{ text: 'Assets', link: '/get-started/assets.md' },
{ text: 'Build Targets', link: '/get-started/build-targets.md' },
{ text: 'Publishing', link: '/get-started/publishing.md' },
{ text: 'Testing', link: '/get-started/testing.md' },
],
},
],
},
socialLinks: [{ icon: 'github', link: 'https://github.com/aklinker1/wxt' }],
},
});
+5
View File
@@ -0,0 +1,5 @@
# API Reference
:::warning 🚧&ensp;Under construction
This documentation does not exist yet.
:::
Binary file not shown.

After

Width:  |  Height:  |  Size: 415 KiB

+85
View File
@@ -0,0 +1,85 @@
# Assets
WXT has two directories for storing assets like CSS, images, or fonts.
- `<srcDir>/public`: Store files that will be copied into the output directory as-is
- `<srcDir>/assets`: Store files that will be processed by Vite during the build process
## `/public` Directory
Place static files like the extension icon or `_locales/` directory here. These files will be copied over to the output directory without being transformed by Vite.
```
<srcDir>
└─ public/
├─ icon-16.png
├─ icon-32.png
├─ icon-48.png
├─ icon-96.png
└─ icon-128.png
```
### Example
You can reference these files by using absolute paths in HTML files or `browser.runtime.getURL` in content scripts.
:::code-group
```html [popup.html]
<img src="/icon-128.png" />
```
```ts [content.ts]
defineContentScript({
main() {
const image = document.createElement('img');
image.src = browser.runtime.getURL('/icon-128.png');
document.body.append(image);
},
});
```
:::
## `/assets` Directory
Files in the assets directory will be processed by Vite. They are imported in your source code, and will be transformed or renamed in the output directory.
```
<srcDir>
└─ assets/
├─ style.css
└─ illustration.svg
```
### Example
:::code-group
```html [popup.html]
<html>
<head>
<link rel="stylesheet" href="~/assets/style.css" />
<!-- ... -->
</head>
<body>
<img src="~/illustration.svg" />
<!-- ... -->
</body>
</html>
```
```ts [content.ts]
import '~/assets/style.css';
import illustration from '~/assets/style.svg';
defineContentScript({
main() {
const image = document.createElement('img');
image.src = illustration;
document.body.append(image);
},
});
```
:::
+46
View File
@@ -0,0 +1,46 @@
# Build Targets
You can build an extension for any combination of browser and manifest verison. Different browsers and manifest versions support different APIs and entrypoints, so be sure to check that your extension functions as expected for each target.
Separate build targets are to separate output directories:
```
<root>
└─ .output
├─ chrome-mv3
├─ firefox-mv2
├─ edge-mv3
└─ ...
```
## Target Browser
To build for a specific browser, pass the `-b --browser` flag from the CLI:
```
wxt --browser firefox
wxt build --browser firefox
```
By default, it will build for `chrome`. When excluding the [`--mv2` or `--mv3` flags](#target-manifest-version), it will default to the commonly accepted version used with that browser.
| Browser | Default Manifest Version |
| ---------------- | :----------------------: |
| `chrome` | 3 |
| `firefox` | 2 |
| `safari` | 2 |
| `edge` | 3 |
| Any other string | 3 |
## Target Manifest Version
To build for a specific manifest version, pass either the `--mv2` flag or `--mv3` flag from the CLI.
```sh
wxt --mv2
wxt build --mv2
```
When the `-b --browser` flag is not passed, it defaults to `chrome`. So here, we're targetting MV2 for Chrome.
+62
View File
@@ -0,0 +1,62 @@
# Configuration
WXT's behavior can be configured via the `wxt.config.ts` file. In this file, you can add Vite plugins, change the directory strucutre of your project, and provide permissions or other fields to the `<outdir>/manifest.json`.
However, since WXT is an opinionated framework, some things cannot be configured.
## Config File
To configure WXT, create a `wxt.config.ts` file in your project root. It should have the following contents:
```ts
import { defineConfig } from 'wxt';
export default defineConfig({
// My WXT config
});
```
:::info
See the [API reference](/api.md) for a full list of options.
:::
## Directory Config
WXT allows you to edit several directories to your liking:
- `root` (default: `process.cwd()`) - Root of the WXT project
- `srcDir` (default: `<root>`) - Location of all your source code
- `entrypointsDir` (default: `<srcDir>/entrypoints`) - Folder containing all the entrypoints.
- `publicDir` (default: `<srcDir>/public`) - Folder containing [public assets](/get-started/assets.md)
### Example
If you want a `src/` directory to contain all your source code, and you want to rename `entrypoints/` to `entries/`, your config would look like this:
```ts
import { defineConfig } from 'wxt';
export default defineConfig({
srcDir: 'src',
entrypointsDir: 'entries',
});
```
## Vite Config
Vite is the bundler used to build each part of an extension. Vite can be configured via the `vite` option.
### Example
A common reason to configure Vite is to add plugins:
```ts
import { defineConfig } from 'wxt';
import vue from '@vitejs/plugin-vue';
export default defineConfig({
vite: {
plugins: [vue()],
},
});
```
+89
View File
@@ -0,0 +1,89 @@
# Defining Entrypoints
Entrypoints are any HTML, JS, or CSS file that needs to be bundled and included with the extension.
They may or may not be listed in the extension's `manifest.json`.
## `/entrypoints` Directory
In WXT, entrypoints are defined by adding a file to the `entrypoints/` directory.
For example, a project that looks like this:
```
<root>
├─ entrypoints/
│ ├─ background.ts
│ ├─ content.ts
│ ├─ injected.ts
│ └─ popup.html
└─ wxt.config.ts
```
would result in the following `manifest.json`:
```json
{
// ...
"manifest_version": 3,
"action": {
// ...
"default_popup": "popup.html"
},
"background": {
// ...
"service_worker": "background.js"
},
"content_scripts": [
{
// ...
"js": ["content-scripts/content.js"]
}
]
}
```
If a file uses a [special name recognized by WXT](/get-started/entrypoints.md), it will be added to the manifest. In this case:
- `popup.html` &rarr; `action.default_popup`
- `content.ts` &rarr; `content_scripts.*.js`
- `background.ts` &rarr; `background.service_worker`
But not all entrypoints are added to the `manifest.json`. If they have a name that is not recognized by WXT, they are still built and included in the extension, but they are unlisted and do not show up in the manifest.
In this case, `injected.ts` gets bundled to `<outdir>/injected.js` and is accessible via `browser.runtime.getURL("/injected.js")`.
:::info
See [`/entrypoints` folder](/get-started/entrypoints.md) documentation for a full list of recognized entrypoint filenames.
:::
## Entrypoint Options
Some entrypoints, like content scripts, actions, or the background, can recieve additional options.
In HTML files, options are listed as `meta` tags:
```html
<html>
<head>
<!-- Defining the popup's "default_icon" field -->
<meta name="manifest.default_icon" content="{ '16': '/icon/16.png' }" />
</head>
</html>
```
In TS files, options are apart of the file's default export:
```ts
export default defineContentScript({
matches: ['*://*.google.com/*'],
runAt: 'document_start',
main() {
// ...
},
});
```
:::info
For a full list of entrypoints and each of their options, see the [`/entrypoints` folder](/get-started/entrypoints.md) documentation.
:::
+98
View File
@@ -0,0 +1,98 @@
# Installation
Bootstrap a new project or start from scratch.
## Bootstrap Project
:::warning 🚧&ensp;This feature is not implemented yet!
See [From Scratch](#from-scratch) instead.
:::
:::code-group
```sh [pnpm]
pnpx wxt@latest init <project-name>
```
```sh [npm]
npx wxt@latest init <project-name>
```
:::
## From Scratch
Create a new NPM project:
:::code-group
```sh [pnpm]
pnpm init <project-name>
cd <project-name>
echo 'shamefully-hoist=true' >> .npmrc
```
```sh [npm]
npm init <project-name>
cd <project-name>
```
```sh [yarn]
yarn init <project-name>
cd <project-name>
```
:::
Then install `wxt`:
:::code-group
```sh [pnpm]
pnpm add wxt
```
```sh [npm]
npm i --save wxt
```
```sh [yarn]
yarn add wxt
```
:::
Finally, add `package.json` scripts:
```json
{
"scripts": {
"dev": "wxt",
"dev:firefox": "wxt --browser firefox",
"build": "wxt build",
"build:firefox": "wxt build --browser firefox"
}
}
```
## Development
Once you've installed WXT, you can start the development server using the `dev` command:
```sh
pnpm dev
```
:::tip 🎉&ensp;Well done!
The dev command will build the extension for development, open the browser, and reload the different parts of the extension when you save changes.
:::
## Next Steps
Now that your WXT project is setup, you're ready to build a out your web extension!
- Learn how to [add entrypoints](./entrypoints.md) like the popup, background, or content scripts
- [Configure WXT](./configuration.md) by creating a `wxt.config.ts` file
+32
View File
@@ -0,0 +1,32 @@
# Introduction
WXT is a free and open source framework for building web extensions in an conventional, intuative, and safe way **_for all browsers_**.
WXT comes with full TypeScript support and auto-imports. Sounds familiar? That's right, **_WXT was based off of Nuxt_** and aims to provide the same greate DX and features.
![Example build output](../assets/cli-output.png)
## Conventions
WXT is an optionated framework. This helps keep projects consistent and easy to pick up.
- **Generated manifest**: Based on your project's file structure
- **Entrypoint configuration**: Configure entrypoints from the same file they're declare in
- **Type-safety is a priority**: Out-of-the-box TypeScript support with improved browser API typing
- **Simple output file structure**: Ouptut file paths minimize the path at runtime
## Development
WXT's dev server supports modern features like HMR to provide a lighting fast dev mode.
When changes can't be hot-reloaded, like content scripts or background scripts, they're reloaded individually to prevent reloading the entire extension and slowing down your development cycle.
## Production-ready
Production builds are optimized for store review, changing as few files as possible between builds.
In addition, WXT fully supports Firefox's source code requirements when using a bundler. It will automatically create and upload a ZIP file of your source code.
:::info
See [Publishing](./publishing.md) for more info around production builds.
:::
+5
View File
@@ -0,0 +1,5 @@
# Publishing
:::warning 🚧&ensp;Not implemented yet!
For now, manually zip the output directory and upload to stores by hand.
:::
+5
View File
@@ -0,0 +1,5 @@
# Testing
:::warning 🚧&ensp;Testing utils are not implemented yet!
Eventually, the plan is to have an integration with Vitest.
:::
+5
View File
@@ -0,0 +1,5 @@
# Guide
:::warning 🚧&ensp;Under construction
This documentation does not exist yet.
:::
+49
View File
@@ -0,0 +1,49 @@
---
# https://vitepress.dev/reference/default-theme-home-page
layout: home
titleTemplate: 'Next Generation Web Extension Framework'
hero:
name: WXT
text: Next gen framework for web extensions
tagline: Powered by Vite, inspired by Nuxt.
actions:
- theme: brand
text: Get Started
link: /get-started/installation
- theme: alt
text: Learn More
link: /get-started/introduction
features:
- icon: 🌐
title: Supported Browsers
details: Chrome, Firefox, Edge, Safari, and any Chromium based browser.
- icon: ✅
title: MV2 and MV3
details: Supports both manifest versions for each browser.
- icon: ⚡
title: Fast Dev Mode
details: HMR for UIs and fast reload for background and content scripts.
- icon: 📂
title: File Based Entrypoints
details: Manifest is generated based on files inside the project.
- icon: 🚔
title: TypeScript
details: Scale projects with full TS support.
- icon: 🦾
title: Auto-imports
details: Nuxt-like auto-imports to speed up development.
- icon: ⬇️
title: Bundle Remote Code
details: Downloads and bundles remote code imported from URLs.
- icon: 🎨
title: Frontend framework agnostic
details: Works with any front-end framework with a Vite plugin.
- icon: 🤖
title: Automated Publishing
details: 'TODO: Automatically zip, upload, and release extensions.'
- icon: 📏
title: Bundle analysis
details: 'TODO: Tools for analyizing the final extension bundle.'
---
+24
View File
@@ -69,4 +69,28 @@ describe('Output Directory Structure', () => {
{\\"manifest_version\\":3,\\"name\\":\\"E2E Extension\\",\\"version\\":\\"0.0.0\\",\\"version_name\\":\\"0.0.0-test\\",\\"content_scripts\\":[{\\"matches\\":[\\"*://*/*\\"],\\"css\\":[\\"assets/one.css\\",\\"assets/two.css\\"],\\"js\\":[\\"content-scripts/one.js\\",\\"content-scripts/two.js\\"]}]}"
`);
});
it('should allow inputs with invalid JS variable names, like dashes', async () => {
const project = new TestProject();
project.addFile(
'entrypoints/overlay-one.content.ts',
`export default defineContentScript({
matches: ["*://*/*"],
main: () => {},
})`,
);
await project.build();
expect(await project.serializeOutput()).toMatchInlineSnapshot(`
".output/chrome-mv3/content-scripts/overlay-one.js
----------------------------------------
(function(){\\"use strict\\";function i(n){return n}const o={matches:[\\"*://*/*\\"],main:()=>{}};function t(n,...e){if(typeof e[0]==\\"string\\"){const c=e.shift();n(\`[wxt] \${c}\`,...e)}else n(\\"[wxt]\\",...e)}var r={debug:(...n)=>t(console.debug,...n),log:(...n)=>t(console.log,...n),warn:(...n)=>t(console.warn,...n),error:(...n)=>t(console.error,...n)};(async()=>{try{await o.main()}catch(n){r.error(\\"The content script crashed on startup!\\",n)}})()})();
================================================================================
.output/chrome-mv3/manifest.json
----------------------------------------
{\\"manifest_version\\":3,\\"name\\":\\"E2E Extension\\",\\"version\\":\\"0.0.0\\",\\"version_name\\":\\"0.0.0-test\\",\\"content_scripts\\":[{\\"matches\\":[\\"*://*/*\\"],\\"js\\":[\\"content-scripts/overlay-one.js\\"]}]}"
`);
});
});
+28
View File
@@ -55,4 +55,32 @@ describe('User Config', () => {
{\\"manifest_version\\":3,\\"name\\":\\"E2E Extension\\",\\"version\\":\\"0.0.0\\",\\"version_name\\":\\"0.0.0-test\\",\\"background\\":{\\"service_worker\\":\\"background.js\\"}}"
`);
});
it('should merge inline and user config based manifests', async () => {
const project = new TestProject();
project.addFile(
'wxt.config.ts',
`import { defineConfig } from 'wxt';
export default defineConfig({
manifest: ({ mode, browser }) => ({
// @ts-expect-error
example_customization: [mode, browser],
})
})`,
);
await project.build({
// @ts-expect-error: Specifically setting an invalid field for the test - it should show up in the snapshot
manifest: ({ manifestVersion, command }) => ({
example_customization: [String(manifestVersion), command],
}),
});
const output = await project.serializeOutput();
expect(output).toMatchInlineSnapshot(`
".output/chrome-mv3/manifest.json
----------------------------------------
{\\"manifest_version\\":3,\\"name\\":\\"E2E Extension\\",\\"version\\":\\"0.0.0\\",\\"version_name\\":\\"0.0.0-test\\",\\"example_customization\\":[\\"production\\",\\"chrome\\",\\"3\\",\\"build\\"]}"
`);
});
});
+8 -9
View File
@@ -55,6 +55,7 @@ export class TestProject {
*/
addFile(filename: string, content?: string) {
this.files.push([filename, content ?? '']);
if (filename === 'wxt.config.ts') this.config = {};
}
/**
@@ -63,15 +64,13 @@ export class TestProject {
async build(config: InlineConfig = {}) {
if (this.config == null) this.setConfigFileConfig();
await Promise.all(
this.files.map(async (file) => {
const [name, content] = file;
const filePath = resolve(this.root, name);
const fileDir = dirname(filePath);
await fs.ensureDir(fileDir);
await fs.writeFile(filePath, content ?? '', 'utf-8');
}),
);
for (const file of this.files) {
const [name, content] = file;
const filePath = resolve(this.root, name);
const fileDir = dirname(filePath);
await fs.ensureDir(fileDir);
await fs.writeFile(filePath, content ?? '', 'utf-8');
}
execSync('npm i --ignore-scripts', { cwd: this.root });
await build({ ...config, root: this.root });
+26 -4
View File
@@ -1,8 +1,12 @@
{
"name": "wxt",
"type": "module",
"version": "0.0.2",
"version": "0.1.5",
"description": "Next gen framework for developing web extensions",
"engines": {
"node": ">=18.16.0",
"pnpm": ">=8"
},
"repository": {
"type": "git",
"url": "https://github.com/aklinker1/wxt"
@@ -49,9 +53,15 @@
"test": "vitest",
"test:coverage": "vitest run --coverage",
"prepare": "simple-git-hooks",
"prepublish": "pnpm -s build"
"prepublish": "pnpm -s build",
"docs:dev": "vitepress dev docs",
"docs:build": "vitepress build docs",
"docs:preview": "vitepress preview docs"
},
"dependencies": {
"@types/webextension-polyfill": "^0.10.0",
"@webext-core/fake-browser": "^1.2.2",
"@webext-core/match-patterns": "^1.0.1",
"async-mutex": "^0.4.0",
"c12": "^1.4.2",
"cac": "^6.7.14",
@@ -75,7 +85,6 @@
"@types/lodash.merge": "^4.6.7",
"@types/node": "^20.3.1",
"@types/picomatch": "^2.3.0",
"@types/webextension-polyfill": "^0.10.0",
"@vitest/coverage-v8": "^0.32.2",
"lodash.merge": "^4.6.2",
"npm-run-all": "^4.1.5",
@@ -86,7 +95,9 @@
"tsup": "^7.0.0",
"tsx": "^3.12.7",
"typescript": "^5.1.3",
"vitest": "^0.32.2",
"vitepress": "1.0.0-beta.5",
"vitest": "^0.32.4",
"vitest-mock-extended": "^1.1.4",
"webextension-polyfill": "^0.10.0"
},
"peerDependencies": {
@@ -95,5 +106,16 @@
"packageManager": "pnpm@8.6.3",
"simple-git-hooks": {
"pre-commit": "pnpm pretty-quick --staged"
},
"pnpm": {
"peerDependencyRules": {
"ignoreMissing": [
"@algolia/client-search",
"search-insights"
],
"allowAny": [
"node-fetch"
]
}
}
}
+1844 -1057
View File
File diff suppressed because it is too large Load Diff
+7
View File
@@ -57,6 +57,13 @@ await Promise.all([
sourcemap: true,
silent: true,
}),
tsup.build({
entry: {
'virtual-modules/fake-browser': `src/client/virtual-modules/fake-browser.ts`,
},
format: ['esm', 'cjs'],
silent: true,
}),
]).catch((err) => {
spinner.fail();
console.error(err);
+1 -1
View File
@@ -23,7 +23,7 @@ export const dev = defineCommand<
};
const server = await wxt.createServer(cliConfig);
await server.listen(server.port);
await server.start();
return true;
});
+48
View File
@@ -0,0 +1,48 @@
import browser, { Manifest } from 'webextension-polyfill';
import { logger } from './logger';
import { MatchPattern } from '@webext-core/match-patterns';
export function reloadContentScript(contentScript: Manifest.ContentScript) {
const manifest = browser.runtime.getManifest();
if (manifest.manifest_version == 2) {
void reloadContentScriptMv2(contentScript);
} else {
void reloadContentScriptMv3(contentScript);
}
}
export async function reloadContentScriptMv3(
contentScript: Manifest.ContentScript,
) {
const id = `wxt:${contentScript.js![0]}`;
logger.log('Reloading content script:', contentScript);
const registered = await browser.scripting.getRegisteredContentScripts();
logger.debug('Existing scripts:', registered);
const existing = registered.find((cs) => cs.id === id);
if (existing) {
logger.debug('Updating content script', existing);
await browser.scripting.updateContentScripts([{ ...contentScript, id }]);
} else {
logger.debug('Registering new content script...');
await browser.scripting.registerContentScripts([{ ...contentScript, id }]);
}
const allTabs = await browser.tabs.query({});
const matchPatterns = contentScript.matches.map(
(match) => new MatchPattern(match),
);
const matchingTabs = allTabs.filter((tab) => {
const url = tab.url;
if (!url) return false;
return !!matchPatterns.find((pattern) => pattern.includes(url));
});
await Promise.all(matchingTabs.map((tab) => browser.tabs.reload(tab.id)));
}
export async function reloadContentScriptMv2(
contentScript: Manifest.ContentScript,
) {
throw Error('TODO: reloadContentScriptMv2');
}
@@ -3,15 +3,26 @@ import { setupWebSocket } from '../utils/setupWebSocket';
import { logger } from '../utils/logger';
import browser from 'webextension-polyfill';
import { keepServiceWorkerAlive } from '../utils/keepServiceWorkerAlive';
import { reloadContentScript } from '../utils/reloadContentScript';
if (__COMMAND__ === 'serve') {
try {
setupWebSocket((message) => {
const ws = setupWebSocket((message) => {
if (message.event === 'wxt:reload-extension') browser.runtime.reload();
if (message.event === 'wxt:reload-content-script' && message.data != null)
reloadContentScript(message.data);
});
// Web Socket will disconnect if the service worker is killed
keepServiceWorkerAlive();
if (__MANIFEST_VERSION__ === 3) {
// Tell the server the background script is loaded and ready to go
ws.addEventListener('open', () => {
const msg = { type: 'custom', event: 'wxt:background-initialized' };
ws.send(JSON.stringify(msg));
});
// Web Socket will disconnect if the service worker is killed
keepServiceWorkerAlive();
}
} catch (err) {
logger.error('Failed to setup web socket connection with dev server', err);
}
@@ -0,0 +1,3 @@
import { fakeBrowser as browser } from '@webext-core/fake-browser';
export default browser;
@@ -20,3 +20,4 @@ declare const __COMMAND__: 'build' | 'serve';
declare const __DEV_SERVER_PROTOCOL__: string;
declare const __DEV_SERVER_HOSTNAME__: string;
declare const __DEV_SERVER_PORT__: string;
declare const __MANIFEST_VERSION__: 2 | 3;
+106
View File
@@ -0,0 +1,106 @@
import { Manifest } from 'webextension-polyfill';
import { BuildOutput } from './types';
import { buildEntrypoints } from './build/buildEntrypoints';
import { findEntrypoints } from './build/findEntrypoints';
import { generateTypesDir } from './build/generateTypesDir';
import { InternalConfig, EntrypointGroup } from './types';
import { generateMainfest, writeManifest } from './utils/manifest';
import pc from 'picocolors';
import * as vite from 'vite';
import fs from 'fs-extra';
import { groupEntrypoints } from './utils/groupEntrypoints';
import { formatDuration } from './utils/formatDuration';
import { printBuildSummary } from './log/printBuildSummary';
/**
* Builds the extension based on an internal config.
*
* This function:
* 1. Cleans the output directory
* 2. Executes the rebuild function with a blank previous output so everything is built (see
* `rebuild` for more details)
* 3. Prints the summary
*/
export async function buildInternal(
config: InternalConfig,
): Promise<BuildOutput> {
const verb = config.command === 'serve' ? 'Pre-rendering' : 'Building';
const target = `${config.browser}-mv${config.manifestVersion}`;
config.logger.info(
`${verb} ${pc.cyan(target)} for ${pc.cyan(config.mode)} with ${pc.green(
`Vite ${vite.version}`,
)}`,
);
const startTime = Date.now();
// Cleanup
await fs.rm(config.outDir, { recursive: true, force: true });
await fs.ensureDir(config.outDir);
const entrypoints = await findEntrypoints(config);
const groups = groupEntrypoints(entrypoints);
const { output } = await rebuild(config, groups);
// Post-build
config.logger.success(
`Built extension in ${formatDuration(Date.now() - startTime)}`,
);
await printBuildSummary(output, config);
return output;
}
/**
* Given a configuration, list of entrypoints, and an existing, partial output, build the
* entrypoints and merge the new output with the existing output.
*
* This function will:
* 1. Generate the .wxt directory's types
* 2. Build the `entrypointGroups` (and copies public files)
* 3. Generate the latest manifest for all entrypoints
* 4. Write the new manifest to the file system
*/
export async function rebuild(
config: InternalConfig,
entrypointGroups: EntrypointGroup[],
existingOutput: Omit<BuildOutput, 'manifest'> = {
steps: [],
publicAssets: [],
},
): Promise<{ output: BuildOutput; manifest: Manifest.WebExtensionManifest }> {
// Update types directory with new files and types
const allEntrypoints = await findEntrypoints(config);
await generateTypesDir(allEntrypoints, config);
// Build and merge the outputs
const newOutput = await buildEntrypoints(entrypointGroups, config);
const mergedOutput: Omit<BuildOutput, 'manifest'> = {
steps: [...existingOutput.steps, ...newOutput.steps],
publicAssets: [...existingOutput.publicAssets, ...newOutput.publicAssets],
};
const newManifest = await generateMainfest(
allEntrypoints,
mergedOutput,
config,
);
const finalOutput: BuildOutput = {
manifest: newManifest,
...newOutput,
};
// Write manifest
await writeManifest(newManifest, finalOutput, config);
return {
output: {
manifest: newManifest,
steps: [...existingOutput.steps, ...finalOutput.steps],
publicAssets: [
...existingOutput.publicAssets,
...finalOutput.publicAssets,
],
},
manifest: newManifest,
};
}
@@ -7,10 +7,11 @@ import {
PopupEntrypoint,
} from '../../types';
import { resolve } from 'path';
import { FindEntrypointsConfig, findEntrypoints } from '../findEntrypoints';
import { findEntrypoints } from '../findEntrypoints';
import fs from 'fs-extra';
import { importTsFile } from '../../utils/importTsFile';
import glob from 'fast-glob';
import { fakeInternalConfig } from '../../../testing/fake-objects';
vi.mock('../../utils/importTsFile');
const importTsFileMock = vi.mocked(importTsFile);
@@ -24,24 +25,11 @@ const readFileMock = vi.mocked(
);
describe('findEntrypoints', () => {
const config: FindEntrypointsConfig = {
const config = fakeInternalConfig({
root: '/',
entrypointsDir: resolve('/src/entrypoints'),
outDir: resolve('.output'),
logger: {
debug: vi.fn(),
error: vi.fn(),
fatal: (...args) => {
throw Error('logger.fatal called with: ' + JSON.stringify(args));
},
info: vi.fn(),
log: vi.fn(),
warn: vi.fn(),
success: vi.fn(),
},
command: 'build',
mode: 'production',
};
});
it.each<[string, string, PopupEntrypoint]>([
[
@@ -189,7 +177,7 @@ describe('findEntrypoints', () => {
expect(entrypoints).toHaveLength(1);
expect(entrypoints[0]).toEqual({ ...expected, options });
expect(importTsFileMock).toBeCalledWith(config.root, expected.inputPath);
expect(importTsFileMock).toBeCalledWith(expected.inputPath, config);
},
);
@@ -216,7 +204,7 @@ describe('findEntrypoints', () => {
expect(entrypoints).toHaveLength(1);
expect(entrypoints[0]).toEqual({ ...expected, options });
expect(importTsFileMock).toBeCalledWith(config.root, expected.inputPath);
expect(importTsFileMock).toBeCalledWith(expected.inputPath, config);
},
);
+4 -4
View File
@@ -45,12 +45,12 @@ async function buildSingleEntrypoint(
? `virtual:wxt-${entrypoint.type}?${entrypoint.inputPath}`
: entrypoint.inputPath;
const libMode: vite.InlineConfig = {
const libMode: vite.UserConfig = {
build: {
lib: {
entry,
formats: ['iife'],
name: entrypoint.name,
name: '_',
fileName: entrypoint.name,
},
rollupOptions: {
@@ -89,7 +89,7 @@ async function buildMultipleEntrypoints(
entrypoints: Entrypoint[],
config: InternalConfig,
): Promise<BuildStepOutput> {
const multiPage: vite.InlineConfig = {
const multiPage: vite.UserConfig = {
plugins: [plugins.multipageMove(entrypoints, config)],
build: {
rollupOptions: {
@@ -112,7 +112,7 @@ async function buildMultipleEntrypoints(
const entryConfig = vite.mergeConfig(
multiPage,
config.vite,
) as vite.InlineConfig;
) as vite.UserConfig;
const result = await vite.build(entryConfig);
return {
+7 -12
View File
@@ -21,7 +21,7 @@ import { getEntrypointName } from '../utils/entrypoints';
* Return entrypoints and their configuration by looking through the
*/
export async function findEntrypoints(
config: FindEntrypointsConfig,
config: InternalConfig,
): Promise<Entrypoint[]> {
const relativePaths = await glob('**/*', {
cwd: config.entrypointsDir,
@@ -103,7 +103,7 @@ export async function findEntrypoints(
* @param content String contents of the file at the path.
*/
async function getPopupEntrypoint(
config: FindEntrypointsConfig,
config: InternalConfig,
path: string,
): Promise<PopupEntrypoint> {
const options: PopupEntrypoint['options'] = {};
@@ -150,7 +150,7 @@ async function getPopupEntrypoint(
* @param content String contents of the file at the path.
*/
async function getOptionsEntrypoint(
config: FindEntrypointsConfig,
config: InternalConfig,
path: string,
): Promise<OptionsEntrypoint> {
const options: OptionsEntrypoint['options'] = {};
@@ -192,11 +192,11 @@ async function getOptionsEntrypoint(
* @param path Absolute path to the background's TS file.
*/
async function getBackgroundEntrypoint(
config: FindEntrypointsConfig,
config: InternalConfig,
path: string,
): Promise<BackgroundEntrypoint> {
const { main: _, ...options } =
await importTsFile<BackgroundScriptDefintition>(config.root, path);
await importTsFile<BackgroundScriptDefintition>(path, config);
if (options == null) {
throw Error('Background script does not have a default export');
}
@@ -213,13 +213,13 @@ async function getBackgroundEntrypoint(
* @param path Absolute path to the content script's TS file.
*/
async function getContentScriptEntrypoint(
config: FindEntrypointsConfig,
config: InternalConfig,
name: string,
path: string,
): Promise<ContentScriptEntrypoint> {
const { main: _, ...options } = await importTsFile<ContentScriptDefinition>(
config.root,
path,
config,
);
if (options == null) {
throw Error(`Content script ${name} does not have a default export`);
@@ -274,8 +274,3 @@ const PATH_GLOB_TO_TYPE_MAP: Record<string, Entrypoint['type'] | 'ignored'> = {
// Don't warn about any files in subdirectories, like CSS or JS entrypoints for HTML files
'*/*': 'ignored',
};
export type FindEntrypointsConfig = Pick<
InternalConfig,
'root' | 'entrypointsDir' | 'outDir' | 'logger' | 'mode' | 'command'
>;
+26 -11
View File
@@ -48,22 +48,23 @@ async function writePathsDeclarationFile(
config: InternalConfig,
): Promise<string> {
const filePath = resolve(config.typesDir, 'paths.d.ts');
const unions = entrypoints
.map((entry) => {
const path = getEntrypointBundlePath(
entry,
config.outDir,
entry.inputPath.endsWith('.html') ? '.html' : '.js',
);
return ` | "/${path}"`;
})
.sort();
await fs.writeFile(
filePath,
[
'// Generated by wxt',
'type EntrypointPath =',
...entrypoints
.map((entry) => {
const path = getEntrypointBundlePath(
entry,
config.outDir,
entry.inputPath.endsWith('.html') ? '.html' : '.js',
);
return ` | "/${path}"`;
})
.sort(),
...(unions.length === 0 ? [' never'] : unions),
].join('\n') + '\n',
);
@@ -99,6 +100,7 @@ async function writeMainDeclarationFile(
filePath,
[
'// Generated by wxt',
`/// <reference types="vite/client" />`,
...references.map(
(ref) => `/// <reference types="./${relative(dir, ref)}" />`,
),
@@ -128,7 +130,20 @@ async function writeTsConfigFile(
"strict": true,
/* Completeness */
"skipLibCheck": true
"skipLibCheck": true,
/* Aliases */
"baseUrl": "${relative(dir, config.root)}",
"paths": {
"@@": ["."],
"@@/*": ["./*"],
"~~": ["."],
"~~/*": ["./*"],
"@": ["${relative(config.root, config.srcDir)}"],
"@/*": ["${relative(config.root, config.srcDir)}/*"],
"~": ["${relative(config.root, config.srcDir)}"],
"~/*": ["${relative(config.root, config.srcDir)}/*"]
}
},
"include": [
"${relative(dir, config.root)}/**/*",
+19 -11
View File
@@ -1,4 +1,4 @@
import path, { extname, relative, resolve } from 'path';
import path, { relative, resolve } from 'path';
import { BuildOutput, InternalConfig } from '../types';
import { printTable } from './printTable';
import pc from 'picocolors';
@@ -13,14 +13,8 @@ export async function printBuildSummary(
...output.steps.flatMap((step) => step.chunks),
...output.publicAssets,
].sort((l, r) => {
const lWeight =
CHUNK_SORT_WEIGHTS[l.fileName] ??
CHUNK_SORT_WEIGHTS[extname(l.fileName)] ??
DEFAULT_SORT_WEIGHT;
const rWeight =
CHUNK_SORT_WEIGHTS[r.fileName] ??
CHUNK_SORT_WEIGHTS[extname(r.fileName)] ??
DEFAULT_SORT_WEIGHT;
const lWeight = getChunkSortWeight(l.fileName);
const rWeight = getChunkSortWeight(r.fileName);
const diff = lWeight - rWeight;
if (diff !== 0) return diff;
return l.fileName.localeCompare(r.fileName);
@@ -34,9 +28,8 @@ export async function printBuildSummary(
relative(process.cwd(), config.outDir) + path.sep,
chunk.fileName,
];
const ext = extname(chunk.fileName);
const prefix = i === chunks.length - 1 ? ' └─' : ' ├─';
const color = CHUNK_COLORS[ext] ?? DEFAULT_COLOR;
const color = getChunkColor(chunk.fileName);
const stats = await fs.lstat(resolve(config.outDir, chunk.fileName));
totalSize += stats.size;
const size = String(filesize(stats.size));
@@ -58,13 +51,28 @@ const DEFAULT_SORT_WEIGHT = 100;
const CHUNK_SORT_WEIGHTS: Record<string, number> = {
'manifest.json': 0,
'.html': 1,
'.js.map': 2,
'.js': 2,
'.css': 3,
};
function getChunkSortWeight(filename: string) {
return (
Object.entries(CHUNK_SORT_WEIGHTS).find(([key]) =>
filename.endsWith(key),
)?.[1] ?? DEFAULT_SORT_WEIGHT
);
}
const DEFAULT_COLOR = pc.blue;
const CHUNK_COLORS: Record<string, (text: string) => string> = {
'.js.map': pc.gray,
'.html': pc.green,
'.css': pc.magenta,
'.js': pc.cyan,
};
function getChunkColor(filename: string) {
return (
Object.entries(CHUNK_COLORS).find(([key]) => filename.endsWith(key))?.[1] ??
DEFAULT_COLOR
);
}
+131
View File
@@ -0,0 +1,131 @@
import {
BuildStepOutput,
EntrypointGroup,
InternalConfig,
WxtDevServer,
} from './types';
import * as vite from 'vite';
import { findOpenPort } from './utils/findOpenPort';
import { Manifest } from 'webextension-polyfill';
import { getEntrypointBundlePath } from './utils/entrypoints';
import { getContentScriptCssFiles } from './utils/manifest';
import { createWebExtRunner } from './runners/createWebExtRunner';
import { buildInternal } from './build';
export async function getServerInfo(): Promise<ServerInfo> {
const port = await findOpenPort(3000, 3010);
const hostname = 'localhost';
const origin = `http://${hostname}:${port}`;
const serverConfig: vite.InlineConfig = {
server: {
origin,
},
};
return {
port,
hostname,
origin,
viteServerConfig: serverConfig,
};
}
export async function setupServer(
serverInfo: ServerInfo,
config: InternalConfig,
): Promise<WxtDevServer> {
const runner = createWebExtRunner();
const viteServer = await vite.createServer(
vite.mergeConfig(serverInfo, config.vite),
);
const start = async () => {
await viteServer.listen(server.port);
config.logger.success(`Started dev server @ ${serverInfo.origin}`);
server.currentOutput = await buildInternal(config);
config.logger.info('Opening browser...');
await runner.openBrowser(config);
config.logger.success('Opened!');
};
const reloadExtension = () => {
viteServer.ws.send('wxt:reload-extension');
};
const reloadPage = (path: string) => {
// Can't use Vite's built-in "full-reload" event because it doesn't like our paths, it expects
// paths ending in "/index.html"
viteServer.ws.send('wxt:reload-page', path);
};
const reloadContentScript = (contentScript: Manifest.ContentScript) => {
viteServer.ws.send('wxt:reload-content-script', contentScript);
};
const server: WxtDevServer = {
...viteServer,
start,
currentOutput: {
manifest: {
manifest_version: 3,
name: '',
version: '',
},
publicAssets: [],
steps: [],
},
port: serverInfo.port,
hostname: serverInfo.hostname,
origin: serverInfo.origin,
reloadExtension,
reloadPage,
reloadContentScript,
};
return server;
}
/**
* From the server, tell the client to reload content scripts from the provided build step outputs.
*/
export function reloadContentScripts(
steps: BuildStepOutput[],
config: InternalConfig,
server: WxtDevServer,
) {
if (config.manifestVersion === 3) {
steps.forEach((step) => {
const entry = step.entrypoints;
if (Array.isArray(entry) || entry.type !== 'content-script') return;
const js = [getEntrypointBundlePath(entry, config.outDir, '.js')];
const css = getContentScriptCssFiles([entry], server.currentOutput);
server.reloadContentScript({
js,
css,
...entry.options,
});
});
} else {
server.reloadExtension();
}
}
export function reloadHtmlPages(
groups: EntrypointGroup[],
server: WxtDevServer,
config: InternalConfig,
) {
groups.flat().forEach((entry) => {
const path = getEntrypointBundlePath(entry, config.outDir, '.html');
server.reloadPage(path);
});
}
interface ServerInfo {
port: number;
hostname: string;
origin: string;
viteServerConfig: vite.InlineConfig;
}
+33 -3
View File
@@ -19,8 +19,8 @@ export interface InlineConfig {
browser?: TargetBrowser;
manifestVersion?: TargetManifestVersion;
logger?: Logger;
vite?: Omit<vite.InlineConfig, 'root' | 'configFile' | 'mode'>;
manifest?: UserManifest;
vite?: Omit<vite.UserConfig, 'root' | 'configFile' | 'mode'>;
manifest?: UserManifest | Promise<UserManifest> | UserManifestFn;
server?: WxtDevServer;
runner?: ExtensionRunnerConfig;
}
@@ -54,6 +54,14 @@ export interface WxtDevServer extends vite.ViteDevServer {
* Ex: `"http://localhost:3000"`
*/
origin: string;
/**
* Stores the current build output of the server.
*/
currentOutput: BuildOutput;
/**
* Start the server on the first open port.
*/
start(): Promise<void>;
/**
* Tell the extension to reload by running `browser.runtime.reload`.
*/
@@ -70,6 +78,12 @@ export interface WxtDevServer extends vite.ViteDevServer {
* server.reloadPage("sandbox.html")
*/
reloadPage: (path: string) => void;
/**
* Tell the extension to restart a content script.
*
* @param contentScript The manifest definition for a content script
*/
reloadContentScript: (contentScript: Manifest.ContentScript) => void;
}
export type TargetBrowser = 'chrome' | 'firefox' | 'safari' | 'edge' | 'opera';
@@ -125,7 +139,6 @@ export interface GenericEntrypoint extends BaseEntrypoint {
| 'sidepanel'
| 'devtools'
| 'unlisted-page'
| 'unlisted-page'
| 'unlisted-script';
}
@@ -213,6 +226,23 @@ export type UserManifest = Omit<
| 'version_name'
>;
export type UserManifestFn = (
env: ConfigEnv,
) => UserManifest | Promise<UserManifest>;
export interface ConfigEnv {
mode: string;
command: 'build' | 'serve';
/**
* Browser passed in from the CLI
*/
browser: TargetBrowser;
/**
* Manifest version passed in from the CLI
*/
manifestVersion: 2 | 3;
}
/**
* Configure how the browser starts up.
*/
+18
View File
@@ -0,0 +1,18 @@
import { describe, it, expect } from 'vitest';
import { every } from '../arrays';
describe('Array Utils', () => {
describe('every', () => {
it('should return true when the array is empty', () => {
expect(every([], () => false)).toBe(true);
});
it("should return true when all item predicate's return true", () => {
expect(every([1, 1, 1], (item) => item === 1)).toBe(true);
});
it("should return false when a single item predicate's return false", () => {
expect(every([1, 2, 1], (item) => item === 1)).toBe(false);
});
});
});
@@ -4,7 +4,10 @@ import {
fakeBackgroundEntrypoint,
fakeContentScriptEntrypoint,
fakeFile,
fakeGenericEntrypoint,
fakeManifest,
fakeOptionsEntrypoint,
fakePopupEntrypoint,
fakeRollupOutputAsset,
fakeRollupOutputChunk,
} from '../../../testing/fake-objects';
@@ -129,4 +132,120 @@ describe('Detect Dev Changes', () => {
expect(actual).toEqual(expected);
});
});
describe('HTML Pages', () => {
it('should rebuild then reload only the effected pages', async () => {
const changedPath = '/root/page1/index.html';
const htmlPage1 = fakePopupEntrypoint({
inputPath: changedPath,
});
const htmlPage2 = fakeOptionsEntrypoint({
inputPath: '/root/page2.html',
});
const htmlPage3 = fakeGenericEntrypoint({
type: 'sandbox',
inputPath: '/root/page3.html',
});
const step1: BuildStepOutput = {
entrypoints: [htmlPage1, htmlPage2],
chunks: [
fakeRollupOutputChunk({
moduleIds: [fakeFile(), changedPath],
}),
],
};
const step2: BuildStepOutput = {
entrypoints: [htmlPage3],
chunks: [
fakeRollupOutputChunk({
moduleIds: [fakeFile(), fakeFile(), fakeFile()],
}),
],
};
const currentOutput: BuildOutput = {
manifest: fakeManifest(),
publicAssets: [],
steps: [step1, step2],
};
const expected: DevModeChange = {
type: 'html-reload',
cachedOutput: {
...currentOutput,
steps: [step2],
},
rebuildGroups: [[htmlPage1, htmlPage2]],
};
const actual = detectDevChanges(
[['unknown', changedPath]],
currentOutput,
);
expect(actual).toEqual(expected);
});
});
describe('Content Scripts', () => {
it('should rebuild then reload only the effected content scripts', async () => {
const changedPath = '/root/utils/shared.ts';
const script1 = fakeContentScriptEntrypoint({
inputPath: '/root/overlay1.content/index.ts',
});
const script2 = fakeContentScriptEntrypoint({
inputPath: '/root/overlay2.ts',
});
const script3 = fakeContentScriptEntrypoint({
inputPath: '/root/overlay3.content/index.ts',
});
const step1: BuildStepOutput = {
entrypoints: script1,
chunks: [
fakeRollupOutputChunk({
moduleIds: [fakeFile(), changedPath],
}),
],
};
const step2: BuildStepOutput = {
entrypoints: script2,
chunks: [
fakeRollupOutputChunk({
moduleIds: [fakeFile(), fakeFile(), fakeFile()],
}),
],
};
const step3: BuildStepOutput = {
entrypoints: script3,
chunks: [
fakeRollupOutputChunk({
moduleIds: [changedPath, fakeFile(), fakeFile()],
}),
],
};
const currentOutput: BuildOutput = {
manifest: fakeManifest(),
publicAssets: [],
steps: [step1, step2, step3],
};
const expected: DevModeChange = {
type: 'content-script-reload',
cachedOutput: {
...currentOutput,
steps: [step2],
},
changedSteps: [step1, step3],
rebuildGroups: [script1, script3],
};
const actual = detectDevChanges(
[['unknown', changedPath]],
currentOutput,
);
expect(actual).toEqual(expected);
});
});
});
+11
View File
@@ -0,0 +1,11 @@
/**
* Checks if `predicate` returns truthy for all elements of the array.
*/
export function every<T>(
array: T[],
predicate: (item: T, index: number) => boolean,
): boolean {
for (let i = 0; i < array.length; i++)
if (!predicate(array[i], i)) return false;
return true;
}
+28 -8
View File
@@ -1,5 +1,6 @@
import { BuildOutput, BuildStepOutput, EntrypointGroup } from '../types';
import * as vite from 'vite';
import { every } from './arrays';
/**
* Compare the changed files vs the build output and determine what kind of reload needs to happen:
@@ -60,9 +61,9 @@ export function detectDevChanges(
}
}
const isOnlyHtmlChanges = !changedFiles.find(
([_, file]) => !file.endsWith('.html'),
);
const isOnlyHtmlChanges =
changedFiles.length > 0 &&
every(changedFiles, ([_, file]) => file.endsWith('.html'));
if (isOnlyHtmlChanges) {
return {
type: 'html-reload',
@@ -71,6 +72,21 @@ export function detectDevChanges(
};
}
const isOnlyContentScripts =
changedOutput.steps.length > 0 &&
every(
changedOutput.steps.flatMap((step) => step.entrypoints),
(entry) => entry.type === 'content-script',
);
if (isOnlyContentScripts) {
return {
type: 'content-script-reload',
cachedOutput: unchangedOutput,
changedSteps: changedOutput.steps,
rebuildGroups: changedOutput.steps.map((step) => step.entrypoints),
};
}
return {
type: 'extension-reload',
cachedOutput: unchangedOutput,
@@ -114,9 +130,12 @@ function findEffectedSteps(
* Contains information about what files changed, what needs rebuilt, and the type of reload that is
* required.
*/
export type DevModeChange = NoChange | HtmlReload | ExtensionReload;
export type DevModeChange =
| NoChange
| HtmlReload
| ExtensionReload
| ContentScriptReload;
// | BrowserRestart
// | ContentScriptReload
interface NoChange {
type: 'no-change';
@@ -145,9 +164,10 @@ interface ExtensionReload extends RebuildChange {
// type: 'browser-restart';
// }
// interface ContentScriptReload extends RebuildChange {
// type: 'content-script-reload';
// }
interface ContentScriptReload extends RebuildChange {
type: 'content-script-reload';
changedSteps: BuildStepOutput[];
}
/**
* When figuring out what needs reloaded, this stores the step that was changed, or the public
+32 -7
View File
@@ -1,13 +1,15 @@
import {
ConfigEnv,
ExtensionRunnerConfig,
InlineConfig,
InternalConfig,
UserConfig,
UserManifest,
UserManifestFn,
} from '../types';
import path, { resolve } from 'node:path';
import * as vite from 'vite';
import { consola } from 'consola';
import { importTsFile } from './importTsFile';
import * as plugins from '../vite-plugins';
import { createFsCache } from './createFsCache';
import { getGlobals } from './globals';
@@ -43,7 +45,6 @@ export async function getInternalConfig(
command,
logger,
vite: config.vite ?? {},
manifest: config.manifest ?? {},
imports: config.imports ?? {},
runnerConfig: await loadConfig<ExtensionRunnerConfig>({
name: 'web-ext',
@@ -59,10 +60,12 @@ export async function getInternalConfig(
mode,
};
if (config.configFile !== false) {
userConfig = await importTsFile<UserConfig>(
root,
path.resolve(root, config.configFile ?? 'wxt.config.ts'),
);
const loaded = await loadConfig<UserConfig>({
name: 'wxt',
cwd: root,
rcFile: false,
});
userConfig = loaded.config ?? {};
}
// Merge inline and user configs
@@ -81,6 +84,12 @@ export async function getInternalConfig(
const wxtDir = resolve(srcDir, '.wxt');
const typesDir = resolve(wxtDir, 'types');
// Merge manifest sources
const env: ConfigEnv = { mode, browser, manifestVersion, command };
const userManifest = await resolveManifestConfig(env, userConfig.manifest);
const inlineManifest = await resolveManifestConfig(env, config.manifest);
const manifest = vite.mergeConfig(userManifest, inlineManifest);
const finalConfig: InternalConfig = {
...merged,
srcDir,
@@ -89,6 +98,7 @@ export async function getInternalConfig(
wxtDir: wxtDir,
typesDir,
fsCache: createFsCache(wxtDir),
manifest,
};
// Customize the default vite config
@@ -126,5 +136,20 @@ export async function getInternalConfig(
*/
type InternalConfigNoUserDirs = Omit<
InternalConfig,
'srcDir' | 'publicDir' | 'entrypointsDir' | 'wxtDir' | 'typesDir' | 'fsCache'
| 'srcDir'
| 'publicDir'
| 'entrypointsDir'
| 'wxtDir'
| 'typesDir'
| 'fsCache'
| 'manifest'
>;
async function resolveManifestConfig(
env: ConfigEnv,
manifest: UserManifest | Promise<UserManifest> | UserManifestFn | undefined,
): Promise<UserManifest> {
return await (typeof manifest === 'function'
? manifest(env)
: manifest ?? {});
}
+50 -27
View File
@@ -1,44 +1,67 @@
import { consola } from 'consola';
import createJITI from 'jiti';
import transform from 'jiti/dist/babel';
import { InternalConfig } from '../types';
import { createUnimport } from 'unimport';
import fs from 'fs-extra';
import { resolve } from 'path';
import { scanExports } from 'unimport';
import transform from 'jiti/dist/babel';
import { getUnimportOptions } from './auto-imports';
export async function importTsFile<T>(root: string, path: string): Promise<T> {
const clientImports = await scanExports(
resolve(root, 'node_modules/wxt/dist/client.js'),
/**
* Get the value from the default export of a `path`.
*
* It works by:
*
* 1. Reading the file text
* 2. Stripping all imports from it via regex
* 3. Auto-import only the client helper functions
*
* This prevents resolving imports of imports, speeding things up and preventing "xxx is not
* defined" errors.
*
* Downside is that code cannot be executed outside of the main fucntion for the entrypoint,
* otherwise you will see "xxx is not defined" errors for any imports used outside of main function.
*/
export async function importTsFile<T>(
path: string,
config: InternalConfig,
): Promise<T> {
config.logger.debug('Loading file metadata:', path);
const unimport = createUnimport({
...getUnimportOptions(config),
// Only allow specific imports, not all from the project
imports: [{ name: '*', as: 'browser', from: 'webextension-polyfill' }],
dirs: [],
});
await unimport.init();
const text = await fs.readFile(path, 'utf-8');
const textNoImports = text.replace(/import.*[\n;]/gm, '');
const { code } = await unimport.injectImports(textNoImports);
config.logger.debug(
['Text:', text, 'No imports:', textNoImports, 'Code:', code].join('\n'),
);
const jiti = createJITI(__filename, {
cache: false,
esmResolve: true,
interopDefault: true,
alias: {
'webextension-polyfill': resolve(
config.root,
'node_modules/wxt/dist/virtual-modules/fake-browser.js',
),
},
transform(opts) {
// Remove CSS imports from the source code - Jiti can't handle them.
opts.source = opts.source.replace(/^import ['"].*\.css['"];?$/gm, '');
opts.source = opts.source.replace(
/^import\s+.*\s+from ['"]webextension-polyfill['"];?$/gm,
'',
);
// Append any wxt/client functions so babel doesn't complain about undefined variables
if (opts.filename === path) {
// TODO: Only append import if it isn't already imported
const imports =
clientImports
.map((i) => `import { ${i.name} } from "${i.from}";`)
.join('\n') + '\n';
opts.source = imports + opts.source;
}
// Call the default babel transformer with our modified source code
return transform(opts);
if (opts.filename === path) return transform({ ...opts, source: code });
else return transform(opts);
},
});
try {
return await jiti(path);
} catch (err) {
consola.error(`Failed to import file: ${path}`);
config.logger.error(err);
throw err;
}
}
+42 -17
View File
@@ -65,6 +65,7 @@ export async function generateMainfest(
addEntrypoints(manifest, entrypoints, buildOutput, config);
if (config.command === 'serve') addDevModeCsp(manifest, config);
if (config.command === 'serve') addDevModePermissions(manifest, config);
return manifest;
}
@@ -270,24 +271,23 @@ function addEntrypoints(
}
if (contentScripts?.length) {
if (config.command === 'serve') {
const permissionsKey =
config.manifestVersion === 2 ? 'permissions' : 'host_permissions';
const hostPermissions = new Set<string>(manifest[permissionsKey] ?? []);
// Don't add content scripts to the manifest in dev mode for MV3 - they're managed and reloaded
// at runtime
if (config.command === 'serve' && config.manifestVersion === 3) {
const hostPermissions = new Set<string>(manifest.host_permissions ?? []);
contentScripts.forEach((script) => {
script.options.matches.forEach((matchPattern) => {
hostPermissions.add(matchPattern);
});
});
manifest[permissionsKey] = Array.from(hostPermissions).sort();
hostPermissions.forEach((permission) =>
addHostPermission(manifest, permission),
);
} else {
const hashToEntrypointsMap = contentScripts.reduce((map, script) => {
const hash = JSON.stringify(script.options);
if (!map.has(hash)) {
map.set(hash, [script]);
} else {
map.get(hash)?.push(script);
}
if (map.has(hash)) map.get(hash)?.push(script);
else map.set(hash, [script]);
return map;
}, new Map<string, ContentScriptEntrypoint[]>());
@@ -316,13 +316,9 @@ function addDevModeCsp(
const allowedCsp = config.server?.origin ?? 'http://localhost:*';
if (manifest.manifest_version === 3) {
manifest.host_permissions ??= [];
if (!manifest.host_permissions.includes(permission))
manifest.host_permissions.push(permission);
addHostPermission(manifest, permission);
} else {
manifest.permissions ??= [];
if (!manifest.permissions.includes(permission))
manifest.permissions.push(permission);
addPermission(manifest, permission);
}
const csp = new ContentSecurityPolicy(
@@ -345,11 +341,22 @@ function addDevModeCsp(
}
}
function addDevModePermissions(
manifest: Manifest.WebExtensionManifest,
config: InternalConfig,
) {
// For reloading the page
addPermission(manifest, 'tabs');
// For registering content scripts
if (config.manifestVersion === 3) addPermission(manifest, 'scripting');
}
/**
* Returns the bundle paths to CSS files associated with a list of content scripts, or undefined if
* there is no associated CSS.
*/
function getContentScriptCssFiles(
export function getContentScriptCssFiles(
contentScripts: ContentScriptEntrypoint[],
buildOutput: Omit<BuildOutput, 'manifest'>,
): string[] | undefined {
@@ -368,3 +375,21 @@ function getContentScriptCssFiles(
if (css.length > 0) return css;
return undefined;
}
function addPermission(
manifest: Manifest.WebExtensionManifest,
permission: string,
): void {
manifest.permissions ??= [];
if (manifest.permissions.includes(permission)) return;
manifest.permissions.push(permission);
}
function addHostPermission(
manifest: Manifest.WebExtensionManifest,
hostPermission: string,
): void {
manifest.host_permissions ??= [];
if (manifest.host_permissions.includes(hostPermission)) return;
manifest.host_permissions.push(hostPermission);
}
+9 -12
View File
@@ -11,20 +11,17 @@ export function devHtmlPrerender(config: InternalConfig): vite.Plugin {
return {
apply: 'build',
name: 'wxt:dev-html-prerender',
config(userConfig) {
return vite.mergeConfig(
{
resolve: {
alias: {
'@wxt/reload-html': resolve(
config.root,
'node_modules/wxt/dist/virtual-modules/reload-html.js',
),
},
config() {
return {
resolve: {
alias: {
'@wxt/reload-html': resolve(
config.root,
'node_modules/wxt/dist/virtual-modules/reload-html.js',
),
},
},
userConfig,
);
};
},
async transform(html, id) {
const server = config.server;
+10 -9
View File
@@ -7,18 +7,19 @@ import { InternalConfig } from '../types';
export function devServerGlobals(internalConfig: InternalConfig): Plugin {
return {
name: 'wxt:dev-server-globals',
config(config) {
config() {
if (internalConfig.server == null || internalConfig.command == 'build')
return;
config.define ??= {};
config.define.__DEV_SERVER_PROTOCOL__ = JSON.stringify('ws:');
config.define.__DEV_SERVER_HOSTNAME__ = JSON.stringify(
internalConfig.server.hostname,
);
config.define.__DEV_SERVER_PORT__ = JSON.stringify(
internalConfig.server.port,
);
return {
define: {
__DEV_SERVER_PROTOCOL__: JSON.stringify('ws:'),
__DEV_SERVER_HOSTNAME__: JSON.stringify(
internalConfig.server.hostname,
),
__DEV_SERVER_PORT__: JSON.stringify(internalConfig.server.port),
},
};
},
};
}
+12 -1
View File
@@ -2,6 +2,16 @@ import { createUnimport } from 'unimport';
import { InternalConfig } from '../types';
import { getUnimportOptions } from '../utils/auto-imports';
import { Plugin } from 'vite';
import { extname } from 'path';
const ENABLED_EXTENSIONS: Record<string, boolean | undefined> = {
'.js': true,
'.jsx': true,
'.ts': true,
'.tsx': true,
'.vue': true,
'.svelte': true,
};
/**
* Inject any global imports defined by unimport
@@ -16,7 +26,8 @@ export function unimport(config: InternalConfig): Plugin {
await unimport.scanImportsFromDir(undefined, { cwd: config.srcDir });
},
async transform(code, id) {
return unimport.injectImports(code, id);
const ext = extname(id);
if (ENABLED_EXTENSIONS[ext]) return unimport.injectImports(code, id);
},
};
}
+35 -145
View File
@@ -1,32 +1,19 @@
import {
BuildOutput,
WxtDevServer,
InlineConfig,
InternalConfig,
EntrypointGroup,
} from './core/types';
import { BuildOutput, WxtDevServer, InlineConfig } from './core/types';
import { getInternalConfig } from './core/utils/getInternalConfig';
import { findEntrypoints } from './core/build/findEntrypoints';
import { buildEntrypoints } from './core/build/buildEntrypoints';
import { generateMainfest, writeManifest } from './core/utils/manifest';
import { printBuildSummary } from './core/log/printBuildSummary';
import fs from 'fs-extra';
import { generateTypesDir } from './core/build/generateTypesDir';
import pc from 'picocolors';
import * as vite from 'vite';
import { findOpenPort } from './core/utils/findOpenPort';
import { formatDuration } from './core/utils/formatDuration';
import { createWebExtRunner } from './core/runners/createWebExtRunner';
import { groupEntrypoints } from './core/utils/groupEntrypoints';
import { Manifest } from 'webextension-polyfill';
import { detectDevChanges } from './core/utils/detectDevChanges';
import { Mutex } from 'async-mutex';
import { consola } from 'consola';
import { relative } from 'node:path';
import { getEntrypointOutputFile } from './core/utils/entrypoints';
import { buildInternal, rebuild } from './core/build';
import {
getEntrypointBundlePath,
getEntrypointOutputFile,
} from './core/utils/entrypoints';
getServerInfo,
reloadContentScripts,
reloadHtmlPages,
setupServer,
} from './core/server';
export { version } from '../package.json';
export * from './core/types/external';
@@ -44,33 +31,35 @@ export async function build(config: InlineConfig): Promise<BuildOutput> {
export async function createServer(
config?: InlineConfig,
): Promise<WxtDevServer> {
const port = await findOpenPort(3000, 3010);
const hostname = 'localhost';
const origin = `http://${hostname}:${port}`;
const serverConfig: vite.InlineConfig = {
server: {
origin,
},
const serverInfo = await getServerInfo();
const getLatestInternalConfig = () => {
const viteConfig: vite.InlineConfig = vite.mergeConfig(
serverInfo.viteServerConfig,
config?.vite ?? {},
);
return getInternalConfig({ ...config, vite: viteConfig }, 'serve');
};
let internalConfig = await getInternalConfig(
vite.mergeConfig(serverConfig, config ?? {}),
'serve',
);
const runner = createWebExtRunner();
let internalConfig = await getLatestInternalConfig();
const server = await setupServer(serverInfo, internalConfig);
internalConfig.server = server;
let hasBuiltOnce = false;
let currentOutput: BuildOutput | undefined;
const fileChangedMutex = new Mutex();
const changeQueue: Array<[string, string]> = [];
const viteServer = await vite.createServer(internalConfig.vite);
viteServer.watcher.on('all', async (event, path, stats) => {
if (!hasBuiltOnce || path.startsWith(internalConfig.outBaseDir)) return;
server.ws.on('wxt:background-initialized', () => {
// Register content scripts for the first time since they're not listed in the manifest
reloadContentScripts(server.currentOutput.steps, internalConfig, server);
});
server.watcher.on('all', async (event, path, _stats) => {
if (path.startsWith(internalConfig.outBaseDir)) return;
changeQueue.push([event, path]);
await fileChangedMutex.runExclusive(async () => {
const fileChanges = changeQueue.splice(0, changeQueue.length);
const changes = detectDevChanges(fileChanges, currentOutput);
const changes = detectDevChanges(fileChanges, server.currentOutput);
if (changes.type === 'no-change') return;
@@ -90,10 +79,7 @@ export async function createServer(
.join(pc.dim(', '));
// Get latest config and Rebuild groups with changes
internalConfig = await getInternalConfig(
vite.mergeConfig(serverConfig, config ?? {}),
'serve',
);
internalConfig = await getLatestInternalConfig();
internalConfig.server = server;
const { output: newOutput } = await rebuild(
internalConfig,
@@ -101,119 +87,23 @@ export async function createServer(
changes.rebuildGroups,
changes.cachedOutput,
);
currentOutput = newOutput;
server.currentOutput = newOutput;
// Perform reloads
switch (changes.type) {
case 'extension-reload':
server.reloadExtension();
consola.success(`Reloaded extension: ${rebuiltNames}`);
break;
case 'html-reload':
changes.rebuildGroups.flat().forEach((entry) => {
const path = getEntrypointBundlePath(
entry,
internalConfig.outDir,
'.html',
);
server.reloadPage(path);
});
consola.success(`Reloaded pages: ${rebuiltNames}`);
reloadHtmlPages(changes.rebuildGroups, server, internalConfig);
break;
case 'content-script-reload':
reloadContentScripts(changes.changedSteps, internalConfig, server);
break;
}
consola.success(`Reloaded: ${rebuiltNames}`);
});
});
const server: WxtDevServer = {
...viteServer,
async listen(port, isRestart) {
const res = await viteServer.listen(port, isRestart);
if (!isRestart) {
internalConfig.logger.success(`Started dev server @ ${origin}`);
internalConfig.logger.info('Opening browser...');
await runner.openBrowser(internalConfig);
internalConfig.logger.success('Opened!');
}
return res;
},
port,
hostname,
origin,
reloadExtension: () => {
server.ws.send('wxt:reload-extension');
},
reloadPage: (path) => {
// Can't use Vite's built-in "full-reload" event because it doesn't like our paths, it expects
// paths ending in "/index.html"
server.ws.send('wxt:reload-page', path);
},
};
internalConfig.logger.info('Created dev server');
internalConfig.server = server;
currentOutput = await buildInternal(internalConfig);
hasBuiltOnce = true;
return server;
}
async function buildInternal(config: InternalConfig): Promise<BuildOutput> {
const verb = config.command === 'serve' ? 'Pre-rendering' : 'Building';
const target = `${config.browser}-mv${config.manifestVersion}`;
config.logger.info(
`${verb} ${pc.cyan(target)} for ${pc.cyan(config.mode)} with ${pc.green(
`Vite ${vite.version}`,
)}`,
);
const startTime = Date.now();
// Cleanup
await fs.rm(config.outDir, { recursive: true, force: true });
await fs.ensureDir(config.outDir);
const entrypoints = await findEntrypoints(config);
const groups = groupEntrypoints(entrypoints);
const { output } = await rebuild(config, groups);
// Post-build
config.logger.success(
`Built extension in ${formatDuration(Date.now() - startTime)}`,
);
await printBuildSummary(output, config);
return output;
}
export async function rebuild(
config: InternalConfig,
entrypointGroups: EntrypointGroup[],
existingOutput: Omit<BuildOutput, 'manifest'> = {
steps: [],
publicAssets: [],
},
): Promise<{ output: BuildOutput; manifest: Manifest.WebExtensionManifest }> {
// Build
const allEntrypoints = await findEntrypoints(config);
await generateTypesDir(allEntrypoints, config);
const buildOutput = await buildEntrypoints(entrypointGroups, config);
const manifest = await generateMainfest(allEntrypoints, buildOutput, config);
const output: BuildOutput = {
manifest,
...buildOutput,
};
// Write manifest
await writeManifest(manifest, output, config);
return {
output: {
manifest,
steps: [...existingOutput.steps, ...output.steps],
publicAssets: [...existingOutput.publicAssets, ...output.publicAssets],
},
manifest,
};
}
+86
View File
@@ -6,11 +6,15 @@ import {
BackgroundEntrypoint,
ContentScriptEntrypoint,
GenericEntrypoint,
OptionsEntrypoint,
PopupEntrypoint,
} from '..';
import { faker } from '@faker-js/faker';
import merge from 'lodash.merge';
import { Rollup } from 'vite';
import { Manifest } from 'webextension-polyfill';
import { FsCache, InternalConfig, WxtDevServer } from '../core/types';
import { mock } from 'vitest-mock-extended';
faker.seed(__TEST_SEED__);
@@ -75,6 +79,63 @@ export const fakeUnlistedScriptEntrypoint =
outputDir: fakeDir('.output'),
}));
export const fakeOptionsEntrypoint = fakeObjectCreator<OptionsEntrypoint>(
() => ({
type: 'options',
inputPath: fakeFile('src'),
name: faker.string.alpha(),
outputDir: fakeDir('.output'),
options: {
browserStyle: faker.helpers.arrayElement([true, false, undefined]),
chromeStyle: faker.helpers.arrayElement([true, false, undefined]),
openInTab: faker.helpers.arrayElement([true, false, undefined]),
},
}),
);
export const fakePopupEntrypoint = fakeObjectCreator<PopupEntrypoint>(() => ({
type: 'popup',
inputPath: fakeFile('src'),
name: faker.string.alpha(),
outputDir: fakeDir('.output'),
options: {
defaultTitle: faker.helpers.arrayElement([
faker.person.fullName(),
undefined,
]),
defaultIcon: faker.helpers.arrayElement([
{
'16': 'icon/16.png',
'24': 'icon/24.png',
'64': 'icon/64.png',
},
]),
mv2Key: faker.helpers.arrayElement([
'browser_action',
'page_action',
undefined,
]),
},
}));
export const fakeGenericEntrypoint = fakeObjectCreator<GenericEntrypoint>(
() => ({
type: faker.helpers.arrayElement([
'sandbox',
'bookmarks',
'history',
'newtab',
'sidepanel',
'devtools',
'unlisted-page',
'unlisted-script',
]),
inputPath: fakeFile('src'),
name: faker.string.alpha(),
outputDir: fakeDir('.output'),
}),
);
export const fakeRollupOutputChunk = fakeObjectCreator<Rollup.OutputChunk>(
() => ({
type: 'chunk',
@@ -133,3 +194,28 @@ export function fakeArray<T>(createItem: () => T, count = 3): T[] {
}
return array;
}
export const fakeInternalConfig = fakeObjectCreator<InternalConfig>(() => ({
browser: faker.helpers.arrayElement(['chrome', 'firefox']),
command: faker.helpers.arrayElement(['build', 'serve']),
entrypointsDir: fakeDir(),
fsCache: mock<FsCache>(),
imports: {},
logger: mock(),
manifest: fakeManifest(),
manifestVersion: faker.helpers.arrayElement([2, 3]),
mode: faker.helpers.arrayElement(['development', 'production']),
outBaseDir: fakeDir(),
outDir: fakeDir(),
publicDir: fakeDir(),
root: fakeDir(),
runnerConfig: {
config: {},
},
srcDir: fakeDir(),
storeIds: {},
typesDir: fakeDir(),
vite: {},
wxtDir: fakeDir(),
server: mock<WxtDevServer>(),
}));
+5
View File
@@ -0,0 +1,5 @@
{
"github": {
"silent": true
}
}