-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbuild.js
More file actions
297 lines (266 loc) · 8.54 KB
/
build.js
File metadata and controls
297 lines (266 loc) · 8.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
/**
* Multi-entry Vite build script for the Chrome extension.
* Builds three bundles sequentially: content, background, injected.
*
* Uses rollupOptions.input (not lib mode) to avoid aggressive tree-shaking
* that strips side-effect code like event listeners, DOM mutations,
* and bridge communication.
*/
import { build } from "vite";
import { svelte } from "@sveltejs/vite-plugin-svelte";
import { resolve, dirname } from "path";
import { fileURLToPath } from "url";
import { copyFileSync, mkdirSync, existsSync, readdirSync, statSync, readFileSync, writeFileSync } from "fs";
import { execSync } from "child_process";
import { zipSync, strToU8 } from "fflate";
const __dirname = dirname(fileURLToPath(import.meta.url));
const targetArg = process.argv.find(arg => arg.startsWith('--target='));
const target = targetArg ? targetArg.split('=')[1] : 'chrome';
console.log(`\n🎯 Target Browser: ${target.toUpperCase()}`);
const distFolderName = `dist-${target}`;
/** @type {Array<import('vite').InlineConfig>} */
const builds = [
// ── Content Script ──
{
plugins: [svelte()],
esbuild: {
charset: 'ascii'
},
build: {
emptyOutDir: true,
outDir: resolve(__dirname, distFolderName),
rollupOptions: {
input: resolve(__dirname, "src/content/index.js"),
output: {
format: "iife",
entryFileNames: "content.js",
assetFileNames: "content.[ext]",
inlineDynamicImports: true,
},
// Preserve all side-effect code (bridge events, DOM mutations, etc.)
treeshake: false,
},
cssCodeSplit: false,
minify: true,
sourcemap: false,
},
define: {
"process.env.NODE_ENV": '"production"',
},
},
// ── Background Service Worker ──
{
plugins: [],
esbuild: {
charset: 'ascii'
},
build: {
emptyOutDir: false,
outDir: resolve(__dirname, distFolderName),
rollupOptions: {
input: resolve(__dirname, "src/background/index.js"),
output: {
format: "iife",
entryFileNames: "background.js",
inlineDynamicImports: true,
},
treeshake: false,
},
minify: true,
sourcemap: false,
},
},
// ── Injected Script (MAIN world) ──
{
plugins: [],
esbuild: {
charset: 'ascii'
},
build: {
emptyOutDir: false,
outDir: resolve(__dirname, distFolderName),
rollupOptions: {
input: resolve(__dirname, "src/injected/index.js"),
output: {
format: "iife",
entryFileNames: "injected.js",
inlineDynamicImports: true,
},
treeshake: false,
},
minify: true,
sourcemap: false,
},
},
// ── Sandbox Script (Safe Eval World) ──
{
plugins: [],
esbuild: {
charset: 'ascii'
},
build: {
emptyOutDir: false,
outDir: resolve(__dirname, distFolderName),
rollupOptions: {
input: resolve(__dirname, "src/sandbox/index.js"),
output: {
format: "iife",
entryFileNames: "sandbox.js",
inlineDynamicImports: true,
},
treeshake: false,
},
minify: true,
sourcemap: false,
},
},
];
async function run() {
for (const config of builds) {
await build({ ...config, configFile: false });
}
// Copy static folder to dist
console.log(`📂 Copying static assets to ${distFolderName}...`);
const distDir = resolve(__dirname, distFolderName);
const staticSrc = resolve(__dirname, "static");
const staticDest = resolve(distDir, "static");
function copyRecursiveSync(src, dest) {
if (statSync(src).isDirectory()) {
if (!existsSync(dest)) mkdirSync(dest, { recursive: true });
readdirSync(src).forEach(childItem => {
copyRecursiveSync(resolve(src, childItem), resolve(dest, childItem));
});
} else {
copyFileSync(src, dest);
}
}
if (existsSync(staticSrc)) {
try {
if (!existsSync(staticDest)) mkdirSync(staticDest, { recursive: true });
readdirSync(staticSrc).forEach(item => {
if (item === 'manifest.json' || item === 'sandbox.html') return;
copyRecursiveSync(resolve(staticSrc, item), resolve(staticDest, item));
});
} catch (e) {
console.warn("Static copy warning:", e.message);
}
}
// Handle manifest based on target
const manifestPath = resolve(__dirname, "static/manifest.json");
const manifest = JSON.parse(readFileSync(manifestPath, "utf8"));
if (target === "firefox") {
// Firefox MV3 specific settings
manifest.browser_specific_settings = {
gecko: {
id: "betterdeepseek@goygoyengine.com",
strict_min_version: "109.0",
data_collection_permissions: {
required: ["none"]
}
}
};
// In Firefox MV3, we use 'scripts' because service workers were late to the party.
// Since our build format is IIFE, we DON'T set type: "module".
if (manifest.background && manifest.background.service_worker) {
manifest.background = {
scripts: [manifest.background.service_worker]
};
}
// Firefox MV3 does not support the 'sandbox' property inside 'content_security_policy'
if (manifest.content_security_policy) {
delete manifest.content_security_policy.sandbox;
}
}
writeFileSync(
resolve(distDir, "manifest.json"),
JSON.stringify(manifest, null, 2)
);
// Copy sandbox.html to root dist
copyFileSync(
resolve(__dirname, "static/sandbox.html"),
resolve(distDir, "sandbox.html")
);
console.log("\n🧹 Cleaning non-ASCII characters from bundle...");
try {
execSync(`node scripts/sanitize-dist.js --target=${target}`, { stdio: "inherit" });
} catch (e) {
console.error("Sanitization failed:", e.message);
}
console.log(`\n✅ All builds complete. Extension ready in ${distFolderName}/`);
// ── Create ZIP Archive ──
console.log(`\n📦 Creating ZIP archive: better-deepseek-${target}.zip...`);
try {
const zipData = {};
function addDirToZipSync(currentPath, zipRoot = "") {
const items = readdirSync(currentPath);
for (const item of items) {
const fullPath = resolve(currentPath, item);
const zipPath = zipRoot ? `${zipRoot}/${item}` : item;
if (statSync(fullPath).isDirectory()) {
addDirToZipSync(fullPath, zipPath);
} else {
zipData[zipPath] = new Uint8Array(readFileSync(fullPath));
}
}
}
addDirToZipSync(distDir);
const zipped = zipSync(zipData);
writeFileSync(resolve(__dirname, `better-deepseek-${target}.zip`), zipped);
console.log(`✅ ZIP created successfully: better-deepseek-${target}.zip\n`);
} catch (e) {
console.error("❌ ZIP creation failed:", e.message);
}
}
/**
* Creates a source code ZIP for Mozilla submission.
*/
async function generateSourceZip() {
console.log("\n📦 Creating SOURCE CODE archive for Mozilla submission...");
try {
const zipData = {};
const rootFiles = ["build.js", "package.json", "package-lock.json", "README.md", "LICENSE"];
const rootDirs = ["src", "static", "scripts", "styles"];
for (const file of rootFiles) {
const fullPath = resolve(__dirname, file);
if (existsSync(fullPath)) {
zipData[file] = new Uint8Array(readFileSync(fullPath));
}
}
function addDirToZipSync(currentPath, zipRoot) {
const items = readdirSync(currentPath);
for (const item of items) {
const fullPath = resolve(currentPath, item);
const zipPath = `${zipRoot}/${item}`;
if (statSync(fullPath).isDirectory()) {
addDirToZipSync(fullPath, zipPath);
} else {
zipData[zipPath] = new Uint8Array(readFileSync(fullPath));
}
}
}
for (const dir of rootDirs) {
const fullPath = resolve(__dirname, dir);
if (existsSync(fullPath)) {
addDirToZipSync(fullPath, dir);
}
}
const zipped = zipSync(zipData);
writeFileSync(resolve(__dirname, "better-deepseek-source.zip"), zipped);
console.log("✅ Source code ZIP created successfully: better-deepseek-source.zip\n");
console.log("Submit this file to Mozilla as requested in the 'Source Code' section.");
} catch (e) {
console.error("❌ Source ZIP creation failed:", e.message);
}
}
async function start() {
const isSource = process.argv.includes("--source");
if (isSource) {
await generateSourceZip();
return;
}
await run();
}
start().catch((err) => {
console.error("Build failed:", err);
process.exit(1);
});