Update formatting, a small fix, and some cleanup

pull/25/head v0.4.1
neobooru 2021-01-01 23:26:18 +01:00
parent 78fcc974da
commit c044a68a13
21 changed files with 1562 additions and 1714 deletions

View File

@ -1,4 +1,4 @@
{ {
"printWidth": 120, "printWidth": 120,
"tabWidth": 4 "tabWidth": 2
} }

View File

@ -4,12 +4,16 @@ Chrome/Firefox extension which can import media from various sites into a [szuru
## Supported sites ## Supported sites
- Gelbooru/Safebooru/Rule34.xxx
- Danbooru (and Safebooru variant) - Danbooru (and Safebooru variant)
- Rule34 paheal (Shimmie2) - Gelbooru/Safebooru/Rule34.xxx/tbib.org
- yande.re/konachan (Moebooru) - yande.re/konachan (Moebooru)
- SankakuComplex (doesn't currently work because of the hotlink protection)
- Rule34 paheal (Shimmie2)
- E-Shuushuu
- Zerochan
- Reddit - Reddit
- Twitter - Twitter
- Fallback (simply grabs the largest image on a page)
## Installation ## Installation
@ -26,15 +30,24 @@ The layout is obviously not designed for mobile, so at times it looks less than
## How does it work? ## How does it work?
This add-on has two parts. The first part is the popup, which is what pops up when you click on the logo. The second part is a content script which is injected on _every_ website ([why?](#Why-is-the-content-script-injected-on-every-page)). This add-on has three parts.
The first part is the popup, which is what pops up when you click on the logo.
The second part is a content script which is injected on the page you visit. This script tries to find importable content on the current page and sends this to the popup.
The third part is the background script which handles the upload functionality. This was previously part of the popup, but has since been moved to the background script.
### The popup ### The popup
When opened (when you click on the add-on logo in your browser) it sends a message to the content script injected on the current page (active tab). This message asks the content script to scrape the DOM and return a SzuruPost element (with a source, imageUrl, safety, and a list of tags). Once it receives this element it renders it in the popup where you can make changes before importing it. When opened (when you click on the add-on logo in your browser) it sends a message to the content script injected on the current page (active tab). This message asks the content script to scrape the DOM and return a SzuruPost element (with a source, imageUrl, safety, and a list of tags). Once it receives this element it renders it in the popup where you can make changes before importing it. When you click on the "Upload" button the SzuruPost will be sent to the background script which will handle the upload functionality. This is done so that the upload continues even after you close the popup. This means that you can close the popup after clicking the "Upload" button and it'll continue with the upload.
### The content script ### The content script
This script is injected on every page ([why?](#Why-is-the-content-script-injected-on-every-page)) and does absolutely nothing until it receives the 'grab_post' message from the popup. Once it does received this message it checks if there are any loaders available to scrape this page. If a matching loader is found it'll pass the DOM of this page to the loader. The loader then uses the DOM to fill (as much as possible) a SzuruPost object. The SzuruPost is then passed back to the popup where you can change the post before importing it. This script is injected on every page and does absolutely nothing until it receives the 'grab_post' message from the popup. Once it does received this message it checks if there are any loaders available to scrape this page. If a matching loader is found it'll pass the DOM of this page to the loader. The loader then uses the DOM to fill (as much as possible) a SzuruPost object. The SzuruPost is then passed back to the popup where you can change the post before importing it.
### The background script
This script handles the uploading of a post. It will also update a tag's category in your szurubooru instance when it differs from what is imported.
## Build/debug ## Build/debug
@ -57,9 +70,9 @@ Firefox: `about:debugging` -> "Load Temporary Add-on..." -> Select any file in t
## Planned features ## Planned features
These are some things I might work on. Though honestly I don't expect this extension to change much anytime soon.
- Finishing the initial version of this add-on (see visual design doc for all features) - Finishing the initial version of this add-on (see visual design doc for all features)
- Auto-set tag category when creating a new tag (imported tag)
- Reverse image search to check whether (similar) file already exist before uploading it
- Right click any image on a page to import it - Right click any image on a page to import it
- Configurable list of tags to always ignore (e.g. tagme, highres) - Configurable list of tags to always ignore (e.g. tagme, highres)
- [low priority] Import artist commentary - [low priority] Import artist commentary
@ -97,10 +110,6 @@ Because the CORS spec is a bitch the preflight request is sent without the clien
</Location> </Location>
``` ```
### Why is the content script injected on every page?
Because I didn't know that you can inject a script from the popup (after opening it, so only when needed). I might change this later.
### Why send the DOM to the ILoader instead of just an url? ### Why send the DOM to the ILoader instead of just an url?
If we send an URL to the ILoader it has to download the page again itself, which can go wrong in a dozen ways: If we send an URL to the ILoader it has to download the page again itself, which can go wrong in a dozen ways:
@ -110,7 +119,3 @@ If we send an URL to the ILoader it has to download the page again itself, which
3. If you made changes to the DOM but didn't submit them to the server (e.g. edit post page) the ILoader would see a different page (kinda the same as point 2) 3. If you made changes to the DOM but didn't submit them to the server (e.g. edit post page) the ILoader would see a different page (kinda the same as point 2)
4. If any form of authentication (username+password/client certificate/etc) is involved it gets tricky 4. If any form of authentication (username+password/client certificate/etc) is involved it gets tricky
5. We already have the DOM, why download it again? 5. We already have the DOM, why download it again?
### Why is the CSS so bad?
Because CSS scares me.

1631
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,9 +1,12 @@
{ {
"name": "szuru-chrome", "name": "szuru-chrome",
"version": "0.3.2", "version": "0.4.1",
"description": "Import media from various sites into szurubooru", "description": "Import media from various sites into szurubooru.",
"author": "neobooru", "author": "neobooru",
"license": "MIT", "license": "MIT",
"repository": {
"url": "https://github.com/neobooru/SzuruChrome"
},
"scripts": { "scripts": {
"build": "cross-env NODE_ENV=production webpack --hide-modules", "build": "cross-env NODE_ENV=production webpack --hide-modules",
"build:dev": "cross-env NODE_ENV=development webpack --hide-modules", "build:dev": "cross-env NODE_ENV=development webpack --hide-modules",
@ -12,9 +15,8 @@
"watch:dev": "cross-env HMR=true npm run build:dev -- --watch" "watch:dev": "cross-env HMR=true npm run build:dev -- --watch"
}, },
"dependencies": { "dependencies": {
"axios": "^0.19.2", "axios": "^0.21.1",
"neo-scraper": "^0.2.5", "neo-scraper": "^0.2.5",
"ts-optchain": "^0.1.8",
"vue": "^2.6.11", "vue": "^2.6.11",
"webextension-polyfill": "^0.3.1" "webextension-polyfill": "^0.3.1"
}, },
@ -24,7 +26,6 @@
"core-js": "^3.6.5", "core-js": "^3.6.5",
"cross-env": "^5.2.1", "cross-env": "^5.2.1",
"css-loader": "^2.1.1", "css-loader": "^2.1.1",
"ejs": "^2.7.4",
"file-loader": "^1.1.11", "file-loader": "^1.1.11",
"mini-css-extract-plugin": "^0.4.4", "mini-css-extract-plugin": "^0.4.4",
"node-sass": "^4.14.1", "node-sass": "^4.14.1",

View File

@ -1,52 +1,52 @@
#!/usr/bin/env node #!/usr/bin/env node
const fs = require('fs'); const fs = require("fs");
const path = require('path'); const path = require("path");
const archiver = require('archiver'); const archiver = require("archiver");
const DEST_DIR = path.join(__dirname, '../dist'); const DEST_DIR = path.join(__dirname, "../dist");
const DEST_ZIP_DIR = path.join(__dirname, '../dist-zip'); const DEST_ZIP_DIR = path.join(__dirname, "../dist-zip");
const extractExtensionData = () => { const extractExtensionData = () => {
const extPackageJson = require('../package.json'); const extPackageJson = require("../package.json");
return { return {
name: extPackageJson.name, name: extPackageJson.name,
version: extPackageJson.version version: extPackageJson.version
} };
}; };
const makeDestZipDirIfNotExists = () => { const makeDestZipDirIfNotExists = () => {
if(!fs.existsSync(DEST_ZIP_DIR)) { if (!fs.existsSync(DEST_ZIP_DIR)) {
fs.mkdirSync(DEST_ZIP_DIR); fs.mkdirSync(DEST_ZIP_DIR);
} }
} };
const buildZip = (src, dist, zipFilename) => { const buildZip = (src, dist, zipFilename) => {
console.info(`Building ${zipFilename}...`); console.info(`Building ${zipFilename}...`);
const archive = archiver('zip', { zlib: { level: 9 }}); const archive = archiver("zip", { zlib: { level: 9 } });
const stream = fs.createWriteStream(path.join(dist, zipFilename)); const stream = fs.createWriteStream(path.join(dist, zipFilename));
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
archive archive
.directory(src, false) .directory(src, false)
.on('error', err => reject(err)) .on("error", err => reject(err))
.pipe(stream); .pipe(stream);
stream.on('close', () => resolve()); stream.on("close", () => resolve());
archive.finalize(); archive.finalize();
}); });
}; };
const main = () => { const main = () => {
const {name, version} = extractExtensionData(); const { name, version } = extractExtensionData();
const zipFilename = `${name}-v${version}.zip`; const zipFilename = `${name}-v${version}.zip`;
makeDestZipDirIfNotExists(); makeDestZipDirIfNotExists();
buildZip(DEST_DIR, DEST_ZIP_DIR, zipFilename) buildZip(DEST_DIR, DEST_ZIP_DIR, zipFilename)
.then(() => console.info('OK')) .then(() => console.info("OK"))
.catch(console.err); .catch(console.err);
}; };

View File

@ -4,8 +4,8 @@
export type Safety = "safe" | "sketchy" | "unsafe"; export type Safety = "safe" | "sketchy" | "unsafe";
export type TagsResult = PagedSearchResult<Tag> export type TagsResult = PagedSearchResult<Tag>;
export type TagCategoriesResult = UnpagedSearchResult<TagCategory> export type TagCategoriesResult = UnpagedSearchResult<TagCategory>;
export interface SzuruError { export interface SzuruError {
name: string; name: string;

View File

@ -15,7 +15,7 @@ export default class SzuruWrapper {
authToken: string; authToken: string;
private readonly baseHeaders = { private readonly baseHeaders = {
"Accept": "application/json", Accept: "application/json",
"Content-Type": "application/json" "Content-Type": "application/json"
}; };
@ -79,7 +79,7 @@ export default class SzuruWrapper {
const config: AxiosRequestConfig = { const config: AxiosRequestConfig = {
method: "GET", method: "GET",
url: fullUrl url: fullUrl
} };
config.headers = { ...this.baseHeaders, ...additionalHeaders }; config.headers = { ...this.baseHeaders, ...additionalHeaders };
return await this.execute(config); return await this.execute(config);
@ -91,7 +91,7 @@ export default class SzuruWrapper {
method: "POST", method: "POST",
url: fullUrl, url: fullUrl,
data: data data: data
} };
config.headers = { ...this.baseHeaders, ...additionalHeaders }; config.headers = { ...this.baseHeaders, ...additionalHeaders };
return await this.execute(config); return await this.execute(config);
@ -103,7 +103,7 @@ export default class SzuruWrapper {
method: "PUT", method: "PUT",
url: fullUrl, url: fullUrl,
data: data data: data
} };
config.headers = { ...this.baseHeaders, ...additionalHeaders }; config.headers = { ...this.baseHeaders, ...additionalHeaders };
return await this.execute(config); return await this.execute(config);

View File

@ -1,6 +1,6 @@
{ {
"name": "SzuruChrome", "name": "SzuruChrome",
"description": "Import media from various sites into szurubooru", "description": "Import media from various sites into szurubooru.",
"version": null, "version": null,
"manifest_version": 2, "manifest_version": 2,
"icons": { "icons": {
@ -34,7 +34,7 @@
}, },
"browser_specific_settings": { "browser_specific_settings": {
"gecko": { "gecko": {
"id": "{8cc2afc8-6c4a-4d2b-9513-46e46e5b4208}" "id": "{13372607-2257-4360-8f51-5ce66fa73350}"
} }
} }
} }

View File

@ -24,11 +24,7 @@
<br /> <br />
<label> <label>
Automatically search for similar posts Automatically search for similar posts
<input <input type="checkbox" name="autoSearchSimilar" v-model="autoSearchSimilar" />
type="checkbox"
name="autoSearchSimilar"
v-model="autoSearchSimilar"
/>
</label> </label>
<br /> <br />
<div class="settings-footer-buttons"> <div class="settings-footer-buttons">
@ -41,7 +37,6 @@
<script lang="ts"> <script lang="ts">
import Vue from "vue"; import Vue from "vue";
import { oc } from "ts-optchain";
import SzuruWrapper from "../SzuruWrapper"; import SzuruWrapper from "../SzuruWrapper";
import { Config, SzuruSiteConfig } from "../Config"; import { Config, SzuruSiteConfig } from "../Config";
@ -51,7 +46,7 @@ export default Vue.extend({
domain: "", domain: "",
username: "", username: "",
authToken: "", authToken: "",
autoSearchSimilar: false autoSearchSimilar: false,
}; };
}, },
methods: { methods: {
@ -64,7 +59,7 @@ export default Vue.extend({
const api = new SzuruWrapper(this.domain, this.username, this.authToken); const api = new SzuruWrapper(this.domain, this.username, this.authToken);
try { try {
const info = (await api.getInfo()) as any; const info = (await api.getInfo()) as any;
const instanceName = oc(info).config.domain; const instanceName = info?.config.name;
if (instanceName == undefined) { if (instanceName == undefined) {
alert(`Connected to ${this.domain}, but it is not a szurubooru instance.`); alert(`Connected to ${this.domain}, but it is not a szurubooru instance.`);
@ -88,7 +83,7 @@ export default Vue.extend({
config.autoSearchSimilar = this.autoSearchSimilar; config.autoSearchSimilar = this.autoSearchSimilar;
await config.save(); await config.save();
} },
}, },
async mounted() { async mounted() {
let config = await Config.load(); let config = await Config.load();
@ -102,7 +97,7 @@ export default Vue.extend({
this.authToken = config.sites[0].authToken; this.authToken = config.sites[0].authToken;
this.autoSearchSimilar = config.autoSearchSimilar; this.autoSearchSimilar = config.autoSearchSimilar;
} }
} },
}); });
</script> </script>

View File

@ -1,18 +1,13 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html lang="en">
<head>
<head>
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<title>SzuruChrome - Options</title> <title>SzuruChrome - Options</title>
<link rel="stylesheet" href="options.css" /> <link rel="stylesheet" href="options.css" />
<% if (NODE_ENV === 'development') { %> </head>
<!-- Load some resources only in development environment -->
<% } %>
</head>
<body> <body>
<div id="app"></div> <div id="app"></div>
<script src="options.js"></script> <script src="options.js"></script>
</body> </body>
</html> </html>

View File

@ -1,9 +1,9 @@
import '../css/style.css'; import "../css/style.css";
import Vue from 'vue'; import Vue from "vue";
import App from './App'; import App from "./App";
new Vue({ new Vue({
el: '#app', el: "#app",
render: h => h(App) render: h => h(App)
}) });

View File

@ -2,12 +2,7 @@
<div class="popup-container"> <div class="popup-container">
<div class="popup-messages"> <div class="popup-messages">
<ul class="messages"> <ul class="messages">
<li <li v-for="msg in messages" :key="msg.name" :class="getMessageClasses(msg)" v-html="msg.content"></li>
v-for="msg in messages"
:key="msg.name"
:class="getMessageClasses(msg)"
v-html="msg.content"
></li>
</ul> </ul>
</div> </div>
@ -51,13 +46,9 @@
<span>Tags</span> <span>Tags</span>
</div> </div>
<div class="section-row" style="display:flex;"> <div class="section-row" style="display: flex">
<input type="text" v-model="addTagInput" v-on:keyup.enter="addTag" /> <input type="text" v-model="addTagInput" v-on:keyup.enter="addTag" />
<button <button class="primary" style="margin-left: 5px; height: auto" @click="addTag">Add</button>
class="primary"
style="margin-left: 5px; height: auto;"
@click="addTag"
>Add</button>
</div> </div>
<div class="section-row"> <div class="section-row">
@ -83,20 +74,16 @@
<div class="popup-right"> <div class="popup-right">
<div class="popup-section"> <div class="popup-section">
<select v-model="selectedPost"> <select v-model="selectedPost">
<option <option v-for="post in posts" v-bind:key="post" v-bind:value="post">{{ post.name }}</option>
v-for="post in posts"
v-bind:key="post"
v-bind:value="post"
>{{ post.name }}</option>
</select> </select>
</div> </div>
<div class="popup-section"> <div class="popup-section">
<img :src="selectedPost.imageUrl" /> <img :src="selectedPost.imageUrl" />
<div style="display: flex;"> <div style="display: flex">
<button class="primary" @click="findSimilar">Find similar</button> <button class="primary" @click="findSimilar">Find similar</button>
<button class="primary full" style="margin-left: 5px;" @click="upload">Import</button> <button class="primary full" style="margin-left: 5px" @click="upload">Import</button>
</div> </div>
</div> </div>
</div> </div>
@ -125,7 +112,7 @@ export default Vue.extend({
posts: [] as ScrapedPostViewModel[], posts: [] as ScrapedPostViewModel[],
selectedPost: new ScrapedPost(), // Shouldn't be null because VueJS gets a mental breakdown when it sees a null. selectedPost: new ScrapedPost(), // Shouldn't be null because VueJS gets a mental breakdown when it sees a null.
messages: [] as Message[], messages: [] as Message[],
addTagInput: "" addTagInput: "",
}; };
}, },
watch: { watch: {
@ -134,7 +121,7 @@ export default Vue.extend({
// No need to check if any vars are unset, findSimilar does that internally // No need to check if any vars are unset, findSimilar does that internally
this.findSimilar(); this.findSimilar();
} }
} },
}, },
methods: { methods: {
// Try to scrape the post from the page // Try to scrape the post from the page
@ -143,7 +130,7 @@ export default Vue.extend({
const activeTab = ( const activeTab = (
await browser.tabs.query({ await browser.tabs.query({
active: true, active: true,
currentWindow: true currentWindow: true,
}) })
)[0]; )[0];
@ -254,7 +241,7 @@ export default Vue.extend({
if (this.selectedPost) { if (this.selectedPost) {
const tagName = this.addTagInput; const tagName = this.addTagInput;
this.addTagInput = ""; this.addTagInput = "";
if (this.selectedPost.tags.find(x => x.name == tagName) == undefined) { if (this.selectedPost.tags.find((x) => x.name == tagName) == undefined) {
this.selectedPost.tags.push(new ScrapedTag(tagName)); this.selectedPost.tags.push(new ScrapedTag(tagName));
} }
} }
@ -292,7 +279,7 @@ export default Vue.extend({
); );
} }
} }
} },
}, },
async mounted() { async mounted() {
this.config = await Config.load(); this.config = await Config.load();
@ -320,7 +307,7 @@ export default Vue.extend({
// Always call grabPost, even when there is no activeSite // Always call grabPost, even when there is no activeSite
this.grabPost(); this.grabPost();
} },
}); });
</script> </script>

