@crxjs/vite-plugin 1.0.13 → 2.0.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/dist/index.cjs +1336 -1309
  2. package/dist/index.d.ts +31 -19
  3. package/dist/index.mjs +1331 -1305
  4. package/package.json +25 -21
package/dist/index.cjs CHANGED
@@ -2,23 +2,25 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- var rollup = require('rollup');
6
5
  var acornWalk = require('acorn-walk');
7
6
  var crypto = require('crypto');
8
- var debug$5 = require('debug');
9
- var fg = require('fast-glob');
7
+ var debug$2 = require('debug');
10
8
  var v8 = require('v8');
11
- var fs = require('fs');
12
- var MagicString = require('magic-string');
13
9
  var path = require('path');
14
- var fsExtra = require('fs-extra');
10
+ var fsx = require('fs-extra');
15
11
  var perf_hooks = require('perf_hooks');
16
- var colors = require('picocolors');
12
+ var rollup = require('rollup');
13
+ var lexer = require('es-module-lexer');
14
+ var promises = require('fs/promises');
15
+ var MagicString = require('magic-string');
17
16
  var vite = require('vite');
17
+ var fs = require('fs');
18
18
  var module$1 = require('module');
19
+ var fg = require('fast-glob');
20
+ var getPort = require('get-port');
19
21
  var cheerio = require('cheerio');
20
22
  var jsesc = require('jsesc');
21
- var injector = require('connect-injector');
23
+ var colors = require('picocolors');
22
24
 
23
25
  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
24
26
 
@@ -40,72 +42,63 @@ function _interopNamespace(e) {
40
42
  return Object.freeze(n);
41
43
  }
42
44
 
43
- var debug__default = /*#__PURE__*/_interopDefaultLegacy(debug$5);
44
- var fg__default = /*#__PURE__*/_interopDefaultLegacy(fg);
45
+ var debug__default = /*#__PURE__*/_interopDefaultLegacy(debug$2);
45
46
  var v8__default = /*#__PURE__*/_interopDefaultLegacy(v8);
47
+ var fsx__default = /*#__PURE__*/_interopDefaultLegacy(fsx);
48
+ var lexer__namespace = /*#__PURE__*/_interopNamespace(lexer);
46
49
  var MagicString__default = /*#__PURE__*/_interopDefaultLegacy(MagicString);
47
- var fsExtra__default = /*#__PURE__*/_interopDefaultLegacy(fsExtra);
48
- var colors__default = /*#__PURE__*/_interopDefaultLegacy(colors);
50
+ var fg__default = /*#__PURE__*/_interopDefaultLegacy(fg);
51
+ var getPort__default = /*#__PURE__*/_interopDefaultLegacy(getPort);
49
52
  var jsesc__default = /*#__PURE__*/_interopDefaultLegacy(jsesc);
50
- var injector__default = /*#__PURE__*/_interopDefaultLegacy(injector);
53
+ var colors__default = /*#__PURE__*/_interopDefaultLegacy(colors);
54
+
55
+ const pluginName$1 = "crx:optionsProvider";
56
+ const pluginOptionsProvider = (options) => {
57
+ return {
58
+ name: pluginName$1,
59
+ api: {
60
+ crx: {
61
+ options
62
+ }
63
+ }
64
+ };
65
+ };
66
+ const getOptions = ({ plugins }) => {
67
+ if (typeof plugins === "undefined") {
68
+ throw new Error("config.plugins is undefined");
69
+ }
70
+ let options;
71
+ for (const p of plugins.flat()) {
72
+ if (isCrxPlugin(p)) {
73
+ if (p.name === pluginName$1) {
74
+ const plugin = p;
75
+ options = plugin.api.crx.options;
76
+ if (options)
77
+ break;
78
+ }
79
+ }
80
+ }
81
+ if (typeof options === "undefined") {
82
+ throw Error("Unable to get CRXJS options");
83
+ }
84
+ return options;
85
+ };
86
+ function isCrxPlugin(p) {
87
+ return !!p && typeof p === "object" && !(p instanceof Promise) && !Array.isArray(p) && p.name.startsWith("crx:");
88
+ }
89
+
90
+ var workerHmrClient = "const ownOrigin = new URL(chrome.runtime.getURL(\"/\")).origin;\nself.addEventListener(\"fetch\", (fetchEvent) => {\n const url = new URL(fetchEvent.request.url);\n if (url.origin === ownOrigin) {\n fetchEvent.respondWith(sendToServer(url));\n }\n});\nasync function sendToServer(url) {\n url.protocol = \"http:\";\n url.host = \"localhost\";\n url.port = __SERVER_PORT__;\n url.searchParams.set(\"t\", Date.now().toString());\n const response = await fetch(url.href.replace(/=$|=(?=&)/g, \"\"));\n return new Response(response.body, {\n headers: {\n \"Content-Type\": response.headers.get(\"Content-Type\") ?? \"text/javascript\"\n }\n });\n}\nconst ports = /* @__PURE__ */ new Set();\nchrome.runtime.onConnect.addListener((port) => {\n if (port.name === \"@crx/client\") {\n ports.add(port);\n port.onDisconnect.addListener((port2) => ports.delete(port2));\n port.onMessage.addListener((message) => {\n });\n port.postMessage({ data: JSON.stringify({ type: \"connected\" }) });\n }\n});\nfunction notifyContentScripts(payload) {\n const data = JSON.stringify(payload);\n for (const port of ports)\n port.postMessage({ data });\n}\nconsole.log(\"[vite] connecting...\");\nconst socketProtocol = __HMR_PROTOCOL__ || (location.protocol === \"https:\" ? \"wss\" : \"ws\");\nconst socketHost = `${__HMR_HOSTNAME__ || location.hostname}:${__HMR_PORT__}`;\nconst socket = new WebSocket(`${socketProtocol}://${socketHost}`, \"vite-hmr\");\nconst base = __BASE__ || \"/\";\nsocket.addEventListener(\"message\", async ({ data }) => {\n handleSocketMessage(JSON.parse(data));\n});\nfunction isCrxHmrPayload(x) {\n return x.type === \"custom\" && x.event.startsWith(\"crx:\");\n}\nfunction handleSocketMessage(payload) {\n if (isCrxHmrPayload(payload)) {\n handleCrxHmrPayload(payload);\n } else if (payload.type === \"connected\") {\n console.log(`[vite] connected.`);\n const interval = setInterval(() => socket.send(\"ping\"), __HMR_TIMEOUT__);\n socket.addEventListener(\"close\", () => clearInterval(interval));\n }\n}\nfunction handleCrxHmrPayload(payload) {\n notifyContentScripts(payload);\n switch (payload.event) {\n case \"crx:runtime-reload\":\n console.log(\"[crx] runtime reload\");\n chrome.runtime.reload();\n break;\n }\n}\nasync function waitForSuccessfulPing(ms = 1e3) {\n while (true) {\n try {\n await fetch(`${base}__vite_ping`);\n break;\n } catch (e) {\n await new Promise((resolve) => setTimeout(resolve, ms));\n }\n }\n}\nsocket.addEventListener(\"close\", async ({ wasClean }) => {\n if (wasClean)\n return;\n console.log(`[vite] server connection lost. polling for restart...`);\n await waitForSuccessfulPing();\n handleCrxHmrPayload({\n type: \"custom\",\n event: \"crx:runtime-reload\"\n });\n});\n";
51
91
 
52
92
  const _debug = (id) => debug__default["default"]("crx").extend(id);
53
93
  const structuredClone = (obj) => {
54
94
  return v8__default["default"].deserialize(v8__default["default"].serialize(obj));
55
95
  };
56
- const createHash = (data, length = 5) => crypto.createHash("sha1").update(data).digest("base64").replace(/[^A-Za-z0-9]/g, "").slice(0, length);
96
+ const hash = (data, length = 5) => crypto.createHash("sha1").update(data).digest("base64").replace(/[^A-Za-z0-9]/g, "").slice(0, length);
57
97
  const isString = (x) => typeof x === "string";
58
- const isTruthy = (x) => !!x;
59
98
  function isObject(value) {
60
99
  return Object.prototype.toString.call(value) === "[object Object]";
61
100
  }
62
101
  const isResourceByMatch = (x) => "matches" in x;