View File

@ -1,18 +1,13 @@
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html lang="en">
<head>
<head>
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<title>Title</title> <title>Title</title>
<link rel="stylesheet" href="popup.css" /> <link rel="stylesheet" href="popup.css" />
<% if (NODE_ENV === 'development') { %> </head>
<!-- Load some resources only in development environment -->
<% } %>
</head>
<body> <body>
<div id="app"></div> <div id="app"></div>
<script src="popup.js"></script> <script src="popup.js"></script>
</body> </body>
</html> </html>

View File

@ -1,11 +1,11 @@
import '../css/style.css'; import "../css/style.css";
import '../css/fontawesome.css'; import "../css/fontawesome.css";
import '../css/solid.css'; import "../css/solid.css";
import Vue from 'vue'; import Vue from "vue";
import App from './App'; import App from "./App";
new Vue({ new Vue({
el: '#app', el: "#app",
render: h => h(App) render: h => h(App)
}) });

View File

@ -18,7 +18,9 @@ async function uploadPost(post: ScrapedPost) {
browser.runtime.sendMessage(new BrowserCommand("push_message", new Message("Uploading..."))); browser.runtime.sendMessage(new BrowserCommand("push_message", new Message("Uploading...")));
const createdPost = await szuru.createPost(post); const createdPost = await szuru.createPost(post);
browser.runtime.sendMessage(new BrowserCommand("remove_messages", 1)); browser.runtime.sendMessage(new BrowserCommand("remove_messages", 1));
browser.runtime.sendMessage(new BrowserCommand("push_message", new Message("Uploaded post " + createdPost.id, "success"))); browser.runtime.sendMessage(
new BrowserCommand("push_message", new Message("Uploaded post " + createdPost.id, "success"))
);
// TODO: Clicking a link doesn't actually open it in a new tab, // TODO: Clicking a link doesn't actually open it in a new tab,
// see https://stackoverflow.com/questions/8915845 // see https://stackoverflow.com/questions/8915845
@ -32,18 +34,24 @@ async function uploadPost(post: ScrapedPost) {
.filter(x => x.category == "default") .filter(x => x.category == "default")
.filter(x => tagsWithCategory.some(y => x.names.includes(y.name))); .filter(x => tagsWithCategory.some(y => x.names.includes(y.name)));
if (unsetCategoryTags.length != 0) { if (unsetCategoryTags.length != 0) {
browser.runtime.sendMessage(new BrowserCommand("push_message", new Message(`${unsetCategoryTags.length} tags need a different category`))); browser.runtime.sendMessage(
new BrowserCommand("push_message", new Message(`${unsetCategoryTags.length} tags need a different category`))
);
// unsetCategoryTags is of type MicroTag[] and we need a Tag resource to update it, so let's get those // unsetCategoryTags is of type MicroTag[] and we need a Tag resource to update it, so let's get those
const query = "?query=" + unsetCategoryTags.map(x => encodeTagName(x.names[0])); const query = "?query=" + unsetCategoryTags.map(x => encodeTagName(x.names[0]));
const tags = (await szuru.getTags(query)).results; const tags = (await szuru.getTags(query)).results;
for (let i in tags) { for (let i in tags) {
browser.runtime.sendMessage(new BrowserCommand("remove_messages", 1)); browser.runtime.sendMessage(new BrowserCommand("remove_messages", 1));
browser.runtime.sendMessage(new BrowserCommand("push_message", new Message(`Updating tag ${i}/${unsetCategoryTags.length}`))); browser.runtime.sendMessage(
new BrowserCommand("push_message", new Message(`Updating tag ${i}/${unsetCategoryTags.length}`))
);
tags[i].category = tagsWithCategory.find(x => tags[i].names.includes(x.name))!.category!; tags[i].category = tagsWithCategory.find(x => tags[i].names.includes(x.name))!.category!;
await szuru.updateTag(tags[i]); await szuru.updateTag(tags[i]);
} }
browser.runtime.sendMessage(new BrowserCommand("remove_messages", 1)); browser.runtime.sendMessage(new BrowserCommand("remove_messages", 1));
browser.runtime.sendMessage(new BrowserCommand("push_message", new Message(`Updated ${tags.length} tags`, "success"))); browser.runtime.sendMessage(
new BrowserCommand("push_message", new Message(`Updated ${tags.length} tags`, "success"))
);
} }
} catch (ex) { } catch (ex) {
const error = ex as SzuruError; const error = ex as SzuruError;
@ -65,7 +73,8 @@ function encodeTagName(tagName: string) {
async function messageHandler(cmd: BrowserCommand, sender: Runtime.MessageSender): Promise<any> { async function messageHandler(cmd: BrowserCommand, sender: Runtime.MessageSender): Promise<any> {
switch (cmd.name) { switch (cmd.name) {
case "upload_post": return uploadPost(cmd.data); case "upload_post":
return uploadPost(cmd.data);
} }
} }

View File

@ -9,7 +9,8 @@ function grabPost(): ScrapeResults {
async function messageHandler(cmd: BrowserCommand, sender: Runtime.MessageSender): Promise<any> { async function messageHandler(cmd: BrowserCommand, sender: Runtime.MessageSender): Promise<any> {
switch (cmd.name) { switch (cmd.name) {
case "grab_post": return grabPost(); case "grab_post":
return grabPost();
} }
} }

View File

@ -3,7 +3,7 @@
"outDir": "./dist/", "outDir": "./dist/",
"sourceMap": true, "sourceMap": true,
"strict": true, "strict": true,
"module": "es2015", "module": "es2020",
"moduleResolution": "node", "moduleResolution": "node",
"target": "es6", "target": "es6",
"skipLibCheck": true, "skipLibCheck": true,
@ -12,11 +12,6 @@
"lib": [ "lib": [
"es2017", "es2017",
"dom" "dom"
],
"plugins": [
{
"transform": "ts-optchain/transform"
}
] ]
}, },
"include": [ "include": [

View File

@ -1,118 +1,114 @@
const webpack = require('webpack'); const webpack = require("webpack");
const ejs = require('ejs'); const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const MiniCssExtractPlugin = require('mini-css-extract-plugin'); const CopyWebpackPlugin = require("copy-webpack-plugin");
const CopyWebpackPlugin = require('copy-webpack-plugin'); const ExtensionReloader = require("webpack-extension-reloader");
const ExtensionReloader = require('webpack-extension-reloader'); const { VueLoaderPlugin } = require("vue-loader");
const { VueLoaderPlugin } = require('vue-loader'); const { version } = require("./package.json");
const { version } = require('./package.json');
const config = { const config = {
mode: process.env.NODE_ENV, mode: process.env.NODE_ENV,
context: __dirname + '/src', context: __dirname + "/src",
entry: { entry: {
'scripts/content': './scripts/content.ts', "scripts/content": "./scripts/content.ts",
'scripts/background': './scripts/background.ts', "scripts/background": "./scripts/background.ts",
'popup/popup': './popup/popup.ts', "popup/popup": "./popup/popup.ts",
'options/options': './options/options.ts', "options/options": "./options/options.ts"
}, },
output: { output: {
path: __dirname + '/dist', path: __dirname + "/dist",
filename: '[name].js', filename: "[name].js"
}, },
resolve: { resolve: {
extensions: ['.ts', '.js', '.vue'], extensions: [".ts", ".js", ".vue"]
}, },
devtool: 'inline-source-map', performance: {
hints: false
},
devtool: "inline-source-map",
module: { module: {
rules: [ rules: [
{ {
test: /\.vue$/, test: /\.vue$/,
loaders: 'vue-loader', loaders: "vue-loader"
}, },
{ {
test: /\.tsx?$/, test: /\.tsx?$/,
loader: 'ts-loader', loader: "ts-loader",
exclude: /node_modules/, exclude: /node_modules/,
options: { options: {
appendTsSuffixTo: [/\.vue$/], appendTsSuffixTo: [/\.vue$/]
} }
}, },
{ {
test: /\.css$/, test: /\.css$/,
use: [MiniCssExtractPlugin.loader, 'css-loader'], use: [MiniCssExtractPlugin.loader, "css-loader"]
}, },
{ {
test: /\.(png|jpg|gif|svg|ico)$/, test: /\.(png|jpg|gif|svg|ico)$/,
loader: 'file-loader', loader: "file-loader",
options: { options: {
name: '[name].[ext]?emitFile=false', name: "[name].[ext]?emitFile=false"
}, }
}, },
{ {
test: /\.(woff(2)?|ttf|eot|svg)(\?v=\d+\.\d+\.\d+)?$/, test: /\.(woff(2)?|ttf|eot|svg)(\?v=\d+\.\d+\.\d+)?$/,
loader: 'file-loader', loader: "file-loader",
options: { options: {
name: '[name].[ext]?emitFile=false', name: "[name].[ext]?emitFile=false",
outputPath: '/fonts/' outputPath: "/fonts/"
}, }
}, }
], ]
}, },
plugins: [ plugins: [
new webpack.DefinePlugin({ new webpack.DefinePlugin({
global: 'window', global: "window"
}), }),
new VueLoaderPlugin(), new VueLoaderPlugin(),
new MiniCssExtractPlugin({ new MiniCssExtractPlugin({
filename: '[name].css', filename: "[name].css"
}), }),
new CopyWebpackPlugin([ new CopyWebpackPlugin([
{ from: 'icons', to: 'icons', ignore: ['icon.xcf'] }, { from: "icons", to: "icons", ignore: ["icon.xcf"] },
{ from: 'popup/popup.html', to: 'popup/popup.html', transform: transformHtml }, { from: "popup/popup.html", to: "popup/popup.html" },
{ from: 'options/options.html', to: 'options/options.html', transform: transformHtml }, { from: "options/options.html", to: "options/options.html" },
{ {
from: 'manifest.json', from: "manifest.json",
to: 'manifest.json', to: "manifest.json",
transform: (content) => { transform: content => {
const jsonContent = JSON.parse(content); const jsonContent = JSON.parse(content);
jsonContent.version = version; jsonContent.version = version;
if (config.mode === 'development') { if (config.mode === "development") {
jsonContent['content_security_policy'] = "script-src 'self' 'unsafe-eval'; object-src 'self'"; jsonContent["content_security_policy"] = "script-src 'self' 'unsafe-eval'; object-src 'self'";
} }
return JSON.stringify(jsonContent, null, 2); return JSON.stringify(jsonContent, null, 2);
}, }
}, }
]), ])
] ]
}; };
if (config.mode === 'production') { if (config.mode === "production") {
config.plugins = (config.plugins || []).concat([ config.plugins = (config.plugins || []).concat([
new webpack.DefinePlugin({ new webpack.DefinePlugin({
'process.env': { "process.env": {
NODE_ENV: '"production"', NODE_ENV: '"production"'
}, }
}), })
]); ]);
} }
if (process.env.HMR === 'true') { if (process.env.HMR === "true") {
config.plugins = (config.plugins || []).concat([ config.plugins = (config.plugins || []).concat([
new ExtensionReloader({ new ExtensionReloader({
entries: { entries: {
contentScript: 'scripts/content', contentScript: "scripts/content",
background: 'scripts/background' background: "scripts/background"
} }
}), })
]); ]);
} }
function transformHtml(content) {
return ejs.render(content.toString(), {
...process.env,
});
}
module.exports = config; module.exports = config;