63
- async function manifestFiles(manifest, options = {}) {
64
- let locales = [];
65
- if (manifest.default_locale)
66
- locales = await fg__default["default"]("_locales/**/messages.json", options);
67
- const rulesets = manifest.declarative_net_request?.rule_resources.flatMap(({ path }) => path) ?? [];
68
- const contentScripts = manifest.content_scripts?.flatMap(({ js }) => js) ?? [];
69
- const contentStyles = manifest.content_scripts?.flatMap(({ css }) => css);
70
- const serviceWorker = manifest.background?.service_worker;
71
- const htmlPages = htmlFiles(manifest);
72
- const icons = [
73
- Object.values(isString(manifest.icons) ? [manifest.icons] : manifest.icons ?? {}),
74
- Object.values(isString(manifest.action?.default_icon) ? [manifest.action?.default_icon] : manifest.action?.default_icon ?? {})
75
- ].flat();
76
- let webAccessibleResources = [];
77
- if (manifest.web_accessible_resources) {
78
- const resources = await Promise.all(manifest.web_accessible_resources.flatMap(({ resources: resources2 }) => resources2).map(async (r) => {
79
- if (["*", "**/*"].includes(r))
80
- return void 0;
81
- if (fg__default["default"].isDynamicPattern(r))
82
- return fg__default["default"](r, options);
83
- return r;
84
- }));
85
- webAccessibleResources = resources.flat().filter(isString);
86
- }
87
- return {
88
- contentScripts: [...new Set(contentScripts)].filter(isString),
89
- contentStyles: [...new Set(contentStyles)].filter(isString),
90
- html: htmlPages,
91
- icons: [...new Set(icons)].filter(isString),
92
- locales: [...new Set(locales)].filter(isString),
93
- rulesets: [...new Set(rulesets)].filter(isString),
94
- background: [serviceWorker].filter(isString),
95
- webAccessibleResources
96
- };
97
- }
98
- function htmlFiles(manifest) {
99
- const files = [
100
- manifest.action?.default_popup,
101
- Object.values(manifest.chrome_url_overrides ?? {}),
102
- manifest.devtools_page,
103
- manifest.options_page,
104
- manifest.options_ui?.page,
105
- manifest.sandbox?.pages
106
- ].flat().filter(isString).map((s) => s.split("#")[0]).sort();
107
- return [...new Set(files)];
108
- }
109
102
  function decodeManifest(code) {
110
103
  const tree = this.parse(code);
111
104
  let literal;
@@ -132,67 +125,25 @@ function encodeManifest(manifest) {
132
125
  const json = JSON.stringify(JSON.stringify(manifest));
133
126
  return `export default ${json}`;
134
127
  }
135
- const stubMatchPattern = (pattern) => {
128
+ function parseJsonAsset(bundle, key) {
129
+ const asset = bundle[key];
130
+ if (typeof asset === "undefined")
131
+ throw new TypeError(`OutputBundle["${key}"] is undefined.`);
132
+ if (asset.type !== "asset")
133
+ throw new Error(`OutputBundle["${key}"] is not an OutputAsset.`);
134
+ if (typeof asset.source !== "string")
135
+ throw new TypeError(`OutputBundle["${key}"].source is not a string.`);
136
+ return JSON.parse(asset.source);
137
+ }
138
+ const getMatchPatternOrigin = (pattern) => {
139
+ if (pattern.startsWith("<"))
140
+ return pattern;
136
141
  const [schema, rest] = pattern.split("://");
137
142
  const [origin, pathname] = rest.split("/");
138
143
  const root = `${schema}://${origin}`;
139
144
  return pathname ? `${root}/*` : root;
140
145
  };
141
146
 
142
- const idBySource = /* @__PURE__ */ new Map();
143
- const idByUrl = /* @__PURE__ */ new Map();
144
- const urlById = /* @__PURE__ */ new Map();
145
- function setUrlMeta({
146
- id,
147
- source,
148
- url
149
- }) {
150
- idBySource.set(source, id);
151
- idByUrl.set(url, id);
152
- urlById.set(id, url);
153
- }
154
- const fileById = /* @__PURE__ */ new Map();
155
- const fileByUrl = /* @__PURE__ */ new Map();
156
- const pathById = /* @__PURE__ */ new Map();
157
- const pathByUrl = /* @__PURE__ */ new Map();
158
- const setFileMeta = ({ file, id }) => {
159
- const url = urlById.get(id);
160
- if (!url)
161
- return;
162
- fileById.set(id, file);
163
- fileByUrl.set(url, file);
164
- const pathName = `/${file}`;
165
- pathById.set(id, pathName);
166
- pathByUrl.set(url, pathName);
167
- };
168
- const ownerById = /* @__PURE__ */ new Map();
169
- const pathByOwner = /* @__PURE__ */ new Map();
170
- const ownersByFile = /* @__PURE__ */ new Map();
171
- const setOwnerMeta = ({ owner, id }) => {
172
- const pathName = pathById.get(id);
173
- if (!pathName)
174
- return;
175
- pathByOwner.set(owner, pathName);
176
- ownerById.set(id, owner);
177
- const fileName = fileById.get(id);
178
- const owners = ownersByFile.get(fileName) ?? /* @__PURE__ */ new Set();
179
- owners.add(owner);
180
- ownersByFile.set(fileName, owners);
181
- };
182
- const outputById = /* @__PURE__ */ new Map();
183
- const outputByOwner = /* @__PURE__ */ new Map();
184
- const setOutputMeta = ({
185
- output,
186
- id
187
- }) => {
188
- const ownerName = ownerById.get(id);
189
- if (!ownerName)
190
- return;
191
- outputByOwner.set(ownerName, output);
192
- outputById.set(id, output);
193
- };
194
- const transformResultByOwner = /* @__PURE__ */ new Map();
195
-
196
147
  const {
197
148
  basename,
198
149
  dirname,
@@ -209,168 +160,39 @@ const {
209
160
  sep
210
161
  } = path.posix;
211
162
 
212
- const viteClientId = "/@vite/client";
213
- const customElementsId = "@webcomponents/custom-elements";
214
- const reactRefreshId = "/@react-refresh";
215
- const contentHmrPortId = "/crx-client-port";
216
- const manifestId = "/crx-manifest";
217
- const preambleId = "/crx-client-preamble";
218
- const stubId = "/crx-stub";
219
- const workerClientId = "/crx-client-worker";
220
-
221
- const { readFile: readFile$2 } = fs.promises;
222
- const debug$4 = _debug("file-writer").extend("chunks");
223
- for (const source of [viteClientId, customElementsId]) {
224
- setUrlMeta(sourceToUrlMeta(source));
225
- }
226
- setUrlMeta({
227
- source: reactRefreshId,
228
- id: "/react-refresh",
229
- url: reactRefreshId
230
- });
231
- function sourceToUrlMeta(source) {
232
- const [p, query = ""] = source.split("?");
233
- const pathname = p.replace(/^\/@id\//, "").replace(/^\/@fs/, "");
234
- const url = [pathname, query].filter(isTruthy).join("?");
235
- const hash = createHash(url);
236
- const base = p.split("/").slice(-4).filter(isTruthy).join("-");
237
- const id = `/${base}-${hash}.js`.replace(/[@]/g, "");
238
- return { id, url, source };
239
- }
240
- const pluginFileWriterChunks = () => {
241
- let server;
242
- return {
243
- name: "crx:file-writer-chunks",
244
- apply: "build",
245
- fileWriterStart(_server) {
246
- server = _server;
247
- },
248
- async resolveId(source, importer) {
249
- if (this.meta.watchMode) {
250
- if (idBySource.has(source)) {
251
- const id = idBySource.get(source);
252
- debug$4(`resolved cached ${source} -> ${id}`);
253
- return id;
254
- } else if (importer) {
255
- const meta = sourceToUrlMeta(source);
256
- setUrlMeta(meta);
257
- const { id } = meta;
258
- debug$4(`resolved ${source} -> ${id}`);
259
- return id;
260
- } else {
261
- const [rawUrl] = await server.moduleGraph.resolveUrl(source);
262
- const name = rawUrl.split("/").join("-").replace(/^-/, "");
263
- const url = rawUrl.startsWith("/") ? rawUrl : `/${rawUrl}`;
264
- const id = `/${name}-${createHash(url)}.js`;
265
- setUrlMeta({ url, id, source });
266
- debug$4(`resolved entry ${source} -> ${id}`);
267
- return id;
268
- }
269
- }
270
- },
271
- async load(id) {
272
- if (this.meta.watchMode && urlById.has(id)) {
273
- const url = urlById.get(id);
274
- let serverModule = await server.moduleGraph.getModuleByUrl(url);
275
- let transformResult = null;
276
- if (!serverModule) {
277
- transformResult = await server.transformRequest(url);
278
- serverModule = await server.moduleGraph.getModuleByUrl(url);
279
- }
280
- if (!serverModule)
281
- throw new Error(`Unable to load "${url}" from server.`);
282
- const { file, url: owner } = serverModule;
283
- transformResult = transformResult ?? transformResultByOwner.get(owner) ?? serverModule.transformResult;
284
- if (!transformResult)
285
- transformResult = await server.transformRequest(url);
286
- if (!transformResult)
287
- throw new TypeError(`Unable to load "${url}" from server.`);
288
- transformResultByOwner.set(owner, transformResult);
289
- if (file) {
290
- setFileMeta({ id, file });
291
- this.addWatchFile(file);
292
- if (urlById.get(id).includes("?import"))
293
- this.emitFile({
294
- type: "asset",
295
- fileName: relative(server.config.root, file),
296
- source: await readFile$2(file)
297
- });
298
- }
299
- if (url)
300
- setOwnerMeta({ id, owner });
301
- return { code: transformResult.code, map: transformResult.map };
302
- }
303
- return null;
304
- },
305
- outputOptions(options) {
306
- const cacheDir = relative(server.config.root, server.config.cacheDir);
307
- const fileNameById = /* @__PURE__ */ new Map();
308
- fileNameById.set("/react-refresh", "vendor/react-refresh.js");
309
- function fileNames(info) {
310
- const id = info.type === "chunk" ? info.facadeModuleId : info.name;
311
- if (id && fileNameById.has(id))
312
- return fileNameById.get(id);
313
- let fileName = info.type === "chunk" ? "assets/[name].js" : "assets/[name].[ext]";
314
- if (id && fileById.has(id)) {
315
- fileName = fileById.get(id);
316
- const url = new URL(urlById.get(id), "stub://stub");
317
- if (url.searchParams.has("type"))
318
- fileName += `.${url.searchParams.get("type")}`;
319
- if (url.searchParams.has("index"))
320
- fileName += `.${url.searchParams.get("index")}`;
321
- }
322
- if (id?.startsWith("/@crx/"))
323
- fileName = `vendor/${id.slice("/@crx/".length).split("/").join("-")}`;
324
- if (fileName.startsWith(server.config.root))
325
- fileName = fileName.slice(server.config.root.length + 1);
326
- if (fileName.startsWith(cacheDir))
327
- fileName = `vendor/${fileName.slice(cacheDir.length + 1)}`;
328
- if (fileName.includes("/node_modules/"))
329
- fileName = `vendor/${fileName.split("/node_modules/").pop().split("/").join("-").replace("vite-dist-client", "vite")}`;
330
- if (fileName.startsWith("/"))
331
- fileName = fileName.slice(1);
332
- if (!fileName.endsWith(".js"))
333
- fileName += ".js";
334
- if (id)
335
- fileNameById.set(id, fileName);
336
- fileName = fileName.replace(/:/g, "-").replace(/@/, "");
337
- return fileName;
338
- }
339
- return {
340
- ...options,
341
- preserveModules: true,
342
- assetFileNames: fileNames,
343
- entryFileNames: fileNames
344
- };
345
- },
346
- generateBundle(options, bundle) {
347
- for (const chunk of Object.values(bundle))
348
- if (chunk.type === "chunk") {
349
- const { facadeModuleId: id, modules, code, fileName } = chunk;
350
- if (!id || Object.keys(modules).length !== 1)
351
- continue;
352
- const url = urlById.get(id);
353
- if (url === viteClientId)
354
- continue;
355
- const ownerPath = ownerById.get(id);
356
- if (!ownerPath)
357
- continue;
358
- const index = code.indexOf("createHotContext(");
359
- if (index === -1)
360
- continue;
361
- const start = code.indexOf(ownerPath, index);
362
- const end = start + ownerPath.length;
363
- if (start > 0) {
364
- const outputName = `/${fileName}`;
365
- setOutputMeta({ id, output: outputName });
366
- const magic = new MagicString__default["default"](code);
367
- magic.overwrite(start, end, outputName);
368
- chunk.code = magic.toString();
369
- }
370
- }
163
+ function defineClientValues(code, config) {
164
+ let options = config.server.hmr;
165
+ options = options && typeof options !== "boolean" ? options : {};
166
+ const host = options.host || null;
167
+ const protocol = options.protocol || null;
168
+ const timeout = options.timeout || 3e4;
169
+ const overlay = options.overlay !== false;
170
+ let hmrPort;
171
+ if (isObject(config.server.hmr)) {
172
+ hmrPort = config.server.hmr.clientPort || config.server.hmr.port;
173
+ }
174
+ if (config.server.middlewareMode) {
175
+ hmrPort = String(hmrPort || 24678);
176
+ } else {
177
+ hmrPort = String(hmrPort || options.port || config.server.port);
178
+ }
179
+ let hmrBase = config.base;
180
+ if (options.path) {
181
+ hmrBase = join(hmrBase, options.path);
182
+ }
183
+ if (hmrBase !== "/") {
184
+ hmrPort = normalize(`${hmrPort}${hmrBase}`);
185
+ }
186
+ return code.replace(`__MODE__`, JSON.stringify(config.mode)).replace(`__BASE__`, JSON.stringify(config.base)).replace(`__DEFINES__`, serializeDefine(config.define || {})).replace(`__HMR_PROTOCOL__`, JSON.stringify(protocol)).replace(`__HMR_HOSTNAME__`, JSON.stringify(host)).replace(`__HMR_PORT__`, JSON.stringify(hmrPort)).replace(`__HMR_TIMEOUT__`, JSON.stringify(timeout)).replace(`__HMR_ENABLE_OVERLAY__`, JSON.stringify(overlay)).replace(`__SERVER_PORT__`, JSON.stringify(config.server.port?.toString()));
187
+ function serializeDefine(define) {
188
+ let res = `{`;
189
+ for (const key in define) {
190
+ const val = define[key];
191
+ res += `${JSON.stringify(key)}: ${typeof val === "string" ? `(${val})` : JSON.stringify(val)}, `;
371
192
  }
372
- };
373
- };
193
+ return res + `}`;
194
+ }
195
+ }
374
196
 
375
197
  /******************************************************************************
376
198
  Copyright (c) Microsoft Corporation.
@@ -1269,46 +1091,67 @@ var AnonymousSubject = (function (_super) {
1269
1091
  return AnonymousSubject;
1270
1092
  }(Subject));
1271
1093
 
1272
- var BehaviorSubject = (function (_super) {
1273
- __extends(BehaviorSubject, _super);
1274
- function BehaviorSubject(_value) {
1094
+ var dateTimestampProvider = {
1095
+ now: function () {
1096
+ return (dateTimestampProvider.delegate || Date).now();
1097
+ },
1098
+ delegate: undefined,
1099
+ };
1100
+
1101
+ var ReplaySubject = (function (_super) {
1102
+ __extends(ReplaySubject, _super);
1103
+ function ReplaySubject(_bufferSize, _windowTime, _timestampProvider) {
1104
+ if (_bufferSize === void 0) { _bufferSize = Infinity; }
1105
+ if (_windowTime === void 0) { _windowTime = Infinity; }
1106
+ if (_timestampProvider === void 0) { _timestampProvider = dateTimestampProvider; }
1275
1107
  var _this = _super.call(this) || this;
1276
- _this._value = _value;
1108
+ _this._bufferSize = _bufferSize;
1109
+ _this._windowTime = _windowTime;
1110
+ _this._timestampProvider = _timestampProvider;
1111
+ _this._buffer = [];
1112
+ _this._infiniteTimeWindow = true;
1113
+ _this._infiniteTimeWindow = _windowTime === Infinity;
1114
+ _this._bufferSize = Math.max(1, _bufferSize);
1115
+ _this._windowTime = Math.max(1, _windowTime);
1277
1116
  return _this;
1278
1117
  }
1279
- Object.defineProperty(BehaviorSubject.prototype, "value", {
1280
- get: function () {
1281
- return this.getValue();
1282
- },
1283
- enumerable: false,
1284
- configurable: true
1285
- });
1286
- BehaviorSubject.prototype._subscribe = function (subscriber) {
1287
- var subscription = _super.prototype._subscribe.call(this, subscriber);
1288
- !subscription.closed && subscriber.next(this._value);
1289
- return subscription;
1290
- };
1291
- BehaviorSubject.prototype.getValue = function () {
1292
- var _a = this, hasError = _a.hasError, thrownError = _a.thrownError, _value = _a._value;
1293
- if (hasError) {
1294
- throw thrownError;
1118
+ ReplaySubject.prototype.next = function (value) {
1119
+ var _a = this, isStopped = _a.isStopped, _buffer = _a._buffer, _infiniteTimeWindow = _a._infiniteTimeWindow, _timestampProvider = _a._timestampProvider, _windowTime = _a._windowTime;
1120
+ if (!isStopped) {
1121
+ _buffer.push(value);
1122
+ !_infiniteTimeWindow && _buffer.push(_timestampProvider.now() + _windowTime);
1295
1123
  }
1124
+ this._trimBuffer();
1125
+ _super.prototype.next.call(this, value);
1126
+ };
1127
+ ReplaySubject.prototype._subscribe = function (subscriber) {
1296
1128
  this._throwIfClosed();
1297
- return _value;
1129
+ this._trimBuffer();
1130
+ var subscription = this._innerSubscribe(subscriber);
1131
+ var _a = this, _infiniteTimeWindow = _a._infiniteTimeWindow, _buffer = _a._buffer;
1132
+ var copy = _buffer.slice();
1133
+ for (var i = 0; i < copy.length && !subscriber.closed; i += _infiniteTimeWindow ? 1 : 2) {
1134
+ subscriber.next(copy[i]);
1135
+ }
1136
+ this._checkFinalizedStatuses(subscriber);
1137
+ return subscription;
1298
1138
  };
1299
- BehaviorSubject.prototype.next = function (value) {
1300
- _super.prototype.next.call(this, (this._value = value));
1139
+ ReplaySubject.prototype._trimBuffer = function () {
1140
+ var _a = this, _bufferSize = _a._bufferSize, _timestampProvider = _a._timestampProvider, _buffer = _a._buffer, _infiniteTimeWindow = _a._infiniteTimeWindow;
1141
+ var adjustedBufferSize = (_infiniteTimeWindow ? 1 : 2) * _bufferSize;
1142
+ _bufferSize < Infinity && adjustedBufferSize < _buffer.length && _buffer.splice(0, _buffer.length - adjustedBufferSize);
1143
+ if (!_infiniteTimeWindow) {
1144
+ var now = _timestampProvider.now();
1145
+ var last = 0;
1146
+ for (var i = 1; i < _buffer.length && _buffer[i] <= now; i += 2) {
1147
+ last = i;
1148
+ }
1149
+ last && _buffer.splice(0, last + 1);
1150
+ }
1301
1151
  };
1302
- return BehaviorSubject;
1152
+ return ReplaySubject;
1303
1153
  }(Subject));
1304
1154
 
1305
- var dateTimestampProvider = {
1306
- now: function () {
1307
- return (dateTimestampProvider.delegate || Date).now();
1308
- },
1309
- delegate: undefined,
1310
- };
1311
-
1312
1155
  var Action = (function (_super) {
1313
1156
  __extends(Action, _super);
1314
1157
  function Action(scheduler, work) {
@@ -1481,15 +1324,9 @@ function isScheduler(value) {
1481
1324
  function last(arr) {
1482
1325
  return arr[arr.length - 1];
1483
1326
  }
1484
- function popResultSelector(args) {
1485
- return isFunction(last(args)) ? args.pop() : undefined;
1486
- }
1487
1327
  function popScheduler(args) {
1488
1328
  return isScheduler(last(args)) ? args.pop() : undefined;
1489
1329
  }
1490
- function popNumber(args, defaultValue) {
1491
- return typeof last(args) === 'number' ? args.pop() : defaultValue;
1492
- }
1493
1330
 
1494
1331
  var isArrayLike = (function (x) { return x && typeof x.length === 'number' && typeof x !== 'function'; });
1495
1332
 
@@ -1826,6 +1663,15 @@ function from(input, scheduler) {
1826
1663
  return scheduler ? scheduled(input, scheduler) : innerFrom(input);
1827
1664
  }
1828
1665
 
1666
+ function of() {
1667
+ var args = [];
1668
+ for (var _i = 0; _i < arguments.length; _i++) {
1669
+ args[_i] = arguments[_i];
1670
+ }
1671
+ var scheduler = popScheduler(args);
1672
+ return from(args, scheduler);
1673
+ }
1674
+
1829
1675
  var EmptyError = createErrorClass(function (_super) { return function EmptyErrorImpl() {
1830
1676
  _super(this);
1831
1677
  this.name = 'EmptyError';
@@ -1941,6 +1787,18 @@ function mergeAll(concurrent) {
1941
1787
  return mergeMap(identity, concurrent);
1942
1788
  }
1943
1789
 
1790
+ function concatAll() {
1791
+ return mergeAll(1);
1792
+ }
1793
+
1794
+ function concat$1() {
1795
+ var args = [];
1796
+ for (var _i = 0; _i < arguments.length; _i++) {
1797
+ args[_i] = arguments[_i];
1798
+ }
1799
+ return concatAll()(from(args, popScheduler(args)));
1800
+ }
1801
+
1944
1802
  function timer(dueTime, intervalOrScheduler, scheduler) {
1945
1803
  if (dueTime === void 0) { dueTime = 0; }
1946
1804
  if (scheduler === void 0) { scheduler = async; }
@@ -1973,24 +1831,6 @@ function timer(dueTime, intervalOrScheduler, scheduler) {
1973
1831
  });
1974
1832
  }
1975
1833
 
1976
- function merge() {
1977
- var args = [];
1978
- for (var _i = 0; _i < arguments.length; _i++) {
1979
- args[_i] = arguments[_i];
1980
- }
1981
- var scheduler = popScheduler(args);
1982
- var concurrent = popNumber(args, Infinity);
1983
- var sources = args;
1984
- return !sources.length
1985
- ?
1986
- EMPTY
1987
- : sources.length === 1
1988
- ?
1989
- innerFrom(sources[0])
1990
- :
1991
- mergeAll(concurrent)(from(sources, scheduler));
1992
- }
1993
-
1994
1834
  function filter(predicate, thisArg) {
1995
1835
  return operate(function (source, subscriber) {
1996
1836
  var index = 0;
@@ -2016,36 +1856,57 @@ function buffer(closingNotifier) {
2016
1856
  });
2017
1857
  }
2018
1858
 
2019
- function debounce(durationSelector) {
2020
- return operate(function (source, subscriber) {
2021
- var hasValue = false;
2022
- var lastValue = null;
2023
- var durationSubscriber = null;
2024
- var emit = function () {
2025
- durationSubscriber === null || durationSubscriber === void 0 ? void 0 : durationSubscriber.unsubscribe();
2026
- durationSubscriber = null;
2027
- if (hasValue) {
2028
- hasValue = false;
2029
- var value = lastValue;
2030
- lastValue = null;
2031
- subscriber.next(value);
2032
- }
2033
- };
1859
+ function scanInternals(accumulator, seed, hasSeed, emitOnNext, emitBeforeComplete) {
1860
+ return function (source, subscriber) {
1861
+ var hasState = hasSeed;
1862
+ var state = seed;
1863
+ var index = 0;
2034
1864
  source.subscribe(createOperatorSubscriber(subscriber, function (value) {
2035
- durationSubscriber === null || durationSubscriber === void 0 ? void 0 : durationSubscriber.unsubscribe();
2036
- hasValue = true;
2037
- lastValue = value;
2038
- durationSubscriber = createOperatorSubscriber(subscriber, emit, noop);
2039
- innerFrom(durationSelector(value)).subscribe(durationSubscriber);
2040
- }, function () {
2041
- emit();
2042
- subscriber.complete();
2043
- }, undefined, function () {
2044
- lastValue = durationSubscriber = null;
2045
- }));
1865
+ var i = index++;
1866
+ state = hasState
1867
+ ?
1868
+ accumulator(state, value, i)
1869
+ :
1870
+ ((hasState = true), value);
1871
+ emitOnNext && subscriber.next(state);
1872
+ }, emitBeforeComplete &&
1873
+ (function () {
1874
+ hasState && subscriber.next(state);
1875
+ subscriber.complete();
1876
+ })));
1877
+ };
1878
+ }
1879
+
1880
+ function reduce(accumulator, seed) {
1881
+ return operate(scanInternals(accumulator, seed, arguments.length >= 2, false, true));
1882
+ }
1883
+
1884
+ var arrReducer = function (arr, value) { return (arr.push(value), arr); };
1885
+ function toArray() {
1886
+ return operate(function (source, subscriber) {
1887
+ reduce(arrReducer, [])(source).subscribe(subscriber);
1888
+ });
1889
+ }
1890
+
1891
+ function concat() {
1892
+ var args = [];
1893
+ for (var _i = 0; _i < arguments.length; _i++) {
1894
+ args[_i] = arguments[_i];
1895
+ }
1896
+ var scheduler = popScheduler(args);
1897
+ return operate(function (source, subscriber) {
1898
+ concatAll()(from(__spreadArray([source], __read(args)), scheduler)).subscribe(subscriber);
2046
1899
  });
2047
1900
  }
2048
1901
 
1902
+ function concatWith() {
1903
+ var otherSources = [];
1904
+ for (var _i = 0; _i < arguments.length; _i++) {
1905
+ otherSources[_i] = arguments[_i];
1906
+ }
1907
+ return concat.apply(void 0, __spreadArray([], __read(otherSources)));
1908
+ }
1909
+
2049
1910
  function defaultIfEmpty(defaultValue) {
2050
1911
  return operate(function (source, subscriber) {
2051
1912
  var hasValue = false;
@@ -2099,6 +1960,81 @@ function first(predicate, defaultValue) {
2099
1960
  };
2100
1961
  }
2101
1962
 
1963
+ function retry(configOrCount) {
1964
+ if (configOrCount === void 0) { configOrCount = Infinity; }
1965
+ var config;
1966
+ if (configOrCount && typeof configOrCount === 'object') {
1967
+ config = configOrCount;
1968
+ }
1969
+ else {
1970
+ config = {
1971
+ count: configOrCount,
1972
+ };
1973
+ }
1974
+ var _a = config.count, count = _a === void 0 ? Infinity : _a, delay = config.delay, _b = config.resetOnSuccess, resetOnSuccess = _b === void 0 ? false : _b;
1975
+ return count <= 0
1976
+ ? identity
1977
+ : operate(function (source, subscriber) {
1978
+ var soFar = 0;
1979
+ var innerSub;
1980
+ var subscribeForRetry = function () {
1981
+ var syncUnsub = false;
1982
+ innerSub = source.subscribe(createOperatorSubscriber(subscriber, function (value) {
1983
+ if (resetOnSuccess) {
1984
+ soFar = 0;
1985
+ }
1986
+ subscriber.next(value);
1987
+ }, undefined, function (err) {
1988
+ if (soFar++ < count) {
1989
+ var resub_1 = function () {
1990
+ if (innerSub) {
1991
+ innerSub.unsubscribe();
1992
+ innerSub = null;
1993
+ subscribeForRetry();
1994
+ }
1995
+ else {
1996
+ syncUnsub = true;
1997
+ }
1998
+ };
1999
+ if (delay != null) {
2000
+ var notifier = typeof delay === 'number' ? timer(delay) : innerFrom(delay(err, soFar));
2001
+ var notifierSubscriber_1 = createOperatorSubscriber(subscriber, function () {
2002
+ notifierSubscriber_1.unsubscribe();
2003
+ resub_1();
2004
+ }, function () {
2005
+ subscriber.complete();
2006
+ });
2007
+ notifier.subscribe(notifierSubscriber_1);
2008
+ }
2009
+ else {
2010
+ resub_1();
2011
+ }
2012
+ }
2013
+ else {
2014
+ subscriber.error(err);
2015
+ }
2016
+ }));
2017
+ if (syncUnsub) {
2018
+ innerSub.unsubscribe();
2019
+ innerSub = null;
2020
+ subscribeForRetry();
2021
+ }
2022
+ };
2023
+ subscribeForRetry();
2024
+ });
2025
+ }
2026
+
2027
+ function startWith() {
2028
+ var values = [];
2029
+ for (var _i = 0; _i < arguments.length; _i++) {
2030
+ values[_i] = arguments[_i];
2031
+ }
2032
+ var scheduler = popScheduler(values);
2033
+ return operate(function (source, subscriber) {
2034
+ (scheduler ? concat$1(values, source, scheduler) : concat$1(values, source)).subscribe(subscriber);
2035
+ });
2036
+ }
2037
+
2102
2038
  function switchMap(project, resultSelector) {
2103
2039
  return operate(function (source, subscriber) {
2104
2040
  var innerSubscriber = null;
@@ -2120,184 +2056,478 @@ function switchMap(project, resultSelector) {
2120
2056
  });
2121
2057
  }
2122
2058
 
2123
- function withLatestFrom() {
2124
- var inputs = [];
2125
- for (var _i = 0; _i < arguments.length; _i++) {
2126
- inputs[_i] = arguments[_i];
2127
- }
2128
- var project = popResultSelector(inputs);
2059
+ function takeUntil(notifier) {
2129
2060
  return operate(function (source, subscriber) {
2130
- var len = inputs.length;
2131
- var otherValues = new Array(len);
2132
- var hasValue = inputs.map(function () { return false; });
2133
- var ready = false;
2134
- var _loop_1 = function (i) {
2135
- innerFrom(inputs[i]).subscribe(createOperatorSubscriber(subscriber, function (value) {
2136
- otherValues[i] = value;
2137
- if (!ready && !hasValue[i]) {
2138
- hasValue[i] = true;
2139
- (ready = hasValue.every(identity)) && (hasValue = null);
2140
- }
2141
- }, noop));
2142
- };
2143
- for (var i = 0; i < len; i++) {
2144
- _loop_1(i);
2145
- }
2146
- source.subscribe(createOperatorSubscriber(subscriber, function (value) {
2147
- if (ready) {
2148
- var values = __spreadArray([value], __read(otherValues));
2149
- subscriber.next(project ? project.apply(void 0, __spreadArray([], __read(values))) : values);
2150
- }
2151
- }));
2061
+ innerFrom(notifier).subscribe(createOperatorSubscriber(subscriber, function () { return subscriber.complete(); }, noop));
2062
+ !subscriber.closed && source.subscribe(subscriber);
2152
2063
  });
2153
2064
  }
2154
2065
 
2155
- const { pathExistsSync, outputFile, statSync } = fsExtra__default["default"];
2156
- const debug$3 = _debug("file-writer").extend("events");
2157
- const writerEvent$ = new BehaviorSubject({
2158
- type: "init"
2159
- });
2160
- writerEvent$.subscribe((event) => {
2161
- debug$3("watcher event %O", event.type);
2162
- if (event.type === "error") {
2163
- debug$3("watcher error %O", event.error);
2066
+ class RxMap extends Map {
2067
+ static isChangeType = {
2068
+ clear: (x) => x.type === "clear",
2069
+ delete: (x) => x.type === "delete",
2070
+ set: (x) => x.type === "set"
2071
+ };
2072
+ change$;
2073
+ constructor(iterable) {
2074
+ super(iterable);
2075
+ const change$ = new Subject();
2076
+ this.change$ = change$.asObservable();
2077
+ const changeMethodKeys = ["clear", "set", "delete"];
2078
+ for (const type of changeMethodKeys) {
2079
+ const method = this[type];
2080
+ this[type] = function(...args) {
2081
+ const result = method.call(this, ...args);
2082
+ change$.next({ type, key: args[0], value: args[1], map: this });
2083
+ return result;
2084
+ }.bind(this);
2085
+ }
2164
2086
  }
2165
- });
2166
- const filesError$ = writerEvent$.pipe(filter((x) => {
2167
- return x.type === "error";
2168
- }));
2169
- const filesStart$ = writerEvent$.pipe(filter((x) => {
2170
- return x.type === "buildStart";
2171
- }));
2172
- const filesStart = () => firstValueFrom(filesStart$);
2173
- const filesReady$ = writerEvent$.pipe(filter((x) => {
2174
- return x.type === "writeBundle";
2175
- }), switchMap((event) => timer(0, 100).pipe(map(() => event), first(({ bundle, options, timestamp }) => {
2176
- const result = Object.keys(bundle).every((p) => {
2177
- const stats = statSync(join(options.dir, p));
2178
- return stats.mtimeMs > timestamp;
2179
- });
2180
- return result;
2181
- }))));
2182
- const filesReady = () => firstValueFrom(filesReady$);
2183
- const server$ = new Subject();
2184
- const triggerName = firstValueFrom(server$.pipe(map(({ config: { cacheDir } }) => cacheDir), filter(isString), map((dir) => join(dir, ".crx-watch-trigger"))));
2185
- const rebuildFiles = async () => {
2186
- debug$3("rebuildFiles start");
2187
- await filesReady();
2188
- await Promise.all([
2189
- outputFile(await triggerName, Date.now().toString()),
2190
- filesStart()
2191
- ]);
2192
- await filesReady();
2193
- debug$3("rebuildFiles end");
2194
- };
2195
- function startLogger(server) {
2196
- const logger = vite.createLogger(server.config.logLevel, {
2197
- prefix: "[crx]"
2198
- });
2199
- const subs = [
2200
- filesStart$.subscribe(() => {
2201
- const message = colors__default["default"].green("files start");
2202
- const outDir = colors__default["default"].dim(relative(server.config.root, server.config.build.outDir));
2203
- logger.info(`${message} ${outDir}`, { timestamp: true });
2204
- }),
2205
- filesReady$.subscribe(({ duration: d }) => {
2206
- const message = colors__default["default"].green("files ready");
2207
- const duration = colors__default["default"].dim(`in ${colors__default["default"].bold(`${d}ms`)}`);
2208
- logger.info(`${message} ${duration}`, { timestamp: true });
2209
- }),
2210
- filesError$.subscribe(({ error }) => {
2211
- logger.error(colors__default["default"].dim("error from file writer:"), { timestamp: true });
2212
- if (error) {
2213
- const message = error?.stack ?? error.message;
2214
- logger.error(colors__default["default"].red(message));
2215
- }
2216
- })
2217
- ];
2218
- return () => subs.forEach((sub) => sub.unsubscribe());
2219
2087
  }
2220
- const pluginFileWriterEvents = () => {
2221
- let start = perf_hooks.performance.now();
2222
- let stopLogger;
2223
- return {
2224
- name: "crx:file-writer-events",
2225
- enforce: "post",
2226
- apply: "build",
2227
- fileWriterStart(server) {
2228
- debug$3("fileWriterStart");
2229
- stopLogger = startLogger(server);
2230
- },
2231
- closeWatcher() {
2232
- debug$3("closeWatcher");
2233
- stopLogger();
2234
- },
2235
- async buildStart(options) {
2236
- start = perf_hooks.performance.now();
2237
- const filename = await triggerName;
2238
- if (!pathExistsSync(filename)) {
2239
- await outputFile(filename, Date.now().toString());
2088
+
2089
+ const outputFiles = new RxMap();
2090
+
2091
+ _debug("file-writer").extend("utilities");
2092
+ function prefix$1(prefix2, text) {
2093
+ return text.startsWith(prefix2) ? text : prefix2 + text;
2094
+ }
2095
+ function strip(prefix2, text) {
2096
+ return text?.startsWith(prefix2) ? text?.slice(prefix2.length) : text;
2097
+ }
2098
+ function formatFileData(script) {
2099
+ script.id = prefix$1("/", script.id);
2100
+ if (script.fileName)
2101
+ script.fileName = strip("/", script.fileName);
2102
+ if (script.loaderName)
2103
+ script.loaderName = strip("/", script.loaderName);
2104
+ return script;
2105
+ }
2106
+ function getFileName({ type, id }) {
2107
+ let fileName = id.replace(/t=\d+&/, "").replace(/^\//, "").replace(/\?/g, "__").replace(/&/g, "_").replace(/=/g, "--");
2108
+ if (fileName.includes("node_modules/")) {
2109
+ fileName = `vendor/${fileName.split("node_modules/").pop().replace(/\//g, "-")}`;
2110
+ } else if (fileName.startsWith("@")) {
2111
+ fileName = `vendor/${fileName.slice("@".length).replace(/\//g, "-")}`;
2112
+ } else if (fileName.startsWith(".vite/deps/")) {
2113
+ fileName = `vendor/${fileName.slice(".vite/deps/".length)}`;
2114
+ }
2115
+ switch (type) {
2116
+ case "iife":
2117
+ return `${fileName}.iife.js`;
2118
+ case "loader":
2119
+ return `${fileName}-loader.js`;
2120
+ case "module":
2121
+ return `${fileName}.js`;
2122
+ case "asset":
2123
+ return fileName;
2124
+ default:
2125
+ throw new Error(`Unexpected script type "${type}" for "${JSON.stringify({
2126
+ type,
2127
+ id
2128
+ })}"`);
2129
+ }
2130
+ }
2131
+ function getOutputPath(server, fileName) {
2132
+ const {
2133
+ root,
2134
+ build: { outDir }
2135
+ } = server.config;
2136
+ const target = isAbsolute(outDir) ? join(outDir, fileName) : join(root, outDir, fileName);
2137
+ return target;
2138
+ }
2139
+ function getViteUrl({ type, id }) {
2140
+ if (type === "asset") {
2141
+ throw new Error(`File type "${type}" not implemented.`);
2142
+ } else if (type === "iife") {
2143
+ throw new Error(`File type "${type}" not implemented.`);
2144
+ } else if (type === "loader") {
2145
+ throw new Error("Vite does not transform loader files.");
2146
+ } else if (type === "module") {
2147
+ if (id.startsWith("/@id/"))
2148
+ return id.slice("/@id/".length).replace("__x00__", "\0");
2149
+ return prefix$1("/", id);
2150
+ } else {
2151
+ throw new Error(`Invalid file type: "${type}"`);
2152
+ }
2153
+ }
2154
+ async function fileReady(script) {
2155
+ const fileName = getFileName(script);
2156
+ const file = outputFiles.get(fileName);
2157
+ if (!file)
2158
+ throw new Error("unknown script type and id");
2159
+ const { deps } = await file.file;
2160
+ await Promise.all(deps.map(fileReady));
2161
+ }
2162
+
2163
+ const viteClientId = "/@vite/client";
2164
+ const customElementsId = "/@webcomponents/custom-elements";
2165
+ const contentHmrPortId = "/@crx/client-port";
2166
+ const manifestId = "/@crx/manifest";
2167
+ const preambleId = "/@crx/client-preamble";
2168
+ const stubId = "/@crx/stub";
2169
+ const workerClientId = "/@crx/client-worker";
2170
+
2171
+ const pluginBackground = () => {
2172
+ let config;
2173
+ return [
2174
+ {
2175
+ name: "crx:background-client",
2176
+ apply: "serve",
2177
+ resolveId(source) {
2178
+ if (source === `/${workerClientId}`)
2179
+ return workerClientId;
2180
+ },
2181
+ load(id) {
2182
+ if (id === workerClientId) {
2183
+ const base = `http://localhost:${config.server.port}/`;
2184
+ return defineClientValues(workerHmrClient.replace("__BASE__", JSON.stringify(base)), config);
2185
+ }
2240
2186
  }
2241
- this.addWatchFile(filename);
2242
- writerEvent$.next({ type: "buildStart", options });
2243
- debug$3("buildStart");
2244
2187
  },
2245
- writeBundle(options, bundle) {
2246
- const timestamp = perf_hooks.performance.now();
2247
- const duration = Math.round(timestamp - start);
2248
- writerEvent$.next({
2249
- type: "writeBundle",
2250
- options,
2251
- bundle,
2252
- duration,
2253
- timestamp
2254
- });
2255
- debug$3("writeBundle");
2256
- },
2257
- renderError(error) {
2258
- writerEvent$.next({ type: "error", error });
2259
- },
2260
- watchChange(id, { event }) {
2261
- writerEvent$.next({ type: "change", id, event });
2188
+ {
2189
+ name: "crx:background-loader-file",
2190
+ enforce: "post",
2191
+ configResolved(_config) {
2192
+ config = _config;
2193
+ },
2194
+ renderCrxManifest(manifest) {
2195
+ const worker = manifest.background?.service_worker;
2196
+ let loader;
2197
+ if (config.command === "serve") {
2198
+ const port = config.server.port?.toString();
2199
+ if (typeof port === "undefined")
2200
+ throw new Error("server port is undefined in watch mode");
2201
+ loader = `import 'http:/localhost:${port}/@vite/env';
2202
+ `;
2203
+ loader += `import 'http://localhost:${port}${workerClientId}';
2204
+ `;
2205
+ if (worker)
2206
+ loader += `import 'http://localhost:${port}/${worker}';
2207
+ `;
2208
+ } else if (worker) {
2209
+ loader = `import './${worker}';
2210
+ `;
2211
+ } else {
2212
+ return null;
2213
+ }
2214
+ const refId = this.emitFile({
2215
+ type: "asset",
2216
+ fileName: getFileName({ type: "loader", id: "service-worker" }),
2217
+ source: loader
2218
+ });
2219
+ manifest.background = {
2220
+ service_worker: this.getFileName(refId),
2221
+ type: "module"
2222
+ };
2223
+ return manifest;
2224
+ }
2262
2225
  }
2263
- };
2226
+ ];
2264
2227
  };
2265
2228
 
2266
- var precontrollerScript = "const id = setInterval(() => location.reload(), 100);\nsetTimeout(() => clearInterval(id), 5e3);\n";
2229
+ var contentHmrPort = "function isCrxHMRPayload(x) {\n return x.type === \"custom\" && x.event.startsWith(\"crx:\");\n}\nclass HMRPort {\n port;\n callbacks = /* @__PURE__ */ new Map();\n constructor() {\n setInterval(() => {\n try {\n this.port?.postMessage({ data: \"ping\" });\n } catch (error) {\n if (error instanceof Error && error.message.includes(\"Extension context invalidated.\")) {\n location.reload();\n } else\n throw error;\n }\n }, __CRX_HMR_TIMEOUT__);\n setInterval(this.initPort, 5 * 60 * 1e3);\n this.initPort();\n }\n initPort = () => {\n this.port?.disconnect();\n this.port = chrome.runtime.connect({ name: \"@crx/client\" });\n this.port.onDisconnect.addListener(this.handleDisconnect.bind(this));\n this.port.onMessage.addListener(this.handleMessage.bind(this));\n this.port.postMessage({ type: \"connected\" });\n };\n handleDisconnect = () => {\n if (this.callbacks.has(\"close\"))\n for (const cb of this.callbacks.get(\"close\")) {\n cb({ wasClean: true });\n }\n };\n handleMessage = (message) => {\n const forward = (data) => {\n if (this.callbacks.has(\"message\"))\n for (const cb of this.callbacks.get(\"message\")) {\n cb({ data });\n }\n };\n const payload = JSON.parse(message.data);\n if (isCrxHMRPayload(payload)) {\n if (payload.event === \"crx:runtime-reload\") {\n console.log(\"[crx] runtime reload\");\n setTimeout(() => location.reload(), 500);\n } else {\n forward(JSON.stringify(payload.data));\n }\n } else {\n forward(message.data);\n }\n };\n addEventListener = (event, callback) => {\n const cbs = this.callbacks.get(event) ?? /* @__PURE__ */ new Set();\n cbs.add(callback);\n this.callbacks.set(event, cbs);\n };\n send = (data) => {\n if (this.port)\n this.port.postMessage({ data });\n else\n throw new Error(\"HMRPort is not initialized\");\n };\n}\n\nexport { HMRPort };\n";
2267
2230
 
2268
- var precontrollerHtml = "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <title>Waiting for the extension service worker...</title>\n <script src=\"%PATH%\"></script>\n </head>\n <body>\n <h1>Waiting for service worker</h1>\n\n <p>\n If you see this message, it means the service worker has not loaded fully.\n </p>\n\n <p>This page is never added in production.</p>\n </body>\n</html>\n";
2231
+ var contentDevLoader = "(function () {\n 'use strict';\n\n (async () => {\n if (__PREAMBLE__)\n await import(\n /* @vite-ignore */\n chrome.runtime.getURL(__PREAMBLE__)\n );\n await import(\n /* @vite-ignore */\n chrome.runtime.getURL(__CLIENT__)\n );\n await import(\n /* @vite-ignore */\n chrome.runtime.getURL(__SCRIPT__)\n );\n })().catch(console.error);\n\n})();\n";
2269
2232
 
2270
- const pluginFileWriterHtml = () => {
2271
- let precontrollerName;
2272
- return {
2273
- name: "crx:file-writer-html",
2274
- apply: "build",
2275
- fileWriterStart(server) {
2276
- const plugins = server.config.plugins;
2277
- const i = plugins.findIndex(({ name }) => name === "alias");
2278
- plugins.splice(i, 0, {
2279
- name: "crx:load-precontroller",
2280
- apply: "serve",
2281
- load(id) {
2282
- if (id === `/${precontrollerName}`)
2283
- return "location.reload();";
2233
+ var contentProLoader = "(function () {\n 'use strict';\n\n (async () => {\n await import(\n /* @vite-ignore */\n chrome.runtime.getURL(__SCRIPT__)\n );\n })().catch(console.error);\n\n})();\n";
2234
+
2235
+ const contentScripts = new RxMap();
2236
+ contentScripts.change$.pipe(filter(RxMap.isChangeType.set)).subscribe(({ map, value }) => {
2237
+ const keyNames = [
2238
+ "refId",
2239
+ "id",
2240
+ "fileName",
2241
+ "loaderName",
2242
+ "resolvedId",
2243
+ "scriptId"
2244
+ ];
2245
+ for (const keyName of keyNames) {
2246
+ const key = value[keyName];
2247
+ if (typeof key === "undefined" || map.has(key)) {
2248
+ continue;
2249
+ } else {
2250
+ map.set(key, value);
2251
+ }
2252
+ }
2253
+ });
2254
+ function hashScriptId(script) {
2255
+ return hash(`${script.type}&${script.id}`);
2256
+ }
2257
+ function createDevLoader({
2258
+ preamble,
2259
+ client,
2260
+ fileName
2261
+ }) {
2262
+ return contentDevLoader.replace(/__PREAMBLE__/g, JSON.stringify(preamble)).replace(/__CLIENT__/g, JSON.stringify(client)).replace(/__SCRIPT__/g, JSON.stringify(fileName)).replace(/__TIMESTAMP__/g, JSON.stringify(Date.now()));
2263
+ }
2264
+ function createProLoader({ fileName }) {
2265
+ return contentProLoader.replace(/__SCRIPT__/g, JSON.stringify(fileName));
2266
+ }
2267
+
2268
+ const serverEvent$ = new ReplaySubject(1);
2269
+ const close$ = serverEvent$.pipe(filter((e) => e.type === "close"), switchMap((e) => of(e)));
2270
+ const start$ = serverEvent$.pipe(filter((e) => e.type === "start"), switchMap((e) => of(e)));
2271
+ const fileWriterEvent$ = new ReplaySubject(1);
2272
+ const buildEnd$ = fileWriterEvent$.pipe(filter((e) => e.type === "build_end"), switchMap((e) => of(e)));
2273
+ fileWriterEvent$.pipe(filter((e) => e.type === "build_start"), switchMap((e) => of(e)));
2274
+ const allFilesReady$ = buildEnd$.pipe(switchMap(() => outputFiles.change$.pipe(startWith({ type: "start" }))), map(() => [...outputFiles.values()]), switchMap((files) => Promise.allSettled(files.map(({ file }) => file))));
2275
+ const isRejected = (x) => x?.status === "rejected";
2276
+ const fileWriterError$ = allFilesReady$.pipe(mergeMap((results) => results.filter(isRejected)), map((rejected) => ({ err: rejected.reason, type: "error" })));
2277
+ firstValueFrom(fileWriterError$.pipe(takeUntil(serverEvent$.pipe(first(({ type }) => type === "close"))), toArray()));
2278
+ function prepFileData(fileId) {
2279
+ const fileName = getFileName(fileId);
2280
+ if (fileId.type === "asset") {
2281
+ return prepAsset(fileName, fileId);
2282
+ } else {
2283
+ return prepScript(fileName, fileId);
2284
+ }
2285
+ }
2286
+ function prepAsset(fileName, { id, source }) {
2287
+ return ($) => $.pipe(mergeMap(async ({ server }) => {
2288
+ const target = getOutputPath(server, fileName);
2289
+ return {
2290
+ target,
2291
+ source: source ?? await promises.readFile(join(server.config.root, id)),
2292
+ deps: []
2293
+ };
2294
+ }));
2295
+ }
2296
+ function prepScript(fileName, script) {
2297
+ return ($) => $.pipe(mergeMap(async ({ server }) => {
2298
+ const target = getOutputPath(server, fileName);
2299
+ const viteUrl = getViteUrl(script);
2300
+ const transformResult = await server.transformRequest(viteUrl);
2301
+ if (!transformResult)
2302
+ throw new TypeError(`Unable to load "${script.id}" from server.`);
2303
+ const { code, deps = [], dynamicDeps = [] } = transformResult;
2304
+ return { target, code, deps: [...deps, ...dynamicDeps].flat(), server };
2305
+ }), retry({ count: 10, delay: 100 }), mergeMap(async ({ target, server, ...rest }) => {
2306
+ const plugins = server.config.plugins;
2307
+ let { code, deps } = rest;
2308
+ for (const plugin of plugins) {
2309
+ const r = await plugin.renderCrxDevScript?.(code, script);
2310
+ if (typeof r === "string")
2311
+ code = r;
2312
+ }
2313
+ return { target, code, deps };
2314
+ }), mergeMap(async ({ target, code, deps }) => {
2315
+ await lexer__namespace.init;
2316
+ const [imports] = lexer__namespace.parse(code, fileName);
2317
+ const depSet = new Set(deps);
2318
+ const magic = new MagicString__default["default"](code);
2319
+ for (const i of imports)
2320
+ if (i.n) {
2321
+ depSet.add(i.n);
2322
+ const fileName2 = getFileName({ type: "module", id: i.n });
2323
+ magic.overwrite(i.s, i.e, `/${fileName2}`);
2324
+ }
2325
+ return { target, source: magic.toString(), deps: [...depSet] };
2326
+ }));
2327
+ }
2328
+ async function allFilesReady() {
2329
+ await firstValueFrom(allFilesReady$);
2330
+ }
2331
+
2332
+ const { outputFile } = fsx__default["default"];
2333
+ _debug("file-writer");
2334
+ async function start({
2335
+ server
2336
+ }) {
2337
+ serverEvent$.next({ type: "start", server });
2338
+ const plugins = server.config.plugins.filter((p) => p.name?.startsWith("crx:"));
2339
+ const { rollupOptions, outDir } = server.config.build;
2340
+ const inputOptions = {
2341
+ input: "index.html",
2342
+ ...rollupOptions,
2343
+ plugins
2344
+ };
2345
+ const rollupOutputOptions = [rollupOptions.output].flat()[0];
2346
+ const outputOptions = {
2347
+ ...rollupOutputOptions,
2348
+ dir: outDir,
2349
+ format: "es"
2350
+ };
2351
+ fileWriterEvent$.next({ type: "build_start" });
2352
+ const build = await rollup.rollup(inputOptions);
2353
+ await build.write(outputOptions);
2354
+ fileWriterEvent$.next({ type: "build_end" });
2355
+ await allFilesReady();
2356
+ }
2357
+ async function close() {
2358
+ serverEvent$.next({ type: "close" });
2359
+ }
2360
+ function add(script) {
2361
+ const fileName = getFileName(script);
2362
+ let file = outputFiles.get(fileName);
2363
+ if (typeof file === "undefined") {
2364
+ file = formatFileData({
2365
+ ...script,
2366
+ fileName,
2367
+ file: write(script)
2368
+ });
2369
+ outputFiles.set(file.fileName, file);
2370
+ }
2371
+ return file;
2372
+ }
2373
+ function update(_id) {
2374
+ const id = prefix$1("/", _id);
2375
+ const types = ["iife", "module"];
2376
+ const updatedFiles = [];
2377
+ for (const type of types) {
2378
+ const fileName = getFileName({ id, type });
2379
+ const scriptFile = outputFiles.get(fileName);
2380
+ if (scriptFile) {
2381
+ scriptFile.file = write({ id, type });
2382
+ updatedFiles.push(scriptFile);
2383
+ outputFiles.set(fileName, scriptFile);
2384
+ }
2385
+ }
2386
+ return updatedFiles;
2387
+ }
2388
+ async function write(fileId) {
2389
+ const start2 = perf_hooks.performance.now();
2390
+ const deps = await firstValueFrom(start$.pipe(prepFileData(fileId), mergeMap(async ({ target, source, deps: deps2 }) => {
2391
+ const files = deps2.map((id) => {
2392
+ const r = [add({ id, type: "module" })];
2393
+ if (id.includes("?import")) {
2394
+ const [imported] = id.split("?import");
2395
+ r.push(add({ id: imported, type: "asset" }));
2396
+ }
2397
+ return r;
2398
+ }).flat();
2399
+ if (source instanceof Uint8Array)
2400
+ await outputFile(target, source);
2401
+ else
2402
+ await outputFile(target, source, { encoding: "utf8" });
2403
+ return files;
2404
+ }), takeUntil(close$), concatWith(of([]))));
2405
+ const close2 = perf_hooks.performance.now();
2406
+ return { start: start2, close: close2, deps };
2407
+ }
2408
+
2409
+ const pluginContentScripts = () => {
2410
+ let server;
2411
+ let preambleCode;
2412
+ let hmrTimeout;
2413
+ let sub = new Subscription();
2414
+ return [
2415
+ {
2416
+ name: "crx:content-scripts",
2417
+ apply: "serve",
2418
+ config(config) {
2419
+ const { contentScripts: contentScripts2 = {} } = getOptions(config);
2420
+ hmrTimeout = contentScripts2.hmrTimeout ?? 5e3;
2421
+ preambleCode = preambleCode ?? contentScripts2.preambleCode;
2422
+ },
2423
+ async configureServer(_server) {
2424
+ server = _server;
2425
+ if (typeof preambleCode === "undefined" && server.config.plugins.some(({ name = "none" }) => name.toLowerCase().includes("react"))) {
2426
+ try {
2427
+ const react = await Promise.resolve().then(function () { return /*#__PURE__*/_interopNamespace(require('@vitejs/plugin-react')); });
2428
+ preambleCode = react.default.preambleCode;
2429
+ } catch (error) {
2430
+ preambleCode = false;
2431
+ }
2284
2432
  }
2285
- });
2433
+ sub.add(contentScripts.change$.pipe(filter(RxMap.isChangeType.set)).subscribe(({ value: script }) => {
2434
+ const { type, id } = script;
2435
+ if (type === "loader") {
2436
+ let preamble = { fileName: "" };
2437
+ if (preambleCode)
2438
+ preamble = add({ type: "module", id: preambleId });
2439
+ const client = add({ type: "module", id: viteClientId });
2440
+ const file = add({ type: "module", id });
2441
+ const loader = add({
2442
+ type: "asset",
2443
+ id: getFileName({ type: "loader", id }),
2444
+ source: createDevLoader({
2445
+ preamble: preamble.fileName,
2446
+ client: client.fileName,
2447
+ fileName: file.fileName
2448
+ })
2449
+ });
2450
+ script.fileName = loader.fileName;
2451
+ } else if (type === "iife") {
2452
+ throw new Error("IIFE content scripts are not implemented");
2453
+ } else {
2454
+ const file = add({ type: "module", id });
2455
+ script.fileName = file.fileName;
2456
+ }
2457
+ }));
2458
+ },
2459
+ resolveId(source) {
2460
+ if (source === preambleId)
2461
+ return preambleId;
2462
+ if (source === contentHmrPortId)
2463
+ return contentHmrPortId;
2464
+ },
2465
+ load(id) {
2466
+ if (id === preambleId && typeof preambleCode === "string") {
2467
+ const defined = preambleCode.replace(/__BASE__/g, server.config.base);
2468
+ return defined;
2469
+ }
2470
+ if (id === contentHmrPortId) {
2471
+ const defined = contentHmrPort.replace("__CRX_HMR_TIMEOUT__", JSON.stringify(hmrTimeout));
2472
+ return defined;
2473
+ }
2474
+ },
2475
+ closeBundle() {
2476
+ sub.unsubscribe();
2477
+ sub = new Subscription();
2478
+ }
2479
+ },
2480
+ {
2481
+ name: "crx:content-scripts",
2482
+ apply: "build",
2483
+ enforce: "pre",
2484
+ generateBundle() {
2485
+ for (const [key, script] of contentScripts)
2486
+ if (key === script.refId) {
2487
+ if (script.type === "module") {
2488
+ const fileName = this.getFileName(script.refId);
2489
+ script.fileName = fileName;
2490
+ } else if (script.type === "loader") {
2491
+ const fileName = this.getFileName(script.refId);
2492
+ script.fileName = fileName;
2493
+ const refId = this.emitFile({
2494
+ type: "asset",
2495
+ name: getFileName({ type: "loader", id: basename(script.id) }),
2496
+ source: createProLoader({ fileName })
2497
+ });
2498
+ script.loaderName = this.getFileName(refId);
2499
+ } else if (script.type === "iife") {
2500
+ throw new Error("IIFE content scripts are not implemented");
2501
+ }
2502
+ contentScripts.set(script.refId, formatFileData(script));
2503
+ }
2504
+ }
2505
+ }
2506
+ ];
2507
+ };
2508
+
2509
+ const pluginContentScriptsCss = () => {
2510
+ let injectCss;
2511
+ return {
2512
+ name: "crx:content-scripts-css",
2513
+ enforce: "post",
2514
+ config(config) {
2515
+ const { contentScripts: contentScripts2 = {} } = getOptions(config);
2516
+ injectCss = contentScripts2.injectCss ?? true;
2286
2517
  },
2287
2518
  renderCrxManifest(manifest) {
2288
- if (this.meta.watchMode) {
2289
- const refId = this.emitFile({
2290
- type: "asset",
2291
- name: "precontroller.js",
2292
- source: precontrollerScript
2293
- });
2294
- precontrollerName = this.getFileName(refId);
2295
- for (const fileName of htmlFiles(manifest)) {
2296
- this.emitFile({
2297
- type: "asset",
2298
- fileName,
2299
- source: precontrollerHtml.replace("%PATH%", `/${precontrollerName}`)
2300
- });
2519
+ if (injectCss) {
2520
+ if (manifest.content_scripts) {
2521
+ for (const script of manifest.content_scripts)
2522
+ if (script.js)
2523
+ for (const fileName of script.js)
2524
+ if (contentScripts.has(fileName)) {
2525
+ const { css } = contentScripts.get(fileName);
2526
+ if (css?.length)
2527
+ script.css = [script.css ?? [], css].flat();
2528
+ } else {
2529
+ throw new Error(`Content script is undefined by fileName: ${fileName}`);
2530
+ }
2301
2531
  }
2302
2532
  }
2303
2533
  return manifest;
@@ -2305,89 +2535,257 @@ const pluginFileWriterHtml = () => {
2305
2535
  };
2306
2536
  };
2307
2537
 
2308
- const { readFile: readFile$1 } = fs.promises;
2309
- const pluginFileWriterPublic = () => {
2538
+ const pluginDeclaredContentScripts = () => {
2539
+ return [];
2540
+ };
2541
+
2542
+ const _dynamicScriptRegEx = /\b(import.meta).CRX_DYNAMIC_SCRIPT_(.+?);$/gm;
2543
+ const dynamicScriptRegEx = () => {
2544
+ _dynamicScriptRegEx.lastIndex = 0;
2545
+ return _dynamicScriptRegEx;
2546
+ };
2547
+ const pluginDynamicContentScripts = () => {
2310
2548
  let config;
2311
- return {
2312
- name: "crx:file-writer-public",
2313
- apply: "build",
2314
- configResolved(_config) {
2315
- config = _config;
2316
- },
2317
- async buildStart() {
2318
- if (this.meta.watchMode) {
2319
- this.addWatchFile(config.publicDir);
2320
- const publicFiles = await fg__default["default"](`${config.publicDir}/**/*`);
2321
- for (const file of publicFiles) {
2322
- const source = await readFile$1(file);
2323
- const fileName = relative(config.publicDir, file);
2324
- this.emitFile({ type: "asset", fileName, source });
2549
+ return [
2550
+ {
2551
+ name: "crx:dynamic-content-scripts-loader",
2552
+ enforce: "pre",
2553
+ configResolved(_config) {
2554
+ config = _config;
2555
+ },
2556
+ async resolveId(_source, importer) {
2557
+ if (importer && _source.includes("?script")) {
2558
+ const url = new URL(_source, "stub://stub");
2559
+ if (url.searchParams.has("script")) {
2560
+ const [source] = _source.split("?");
2561
+ const resolved = await this.resolve(source, importer, {
2562
+ skipSelf: true
2563
+ });
2564
+ if (!resolved)
2565
+ throw new Error(`Could not resolve dynamic script: "${_source}" from "${importer}"`);
2566
+ const { id } = resolved;
2567
+ let type = "loader";
2568
+ if (url.searchParams.has("module")) {
2569
+ type = "module";
2570
+ } else if (url.searchParams.has("iife")) {
2571
+ type = "iife";
2572
+ }
2573
+ const scriptId = hashScriptId({ type, id });
2574
+ const resolvedId = `${id}?scriptId=${scriptId}`;
2575
+ let script = contentScripts.get(resolvedId);
2576
+ if (typeof script === "undefined") {
2577
+ let refId;
2578
+ let fileName;
2579
+ let loaderName;
2580
+ if (config.command === "build") {
2581
+ refId = this.emitFile({
2582
+ type: "chunk",
2583
+ id,
2584
+ name: basename(id)
2585
+ });
2586
+ } else {
2587
+ refId = scriptId;
2588
+ const relId = relative(config.root, id);
2589
+ fileName = getFileName({
2590
+ type: type === "iife" ? "iife" : "module",
2591
+ id: relId
2592
+ });
2593
+ if (type === "loader")
2594
+ loaderName = getFileName({ type, id: relId });
2595
+ }
2596
+ script = formatFileData({
2597
+ type,
2598
+ id: relative(config.root, id),
2599
+ isDynamicScript: true,
2600
+ fileName,
2601
+ loaderName,
2602
+ refId,
2603
+ scriptId,
2604
+ matches: []
2605
+ });
2606
+ contentScripts.set(script.id, script);
2607
+ }
2608
+ return resolvedId;
2609
+ } else if (url.searchParams.has("scriptId")) {
2610
+ return _source;
2611
+ }
2325
2612
  }
2613
+ },
2614
+ async load(id) {
2615
+ const index = id.indexOf("?scriptId=");
2616
+ if (index > -1) {
2617
+ const scriptId = id.slice(index + "?scriptId=".length);
2618
+ const script = contentScripts.get(scriptId);
2619
+ if (config.command === "build") {
2620
+ return `export default import.meta.CRX_DYNAMIC_SCRIPT_${script.refId};`;
2621
+ } else if (typeof script.fileName === "string") {
2622
+ await fileReady(script);
2623
+ return `export default ${JSON.stringify(script.fileName)};`;
2624
+ } else {
2625
+ throw new Error(`Content script fileName is undefined: "${script.id}"`);
2626
+ }
2627
+ }
2628
+ }
2629
+ },
2630
+ {
2631
+ name: "crx:dynamic-content-scripts-build",
2632
+ apply: "build",
2633
+ generateBundle(options, bundle) {
2634
+ for (const chunk of Object.values(bundle))
2635
+ if (chunk.type === "chunk") {
2636
+ if (dynamicScriptRegEx().test(chunk.code)) {
2637
+ const replaced = chunk.code.replace(dynamicScriptRegEx(), (match, p1, scriptKey) => {
2638
+ const script = contentScripts.get(scriptKey);
2639
+ if (typeof script === "undefined")
2640
+ throw new Error(`Content script refId is undefined: "${match}"`);
2641
+ if (typeof script.fileName === "undefined")
2642
+ throw new Error(`Content script fileName is undefined: "${script.id}"`);
2643
+ return `${JSON.stringify(`/${script.loaderName ?? script.fileName}`)};`;
2644
+ });
2645
+ chunk.code = replaced;
2646
+ }
2647
+ }
2326
2648
  }
2327
2649
  }
2650
+ ];
2651
+ };
2652
+
2653
+ const logger = vite.createLogger("error", { prefix: "crxjs" });
2654
+ const pluginFileWriter = () => {
2655
+ fileWriterError$.subscribe((error) => {
2656
+ logger.error(error.err.message, { error: error.err });
2657
+ });
2658
+ return {
2659
+ name: "crx:file-writer",
2660
+ apply: "serve",
2661
+ configureServer(server) {
2662
+ server.httpServer?.on("listening", async () => {
2663
+ try {
2664
+ await start({ server });
2665
+ } catch (error) {
2666
+ console.error(error);
2667
+ server.close();
2668
+ }
2669
+ });
2670
+ server.httpServer?.on("close", () => close());
2671
+ },
2672
+ closeBundle() {
2673
+ outputFiles.clear();
2674
+ }
2328
2675
  };
2329
2676
  };
2330
2677
 
2331
2678
  const _require = typeof require === "undefined" ? module$1.createRequire((typeof document === 'undefined' ? new (require('u' + 'rl').URL)('file:' + __filename).href : (document.currentScript && document.currentScript.src || new URL('index.cjs', document.baseURI).href))) : require;
2332
- const customElementsPath = _require.resolve(customElementsId);
2679
+ const customElementsPath = _require.resolve(customElementsId.slice(1));
2333
2680
  const customElementsCode = fs.readFileSync(customElementsPath, "utf8");
2334
2681
  const customElementsMap = fs.readFileSync(`${customElementsPath}.map`, "utf8");
2335
2682
  const pluginFileWriterPolyfill = () => {
2336
2683
  return {
2337
2684
  name: "crx:file-writer-polyfill",
2338
- apply: "build",
2685
+ apply: "serve",
2339
2686
  enforce: "pre",
2687
+ resolveId(source) {
2688
+ if (source === customElementsId) {
2689
+ return customElementsId;
2690
+ }
2691
+ },
2340
2692
  load(id) {
2341
- if (id === idByUrl.get(customElementsId)) {
2693
+ if (id === customElementsId) {
2342
2694
  return { code: customElementsCode, map: customElementsMap };
2343
2695
  }
2344
2696
  },
2345
- transform(code, id) {
2346
- if (id === idByUrl.get(viteClientId)) {
2697
+ renderCrxDevScript(code, { type, id }) {
2698
+ if (type === "module" && id === viteClientId) {
2347
2699
  const magic = new MagicString__default["default"](code);
2348
2700
  magic.prepend(`import '${customElementsId}';`);
2349
2701
  magic.prepend(`import { HMRPort } from '${contentHmrPortId}';`);
2350
2702
  const ws = "new WebSocket";
2351
2703
  const index = code.indexOf(ws);
2352
2704
  magic.overwrite(index, index + ws.length, "new HMRPort");
2353
- return { code: magic.toString(), map: magic.generateMap() };
2705
+ return magic.toString();
2354
2706
  }
2355
2707
  }
2356
2708
  };
2357
2709
  };
2358
2710
 
2359
- function isUpdatePayload(p) {
2360
- return p.type === "update";
2361
- }
2362
- function isFullReloadPayload(p) {
2363
- return p.type === "full-reload";
2711
+ async function manifestFiles(manifest, options = {}) {
2712
+ let locales = [];
2713
+ if (manifest.default_locale)
2714
+ locales = await fg__default["default"]("_locales/**/messages.json", options);
2715
+ const rulesets = manifest.declarative_net_request?.rule_resources.flatMap(({ path }) => path) ?? [];
2716
+ const contentScripts = manifest.content_scripts?.flatMap(({ js }) => js) ?? [];
2717
+ const contentStyles = manifest.content_scripts?.flatMap(({ css }) => css);
2718
+ const serviceWorker = manifest.background?.service_worker;
2719
+ const htmlPages = htmlFiles(manifest);
2720
+ const icons = [
2721
+ Object.values(isString(manifest.icons) ? [manifest.icons] : manifest.icons ?? {}),
2722
+ Object.values(isString(manifest.action?.default_icon) ? [manifest.action?.default_icon] : manifest.action?.default_icon ?? {})
2723
+ ].flat();
2724
+ let webAccessibleResources = [];
2725
+ if (manifest.web_accessible_resources) {
2726
+ const resources = await Promise.all(manifest.web_accessible_resources.flatMap(({ resources: resources2 }) => resources2).map(async (r) => {
2727
+ if (["*", "**/*"].includes(r))
2728
+ return void 0;
2729
+ if (fg__default["default"].isDynamicPattern(r))
2730
+ return fg__default["default"](r, options);
2731
+ return r;
2732
+ }));
2733
+ webAccessibleResources = resources.flat().filter(isString);
2734
+ }
2735
+ return {
2736
+ contentScripts: [...new Set(contentScripts)].filter(isString),
2737
+ contentStyles: [...new Set(contentStyles)].filter(isString),
2738
+ html: htmlPages,
2739
+ icons: [...new Set(icons)].filter(isString),
2740
+ locales: [...new Set(locales)].filter(isString),
2741
+ rulesets: [...new Set(rulesets)].filter(isString),
2742
+ background: [serviceWorker].filter(isString),
2743
+ webAccessibleResources
2744
+ };
2364
2745
  }
2365
- function isPrunePayload(p) {
2366
- return p.type === "prune";
2746
+ async function dirFiles(dir) {
2747
+ const files = await fg__default["default"](`${dir}/**/*`);
2748
+ return files;
2367
2749
  }
2368
- function isCrxHMRPayload(x) {
2369
- return x.type === "custom" && x.event.startsWith("crx:");
2750
+ function htmlFiles(manifest) {
2751
+ const files = [
2752
+ manifest.action?.default_popup,
2753
+ Object.values(manifest.chrome_url_overrides ?? {}),
2754
+ manifest.devtools_page,
2755
+ manifest.options_page,
2756
+ manifest.options_ui?.page,
2757
+ manifest.sandbox?.pages
2758
+ ].flat().filter(isString).map((s) => s.split("#")[0]).sort();
2759
+ return [...new Set(files)];
2370
2760
  }
2761
+
2762
+ const pluginFileWriterPublic = () => {
2763
+ let config;
2764
+ return {
2765
+ name: "crx:file-writer-public",
2766
+ apply: "serve",
2767
+ configResolved(_config) {
2768
+ config = _config;
2769
+ },
2770
+ async generateBundle() {
2771
+ const publicDir = isAbsolute(config.publicDir) ? config.publicDir : resolve(config.root, config.publicDir);
2772
+ const files = await dirFiles(publicDir);
2773
+ for (const filepath of files) {
2774
+ const source = await promises.readFile(filepath);
2775
+ const fileName = relative(publicDir, filepath);
2776
+ this.emitFile({ type: "asset", source, fileName });
2777
+ }
2778
+ }
2779
+ };
2780
+ };
2781
+
2782
+ _debug("file-writer").extend("hmr");
2783
+ const isCrxHMRPayload = (p) => p.type === "custom" && p.event.startsWith("crx:");
2371
2784
  const hmrPayload$ = new Subject();
2372
- const hmrPrune$ = hmrPayload$.pipe(filter(isPrunePayload));
2373
- const hmrFullReload$ = hmrPayload$.pipe(filter(isFullReloadPayload));
2374
- const hmrUpdate$ = hmrPayload$.pipe(filter(isUpdatePayload));
2375
- const payload$ = merge(hmrFullReload$, hmrPrune$, hmrUpdate$);
2376
- const rebuildSignal$ = payload$.pipe(buffer(payload$.pipe(debounce(() => filesReady$))), map((payloads) => {
2377
- if (payloads.every(isUpdatePayload)) {
2378
- const owners = /* @__PURE__ */ new Set();
2379
- for (const { updates } of payloads)
2380
- for (const { path } of updates)
2381
- if (transformResultByOwner.has(path))
2382
- owners.add(path);
2383
- return { type: "partial", owners };
2384
- }
2385
- return { type: "full" };
2386
- }), filter((rebuild) => rebuild.type === "partial" ? rebuild.owners.size > 0 : true));
2387
- const crxHmrPayload$ = hmrPayload$.pipe(filter((p) => !isCrxHMRPayload(p)), buffer(filesReady$), mergeMap((pps) => {
2785
+ const crxHMRPayload$ = hmrPayload$.pipe(filter((p) => !isCrxHMRPayload(p)), buffer(allFilesReady$), mergeMap((pps) => {
2388
2786
  let fullReload;
2389
2787
  const payloads = [];
2390
- for (const p of pps.slice(-50))
2788
+ for (const p of pps)
2391
2789
  if (p.type === "full-reload") {
2392
2790
  fullReload = p;
2393
2791
  } else {
@@ -2399,38 +2797,37 @@ const crxHmrPayload$ = hmrPayload$.pipe(filter((p) => !isCrxHMRPayload(p)), buff
2399
2797
  }), map((p) => {
2400
2798
  switch (p.type) {
2401
2799
  case "full-reload": {
2402
- const path = p.path && outputByOwner.get(p.path);
2403
2800
  const fullReload = {
2404
2801
  type: "full-reload",
2405
- path
2802
+ path: p.path && getViteUrl({ id: p.path, type: "module" })
2406
2803
  };
2407
2804
  return fullReload;
2408
2805
  }
2409
2806
  case "prune": {
2410
- const paths = [];
2411
- for (const owner of p.paths)
2412
- if (outputByOwner.has(owner))
2413
- paths.push(outputByOwner.get(owner));
2414
- return { type: "prune", paths };
2807
+ const prune = {
2808
+ type: "prune",
2809
+ paths: p.paths.map((id) => getViteUrl({ id, type: "module" }))
2810
+ };
2811
+ return prune;
2415
2812
  }
2416
2813
  case "update": {
2417
- const updates = [];
2418
- for (const { acceptedPath, path, ...rest } of p.updates)
2419
- if (outputByOwner.has(acceptedPath) && outputByOwner.has(path))
2420
- updates.push({
2421
- ...rest,
2422
- acceptedPath: outputByOwner.get(acceptedPath),
2423
- path: outputByOwner.get(path)
2424
- });
2425
- return { type: "update", updates };
2814
+ const update = {
2815
+ type: "update",
2816
+ updates: p.updates.map(({ acceptedPath: ap, path: p2, ...rest }) => ({
2817
+ ...rest,
2818
+ acceptedPath: prefix$1("/", getFileName({ id: ap, type: "module" })),
2819
+ path: prefix$1("/", getFileName({ id: p2, type: "module" }))
2820
+ }))
2821
+ };
2822
+ return update;
2426
2823
  }
2427
2824
  default:
2428
2825
  return p;
2429
2826
  }
2430
- }), withLatestFrom(filesReady$), filter(([p, { bundle }]) => {
2827
+ }), filter((p) => {
2431
2828
  switch (p.type) {
2432
2829
  case "full-reload":
2433
- return typeof p.path === "undefined" || p.path in bundle;
2830
+ return typeof p.path === "undefined";
2434
2831
  case "prune":
2435
2832
  return p.paths.length > 0;
2436
2833
  case "update":
@@ -2438,127 +2835,13 @@ const crxHmrPayload$ = hmrPayload$.pipe(filter((p) => !isCrxHMRPayload(p)), buff
2438
2835
  default:
2439
2836
  return true;
2440
2837
  }
2441
- }), map(([p]) => ({
2442
- type: "custom",
2443
- event: "crx:content-script-payload",
2444
- data: p
2445
- })));
2446
-
2447
- function sortPlugins(plugins, command) {
2448
- const pre = [];
2449
- const mid = [];
2450
- const post = [];
2451
- for (const p of plugins) {
2452
- if (p.apply === command || !p.apply || !command) {
2453
- if (p.enforce === "pre")
2454
- pre.push(p);
2455
- else if (p.enforce === "post")
2456
- post.push(p);
2457
- else
2458
- mid.push(p);
2459
- }
2460
- }
2461
- return { pre, mid, post };
2462
- }
2463
- const pluginFileWriter = (crxPlugins) => (options) => {
2464
- const chunks = pluginFileWriterChunks();
2465
- const html = pluginFileWriterHtml();
2466
- const events = pluginFileWriterEvents();
2467
- const publicDir = pluginFileWriterPublic();
2468
- const polyfill = pluginFileWriterPolyfill();
2469
- const { pre, mid, post } = sortPlugins(crxPlugins, "build");
2470
- const plugins = [
2471
- ...pre,
2472
- ...mid,
2473
- polyfill,
2474
- chunks,
2475
- html,
2476
- publicDir,
2477
- ...post,
2478
- events
2479
- ].flat();
2480
- let watcher;
2838
+ }), map((data) => {
2481
2839
  return {
2482
- name: "crx:file-writer",
2483
- apply: "serve",
2484
- async config(_config, env) {
2485
- let config = _config;
2486
- for (const p of plugins) {
2487
- const r = await p.config?.(config, env);
2488
- config = r ?? config;
2489
- }
2490
- return config;
2491
- },
2492
- async configResolved(config) {
2493
- await Promise.all(plugins.map((p) => p.configResolved?.(config)));
2494
- },
2495
- configureServer(server) {
2496
- server.httpServer?.once("listening", async () => {
2497
- server$.next(server);
2498
- const optimizedDeps = server._optimizedDeps;
2499
- await optimizedDeps?.scanProcessing;
2500
- const { pre: pre2, mid: mid2, post: post2 } = sortPlugins([
2501
- ...server.config.plugins,
2502
- ...plugins
2503
- ]);
2504
- const allPlugins = [...pre2, ...mid2, ...post2];
2505
- await Promise.all(allPlugins.map(async (p) => {
2506
- try {
2507
- await p.fileWriterStart?.(server);
2508
- } catch (e) {
2509
- const hook = `[${p.name}].fileWriterStart`;
2510
- let error = new Error(`Error in plugin ${hook}`);
2511
- if (e instanceof Error) {
2512
- error = e;
2513
- error.message = `${hook} ${error.message}`;
2514
- } else if (typeof e === "string") {
2515
- error = new Error(`${hook} ${e}`);
2516
- }
2517
- writerEvent$.next({ type: "error", error });
2518
- }
2519
- }));
2520
- watcher = rollup.watch({
2521
- input: stubId,
2522
- context: "this",
2523
- output: {
2524
- dir: server.config.build.outDir,
2525
- format: "es"
2526
- },
2527
- plugins,
2528
- treeshake: false
2529
- });
2530
- watcher.on("event", (event) => {
2531
- if (event.code === "ERROR") {
2532
- const { message, parserError, stack, id, loc, code, frame } = event.error;
2533
- const error = parserError ?? new Error(message);
2534
- if (parserError && message.startsWith("Unexpected token")) {
2535
- const m = `Unexpected token in ${loc?.file ?? id}`;
2536
- error.message = [m, loc?.line, loc?.column].filter(isTruthy).join(":");
2537
- }
2538
- error.stack = (stack ?? error.stack)?.replace(/.+?\n/, `Error: ${error.message}
2539
- `);
2540
- writerEvent$.next({ type: "error", error, code, frame });
2541
- }
2542
- });
2543
- const rebuildSub = rebuildSignal$.subscribe((rebuild) => {
2544
- if (rebuild.type === "partial") {
2545
- for (const owner of rebuild.owners)
2546
- transformResultByOwner.delete(owner);
2547
- } else {
2548
- transformResultByOwner.clear();
2549
- }
2550
- rebuildFiles();
2551
- });
2552
- watcher.on("close", () => {
2553
- rebuildSub.unsubscribe();
2554
- });
2555
- });
2556
- },
2557
- closeBundle() {
2558
- watcher?.close();
2559
- }
2840
+ type: "custom",
2841
+ event: "crx:content-script-payload",
2842
+ data
2560
2843
  };
2561
- };
2844
+ }));
2562
2845
 
2563
2846
  function isImporter(file) {
2564
2847
  const seen = /* @__PURE__ */ new Set();
@@ -2576,68 +2859,108 @@ function isImporter(file) {
2576
2859
  return pred;
2577
2860
  }
2578
2861
 
2579
- const debug$2 = _debug("hmr");
2862
+ const debug$1 = _debug("hmr");
2580
2863
  const crxRuntimeReload = {
2581
2864
  type: "custom",
2582
2865
  event: "crx:runtime-reload"
2583
2866
  };
2584
2867
  const pluginHMR = () => {
2585
- let files;
2868
+ let inputManifestFiles;
2586
2869
  let decoratedSend;
2870
+ let config;
2871
+ let subs;
2587
2872
  return [
2588
- {
2589
- name: "crx:hmr",
2590
- apply: "build",
2591
- enforce: "post",
2592
- async renderCrxManifest(manifest) {
2593
- if (this.meta.watchMode) {
2594
- files = await manifestFiles(manifest);
2595
- }
2596
- return null;
2597
- }
2598
- },
2599
2873
  {
2600
2874
  name: "crx:hmr",
2601
2875
  apply: "serve",
2602
2876
  enforce: "pre",
2603
- config({ server = {}, ...config }) {
2877
+ async config({ server = {}, ...config2 }) {
2604
2878
  if (server.hmr === false)
2605
2879
  return;
2606
2880
  if (server.hmr === true)
2607
2881
  server.hmr = {};
2608
2882
  server.hmr = server.hmr ?? {};
2609
2883
  server.hmr.host = "localhost";
2610
- return { server, ...config };
2884
+ server.hmr.port = server.hmr.port ?? await getPort__default["default"]({ port: getPort.portNumbers(5200, 5300) });
2885
+ return { server, ...config2 };
2611
2886
  },
2612
- configResolved(config) {
2887
+ configResolved(_config) {
2888
+ config = _config;
2613
2889
  const { watch = {} } = config.server;
2614
2890
  config.server.watch = watch;
2615
2891
  watch.ignored = watch.ignored ? [...new Set([watch.ignored].flat())] : [];
2616
2892
  const outDir = isAbsolute(config.build.outDir) ? config.build.outDir : join(config.root, config.build.outDir, "**/*");
2617
- watch.ignored.push(outDir);
2893
+ if (!watch.ignored.includes(outDir))
2894
+ watch.ignored.push(outDir);
2618
2895
  },
2619
2896
  configureServer(server) {
2620
2897
  if (server.ws.send !== decoratedSend) {
2621
2898
  const { send } = server.ws;
2622
2899
  decoratedSend = (payload) => {
2623
- hmrPayload$.next(payload);
2900
+ if (payload.type === "error") {
2901
+ send({
2902
+ type: "custom",
2903
+ event: "crx:content-script-payload",
2904
+ data: payload
2905
+ });
2906
+ } else {
2907
+ hmrPayload$.next(payload);
2908
+ }
2624
2909
  send(payload);
2625
2910
  };
2626
2911
  server.ws.send = decoratedSend;
2627
- crxHmrPayload$.subscribe((payload) => {
2912
+ subs = new Subscription(() => subs = new Subscription());
2913
+ subs.add(fileWriterError$.subscribe(send));
2914
+ subs.add(crxHMRPayload$.subscribe((payload) => {
2628
2915
  send(payload);
2629
- });
2916
+ }));
2630
2917
  }
2631
2918
  },
2632
- handleHotUpdate({ file, modules, server }) {
2633
- const background = files.background[0] && join(server.config.root, files.background[0]);
2634
- if (background) {
2635
- if (file === background || modules.some(isImporter(background))) {
2636
- debug$2("sending runtime reload");
2919
+ closeBundle() {
2920
+ subs.unsubscribe();
2921
+ },
2922
+ handleHotUpdate({ modules, server }) {
2923
+ const { root } = server.config;
2924
+ const relFiles = /* @__PURE__ */ new Set();
2925
+ for (const m of modules)
2926
+ if (m.id?.startsWith(root)) {
2927
+ relFiles.add(m.id.slice(server.config.root.length));
2928
+ }
2929
+ if (inputManifestFiles.background.length) {
2930
+ const background = prefix$1("/", inputManifestFiles.background[0]);
2931
+ if (relFiles.has(background) || modules.some(isImporter(join(server.config.root, background)))) {
2932
+ debug$1("sending runtime reload");
2637
2933
  server.ws.send(crxRuntimeReload);
2638
2934
  return [];
2639
2935
  }
2640
2936
  }
2937
+ for (const [key, script] of contentScripts)
2938
+ if (key === script.id) {
2939
+ if (relFiles.has(script.id) || modules.some(isImporter(join(server.config.root, script.id)))) {
2940
+ relFiles.forEach((relFile) => update(relFile));
2941
+ }
2942
+ }
2943
+ }
2944
+ },
2945
+ {
2946
+ name: "crx:hmr",
2947
+ apply: "serve",
2948
+ enforce: "post",
2949
+ async transformCrxManifest(manifest) {
2950
+ inputManifestFiles = await manifestFiles(manifest, { cwd: config.root });
2951
+ return null;
2952
+ },
2953
+ renderCrxDevScript(code, { id: _id, type }) {
2954
+ if (type === "module" && _id !== "/@vite/client" && code.includes("createHotContext")) {
2955
+ const id = _id.replace(/t=\d+&/, "");
2956
+ const escaped = id.replace(/([?&.])/g, "\\$1");
2957
+ const regexp = new RegExp(`(?<=createHotContext\\(")${escaped}(?="\\))`);
2958
+ const fileUrl = prefix$1("/", getFileName({ id, type }));
2959
+ const replaced = code.replace(regexp, fileUrl);
2960
+ return replaced;
2961
+ } else {
2962
+ return code;
2963
+ }
2641
2964
  }
2642
2965
  }
2643
2966
  ];
@@ -2646,14 +2969,14 @@ const pluginHMR = () => {
2646
2969
  var loader = "try {\n for (const p of JSON.parse(SCRIPTS)) {\n const url = new URL(p, \"https://stub\");\n url.searchParams.set(\"t\", Date.now().toString());\n const req = url.pathname + url.search;\n await import(\n /* @vite-ignore */\n req\n );\n }\n} catch (error) {\n console.error(error);\n}\n";
2647
2970
 
2648
2971
  const pluginName = "crx:html-inline-scripts";
2649
- const debug$1 = _debug(pluginName);
2972
+ const debug = _debug(pluginName);
2650
2973
  const prefix = "@crx/inline-script";
2651
2974
  const isInlineTag = (t) => t.tag === "script" && !t.attrs?.src;
2652
2975
  const toKey = (ctx) => {
2653
2976
  const { dir, name } = parse(ctx.path);
2654
2977
  return join(prefix, dir, name);
2655
2978
  };
2656
- const pluginHtmlAuditor = () => {
2979
+ const pluginHtmlInlineScripts = () => {
2657
2980
  const pages = /* @__PURE__ */ new Map();
2658
2981
  const auditTransformIndexHtml = (p) => {
2659
2982
  let transform;
@@ -2767,15 +3090,19 @@ const pluginHtmlAuditor = () => {
2767
3090
  })}"`;
2768
3091
  return [inline, loader.replace("SCRIPTS", json)].join("\n");
2769
3092
  } else {
2770
- debug$1("page missing %s", id);
3093
+ debug("page missing %s", id);
2771
3094
  }
2772
3095
  }
2773
3096
  }
2774
3097
  };
2775
3098
  };
2776
3099
 
3100
+ var precontrollerJs = "const id = setInterval(() => location.reload(), 100);\nsetTimeout(() => clearInterval(id), 5e3);\n";
3101
+
3102
+ var precontrollerHtml = "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <title>Waiting for the extension service worker...</title>\n <script src=\"%SCRIPT%\"></script>\n </head>\n <body>\n <h1>Waiting for service worker</h1>\n\n <p>\n If you see this message, it means the service worker has not loaded fully.\n </p>\n\n <p>This page is never added in production.</p>\n </body>\n</html>\n";
3103
+
2777
3104
  const { readFile } = fs.promises;
2778
- const pluginManifest = (_manifest) => () => {
3105
+ const pluginManifest = () => {
2779
3106
  let manifest;
2780
3107
  let plugins;
2781
3108
  let refId;
@@ -2785,6 +3112,7 @@ const pluginManifest = (_manifest) => () => {
2785
3112
  name: "crx:manifest-init",
2786
3113
  enforce: "pre",
2787
3114
  async config(config2, env) {
3115
+ const { manifest: _manifest } = await getOptions(config2);
2788
3116
  manifest = await (typeof _manifest === "function" ? _manifest(env) : _manifest);
2789
3117
  if (manifest.manifest_version !== 3)
2790
3118
  throw new Error(`CRXJS does not support Manifest v${manifest.manifest_version}, please use Manifest v3`);
@@ -2793,7 +3121,7 @@ const pluginManifest = (_manifest) => () => {
2793
3121
  contentScripts: js,
2794
3122
  background: sw,
2795
3123
  html
2796
- } = await manifestFiles(manifest);
3124
+ } = await manifestFiles(manifest, { cwd: config2.root });
2797
3125
  const { entries = [] } = config2.optimizeDeps ?? {};
2798
3126
  let { input = [] } = config2.build?.rollupOptions ?? {};
2799
3127
  if (typeof input === "string")
@@ -2826,15 +3154,16 @@ const pluginManifest = (_manifest) => () => {
2826
3154
  },
2827
3155
  {
2828
3156
  name: "crx:manifest-loader",
2829
- apply: "build",
2830
3157
  enforce: "pre",
2831
- buildStart() {
2832
- refId = this.emitFile({
2833
- type: "chunk",
2834
- id: manifestId,
2835
- name: "crx-manifest.js",
2836
- preserveSignature: "strict"
2837
- });
3158
+ buildStart(options) {
3159
+ if (typeof options.input !== "undefined") {
3160
+ refId = this.emitFile({
3161
+ type: "chunk",
3162
+ id: manifestId,
3163
+ name: "crx-manifest.js",
3164
+ preserveSignature: "strict"
3165
+ });
3166
+ }
2838
3167
  },
2839
3168
  resolveId(source) {
2840
3169
  if (source === manifestId)
@@ -2849,13 +3178,22 @@ const pluginManifest = (_manifest) => () => {
2849
3178
  },
2850
3179
  {
2851
3180
  name: "crx:stub-input",
2852
- apply: "build",
2853
3181
  enforce: "pre",
2854
3182
  options({ input, ...options }) {
2855
- return {
2856
- input: isString(input) && input.endsWith("index.html") ? stubId : input,
2857
- ...options
2858
- };
3183
+ let finalInput = input;
3184
+ if (isString(input) && input.endsWith("index.html")) {
3185
+ finalInput = stubId;
3186
+ }
3187
+ if (config.command === "serve") {
3188
+ if (Array.isArray(input)) {
3189
+ finalInput = input.filter((x) => !x.endsWith(".html"));
3190
+ } else if (typeof input === "object") {
3191
+ for (const [key, value] of Object.entries(input))
3192
+ if (value.endsWith(".html"))
3193
+ delete input[key];
3194
+ }
3195
+ }
3196
+ return { input: finalInput, ...options };
2859
3197
  },
2860
3198
  resolveId(source) {
2861
3199
  if (source === stubId)
@@ -2878,7 +3216,6 @@ const pluginManifest = (_manifest) => () => {
2878
3216
  },
2879
3217
  {
2880
3218
  name: "crx:manifest-post",
2881
- apply: "build",
2882
3219
  enforce: "post",
2883
3220
  configResolved(_config) {
2884
3221
  config = _config;
@@ -2900,32 +3237,52 @@ const pluginManifest = (_manifest) => () => {
2900
3237
  if (error instanceof Error)
2901
3238
  error.message = `[${plugin.name}] ${error.message}`;
2902
3239
  throw error;
2903
- }
2904
- }
2905
- if (manifest2.content_scripts?.length) {
2906
- manifest2.content_scripts = manifest2.content_scripts.map(({ js = [], ...rest }) => {
2907
- const refJS = js.map((file) => this.emitFile({
2908
- type: "chunk",
2909
- id: file,
2910
- name: basename(file)
2911
- }));
2912
- return { js: refJS, ...rest };
2913
- });
3240
+ }
2914
3241
  }
2915
- if (!this.meta.watchMode) {
3242
+ if (config.command === "serve") {
3243
+ if (manifest2.content_scripts)
3244
+ for (const { js = [], matches = [] } of manifest2.content_scripts)
3245
+ for (const id2 of js) {
3246
+ contentScripts.set(prefix$1("/", id2), formatFileData({
3247
+ type: "loader",
3248
+ id: id2,
3249
+ matches,
3250
+ refId: hashScriptId({ type: "loader", id: id2 }),
3251
+ fileName: getFileName({ type: "loader", id: id2 })
3252
+ }));
3253
+ }
3254
+ } else {
3255
+ if (manifest2.content_scripts)
3256
+ for (const { js = [], matches = [] } of manifest2.content_scripts)
3257
+ for (const file of js) {
3258
+ const id2 = join(config.root, file);
3259
+ const refId2 = this.emitFile({
3260
+ type: "chunk",
3261
+ id: id2,
3262
+ name: basename(file)
3263
+ });
3264
+ contentScripts.set(file, formatFileData({
3265
+ type: "loader",
3266
+ id: file,
3267
+ refId: refId2,
3268
+ matches
3269
+ }));
3270
+ }
2916
3271
  if (manifest2.background?.service_worker) {
2917
3272
  const file = manifest2.background.service_worker;
3273
+ const id2 = join(config.root, file);
2918
3274
  const refId2 = this.emitFile({
2919
3275
  type: "chunk",
2920
- id: file,
3276
+ id: id2,
2921
3277
  name: basename(file)
2922
3278
  });
2923
3279
  manifest2.background.service_worker = refId2;
2924
3280
  }
2925
3281
  for (const file of htmlFiles(manifest2)) {
3282
+ const id2 = join(config.root, file);
2926
3283
  this.emitFile({
2927
3284
  type: "chunk",
2928
- id: file,
3285
+ id: id2,
2929
3286
  name: basename(file)
2930
3287
  });
2931
3288
  }
@@ -2937,15 +3294,30 @@ const pluginManifest = (_manifest) => () => {
2937
3294
  const manifestName = this.getFileName(refId);
2938
3295
  const manifestJs = bundle[manifestName];
2939
3296
  let manifest2 = decodeManifest.call(this, manifestJs.code);
2940
- if (manifest2.background?.service_worker && !this.meta.watchMode) {
2941
- const ref = manifest2.background.service_worker;
2942
- const name = this.getFileName(ref);
2943
- manifest2.background.service_worker = name;
2944
- }
2945
- manifest2.content_scripts = manifest2.content_scripts?.map(({ js = [], ...rest }) => {
2946
- const refJS = js.map((ref) => this.getFileName(ref));
2947
- return { js: refJS, ...rest };
2948
- });
3297
+ if (config.command === "serve") {
3298
+ if (manifest2.content_scripts)
3299
+ for (const script of manifest2.content_scripts) {
3300
+ script.js = script.js?.map((id) => getFileName({ id, type: "loader" }));
3301
+ }
3302
+ } else {
3303
+ if (manifest2.background?.service_worker) {
3304
+ const ref = manifest2.background.service_worker;
3305
+ const name = this.getFileName(ref);
3306
+ manifest2.background.service_worker = name;
3307
+ }
3308
+ manifest2.content_scripts = manifest2.content_scripts?.map(({ js = [], ...rest }) => {
3309
+ return {
3310
+ js: js.map((id) => {
3311
+ const script = contentScripts.get(id);
3312
+ const fileName = script?.loaderName ?? script?.fileName;
3313
+ if (typeof fileName === "undefined")
3314
+ throw new Error(`Content script fileName is undefined: "${id}"`);
3315
+ return fileName;
3316
+ }),
3317
+ ...rest
3318
+ };
3319
+ });
3320
+ }
2949
3321
  for (const plugin of plugins) {
2950
3322
  try {
2951
3323
  const m = structuredClone(manifest2);
@@ -2969,7 +3341,7 @@ const pluginManifest = (_manifest) => () => {
2969
3341
  "rulesets",
2970
3342
  "webAccessibleResources"
2971
3343
  ];
2972
- const files = await manifestFiles(manifest2);
3344
+ const files = await manifestFiles(manifest2, { cwd: config.root });
2973
3345
  await Promise.all(assetTypes.map((k) => files[k]).flat().map(async (f) => {
2974
3346
  if (typeof bundle[f] === "undefined") {
2975
3347
  let filename = join(config.root, f);
@@ -2987,6 +3359,19 @@ Public dir: "${config.publicDir}"`);
2987
3359
  });
2988
3360
  }
2989
3361
  }));
3362
+ if (config.command === "serve" && files.html.length) {
3363
+ const refId2 = this.emitFile({
3364
+ type: "asset",
3365
+ name: "precontroller.js",
3366
+ source: precontrollerJs
3367
+ });
3368
+ const precontrollerJsName = this.getFileName(refId2);
3369
+ files.html.map((f) => this.emitFile({
3370
+ type: "asset",
3371
+ fileName: f,
3372
+ source: precontrollerHtml.replace("%SCRIPT%", `/${precontrollerJsName}`)
3373
+ }));
3374
+ }
2990
3375
  const manifestJson = bundle["manifest.json"];
2991
3376
  if (typeof manifestJson === "undefined") {
2992
3377
  this.emitFile({
@@ -3003,575 +3388,217 @@ Public dir: "${config.publicDir}"`);
3003
3388
  ];
3004
3389
  };
3005
3390
 
3006
- var contentHmrPort = "function isCrxHMRPayload(x) {\n return x.type === \"custom\" && x.event.startsWith(\"crx:\");\n}\nclass HMRPort {\n port;\n callbacks = /* @__PURE__ */ new Map();\n constructor() {\n setInterval(() => {\n try {\n this.port?.postMessage({ data: \"ping\" });\n } catch (error) {\n if (error instanceof Error && error.message.includes(\"Extension context invalidated.\")) {\n location.reload();\n } else\n throw error;\n }\n }, __CRX_HMR_TIMEOUT__);\n setInterval(this.initPort, 5 * 60 * 1e3);\n this.initPort();\n }\n initPort = () => {\n this.port?.disconnect();\n this.port = chrome.runtime.connect({ name: \"@crx/client\" });\n this.port.onDisconnect.addListener(this.handleDisconnect.bind(this));\n this.port.onMessage.addListener(this.handleMessage.bind(this));\n this.port.postMessage({ type: \"connected\" });\n };\n handleDisconnect = () => {\n if (this.callbacks.has(\"close\"))\n for (const cb of this.callbacks.get(\"close\")) {\n cb({ wasClean: true });\n }\n };\n handleMessage = (message) => {\n const forward = (data) => {\n if (this.callbacks.has(\"message\"))\n for (const cb of this.callbacks.get(\"message\")) {\n cb({ data });\n }\n };\n const payload = JSON.parse(message.data);\n if (isCrxHMRPayload(payload)) {\n if (payload.event === \"crx:runtime-reload\") {\n console.log(\"[crx] runtime reload\");\n setTimeout(() => location.reload(), 500);\n } else {\n forward(JSON.stringify(payload.data));\n }\n } else {\n forward(message.data);\n }\n };\n addEventListener = (event, callback) => {\n const cbs = this.callbacks.get(event) ?? /* @__PURE__ */ new Set();\n cbs.add(callback);\n this.callbacks.set(event, cbs);\n };\n send = (data) => {\n if (this.port)\n this.port.postMessage({ data });\n else\n throw new Error(\"HMRPort is not initialized\");\n };\n}\n\nexport { HMRPort };\n";
3007
-
3008
- var contentDevLoader = "(function () {\n 'use strict';\n\n (async () => {\n if (__PREAMBLE__)\n await import(\n /* @vite-ignore */\n chrome.runtime.getURL(__PREAMBLE__)\n );\n await import(\n /* @vite-ignore */\n chrome.runtime.getURL(__CLIENT__)\n );\n await import(\n /* @vite-ignore */\n chrome.runtime.getURL(__SCRIPT__)\n );\n })().catch(console.error);\n\n})();\n";
3009
-
3010
- var contentProLoader = "(function () {\n 'use strict';\n\n (async () => {\n await import(\n /* @vite-ignore */\n chrome.runtime.getURL(__SCRIPT__)\n );\n })().catch(console.error);\n\n})();\n";
3011
-
3012
- function getScriptId({
3013
- format,
3014
- id
3391
+ function compileFileResources(fileName, {
3392
+ chunks,
3393
+ files,
3394
+ config
3395
+ }, resources = {
3396
+ assets: /* @__PURE__ */ new Set(),
3397
+ css: /* @__PURE__ */ new Set(),
3398
+ imports: /* @__PURE__ */ new Set()
3015
3399
  }) {
3016
- return crypto.createHash("sha1").update(format).update(id).digest("base64").replace(/[^A-Za-z0-9]/g, "").slice(0, 8);
3017
- }
3018
- const debug = _debug("content-scripts");
3019
- const dynamicResourcesName = "<dynamic_resource>";
3020
- const pluginResources = ({ contentScripts = {} }) => {
3021
- const { hmrTimeout = 5e3, injectCss = true } = contentScripts;
3022
- const dynamicScriptsById = /* @__PURE__ */ new Map();
3023
- const dynamicScriptsByLoaderRefId = /* @__PURE__ */ new Map();
3024
- const dynamicScriptsByRefId = /* @__PURE__ */ new Map();
3025
- const dynamicScriptsByScriptId = /* @__PURE__ */ new Map();
3026
- function emitDynamicScript(data) {
3027
- if (data.format === "iife") {
3028
- throw new Error(`Dynamic script format IIFE is unimplemented (imported in file: ${data.importer})`.trim());
3029
- } else {
3030
- data.refId = this.emitFile({ type: "chunk", id: data.id });
3031
- dynamicScriptsByRefId.set(data.refId, data);
3032
- }
3033
- if (data.format === "loader") {
3034
- data.loaderRefId = this.emitFile({
3035
- type: "asset",
3036
- name: `content-script-loader.${parse(data.id).name}.js`,
3037
- source: JSON.stringify(data)
3038
- });
3039
- dynamicScriptsByLoaderRefId.set(data.loaderRefId, data);
3040
- }
3041
- }
3042
- async function resolveDynamicScript(_source, importer) {
3043
- if (importer && _source.includes("?script")) {
3044
- const url = new URL(_source, "stub://stub");
3045
- if (url.searchParams.has("scriptId")) {
3046
- const scriptId = url.searchParams.get("scriptId");
3047
- const { finalId } = dynamicScriptsByScriptId.get(scriptId);
3048
- return finalId;
3049
- } else if (url.searchParams.has("script")) {
3050
- const [source] = _source.split("?");
3051
- const resolved = await this.resolve(source, importer, {
3052
- skipSelf: true
3053
- });
3054
- if (!resolved)
3055
- throw new Error(`Could not resolve dynamic script: "${_source}" from "${importer}"`);
3056
- const { id } = resolved;
3057
- let format = "loader";
3058
- if (url.searchParams.has("module")) {
3059
- format = "module";
3060
- } else if (url.searchParams.has("iife")) {
3061
- format = "iife";
3062
- }
3063
- const scriptId = getScriptId({ format, id });
3064
- const finalId = `${id}?scriptId=${scriptId}`;
3065
- const data = dynamicScriptsByScriptId.get(scriptId) ?? {
3066
- format,
3067
- id,
3068
- importer,
3069
- scriptId,
3070
- finalId
3071
- };
3072
- dynamicScriptsByScriptId.set(scriptId, data);
3073
- dynamicScriptsById.set(finalId, data);
3074
- return finalId;
3400
+ const chunk = chunks.get(fileName);
3401
+ if (chunk) {
3402
+ const { modules, facadeModuleId, imports, dynamicImports } = chunk;
3403
+ for (const x of imports)
3404
+ resources.imports.add(x);
3405
+ for (const x of dynamicImports)
3406
+ resources.imports.add(x);
3407
+ for (const x of [...imports, ...dynamicImports])
3408
+ compileFileResources(x, { chunks, files, config }, resources);
3409
+ for (const m of Object.keys(modules))
3410
+ if (m !== facadeModuleId) {
3411
+ const key = prefix$1("/", relative(config.root, m.split("?")[0]));
3412
+ const script = contentScripts.get(key);
3413
+ if (script)
3414
+ if (typeof script.fileName === "undefined") {
3415
+ throw new Error(`Content script fileName for ${m} is undefined`);
3416
+ } else {
3417
+ resources.imports.add(script.fileName);
3418
+ compileFileResources(script.fileName, { chunks, files, config }, resources);
3419
+ }
3075
3420
  }
3076
- }
3077
3421
  }
3078
- function loadDynamicScript(id) {
3079
- const data = dynamicScriptsById.get(id);
3080
- if (data)
3081
- return `export default import.meta.CRX_DYNAMIC_SCRIPT_${data.scriptId};`;
3422
+ const file = files.get(fileName);
3423
+ if (file) {
3424
+ const { assets = [], css = [] } = file;
3425
+ for (const x of assets)
3426
+ resources.assets.add(x);
3427
+ for (const x of css)
3428
+ resources.css.add(x);
3082
3429
  }
3083
- let port;
3084
- let server;
3085
- let { preambleCode } = contentScripts;
3086
- let preambleRefId;
3087
- let contentClientRefId;
3430
+ return resources;
3431
+ }
3432
+
3433
+ const defineManifest = (manifest) => manifest;
3434
+ const defineDynamicResource = ({
3435
+ matches = ["http://*/*", "https://*/*"],
3436
+ use_dynamic_url = true
3437
+ }) => ({
3438
+ matches,
3439
+ resources: [DYNAMIC_RESOURCE],
3440
+ use_dynamic_url
3441
+ });
3442
+ const DYNAMIC_RESOURCE = "<dynamic_resource>";
3443
+
3444
+ _debug("web-acc-res");
3445
+ const pluginWebAccessibleResources = () => {
3446
+ let config;
3447
+ let injectCss;
3088
3448
  return [
3089
3449
  {
3090
- name: "crx:content-scripts-pre",
3091
- apply: "build",
3092
- enforce: "pre",
3093
- async fileWriterStart(_server) {
3094
- server = _server;
3095
- port = server.config.server.port.toString();
3096
- if (process.env.NODE_ENV !== "test" && typeof preambleCode === "undefined" && server.config.plugins.some(({ name }) => name.toLowerCase().includes("react"))) {
3097
- try {
3098
- const react = await Promise.resolve().then(function () { return /*#__PURE__*/_interopNamespace(require('@vitejs/plugin-react')); });
3099
- preambleCode = react.default.preambleCode;
3100
- } catch (error) {
3101
- preambleCode = false;
3102
- }
3103
- }
3104
- },
3105
- buildStart() {
3106
- if (this.meta.watchMode) {
3107
- if (preambleCode) {
3108
- preambleRefId = this.emitFile({
3109
- type: "chunk",
3110
- id: preambleId,
3111
- name: "content-script-preamble.js"
3112
- });
3113
- }
3114
- contentClientRefId = this.emitFile({
3115
- type: "chunk",
3116
- id: "/@vite/client",
3117
- name: "content-script-client.js"
3118
- });
3119
- }
3120
- },
3121
- resolveId(source) {
3122
- if (source === preambleId)
3123
- return preambleId;
3124
- if (source === contentHmrPortId)
3125
- return contentHmrPortId;
3126
- },
3127
- load(id) {
3128
- if (server && id === preambleId && typeof preambleCode === "string") {
3129
- const defined = preambleCode.replace(/__BASE__/g, server.config.base);
3130
- return defined;
3131
- }
3132
- if (id === contentHmrPortId) {
3133
- const defined = contentHmrPort.replace("__CRX_HMR_TIMEOUT__", JSON.stringify(hmrTimeout));
3134
- return defined;
3135
- }
3136
- }
3137
- },
3138
- {
3139
- name: "crx:dynamic-scripts-load",
3450
+ name: "crx:web-accessible-resources",
3140
3451
  apply: "serve",
3141
- enforce: "pre",
3142
- resolveId: resolveDynamicScript,
3143
- load: loadDynamicScript
3144
- },
3145
- {
3146
- name: "crx:dynamic-scripts-load",
3147
- apply: "build",
3148
- enforce: "pre",
3149
- resolveId(id, importer) {
3150
- if (!this.meta.watchMode)
3151
- return resolveDynamicScript.call(this, id, importer);
3152
- },
3153
- load(id) {
3154
- if (!this.meta.watchMode)
3155
- return loadDynamicScript.call(this, id);
3452
+ enforce: "post",
3453
+ renderCrxManifest(manifest) {
3454
+ manifest.web_accessible_resources = manifest.web_accessible_resources ?? [];
3455
+ manifest.web_accessible_resources = manifest.web_accessible_resources.map(({ resources, ...rest }) => ({
3456
+ resources: resources.filter((r) => r !== DYNAMIC_RESOURCE),
3457
+ ...rest
3458
+ })).filter(({ resources }) => resources.length);
3459
+ manifest.web_accessible_resources.push({
3460
+ use_dynamic_url: true,
3461
+ matches: ["<all_urls>"],
3462
+ resources: ["**/*", "*"]
3463
+ });
3464
+ return manifest;
3156
3465
  }
3157
3466
  },
3158
3467
  {
3159
- name: "crx:dynamic-scripts-build",
3468
+ name: "crx:web-accessible-resources",
3160
3469
  apply: "build",
3161
- buildStart() {
3162
- dynamicScriptsByLoaderRefId.clear();
3163
- dynamicScriptsByRefId.clear();
3164
- for (const [, data] of dynamicScriptsByScriptId) {
3165
- emitDynamicScript.call(this, data);
3166
- }
3167
- },
3168
- async transform(code) {
3169
- if (code.includes("import.meta.CRX_DYNAMIC_SCRIPT_")) {
3170
- const match = code.match(/import.meta.CRX_DYNAMIC_SCRIPT_(.+?);/);
3171
- const index = match.index;
3172
- const [statement, scriptId] = match;
3173
- const data = dynamicScriptsByScriptId.get(scriptId);
3174
- if (!data.refId)
3175
- emitDynamicScript.call(this, data);
3176
- const magic = new MagicString__default["default"](code);
3177
- magic.overwrite(index, index + statement.length, `import.meta.ROLLUP_FILE_URL_${data.loaderRefId ?? data.refId};`);
3178
- return { code: magic.toString(), map: magic.generateMap() };
3179
- }
3180
- },
3181
- resolveFileUrl({ referenceId, fileName, moduleId }) {
3182
- if (moduleId && referenceId) {
3183
- if (dynamicScriptsByRefId.has(referenceId) || dynamicScriptsByLoaderRefId.has(referenceId)) {
3184
- return `"/${fileName}"`;
3185
- }
3186
- }
3470
+ enforce: "post",
3471
+ async config({ build, ...config2 }, { command }) {
3472
+ const { contentScripts: contentScripts2 = {} } = await getOptions(config2);
3473
+ injectCss = contentScripts2.injectCss ?? true;
3474
+ return { ...config2, build: { ...build, manifest: command === "build" } };
3187
3475
  },
3188
- generateBundle(options, bundle) {
3189
- const preambleName = this.meta.watchMode && preambleRefId ? this.getFileName(preambleRefId) : "";
3190
- const contentClientName = this.meta.watchMode && contentClientRefId ? this.getFileName(contentClientRefId) : "";
3191
- for (const data of dynamicScriptsByScriptId.values()) {
3192
- if (data.refId && data.loaderRefId) {
3193
- const scriptName = this.getFileName(data.refId);
3194
- const loaderName = this.getFileName(data.loaderRefId);
3195
- const source = this.meta.watchMode ? contentDevLoader.replace(/__PREAMBLE__/g, JSON.stringify(preambleName)).replace(/__CLIENT__/g, JSON.stringify(contentClientName)).replace(/__SCRIPT__/g, JSON.stringify(scriptName)) : contentProLoader.replace(/__SCRIPT__/g, JSON.stringify(scriptName));
3196
- const asset = bundle[loaderName];
3197
- if (asset?.type === "asset")
3198
- asset.source = source;
3199
- }
3200
- }
3476
+ configResolved(_config) {
3477
+ config = _config;
3201
3478
  },
3202
- writeBundle() {
3203
- for (const [, data] of dynamicScriptsByScriptId) {
3204
- if (data.refId) {
3205
- data.fileName = this.getFileName(data.refId);
3206
- delete data.refId;
3207
- }
3208
- if (data.loaderRefId) {
3209
- data.loaderName = this.getFileName(data.loaderRefId);
3210
- delete data.loaderRefId;
3211
- }
3212
- }
3213
- }
3214
- },
3215
- {
3216
- name: "crx:dynamic-scripts-serve",
3217
- apply: "serve",
3218
- configureServer(server2) {
3219
- server2.middlewares.use(injector__default["default"]((req) => {
3220
- return !!req.url?.includes("?scriptId");
3221
- }, async (content, req, res, callback) => {
3222
- const code = isString(content) ? content : content.toString();
3223
- if (code.includes("import.meta.CRX_DYNAMIC_SCRIPT_")) {
3224
- const matches = Array.from(code.matchAll(/import.meta.CRX_DYNAMIC_SCRIPT_(.+?);/g)).map((m) => ({
3225
- statement: m[0],
3226
- index: m.index,
3227
- data: dynamicScriptsByScriptId.get(m[1])
3228
- }));
3229
- if (matches.some(({ data }) => data.refId))
3230
- await filesReady();
3231
- if (matches.some(({ data }) => !(data.loaderName ?? data.fileName))) {
3232
- await rebuildFiles();
3233
- server2.ws.send(crxRuntimeReload);
3234
- }
3235
- const magic = new MagicString__default["default"](code);
3236
- for (const { index, statement, data } of matches)
3237
- if (typeof index === "number") {
3238
- magic.overwrite(index, index + statement.length, `"/${data.loaderName ?? data.fileName}"`);
3239
- }
3240
- callback(null, magic.toString());
3241
- } else {
3242
- callback(null, code);
3479
+ async renderCrxManifest(manifest, bundle) {
3480
+ const { web_accessible_resources: _war = [] } = manifest;
3481
+ const dynamicScriptMatches = /* @__PURE__ */ new Set();
3482
+ let dynamicScriptDynamicUrl = false;
3483
+ const web_accessible_resources = [];
3484
+ for (const r of _war) {
3485
+ const i = r.resources.indexOf(DYNAMIC_RESOURCE);
3486
+ if (i > -1 && isResourceByMatch(r)) {
3487
+ r.resources = [...r.resources];
3488
+ r.resources.splice(i, 1);
3489
+ for (const p of r.matches)
3490
+ dynamicScriptMatches.add(p);
3491
+ dynamicScriptDynamicUrl = r.use_dynamic_url ?? false;
3243
3492
  }
3244
- }));
3245
- }
3246
- },
3247
- {
3248
- name: "crx:content-script-resources",
3249
- apply: "build",
3250
- enforce: "post",
3251
- config({ build, ...config }, { command }) {
3252
- return { ...config, build: { ...build, manifest: command === "build" } };
3253
- },
3254
- renderCrxManifest(manifest, bundle) {
3255
- manifest.web_accessible_resources = manifest.web_accessible_resources ?? [];
3256
- if (manifest.content_scripts?.length || dynamicScriptsByRefId.size)
3257
- if (this.meta.watchMode) {
3258
- manifest.web_accessible_resources = manifest.web_accessible_resources.map(({ resources, ...rest }) => ({
3259
- resources: resources.filter((r) => r !== dynamicResourcesName),
3260
- ...rest
3261
- })).filter(({ resources }) => resources.length);
3262
- manifest.web_accessible_resources.push({
3263
- use_dynamic_url: true,
3264
- matches: ["<all_urls>"],
3265
- resources: ["**/*", "*"]
3266
- });
3267
- } else {
3268
- const vmAsset = bundle["manifest.json"];
3269
- if (!vmAsset)
3270
- throw new Error("vite manifest is missing");
3271
- const viteManifest = JSON.parse(vmAsset.source);
3272
- debug("vite manifest %O", viteManifest);
3273
- if (Object.keys(viteManifest).length === 0)
3274
- return;
3275
- const filesByName = /* @__PURE__ */ new Map();
3276
- for (const file of Object.values(viteManifest))
3277
- filesByName.set(file.file, file);
3278
- const chunksById = /* @__PURE__ */ new Map();
3279
- for (const [name, chunk] of Object.entries(bundle))
3280
- if (chunk.type === "chunk" && chunk.facadeModuleId)
3281
- chunksById.set(chunk.facadeModuleId, name);
3282
- const getChunkResources = (chunk) => {
3283
- const chunks = /* @__PURE__ */ new Set();
3284
- const assets = /* @__PURE__ */ new Set();
3285
- if (chunk.type === "asset")
3286
- return { chunks, assets };
3287
- const { dynamicImports, imports, modules } = chunk;
3288
- for (const i of dynamicImports)
3289
- chunks.add(i);
3290
- for (const i of imports)
3291
- chunks.add(i);
3292
- for (const id of Object.keys(modules))
3293
- if (dynamicScriptsById.has(id)) {
3294
- const data = dynamicScriptsById.get(id);
3295
- const fileName = this.getFileName(data.refId);
3296
- const chunk2 = bundle[fileName];
3297
- if (chunk2.type === "chunk")
3298
- chunks.add(fileName);
3299
- else
3300
- assets.add(fileName);
3301
- }
3302
- return { chunks, assets };
3303
- };
3304
- const getResources = (name, sets = {
3305
- assets: /* @__PURE__ */ new Set(),
3306
- css: /* @__PURE__ */ new Set(),
3307
- imports: /* @__PURE__ */ new Set()
3308
- }) => {
3309
- const {
3310
- assets = [],
3311
- css = [],
3312
- dynamicImports = [],
3313
- imports = [],
3314
- file
3315
- } = filesByName.get(name) ?? viteManifest[name] ?? {};
3316
- const chunk = bundle[file];
3317
- if (chunk?.type === "chunk") {
3318
- const r = getChunkResources(chunk);
3319
- assets.push(...r.assets);
3320
- for (const chunk2 of r.chunks) {
3321
- sets.imports.add(chunk2);
3322
- getResources(chunk2, sets);
3323
- }
3324
- }
3325
- for (const a of assets)
3326
- sets.assets.add(a);
3327
- for (const c of css)
3328
- sets.css.add(c);
3329
- for (const key of [...dynamicImports, ...imports]) {
3330
- const i = viteManifest[key].file;
3331
- sets.imports.add(i);
3332
- getResources(key, sets);
3333
- }
3334
- return sets;
3335
- };
3336
- for (const script of manifest.content_scripts ?? [])
3337
- if (script.js?.length) {
3338
- for (const name of script.js)
3339
- if (script.matches?.length) {
3340
- const { assets, css, imports } = getResources(name);
3341
- imports.add(name);
3342
- const resource = {
3343
- matches: script.matches,
3344
- resources: [...assets, ...imports],
3345
- use_dynamic_url: true
3346
- };
3347
- if (css.size)
3348
- if (injectCss) {
3349
- script.css = script.css ?? [];
3350
- script.css.push(...css);
3351
- } else {
3352
- resource.resources.push(...css);
3353
- }
3354
- if (resource.resources.length) {
3355
- resource.matches = resource.matches.map(stubMatchPattern);
3356
- manifest.web_accessible_resources.push(resource);
3357
- }
3493
+ if (r.resources.length > 0)
3494
+ web_accessible_resources.push(r);
3495
+ }
3496
+ if (dynamicScriptMatches.size === 0) {
3497
+ dynamicScriptMatches.add("http://*/*");
3498
+ dynamicScriptMatches.add("https://*/*");
3499
+ }
3500
+ if (contentScripts.size > 0) {
3501
+ const viteManifest = parseJsonAsset(bundle, "manifest.json");
3502
+ const viteFiles = /* @__PURE__ */ new Map();
3503
+ for (const [, file] of Object.entries(viteManifest))
3504
+ viteFiles.set(file.file, file);
3505
+ if (viteFiles.size === 0)
3506
+ return null;
3507
+ const bundleChunks = /* @__PURE__ */ new Map();
3508
+ for (const chunk of Object.values(bundle))
3509
+ if (chunk.type === "chunk")
3510
+ bundleChunks.set(chunk.fileName, chunk);
3511
+ const moduleScriptResources = /* @__PURE__ */ new Map();
3512
+ for (const [
3513
+ key,
3514
+ { id, fileName, matches, type, isDynamicScript = false }
3515
+ ] of contentScripts)
3516
+ if (key === id) {
3517
+ if (isDynamicScript || matches.length)
3518
+ if (typeof fileName === "undefined") {
3519
+ throw new Error(`Content script filename is undefined for "${id}"`);
3520
+ } else {
3521
+ const { assets, css, imports } = compileFileResources(fileName, { chunks: bundleChunks, files: viteFiles, config });
3522
+ contentScripts.get(key).css = [...css];
3523
+ if (type === "loader")
3524
+ imports.add(fileName);
3525
+ const resource = {
3526
+ matches: isDynamicScript ? [...dynamicScriptMatches] : matches,
3527
+ resources: [...assets, ...imports],
3528
+ use_dynamic_url: isDynamicScript ? dynamicScriptDynamicUrl : true
3529
+ };
3530
+ if (isDynamicScript || !injectCss) {
3531
+ resource.resources.push(...css);
3358
3532
  }
3359
- }
3360
- const dynamicResourceSet = /* @__PURE__ */ new Set();
3361
- for (const [refId, { format }] of dynamicScriptsByRefId)
3362
- if (format === "loader") {
3363
- const name = this.getFileName(refId);
3364
- const { assets, css, imports } = getResources(name);
3365
- dynamicResourceSet.add(name);
3366
- for (const a of assets)
3367
- dynamicResourceSet.add(a);
3368
- for (const c of css)
3369
- dynamicResourceSet.add(c);
3370
- for (const i of imports)
3371
- dynamicResourceSet.add(i);
3372
- }
3373
- if (dynamicResourceSet.size) {
3374
- let resource = manifest.web_accessible_resources.find(({ resources: [r] }) => r === dynamicResourcesName);
3375
- if (!resource) {
3376
- resource = {
3377
- resources: [dynamicResourcesName],
3378
- matches: ["http://*/*", "https://*/*"]
3379
- };
3380
- manifest.web_accessible_resources.push(resource);
3381
- }
3382
- resource.resources = [...dynamicResourceSet];
3533
+ if (resource.resources.length)
3534
+ if (type === "module") {
3535
+ moduleScriptResources.set(fileName, resource);
3536
+ } else {
3537
+ resource.matches = resource.matches.map(getMatchPatternOrigin);
3538
+ web_accessible_resources.push(resource);
3539
+ }
3540
+ }
3383
3541
  }
3542
+ for (const r of web_accessible_resources)
3543
+ if (isResourceByMatch(r))
3544
+ for (const res of r.resources)
3545
+ moduleScriptResources.delete(res);
3546
+ web_accessible_resources.push(...moduleScriptResources.values());
3547
+ }
3548
+ const hashedResources = /* @__PURE__ */ new Map();
3549
+ const combinedResources = [];
3550
+ for (const r of web_accessible_resources)
3551
+ if (isResourceByMatch(r)) {
3552
+ const { matches, resources, use_dynamic_url = false } = r;
3553
+ const key = JSON.stringify([use_dynamic_url, matches.sort()]);
3554
+ const combined = hashedResources.get(key) ?? /* @__PURE__ */ new Set();
3555
+ for (const res of resources)
3556
+ combined.add(res);
3557
+ hashedResources.set(key, combined);
3558
+ } else {
3559
+ combinedResources.push(r);
3384
3560
  }
3385
- if (manifest.web_accessible_resources?.length) {
3386
- const war = manifest.web_accessible_resources;
3387
- manifest.web_accessible_resources = [];
3388
- const map = /* @__PURE__ */ new Map();
3389
- for (const r of war)
3390
- if (isResourceByMatch(r)) {
3391
- const { matches, resources, use_dynamic_url = false } = r;
3392
- const key = [use_dynamic_url, matches.sort()].map((x) => JSON.stringify(x)).join("::");
3393
- const set = map.get(key) ?? /* @__PURE__ */ new Set();
3394
- resources.forEach((r2) => set.add(r2));
3395
- map.set(key, set);
3396
- } else {
3397
- manifest.web_accessible_resources.push(r);
3398
- }
3399
- for (const [key, set] of map) {
3400
- const [use_dynamic_url, matches] = key.split("::").map((x) => JSON.parse(x));
3401
- manifest.web_accessible_resources.push({
3561
+ for (const [key, resources] of hashedResources)
3562
+ if (resources.size > 0) {
3563
+ const [use_dynamic_url, matches] = JSON.parse(key);
3564
+ combinedResources.push({
3402
3565
  matches,
3403
- resources: [...set],
3566
+ resources: [...resources],
3404
3567
  use_dynamic_url
3405
3568
  });
3406
3569
  }
3407
- } else {
3570
+ if (combinedResources.length === 0)
3408
3571
  delete manifest.web_accessible_resources;
3409
- }
3410
- return manifest;
3411
- }
3412
- },
3413
- {
3414
- name: "crx:content-scripts-post",
3415
- apply: "build",
3416
- enforce: "post",
3417
- renderCrxManifest(manifest, bundle) {
3418
- if (this.meta.watchMode && typeof port === "undefined")
3419
- throw new Error("server port is undefined");
3420
- const preambleName = this.meta.watchMode && preambleRefId ? this.getFileName(preambleRefId) : "";
3421
- const contentClientName = this.meta.watchMode && contentClientRefId ? this.getFileName(contentClientRefId) : "";
3422
- if (!manifest.content_scripts?.length && !dynamicScriptsByRefId.size) {
3423
- delete bundle[contentClientName];
3424
- return manifest;
3425
- }
3426
- manifest.content_scripts = manifest.content_scripts?.map(({ js, ...rest }) => ({
3427
- js: js?.map((f) => {
3428
- const name = `content-script-loader.${parse(f).name}.js`;
3429
- const source = this.meta.watchMode ? contentDevLoader.replace(/__PREAMBLE__/g, JSON.stringify(preambleName)).replace(/__CLIENT__/g, JSON.stringify(contentClientName)).replace(/__SCRIPT__/g, JSON.stringify(f)).replace(/__TIMESTAMP__/g, JSON.stringify(Date.now())) : contentProLoader.replace(/__SCRIPT__/g, JSON.stringify(f));
3430
- const refId = this.emitFile({
3431
- type: "asset",
3432
- name,
3433
- source
3434
- });
3435
- return this.getFileName(refId);
3436
- }),
3437
- ...rest
3438
- }));
3572
+ else
3573
+ manifest.web_accessible_resources = combinedResources;
3439
3574
  return manifest;
3440
3575
  }
3441
3576
  }
3442
3577
  ];
3443
3578
  };
3444
3579
 
3445
- var workerHmrClient = "const ownOrigin = new URL(chrome.runtime.getURL(\"/\")).origin;\nself.addEventListener(\"fetch\", (fetchEvent) => {\n const url = new URL(fetchEvent.request.url);\n if (url.origin === ownOrigin) {\n fetchEvent.respondWith(sendToServer(url));\n }\n});\nasync function sendToServer(url) {\n url.protocol = \"http:\";\n url.host = \"localhost\";\n url.port = __SERVER_PORT__;\n url.searchParams.set(\"t\", Date.now().toString());\n const response = await fetch(url.href.replace(/=$|=(?=&)/g, \"\"));\n return new Response(response.body, {\n headers: {\n \"Content-Type\": response.headers.get(\"Content-Type\") ?? \"text/javascript\"\n }\n });\n}\nconst ports = /* @__PURE__ */ new Set();\nchrome.runtime.onConnect.addListener((port) => {\n if (port.name === \"@crx/client\") {\n ports.add(port);\n port.onDisconnect.addListener((port2) => ports.delete(port2));\n port.onMessage.addListener((message) => {\n });\n port.postMessage({ data: JSON.stringify({ type: \"connected\" }) });\n }\n});\nfunction notifyContentScripts(payload) {\n const data = JSON.stringify(payload);\n for (const port of ports)\n port.postMessage({ data });\n}\nconsole.log(\"[vite] connecting...\");\nconst socketProtocol = __HMR_PROTOCOL__ || (location.protocol === \"https:\" ? \"wss\" : \"ws\");\nconst socketHost = `${__HMR_HOSTNAME__ || location.hostname}:${__HMR_PORT__}`;\nconst socket = new WebSocket(`${socketProtocol}://${socketHost}`, \"vite-hmr\");\nconst base = __BASE__ || \"/\";\nsocket.addEventListener(\"message\", async ({ data }) => {\n handleSocketMessage(JSON.parse(data));\n});\nfunction isCrxHmrPayload(x) {\n return x.type === \"custom\" && x.event.startsWith(\"crx:\");\n}\nfunction handleSocketMessage(payload) {\n if (isCrxHmrPayload(payload)) {\n handleCrxHmrPayload(payload);\n } else if (payload.type === \"connected\") {\n console.log(`[vite] connected.`);\n const interval = setInterval(() => socket.send(\"ping\"), __HMR_TIMEOUT__);\n socket.addEventListener(\"close\", () => clearInterval(interval));\n }\n}\nfunction handleCrxHmrPayload(payload) {\n notifyContentScripts(payload);\n switch (payload.event) {\n case \"crx:runtime-reload\":\n console.log(\"[crx] runtime reload\");\n chrome.runtime.reload();\n break;\n }\n}\nasync function waitForSuccessfulPing(ms = 1e3) {\n while (true) {\n try {\n await fetch(`${base}__vite_ping`);\n break;\n } catch (e) {\n await new Promise((resolve) => setTimeout(resolve, ms));\n }\n }\n}\nsocket.addEventListener(\"close\", async ({ wasClean }) => {\n if (wasClean)\n return;\n console.log(`[vite] server connection lost. polling for restart...`);\n await waitForSuccessfulPing();\n chrome.runtime.reload();\n});\n";
3446
-
3447
- function defineClientValues(code, config) {
3448
- let options = config.server.hmr;
3449
- options = options && typeof options !== "boolean" ? options : {};
3450
- const host = options.host || null;
3451
- const protocol = options.protocol || null;
3452
- const timeout = options.timeout || 3e4;
3453
- const overlay = options.overlay !== false;
3454
- let hmrPort;
3455
- if (isObject(config.server.hmr)) {
3456
- hmrPort = config.server.hmr.clientPort || config.server.hmr.port;
3457
- }
3458
- if (config.server.middlewareMode) {
3459
- hmrPort = String(hmrPort || 24678);
3460
- } else {
3461
- hmrPort = String(hmrPort || options.port || config.server.port);
3462
- }
3463
- let hmrBase = config.base;
3464
- if (options.path) {
3465
- hmrBase = join(hmrBase, options.path);
3466
- }
3467
- if (hmrBase !== "/") {
3468
- hmrPort = normalize(`${hmrPort}${hmrBase}`);
3469
- }
3470
- return code.replace(`__MODE__`, JSON.stringify(config.mode)).replace(`__BASE__`, JSON.stringify(config.base)).replace(`__DEFINES__`, serializeDefine(config.define || {})).replace(`__HMR_PROTOCOL__`, JSON.stringify(protocol)).replace(`__HMR_HOSTNAME__`, JSON.stringify(host)).replace(`__HMR_PORT__`, JSON.stringify(hmrPort)).replace(`__HMR_TIMEOUT__`, JSON.stringify(timeout)).replace(`__HMR_ENABLE_OVERLAY__`, JSON.stringify(overlay)).replace(`__SERVER_PORT__`, JSON.stringify(config.server.port?.toString()));
3471
- function serializeDefine(define) {
3472
- let res = `{`;
3473
- for (const key in define) {
3474
- const val = define[key];
3475
- res += `${JSON.stringify(key)}: ${typeof val === "string" ? `(${val})` : JSON.stringify(val)}, `;
3476
- }
3477
- return res + `}`;
3478
- }
3479
- }
3480
-
3481
- const pluginBackground = () => {
3482
- let port;
3483
- let server;
3580
+ const crx = (options) => {
3484
3581
  return [
3485
- {
3486
- name: "crx:background-client",
3487
- apply: "serve",
3488
- configureServer(_server) {
3489
- server = _server;
3490
- },
3491
- resolveId(source) {
3492
- if (source === `/${workerClientId}`)
3493
- return workerClientId;
3494
- },
3495
- load(id) {
3496
- if (id === workerClientId) {
3497
- const base = `http://localhost:${server.config.server.port}/`;
3498
- return defineClientValues(workerHmrClient.replace("__BASE__", JSON.stringify(base)), server.config);
3499
- }
3500
- }
3501
- },
3502
- {
3503
- name: "crx:background-loader-file",
3504
- apply: "build",
3505
- enforce: "post",
3506
- fileWriterStart(server2) {
3507
- port = server2.config.server.port.toString();
3508
- },
3509
- renderCrxManifest(manifest) {
3510
- const worker = manifest.background?.service_worker;
3511
- let loader;
3512
- if (this.meta.watchMode) {
3513
- if (typeof port === "undefined")
3514
- throw new Error("server port is undefined in watch mode");
3515
- loader = `import 'http:/localhost:${port}/@vite/env';
3516
- `;
3517
- loader += `import 'http://localhost:${port}${workerClientId}';
3518
- `;
3519
- if (worker)
3520
- loader += `import 'http://localhost:${port}/${worker}';
3521
- `;
3522
- } else if (worker) {
3523
- loader = `import './${worker}';
3524
- `;
3525
- } else {
3526
- return null;
3527
- }
3528
- const refId = this.emitFile({
3529
- type: "asset",
3530
- fileName: "service-worker-loader.js",
3531
- source: loader
3532
- });
3533
- manifest.background = {
3534
- service_worker: this.getFileName(refId),
3535
- type: "module"
3536
- };
3537
- return manifest;
3538
- }
3539
- }
3540
- ];
3541
- };
3542
-
3543
- const defineManifest = (manifest) => manifest;
3544
- const defineDynamicResource = ({
3545
- matches = ["http://*/*", "https://*/*"],
3546
- use_dynamic_url = true
3547
- }) => ({
3548
- matches,
3549
- resources: [dynamicResourcesName],
3550
- use_dynamic_url
3551
- });
3552
-
3553
- function init(options, plugins) {
3554
- return plugins.map((p) => p?.(options)).flat().filter((p) => !!p && typeof p.name === "string");
3555
- }
3556
- const crx = ({
3557
- manifest,
3558
- ...options
3559
- }) => {
3560
- const plugins = init(options, [
3561
- pluginHMR,
3562
- pluginHtmlAuditor,
3563
- pluginResources,
3564
- pluginBackground,
3565
- pluginManifest(manifest)
3566
- ]);
3567
- plugins.unshift(...init(options, [pluginFileWriter(plugins)]));
3568
- return plugins;
3582
+ pluginOptionsProvider(options),
3583
+ pluginBackground(),
3584
+ pluginContentScripts(),
3585
+ pluginDeclaredContentScripts(),
3586
+ pluginDynamicContentScripts(),
3587
+ pluginFileWriter(),
3588
+ pluginFileWriterPublic(),
3589
+ pluginFileWriterPolyfill(),
3590
+ pluginHtmlInlineScripts(),
3591
+ pluginWebAccessibleResources(),
3592
+ pluginContentScriptsCss(),
3593
+ pluginHMR(),
3594
+ pluginManifest()
3595
+ ].flat();
3569
3596
  };
3570
3597
  const chromeExtension = crx;
3571
3598
 
3599
+ exports.allFilesReady = allFilesReady;
3572
3600
  exports.chromeExtension = chromeExtension;
3573
3601
  exports.crx = crx;
3574
3602
  exports.defineDynamicResource = defineDynamicResource;
3575
3603
  exports.defineManifest = defineManifest;
3576
- exports.filesReady = filesReady;
3577
- exports.rebuildFiles = rebuildFiles;
3604
+ exports.filesReady = fileReady;