@crxjs/vite-plugin 1.0.14 → 2.0.0-beta.2

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.
package/dist/index.cjs CHANGED
@@ -2,23 +2,26 @@
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 rxjs = require('rxjs');
11
+ var fsx = require('fs-extra');
15
12
  var perf_hooks = require('perf_hooks');
16
- var colors = require('picocolors');
13
+ var rollup = require('rollup');
14
+ var lexer = require('es-module-lexer');
15
+ var promises = require('fs/promises');
16
+ var MagicString = require('magic-string');
17
17
  var vite = require('vite');
18
+ var fs = require('fs');
18
19
  var module$1 = require('module');
20
+ var fg = require('fast-glob');
21
+ var getPort = require('get-port');
19
22
  var cheerio = require('cheerio');
20
23
  var jsesc = require('jsesc');
21
- var injector = require('connect-injector');
24
+ var colors = require('picocolors');
22
25
 
23
26
  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
24
27
 
@@ -40,72 +43,63 @@ function _interopNamespace(e) {
40
43
  return Object.freeze(n);
41
44
  }
42
45
 
43
- var debug__default = /*#__PURE__*/_interopDefaultLegacy(debug$5);
44
- var fg__default = /*#__PURE__*/_interopDefaultLegacy(fg);
46
+ var debug__default = /*#__PURE__*/_interopDefaultLegacy(debug$2);
45
47
  var v8__default = /*#__PURE__*/_interopDefaultLegacy(v8);
48
+ var fsx__default = /*#__PURE__*/_interopDefaultLegacy(fsx);
49
+ var lexer__namespace = /*#__PURE__*/_interopNamespace(lexer);
46
50
  var MagicString__default = /*#__PURE__*/_interopDefaultLegacy(MagicString);
47
- var fsExtra__default = /*#__PURE__*/_interopDefaultLegacy(fsExtra);
48
- var colors__default = /*#__PURE__*/_interopDefaultLegacy(colors);
51
+ var fg__default = /*#__PURE__*/_interopDefaultLegacy(fg);
52
+ var getPort__default = /*#__PURE__*/_interopDefaultLegacy(getPort);
49
53
  var jsesc__default = /*#__PURE__*/_interopDefaultLegacy(jsesc);
50
- var injector__default = /*#__PURE__*/_interopDefaultLegacy(injector);
54
+ var colors__default = /*#__PURE__*/_interopDefaultLegacy(colors);
55
+
56
+ const pluginName$1 = "crx:optionsProvider";
57
+ const pluginOptionsProvider = (options) => {
58
+ return {
59
+ name: pluginName$1,
60
+ api: {
61
+ crx: {
62
+ options
63
+ }
64
+ }
65
+ };
66
+ };
67
+ const getOptions = ({ plugins }) => {
68
+ if (typeof plugins === "undefined") {
69
+ throw new Error("config.plugins is undefined");
70
+ }
71
+ let options;
72
+ for (const p of plugins.flat()) {
73
+ if (isCrxPlugin(p)) {
74
+ if (p.name === pluginName$1) {
75
+ const plugin = p;
76
+ options = plugin.api.crx.options;
77
+ if (options)
78
+ break;
79
+ }
80
+ }
81
+ }
82
+ if (typeof options === "undefined") {
83
+ throw Error("Unable to get CRXJS options");
84
+ }
85
+ return options;
86
+ };
87
+ function isCrxPlugin(p) {
88
+ return !!p && typeof p === "object" && !(p instanceof Promise) && !Array.isArray(p) && p.name.startsWith("crx:");
89
+ }
90
+
91
+ 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
92
 
52
93
  const _debug = (id) => debug__default["default"]("crx").extend(id);
53
94
  const structuredClone = (obj) => {
54
95
  return v8__default["default"].deserialize(v8__default["default"].serialize(obj));
55
96
  };
56
- const createHash = (data, length = 5) => crypto.createHash("sha1").update(data).digest("base64").replace(/[^A-Za-z0-9]/g, "").slice(0, length);
97
+ const hash = (data, length = 5) => crypto.createHash("sha1").update(data).digest("base64").replace(/[^A-Za-z0-9]/g, "").slice(0, length);
57
98
  const isString = (x) => typeof x === "string";
58
- const isTruthy = (x) => !!x;
59
99
  function isObject(value) {
60
100
  return Object.prototype.toString.call(value) === "[object Object]";
61
101
  }
62
102
  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
103
  function decodeManifest(code) {
110
104
  const tree = this.parse(code);
111
105
  let literal;
@@ -132,70 +126,25 @@ function encodeManifest(manifest) {
132
126
  const json = JSON.stringify(JSON.stringify(manifest));
133
127
  return `export default ${json}`;
134
128
  }
135
- const stubMatchPattern = (pattern) => {
136
- if (pattern === "<all_urls>") {
129
+ function parseJsonAsset(bundle, key) {
130
+ const asset = bundle[key];
131
+ if (typeof asset === "undefined")
132
+ throw new TypeError(`OutputBundle["${key}"] is undefined.`);
133
+ if (asset.type !== "asset")
134
+ throw new Error(`OutputBundle["${key}"] is not an OutputAsset.`);
135
+ if (typeof asset.source !== "string")
136
+ throw new TypeError(`OutputBundle["${key}"].source is not a string.`);
137
+ return JSON.parse(asset.source);
138
+ }
139
+ const getMatchPatternOrigin = (pattern) => {
140
+ if (pattern.startsWith("<"))
137
141
  return pattern;
138
- }
139
142
  const [schema, rest] = pattern.split("://");
140
143
  const [origin, pathname] = rest.split("/");
141
144
  const root = `${schema}://${origin}`;
142
145
  return pathname ? `${root}/*` : root;
143
146
  };
144
147
 
145
- const idBySource = /* @__PURE__ */ new Map();
146
- const idByUrl = /* @__PURE__ */ new Map();
147
- const urlById = /* @__PURE__ */ new Map();
148
- function setUrlMeta({
149
- id,
150
- source,
151
- url
152
- }) {
153
- idBySource.set(source, id);
154
- idByUrl.set(url, id);
155
- urlById.set(id, url);
156
- }
157
- const fileById = /* @__PURE__ */ new Map();
158
- const fileByUrl = /* @__PURE__ */ new Map();
159
- const pathById = /* @__PURE__ */ new Map();
160
- const pathByUrl = /* @__PURE__ */ new Map();
161
- const setFileMeta = ({ file, id }) => {
162
- const url = urlById.get(id);
163
- if (!url)
164
- return;
165
- fileById.set(id, file);
166
- fileByUrl.set(url, file);
167
- const pathName = `/${file}`;
168
- pathById.set(id, pathName);
169
- pathByUrl.set(url, pathName);
170
- };
171
- const ownerById = /* @__PURE__ */ new Map();
172
- const pathByOwner = /* @__PURE__ */ new Map();
173
- const ownersByFile = /* @__PURE__ */ new Map();
174
- const setOwnerMeta = ({ owner, id }) => {
175
- const pathName = pathById.get(id);
176
- if (!pathName)
177
- return;
178
- pathByOwner.set(owner, pathName);
179
- ownerById.set(id, owner);
180
- const fileName = fileById.get(id);
181
- const owners = ownersByFile.get(fileName) ?? /* @__PURE__ */ new Set();
182
- owners.add(owner);
183
- ownersByFile.set(fileName, owners);
184
- };
185
- const outputById = /* @__PURE__ */ new Map();
186
- const outputByOwner = /* @__PURE__ */ new Map();
187
- const setOutputMeta = ({
188
- output,
189
- id
190
- }) => {
191
- const ownerName = ownerById.get(id);
192
- if (!ownerName)
193
- return;
194
- outputByOwner.set(ownerName, output);
195
- outputById.set(id, output);
196
- };
197
- const transformResultByOwner = /* @__PURE__ */ new Map();
198
-
199
148
  const {
200
149
  basename,
201
150
  dirname,
@@ -212,2095 +161,559 @@ const {
212
161
  sep
213
162
  } = path.posix;
214
163
 
215
- const viteClientId = "/@vite/client";
216
- const customElementsId = "@webcomponents/custom-elements";
217
- const reactRefreshId = "/@react-refresh";
218
- const contentHmrPortId = "/crx-client-port";
219
- const manifestId = "/crx-manifest";
220
- const preambleId = "/crx-client-preamble";
221
- const stubId = "/crx-stub";
222
- const workerClientId = "/crx-client-worker";
223
-
224
- const { readFile: readFile$2 } = fs.promises;
225
- const debug$4 = _debug("file-writer").extend("chunks");
226
- for (const source of [viteClientId, customElementsId]) {
227
- setUrlMeta(sourceToUrlMeta(source));
228
- }
229
- setUrlMeta({
230
- source: reactRefreshId,
231
- id: "/react-refresh",
232
- url: reactRefreshId
233
- });
234
- function sourceToUrlMeta(source) {
235
- const [p, query = ""] = source.split("?");
236
- const pathname = p.replace(/^\/@id\//, "").replace(/^\/@fs/, "");
237
- const url = [pathname, query].filter(isTruthy).join("?");
238
- const hash = createHash(url);
239
- const base = p.split("/").slice(-4).filter(isTruthy).join("-");
240
- const id = `/${base}-${hash}.js`.replace(/[@]/g, "");
241
- return { id, url, source };
242
- }
243
- const pluginFileWriterChunks = () => {
244
- let server;
245
- return {
246
- name: "crx:file-writer-chunks",
247
- apply: "build",
248
- fileWriterStart(_server) {
249
- server = _server;
250
- },
251
- async resolveId(source, importer) {
252
- if (this.meta.watchMode) {
253
- if (idBySource.has(source)) {
254
- const id = idBySource.get(source);
255
- debug$4(`resolved cached ${source} -> ${id}`);
256
- return id;
257
- } else if (importer) {
258
- const meta = sourceToUrlMeta(source);
259
- setUrlMeta(meta);
260
- const { id } = meta;
261
- debug$4(`resolved ${source} -> ${id}`);
262
- return id;
263
- } else {
264
- const [rawUrl] = await server.moduleGraph.resolveUrl(source);
265
- const name = rawUrl.split("/").join("-").replace(/^-/, "");
266
- const url = rawUrl.startsWith("/") ? rawUrl : `/${rawUrl}`;
267
- const id = `/${name}-${createHash(url)}.js`;
268
- setUrlMeta({ url, id, source });
269
- debug$4(`resolved entry ${source} -> ${id}`);
270
- return id;
271
- }
272
- }
273
- },
274
- async load(id) {
275
- if (this.meta.watchMode && urlById.has(id)) {
276
- const url = urlById.get(id);
277
- let serverModule = await server.moduleGraph.getModuleByUrl(url);
278
- let transformResult = null;
279
- if (!serverModule) {
280
- transformResult = await server.transformRequest(url);
281
- serverModule = await server.moduleGraph.getModuleByUrl(url);
282
- }
283
- if (!serverModule)
284
- throw new Error(`Unable to load "${url}" from server.`);
285
- const { file, url: owner } = serverModule;
286
- transformResult = transformResult ?? transformResultByOwner.get(owner) ?? serverModule.transformResult;
287
- if (!transformResult)
288
- transformResult = await server.transformRequest(url);
289
- if (!transformResult)
290
- throw new TypeError(`Unable to load "${url}" from server.`);
291
- transformResultByOwner.set(owner, transformResult);
292
- if (file) {
293
- setFileMeta({ id, file });
294
- this.addWatchFile(file);
295
- if (urlById.get(id).includes("?import"))
296
- this.emitFile({
297
- type: "asset",
298
- fileName: relative(server.config.root, file),
299
- source: await readFile$2(file)
300
- });
301
- }
302
- if (url)
303
- setOwnerMeta({ id, owner });
304
- return { code: transformResult.code, map: transformResult.map };
305
- }
306
- return null;
307
- },
308
- outputOptions(options) {
309
- const cacheDir = relative(server.config.root, server.config.cacheDir);
310
- const fileNameById = /* @__PURE__ */ new Map();
311
- fileNameById.set("/react-refresh", "vendor/react-refresh.js");
312
- function fileNames(info) {
313
- const id = info.type === "chunk" ? info.facadeModuleId : info.name;
314
- if (id && fileNameById.has(id))
315
- return fileNameById.get(id);
316
- let fileName = info.type === "chunk" ? "assets/[name].js" : "assets/[name].[ext]";
317
- if (id && fileById.has(id)) {
318
- fileName = fileById.get(id);
319
- const url = new URL(urlById.get(id), "stub://stub");
320
- if (url.searchParams.has("type"))
321
- fileName += `.${url.searchParams.get("type")}`;
322
- if (url.searchParams.has("index"))
323
- fileName += `.${url.searchParams.get("index")}`;
324
- }
325
- if (id?.startsWith("/@crx/"))
326
- fileName = `vendor/${id.slice("/@crx/".length).split("/").join("-")}`;
327
- if (fileName.startsWith(server.config.root))
328
- fileName = fileName.slice(server.config.root.length + 1);
329
- if (fileName.startsWith(cacheDir))
330
- fileName = `vendor/${fileName.slice(cacheDir.length + 1)}`;
331
- if (fileName.includes("/node_modules/"))
332
- fileName = `vendor/${fileName.split("/node_modules/").pop().split("/").join("-").replace("vite-dist-client", "vite")}`;
333
- if (fileName.startsWith("/"))
334
- fileName = fileName.slice(1);
335
- if (!fileName.endsWith(".js"))
336
- fileName += ".js";
337
- if (id)
338
- fileNameById.set(id, fileName);
339
- fileName = fileName.replace(/:/g, "-").replace(/@/, "");
340
- return fileName;
341
- }
342
- return {
343
- ...options,
344
- preserveModules: true,
345
- assetFileNames: fileNames,
346
- entryFileNames: fileNames
347
- };
348
- },
349
- generateBundle(options, bundle) {
350
- for (const chunk of Object.values(bundle))
351
- if (chunk.type === "chunk") {
352
- const { facadeModuleId: id, modules, code, fileName } = chunk;
353
- if (!id || Object.keys(modules).length !== 1)
354
- continue;
355
- const url = urlById.get(id);
356
- if (url === viteClientId)
357
- continue;
358
- const ownerPath = ownerById.get(id);
359
- if (!ownerPath)
360
- continue;
361
- const index = code.indexOf("createHotContext(");
362
- if (index === -1)
363
- continue;
364
- const start = code.indexOf(ownerPath, index);
365
- const end = start + ownerPath.length;
366
- if (start > 0) {
367
- const outputName = `/${fileName}`;
368
- setOutputMeta({ id, output: outputName });
369
- const magic = new MagicString__default["default"](code);
370
- magic.overwrite(start, end, outputName);
371
- chunk.code = magic.toString();
372
- }
373
- }
164
+ function defineClientValues(code, config) {
165
+ let options = config.server.hmr;
166
+ options = options && typeof options !== "boolean" ? options : {};
167
+ const host = options.host || null;
168
+ const protocol = options.protocol || null;
169
+ const timeout = options.timeout || 3e4;
170
+ const overlay = options.overlay !== false;
171
+ let hmrPort;
172
+ if (isObject(config.server.hmr)) {
173
+ hmrPort = config.server.hmr.clientPort || config.server.hmr.port;
174
+ }
175
+ if (config.server.middlewareMode) {
176
+ hmrPort = String(hmrPort || 24678);
177
+ } else {
178
+ hmrPort = String(hmrPort || options.port || config.server.port);
179
+ }
180
+ let hmrBase = config.base;
181
+ if (options.path) {
182
+ hmrBase = join(hmrBase, options.path);
183
+ }
184
+ if (hmrBase !== "/") {
185
+ hmrPort = normalize(`${hmrPort}${hmrBase}`);
186
+ }
187
+ 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()));
188
+ function serializeDefine(define) {
189
+ let res = `{`;
190
+ for (const key in define) {
191
+ const val = define[key];
192
+ res += `${JSON.stringify(key)}: ${typeof val === "string" ? `(${val})` : JSON.stringify(val)}, `;
374
193
  }
375
- };
376
- };
377
-
378
- /******************************************************************************
379
- Copyright (c) Microsoft Corporation.
380
-
381
- Permission to use, copy, modify, and/or distribute this software for any
382
- purpose with or without fee is hereby granted.
383
-
384
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
385
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
386
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
387
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
388
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
389
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
390
- PERFORMANCE OF THIS SOFTWARE.
391
- ***************************************************************************** */
392
- /* global Reflect, Promise */
393
-
394
- var extendStatics = function(d, b) {
395
- extendStatics = Object.setPrototypeOf ||
396
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
397
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
398
- return extendStatics(d, b);
399
- };
400
-
401
- function __extends(d, b) {
402
- if (typeof b !== "function" && b !== null)
403
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
404
- extendStatics(d, b);
405
- function __() { this.constructor = d; }
406
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
407
- }
408
-
409
- function __awaiter(thisArg, _arguments, P, generator) {
410
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
411
- return new (P || (P = Promise))(function (resolve, reject) {
412
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
413
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
414
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
415
- step((generator = generator.apply(thisArg, _arguments || [])).next());
416
- });
417
- }
418
-
419
- function __generator(thisArg, body) {
420
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
421
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
422
- function verb(n) { return function (v) { return step([n, v]); }; }
423
- function step(op) {
424
- if (f) throw new TypeError("Generator is already executing.");
425
- while (_) try {
426
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
427
- if (y = 0, t) op = [op[0] & 2, t.value];
428
- switch (op[0]) {
429
- case 0: case 1: t = op; break;
430
- case 4: _.label++; return { value: op[1], done: false };
431
- case 5: _.label++; y = op[1]; op = [0]; continue;
432
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
433
- default:
434
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
435
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
436
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
437
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
438
- if (t[2]) _.ops.pop();
439
- _.trys.pop(); continue;
440
- }
441
- op = body.call(thisArg, _);
442
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
443
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
444
- }
445
- }
446
-
447
- function __values(o) {
448
- var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
449
- if (m) return m.call(o);
450
- if (o && typeof o.length === "number") return {
451
- next: function () {
452
- if (o && i >= o.length) o = void 0;
453
- return { value: o && o[i++], done: !o };
454
- }
455
- };
456
- throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
457
- }
458
-
459
- function __read(o, n) {
460
- var m = typeof Symbol === "function" && o[Symbol.iterator];
461
- if (!m) return o;
462
- var i = m.call(o), r, ar = [], e;
463
- try {
464
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
465
- }
466
- catch (error) { e = { error: error }; }
467
- finally {
468
- try {
469
- if (r && !r.done && (m = i["return"])) m.call(i);
470
- }
471
- finally { if (e) throw e.error; }
472
- }
473
- return ar;
474
- }
475
-
476
- function __spreadArray(to, from, pack) {
477
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
478
- if (ar || !(i in from)) {
479
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
480
- ar[i] = from[i];
481
- }
482
- }
483
- return to.concat(ar || Array.prototype.slice.call(from));
484
- }
485
-
486
- function __await(v) {
487
- return this instanceof __await ? (this.v = v, this) : new __await(v);
488
- }
489
-
490
- function __asyncGenerator(thisArg, _arguments, generator) {
491
- if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
492
- var g = generator.apply(thisArg, _arguments || []), i, q = [];
493
- return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
494
- function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
495
- function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
496
- function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
497
- function fulfill(value) { resume("next", value); }
498
- function reject(value) { resume("throw", value); }
499
- function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
500
- }
501
-
502
- function __asyncValues(o) {
503
- if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
504
- var m = o[Symbol.asyncIterator], i;
505
- return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
506
- function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
507
- function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
508
- }
509
-
510
- function isFunction(value) {
511
- return typeof value === 'function';
194
+ return res + `}`;
195
+ }
512
196
  }
513
197
 
514
- function createErrorClass(createImpl) {
515
- var _super = function (instance) {
516
- Error.call(instance);
517
- instance.stack = new Error().stack;
518
- };
519
- var ctorFunc = createImpl(_super);
520
- ctorFunc.prototype = Object.create(Error.prototype);
521
- ctorFunc.prototype.constructor = ctorFunc;
522
- return ctorFunc;
198
+ class RxMap extends Map {
199
+ static isChangeType = {
200
+ clear: (x) => x.type === "clear",
201
+ delete: (x) => x.type === "delete",
202
+ set: (x) => x.type === "set"
203
+ };
204
+ change$;
205
+ constructor(iterable) {
206
+ super(iterable);
207
+ const change$ = new rxjs.Subject();
208
+ this.change$ = change$.asObservable();
209
+ const changeMethodKeys = ["clear", "set", "delete"];
210
+ for (const type of changeMethodKeys) {
211
+ const method = this[type];
212
+ this[type] = function(...args) {
213
+ const result = method.call(this, ...args);
214
+ change$.next({ type, key: args[0], value: args[1], map: this });
215
+ return result;
216
+ }.bind(this);
217
+ }
218
+ }
523
219
  }
524
220
 
525
- var UnsubscriptionError = createErrorClass(function (_super) {
526
- return function UnsubscriptionErrorImpl(errors) {
527
- _super(this);
528
- this.message = errors
529
- ? errors.length + " errors occurred during unsubscription:\n" + errors.map(function (err, i) { return i + 1 + ") " + err.toString(); }).join('\n ')
530
- : '';
531
- this.name = 'UnsubscriptionError';
532
- this.errors = errors;
533
- };
534
- });
221
+ const outputFiles = new RxMap();
535
222
 
536
- function arrRemove(arr, item) {
537
- if (arr) {
538
- var index = arr.indexOf(item);
539
- 0 <= index && arr.splice(index, 1);
540
- }
223
+ _debug("file-writer").extend("utilities");
224
+ function prefix$1(prefix2, text) {
225
+ return text.startsWith(prefix2) ? text : prefix2 + text;
541
226
  }
542
-
543
- var Subscription = (function () {
544
- function Subscription(initialTeardown) {
545
- this.initialTeardown = initialTeardown;
546
- this.closed = false;
547
- this._parentage = null;
548
- this._finalizers = null;
549
- }
550
- Subscription.prototype.unsubscribe = function () {
551
- var e_1, _a, e_2, _b;
552
- var errors;
553
- if (!this.closed) {
554
- this.closed = true;
555
- var _parentage = this._parentage;
556
- if (_parentage) {
557
- this._parentage = null;
558
- if (Array.isArray(_parentage)) {
559
- try {
560
- for (var _parentage_1 = __values(_parentage), _parentage_1_1 = _parentage_1.next(); !_parentage_1_1.done; _parentage_1_1 = _parentage_1.next()) {
561
- var parent_1 = _parentage_1_1.value;
562
- parent_1.remove(this);
563
- }
564
- }
565
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
566
- finally {
567
- try {
568
- if (_parentage_1_1 && !_parentage_1_1.done && (_a = _parentage_1.return)) _a.call(_parentage_1);
569
- }
570
- finally { if (e_1) throw e_1.error; }
571
- }
572
- }
573
- else {
574
- _parentage.remove(this);
575
- }
576
- }
577
- var initialFinalizer = this.initialTeardown;
578
- if (isFunction(initialFinalizer)) {
579
- try {
580
- initialFinalizer();
581
- }
582
- catch (e) {
583
- errors = e instanceof UnsubscriptionError ? e.errors : [e];
584
- }
585
- }
586
- var _finalizers = this._finalizers;
587
- if (_finalizers) {
588
- this._finalizers = null;
589
- try {
590
- for (var _finalizers_1 = __values(_finalizers), _finalizers_1_1 = _finalizers_1.next(); !_finalizers_1_1.done; _finalizers_1_1 = _finalizers_1.next()) {
591
- var finalizer = _finalizers_1_1.value;
592
- try {
593
- execFinalizer(finalizer);
594
- }
595
- catch (err) {
596
- errors = errors !== null && errors !== void 0 ? errors : [];
597
- if (err instanceof UnsubscriptionError) {
598
- errors = __spreadArray(__spreadArray([], __read(errors)), __read(err.errors));
599
- }
600
- else {
601
- errors.push(err);
602
- }
603
- }
604
- }
605
- }
606
- catch (e_2_1) { e_2 = { error: e_2_1 }; }
607
- finally {
608
- try {
609
- if (_finalizers_1_1 && !_finalizers_1_1.done && (_b = _finalizers_1.return)) _b.call(_finalizers_1);
610
- }
611
- finally { if (e_2) throw e_2.error; }
612
- }
613
- }
614
- if (errors) {
615
- throw new UnsubscriptionError(errors);
616
- }
617
- }
618
- };
619
- Subscription.prototype.add = function (teardown) {
620
- var _a;
621
- if (teardown && teardown !== this) {
622
- if (this.closed) {
623
- execFinalizer(teardown);
624
- }
625
- else {
626
- if (teardown instanceof Subscription) {
627
- if (teardown.closed || teardown._hasParent(this)) {
628
- return;
629
- }
630
- teardown._addParent(this);
631
- }
632
- (this._finalizers = (_a = this._finalizers) !== null && _a !== void 0 ? _a : []).push(teardown);
633
- }
634
- }
635
- };
636
- Subscription.prototype._hasParent = function (parent) {
637
- var _parentage = this._parentage;
638
- return _parentage === parent || (Array.isArray(_parentage) && _parentage.includes(parent));
639
- };
640
- Subscription.prototype._addParent = function (parent) {
641
- var _parentage = this._parentage;
642
- this._parentage = Array.isArray(_parentage) ? (_parentage.push(parent), _parentage) : _parentage ? [_parentage, parent] : parent;
643
- };
644
- Subscription.prototype._removeParent = function (parent) {
645
- var _parentage = this._parentage;
646
- if (_parentage === parent) {
647
- this._parentage = null;
648
- }
649
- else if (Array.isArray(_parentage)) {
650
- arrRemove(_parentage, parent);
651
- }
652
- };
653
- Subscription.prototype.remove = function (teardown) {
654
- var _finalizers = this._finalizers;
655
- _finalizers && arrRemove(_finalizers, teardown);
656
- if (teardown instanceof Subscription) {
657
- teardown._removeParent(this);
658
- }
659
- };
660
- Subscription.EMPTY = (function () {
661
- var empty = new Subscription();
662
- empty.closed = true;
663
- return empty;
664
- })();
665
- return Subscription;
666
- }());
667
- var EMPTY_SUBSCRIPTION = Subscription.EMPTY;
668
- function isSubscription(value) {
669
- return (value instanceof Subscription ||
670
- (value && 'closed' in value && isFunction(value.remove) && isFunction(value.add) && isFunction(value.unsubscribe)));
227
+ function strip(prefix2, text) {
228
+ return text?.startsWith(prefix2) ? text?.slice(prefix2.length) : text;
671
229
  }
672
- function execFinalizer(finalizer) {
673
- if (isFunction(finalizer)) {
674
- finalizer();
675
- }
676
- else {
677
- finalizer.unsubscribe();
678
- }
230
+ function formatFileData(script) {
231
+ script.id = prefix$1("/", script.id);
232
+ if (script.fileName)
233
+ script.fileName = strip("/", script.fileName);
234
+ if (script.loaderName)
235
+ script.loaderName = strip("/", script.loaderName);
236
+ return script;
237
+ }
238
+ function getFileName({ type, id }) {
239
+ let fileName = id.replace(/t=\d+&/, "").replace(/^\//, "").replace(/\?/g, "__").replace(/&/g, "_").replace(/=/g, "--");
240
+ if (fileName.includes("node_modules/")) {
241
+ fileName = `vendor/${fileName.split("node_modules/").pop().replace(/\//g, "-")}`;
242
+ } else if (fileName.startsWith("@")) {
243
+ fileName = `vendor/${fileName.slice("@".length).replace(/\//g, "-")}`;
244
+ } else if (fileName.startsWith(".vite/deps/")) {
245
+ fileName = `vendor/${fileName.slice(".vite/deps/".length)}`;
246
+ }
247
+ switch (type) {
248
+ case "iife":
249
+ return `${fileName}.iife.js`;
250
+ case "loader":
251
+ return `${fileName}-loader.js`;
252
+ case "module":
253
+ return `${fileName}.js`;
254
+ case "asset":
255
+ return fileName;
256
+ default:
257
+ throw new Error(
258
+ `Unexpected script type "${type}" for "${JSON.stringify({
259
+ type,
260
+ id
261
+ })}"`
262
+ );
263
+ }
264
+ }
265
+ function getOutputPath(server, fileName) {
266
+ const {
267
+ root,
268
+ build: { outDir }
269
+ } = server.config;
270
+ const target = isAbsolute(outDir) ? join(outDir, fileName) : join(root, outDir, fileName);
271
+ return target;
272
+ }
273
+ function getViteUrl({ type, id }) {
274
+ if (type === "asset") {
275
+ throw new Error(`File type "${type}" not implemented.`);
276
+ } else if (type === "iife") {
277
+ throw new Error(`File type "${type}" not implemented.`);
278
+ } else if (type === "loader") {
279
+ throw new Error("Vite does not transform loader files.");
280
+ } else if (type === "module") {
281
+ if (id.startsWith("/@id/"))
282
+ return id.slice("/@id/".length).replace("__x00__", "\0");
283
+ return prefix$1("/", id);
284
+ } else {
285
+ throw new Error(`Invalid file type: "${type}"`);
286
+ }
287
+ }
288
+ async function fileReady(script) {
289
+ const fileName = getFileName(script);
290
+ const file = outputFiles.get(fileName);
291
+ if (!file)
292
+ throw new Error("unknown script type and id");
293
+ const { deps } = await file.file;
294
+ await Promise.all(deps.map(fileReady));
679
295
  }
680
296
 
681
- var config = {
682
- onUnhandledError: null,
683
- onStoppedNotification: null,
684
- Promise: undefined,
685
- useDeprecatedSynchronousErrorHandling: false,
686
- useDeprecatedNextContext: false,
687
- };
297
+ const viteClientId = "/@vite/client";
298
+ const customElementsId = "/@webcomponents/custom-elements";
299
+ const contentHmrPortId = "/@crx/client-port";
300
+ const manifestId = "/@crx/manifest";
301
+ const preambleId = "/@crx/client-preamble";
302
+ const stubId = "/@crx/stub";
303
+ const workerClientId = "/@crx/client-worker";
688
304
 
689
- var timeoutProvider = {
690
- setTimeout: function (handler, timeout) {
691
- var args = [];
692
- for (var _i = 2; _i < arguments.length; _i++) {
693
- args[_i - 2] = arguments[_i];
694
- }
695
- var delegate = timeoutProvider.delegate;
696
- if (delegate === null || delegate === void 0 ? void 0 : delegate.setTimeout) {
697
- return delegate.setTimeout.apply(delegate, __spreadArray([handler, timeout], __read(args)));
305
+ const pluginBackground = () => {
306
+ let config;
307
+ return [
308
+ {
309
+ name: "crx:background-client",
310
+ apply: "serve",
311
+ resolveId(source) {
312
+ if (source === `/${workerClientId}`)
313
+ return workerClientId;
314
+ },
315
+ load(id) {
316
+ if (id === workerClientId) {
317
+ const base = `http://localhost:${config.server.port}/`;
318
+ return defineClientValues(
319
+ workerHmrClient.replace("__BASE__", JSON.stringify(base)),
320
+ config
321
+ );
698
322
  }
699
- return setTimeout.apply(void 0, __spreadArray([handler, timeout], __read(args)));
700
- },
701
- clearTimeout: function (handle) {
702
- var delegate = timeoutProvider.delegate;
703
- return ((delegate === null || delegate === void 0 ? void 0 : delegate.clearTimeout) || clearTimeout)(handle);
323
+ }
704
324
  },
705
- delegate: undefined,
325
+ {
326
+ name: "crx:background-loader-file",
327
+ enforce: "post",
328
+ configResolved(_config) {
329
+ config = _config;
330
+ },
331
+ renderCrxManifest(manifest) {
332
+ const worker = manifest.background?.service_worker;
333
+ let loader;
334
+ if (config.command === "serve") {
335
+ const port = config.server.port?.toString();
336
+ if (typeof port === "undefined")
337
+ throw new Error("server port is undefined in watch mode");
338
+ loader = `import 'http:/localhost:${port}/@vite/env';
339
+ `;
340
+ loader += `import 'http://localhost:${port}${workerClientId}';
341
+ `;
342
+ if (worker)
343
+ loader += `import 'http://localhost:${port}/${worker}';
344
+ `;
345
+ } else if (worker) {
346
+ loader = `import './${worker}';
347
+ `;
348
+ } else {
349
+ return null;
350
+ }
351
+ const refId = this.emitFile({
352
+ type: "asset",
353
+ fileName: getFileName({ type: "loader", id: "service-worker" }),
354
+ source: loader
355
+ });
356
+ manifest.background = {
357
+ service_worker: this.getFileName(refId),
358
+ type: "module"
359
+ };
360
+ return manifest;
361
+ }
362
+ }
363
+ ];
706
364
  };
707
365
 
708
- function reportUnhandledError(err) {
709
- timeoutProvider.setTimeout(function () {
710
- {
711
- throw err;
712
- }
713
- });
714
- }
366
+ 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";
715
367
 
716
- function noop() { }
368
+ 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";
717
369
 
718
- var COMPLETE_NOTIFICATION = (function () { return createNotification('C', undefined, undefined); })();
719
- function errorNotification(error) {
720
- return createNotification('E', undefined, error);
721
- }
722
- function nextNotification(value) {
723
- return createNotification('N', value, undefined);
724
- }
725
- function createNotification(kind, value, error) {
726
- return {
727
- kind: kind,
728
- value: value,
729
- error: error,
730
- };
731
- }
370
+ 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";
732
371
 
733
- var context = null;
734
- function errorContext(cb) {
735
- if (config.useDeprecatedSynchronousErrorHandling) {
736
- var isRoot = !context;
737
- if (isRoot) {
738
- context = { errorThrown: false, error: null };
739
- }
740
- cb();
741
- if (isRoot) {
742
- var _a = context, errorThrown = _a.errorThrown, error = _a.error;
743
- context = null;
744
- if (errorThrown) {
745
- throw error;
746
- }
747
- }
748
- }
749
- else {
750
- cb();
372
+ const contentScripts = new RxMap();
373
+ contentScripts.change$.pipe(rxjs.filter(RxMap.isChangeType.set)).subscribe(({ map, value }) => {
374
+ const keyNames = [
375
+ "refId",
376
+ "id",
377
+ "fileName",
378
+ "loaderName",
379
+ "resolvedId",
380
+ "scriptId"
381
+ ];
382
+ for (const keyName of keyNames) {
383
+ const key = value[keyName];
384
+ if (typeof key === "undefined" || map.has(key)) {
385
+ continue;
386
+ } else {
387
+ map.set(key, value);
751
388
  }
389
+ }
390
+ });
391
+ function hashScriptId(script) {
392
+ return hash(`${script.type}&${script.id}`);
752
393
  }
753
-
754
- var Subscriber = (function (_super) {
755
- __extends(Subscriber, _super);
756
- function Subscriber(destination) {
757
- var _this = _super.call(this) || this;
758
- _this.isStopped = false;
759
- if (destination) {
760
- _this.destination = destination;
761
- if (isSubscription(destination)) {
762
- destination.add(_this);
763
- }
764
- }
765
- else {
766
- _this.destination = EMPTY_OBSERVER;
767
- }
768
- return _this;
769
- }
770
- Subscriber.create = function (next, error, complete) {
771
- return new SafeSubscriber(next, error, complete);
772
- };
773
- Subscriber.prototype.next = function (value) {
774
- if (this.isStopped) {
775
- handleStoppedNotification(nextNotification(value), this);
776
- }
777
- else {
778
- this._next(value);
779
- }
780
- };
781
- Subscriber.prototype.error = function (err) {
782
- if (this.isStopped) {
783
- handleStoppedNotification(errorNotification(err), this);
784
- }
785
- else {
786
- this.isStopped = true;
787
- this._error(err);
788
- }
789
- };
790
- Subscriber.prototype.complete = function () {
791
- if (this.isStopped) {
792
- handleStoppedNotification(COMPLETE_NOTIFICATION, this);
793
- }
794
- else {
795
- this.isStopped = true;
796
- this._complete();
797
- }
798
- };
799
- Subscriber.prototype.unsubscribe = function () {
800
- if (!this.closed) {
801
- this.isStopped = true;
802
- _super.prototype.unsubscribe.call(this);
803
- this.destination = null;
804
- }
805
- };
806
- Subscriber.prototype._next = function (value) {
807
- this.destination.next(value);
808
- };
809
- Subscriber.prototype._error = function (err) {
810
- try {
811
- this.destination.error(err);
812
- }
813
- finally {
814
- this.unsubscribe();
815
- }
816
- };
817
- Subscriber.prototype._complete = function () {
818
- try {
819
- this.destination.complete();
820
- }
821
- finally {
822
- this.unsubscribe();
823
- }
824
- };
825
- return Subscriber;
826
- }(Subscription));
827
- var _bind = Function.prototype.bind;
828
- function bind(fn, thisArg) {
829
- return _bind.call(fn, thisArg);
830
- }
831
- var ConsumerObserver = (function () {
832
- function ConsumerObserver(partialObserver) {
833
- this.partialObserver = partialObserver;
834
- }
835
- ConsumerObserver.prototype.next = function (value) {
836
- var partialObserver = this.partialObserver;
837
- if (partialObserver.next) {
838
- try {
839
- partialObserver.next(value);
840
- }
841
- catch (error) {
842
- handleUnhandledError(error);
843
- }
844
- }
845
- };
846
- ConsumerObserver.prototype.error = function (err) {
847
- var partialObserver = this.partialObserver;
848
- if (partialObserver.error) {
849
- try {
850
- partialObserver.error(err);
851
- }
852
- catch (error) {
853
- handleUnhandledError(error);
854
- }
855
- }
856
- else {
857
- handleUnhandledError(err);
858
- }
859
- };
860
- ConsumerObserver.prototype.complete = function () {
861
- var partialObserver = this.partialObserver;
862
- if (partialObserver.complete) {
863
- try {
864
- partialObserver.complete();
865
- }
866
- catch (error) {
867
- handleUnhandledError(error);
868
- }
869
- }
870
- };
871
- return ConsumerObserver;
872
- }());
873
- var SafeSubscriber = (function (_super) {
874
- __extends(SafeSubscriber, _super);
875
- function SafeSubscriber(observerOrNext, error, complete) {
876
- var _this = _super.call(this) || this;
877
- var partialObserver;
878
- if (isFunction(observerOrNext) || !observerOrNext) {
879
- partialObserver = {
880
- next: observerOrNext !== null && observerOrNext !== void 0 ? observerOrNext : undefined,
881
- error: error !== null && error !== void 0 ? error : undefined,
882
- complete: complete !== null && complete !== void 0 ? complete : undefined,
883
- };
884
- }
885
- else {
886
- var context_1;
887
- if (_this && config.useDeprecatedNextContext) {
888
- context_1 = Object.create(observerOrNext);
889
- context_1.unsubscribe = function () { return _this.unsubscribe(); };
890
- partialObserver = {
891
- next: observerOrNext.next && bind(observerOrNext.next, context_1),
892
- error: observerOrNext.error && bind(observerOrNext.error, context_1),
893
- complete: observerOrNext.complete && bind(observerOrNext.complete, context_1),
894
- };
895
- }
896
- else {
897
- partialObserver = observerOrNext;
898
- }
899
- }
900
- _this.destination = new ConsumerObserver(partialObserver);
901
- return _this;
902
- }
903
- return SafeSubscriber;
904
- }(Subscriber));
905
- function handleUnhandledError(error) {
906
- {
907
- reportUnhandledError(error);
908
- }
909
- }
910
- function defaultErrorHandler(err) {
911
- throw err;
912
- }
913
- function handleStoppedNotification(notification, subscriber) {
914
- var onStoppedNotification = config.onStoppedNotification;
915
- onStoppedNotification && timeoutProvider.setTimeout(function () { return onStoppedNotification(notification, subscriber); });
916
- }
917
- var EMPTY_OBSERVER = {
918
- closed: true,
919
- next: noop,
920
- error: defaultErrorHandler,
921
- complete: noop,
922
- };
923
-
924
- var observable = (function () { return (typeof Symbol === 'function' && Symbol.observable) || '@@observable'; })();
925
-
926
- function identity(x) {
927
- return x;
928
- }
929
-
930
- function pipeFromArray(fns) {
931
- if (fns.length === 0) {
932
- return identity;
933
- }
934
- if (fns.length === 1) {
935
- return fns[0];
936
- }
937
- return function piped(input) {
938
- return fns.reduce(function (prev, fn) { return fn(prev); }, input);
939
- };
940
- }
941
-
942
- var Observable = (function () {
943
- function Observable(subscribe) {
944
- if (subscribe) {
945
- this._subscribe = subscribe;
946
- }
947
- }
948
- Observable.prototype.lift = function (operator) {
949
- var observable = new Observable();
950
- observable.source = this;
951
- observable.operator = operator;
952
- return observable;
953
- };
954
- Observable.prototype.subscribe = function (observerOrNext, error, complete) {
955
- var _this = this;
956
- var subscriber = isSubscriber(observerOrNext) ? observerOrNext : new SafeSubscriber(observerOrNext, error, complete);
957
- errorContext(function () {
958
- var _a = _this, operator = _a.operator, source = _a.source;
959
- subscriber.add(operator
960
- ?
961
- operator.call(subscriber, source)
962
- : source
963
- ?
964
- _this._subscribe(subscriber)
965
- :
966
- _this._trySubscribe(subscriber));
967
- });
968
- return subscriber;
969
- };
970
- Observable.prototype._trySubscribe = function (sink) {
971
- try {
972
- return this._subscribe(sink);
973
- }
974
- catch (err) {
975
- sink.error(err);
976
- }
977
- };
978
- Observable.prototype.forEach = function (next, promiseCtor) {
979
- var _this = this;
980
- promiseCtor = getPromiseCtor(promiseCtor);
981
- return new promiseCtor(function (resolve, reject) {
982
- var subscriber = new SafeSubscriber({
983
- next: function (value) {
984
- try {
985
- next(value);
986
- }
987
- catch (err) {
988
- reject(err);
989
- subscriber.unsubscribe();
990
- }
991
- },
992
- error: reject,
993
- complete: resolve,
994
- });
995
- _this.subscribe(subscriber);
996
- });
997
- };
998
- Observable.prototype._subscribe = function (subscriber) {
999
- var _a;
1000
- return (_a = this.source) === null || _a === void 0 ? void 0 : _a.subscribe(subscriber);
1001
- };
1002
- Observable.prototype[observable] = function () {
1003
- return this;
1004
- };
1005
- Observable.prototype.pipe = function () {
1006
- var operations = [];
1007
- for (var _i = 0; _i < arguments.length; _i++) {
1008
- operations[_i] = arguments[_i];
1009
- }
1010
- return pipeFromArray(operations)(this);
1011
- };
1012
- Observable.prototype.toPromise = function (promiseCtor) {
1013
- var _this = this;
1014
- promiseCtor = getPromiseCtor(promiseCtor);
1015
- return new promiseCtor(function (resolve, reject) {
1016
- var value;
1017
- _this.subscribe(function (x) { return (value = x); }, function (err) { return reject(err); }, function () { return resolve(value); });
1018
- });
1019
- };
1020
- Observable.create = function (subscribe) {
1021
- return new Observable(subscribe);
1022
- };
1023
- return Observable;
1024
- }());
1025
- function getPromiseCtor(promiseCtor) {
1026
- var _a;
1027
- return (_a = promiseCtor !== null && promiseCtor !== void 0 ? promiseCtor : config.Promise) !== null && _a !== void 0 ? _a : Promise;
1028
- }
1029
- function isObserver(value) {
1030
- return value && isFunction(value.next) && isFunction(value.error) && isFunction(value.complete);
1031
- }
1032
- function isSubscriber(value) {
1033
- return (value && value instanceof Subscriber) || (isObserver(value) && isSubscription(value));
1034
- }
1035
-
1036
- function hasLift(source) {
1037
- return isFunction(source === null || source === void 0 ? void 0 : source.lift);
1038
- }
1039
- function operate(init) {
1040
- return function (source) {
1041
- if (hasLift(source)) {
1042
- return source.lift(function (liftedSource) {
1043
- try {
1044
- return init(liftedSource, this);
1045
- }
1046
- catch (err) {
1047
- this.error(err);
1048
- }
1049
- });
1050
- }
1051
- throw new TypeError('Unable to lift unknown Observable type');
1052
- };
1053
- }
1054
-
1055
- function createOperatorSubscriber(destination, onNext, onComplete, onError, onFinalize) {
1056
- return new OperatorSubscriber(destination, onNext, onComplete, onError, onFinalize);
1057
- }
1058
- var OperatorSubscriber = (function (_super) {
1059
- __extends(OperatorSubscriber, _super);
1060
- function OperatorSubscriber(destination, onNext, onComplete, onError, onFinalize, shouldUnsubscribe) {
1061
- var _this = _super.call(this, destination) || this;
1062
- _this.onFinalize = onFinalize;
1063
- _this.shouldUnsubscribe = shouldUnsubscribe;
1064
- _this._next = onNext
1065
- ? function (value) {
1066
- try {
1067
- onNext(value);
1068
- }
1069
- catch (err) {
1070
- destination.error(err);
1071
- }
1072
- }
1073
- : _super.prototype._next;
1074
- _this._error = onError
1075
- ? function (err) {
1076
- try {
1077
- onError(err);
1078
- }
1079
- catch (err) {
1080
- destination.error(err);
1081
- }
1082
- finally {
1083
- this.unsubscribe();
1084
- }
1085
- }
1086
- : _super.prototype._error;
1087
- _this._complete = onComplete
1088
- ? function () {
1089
- try {
1090
- onComplete();
1091
- }
1092
- catch (err) {
1093
- destination.error(err);
1094
- }
1095
- finally {
1096
- this.unsubscribe();
1097
- }
1098
- }
1099
- : _super.prototype._complete;
1100
- return _this;
1101
- }
1102
- OperatorSubscriber.prototype.unsubscribe = function () {
1103
- var _a;
1104
- if (!this.shouldUnsubscribe || this.shouldUnsubscribe()) {
1105
- var closed_1 = this.closed;
1106
- _super.prototype.unsubscribe.call(this);
1107
- !closed_1 && ((_a = this.onFinalize) === null || _a === void 0 ? void 0 : _a.call(this));
1108
- }
1109
- };
1110
- return OperatorSubscriber;
1111
- }(Subscriber));
1112
-
1113
- var ObjectUnsubscribedError = createErrorClass(function (_super) {
1114
- return function ObjectUnsubscribedErrorImpl() {
1115
- _super(this);
1116
- this.name = 'ObjectUnsubscribedError';
1117
- this.message = 'object unsubscribed';
1118
- };
1119
- });
1120
-
1121
- var Subject = (function (_super) {
1122
- __extends(Subject, _super);
1123
- function Subject() {
1124
- var _this = _super.call(this) || this;
1125
- _this.closed = false;
1126
- _this.currentObservers = null;
1127
- _this.observers = [];
1128
- _this.isStopped = false;
1129
- _this.hasError = false;
1130
- _this.thrownError = null;
1131
- return _this;
1132
- }
1133
- Subject.prototype.lift = function (operator) {
1134
- var subject = new AnonymousSubject(this, this);
1135
- subject.operator = operator;
1136
- return subject;
1137
- };
1138
- Subject.prototype._throwIfClosed = function () {
1139
- if (this.closed) {
1140
- throw new ObjectUnsubscribedError();
1141
- }
1142
- };
1143
- Subject.prototype.next = function (value) {
1144
- var _this = this;
1145
- errorContext(function () {
1146
- var e_1, _a;
1147
- _this._throwIfClosed();
1148
- if (!_this.isStopped) {
1149
- if (!_this.currentObservers) {
1150
- _this.currentObservers = Array.from(_this.observers);
1151
- }
1152
- try {
1153
- for (var _b = __values(_this.currentObservers), _c = _b.next(); !_c.done; _c = _b.next()) {
1154
- var observer = _c.value;
1155
- observer.next(value);
1156
- }
1157
- }
1158
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
1159
- finally {
1160
- try {
1161
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
1162
- }
1163
- finally { if (e_1) throw e_1.error; }
1164
- }
1165
- }
1166
- });
1167
- };
1168
- Subject.prototype.error = function (err) {
1169
- var _this = this;
1170
- errorContext(function () {
1171
- _this._throwIfClosed();
1172
- if (!_this.isStopped) {
1173
- _this.hasError = _this.isStopped = true;
1174
- _this.thrownError = err;
1175
- var observers = _this.observers;
1176
- while (observers.length) {
1177
- observers.shift().error(err);
1178
- }
1179
- }
1180
- });
1181
- };
1182
- Subject.prototype.complete = function () {
1183
- var _this = this;
1184
- errorContext(function () {
1185
- _this._throwIfClosed();
1186
- if (!_this.isStopped) {
1187
- _this.isStopped = true;
1188
- var observers = _this.observers;
1189
- while (observers.length) {
1190
- observers.shift().complete();
1191
- }
1192
- }
1193
- });
1194
- };
1195
- Subject.prototype.unsubscribe = function () {
1196
- this.isStopped = this.closed = true;
1197
- this.observers = this.currentObservers = null;
1198
- };
1199
- Object.defineProperty(Subject.prototype, "observed", {
1200
- get: function () {
1201
- var _a;
1202
- return ((_a = this.observers) === null || _a === void 0 ? void 0 : _a.length) > 0;
1203
- },
1204
- enumerable: false,
1205
- configurable: true
1206
- });
1207
- Subject.prototype._trySubscribe = function (subscriber) {
1208
- this._throwIfClosed();
1209
- return _super.prototype._trySubscribe.call(this, subscriber);
1210
- };
1211
- Subject.prototype._subscribe = function (subscriber) {
1212
- this._throwIfClosed();
1213
- this._checkFinalizedStatuses(subscriber);
1214
- return this._innerSubscribe(subscriber);
1215
- };
1216
- Subject.prototype._innerSubscribe = function (subscriber) {
1217
- var _this = this;
1218
- var _a = this, hasError = _a.hasError, isStopped = _a.isStopped, observers = _a.observers;
1219
- if (hasError || isStopped) {
1220
- return EMPTY_SUBSCRIPTION;
1221
- }
1222
- this.currentObservers = null;
1223
- observers.push(subscriber);
1224
- return new Subscription(function () {
1225
- _this.currentObservers = null;
1226
- arrRemove(observers, subscriber);
1227
- });
1228
- };
1229
- Subject.prototype._checkFinalizedStatuses = function (subscriber) {
1230
- var _a = this, hasError = _a.hasError, thrownError = _a.thrownError, isStopped = _a.isStopped;
1231
- if (hasError) {
1232
- subscriber.error(thrownError);
1233
- }
1234
- else if (isStopped) {
1235
- subscriber.complete();
1236
- }
1237
- };
1238
- Subject.prototype.asObservable = function () {
1239
- var observable = new Observable();
1240
- observable.source = this;
1241
- return observable;
1242
- };
1243
- Subject.create = function (destination, source) {
1244
- return new AnonymousSubject(destination, source);
1245
- };
1246
- return Subject;
1247
- }(Observable));
1248
- var AnonymousSubject = (function (_super) {
1249
- __extends(AnonymousSubject, _super);
1250
- function AnonymousSubject(destination, source) {
1251
- var _this = _super.call(this) || this;
1252
- _this.destination = destination;
1253
- _this.source = source;
1254
- return _this;
1255
- }
1256
- AnonymousSubject.prototype.next = function (value) {
1257
- var _a, _b;
1258
- (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.next) === null || _b === void 0 ? void 0 : _b.call(_a, value);
1259
- };
1260
- AnonymousSubject.prototype.error = function (err) {
1261
- var _a, _b;
1262
- (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.error) === null || _b === void 0 ? void 0 : _b.call(_a, err);
1263
- };
1264
- AnonymousSubject.prototype.complete = function () {
1265
- var _a, _b;
1266
- (_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.complete) === null || _b === void 0 ? void 0 : _b.call(_a);
1267
- };
1268
- AnonymousSubject.prototype._subscribe = function (subscriber) {
1269
- var _a, _b;
1270
- return (_b = (_a = this.source) === null || _a === void 0 ? void 0 : _a.subscribe(subscriber)) !== null && _b !== void 0 ? _b : EMPTY_SUBSCRIPTION;
1271
- };
1272
- return AnonymousSubject;
1273
- }(Subject));
1274
-
1275
- var BehaviorSubject = (function (_super) {
1276
- __extends(BehaviorSubject, _super);
1277
- function BehaviorSubject(_value) {
1278
- var _this = _super.call(this) || this;
1279
- _this._value = _value;
1280
- return _this;
1281
- }
1282
- Object.defineProperty(BehaviorSubject.prototype, "value", {
1283
- get: function () {
1284
- return this.getValue();
1285
- },
1286
- enumerable: false,
1287
- configurable: true
1288
- });
1289
- BehaviorSubject.prototype._subscribe = function (subscriber) {
1290
- var subscription = _super.prototype._subscribe.call(this, subscriber);
1291
- !subscription.closed && subscriber.next(this._value);
1292
- return subscription;
1293
- };
1294
- BehaviorSubject.prototype.getValue = function () {
1295
- var _a = this, hasError = _a.hasError, thrownError = _a.thrownError, _value = _a._value;
1296
- if (hasError) {
1297
- throw thrownError;
1298
- }
1299
- this._throwIfClosed();
1300
- return _value;
1301
- };
1302
- BehaviorSubject.prototype.next = function (value) {
1303
- _super.prototype.next.call(this, (this._value = value));
1304
- };
1305
- return BehaviorSubject;
1306
- }(Subject));
1307
-
1308
- var dateTimestampProvider = {
1309
- now: function () {
1310
- return (dateTimestampProvider.delegate || Date).now();
1311
- },
1312
- delegate: undefined,
1313
- };
1314
-
1315
- var Action = (function (_super) {
1316
- __extends(Action, _super);
1317
- function Action(scheduler, work) {
1318
- return _super.call(this) || this;
1319
- }
1320
- Action.prototype.schedule = function (state, delay) {
1321
- return this;
1322
- };
1323
- return Action;
1324
- }(Subscription));
1325
-
1326
- var intervalProvider = {
1327
- setInterval: function (handler, timeout) {
1328
- var args = [];
1329
- for (var _i = 2; _i < arguments.length; _i++) {
1330
- args[_i - 2] = arguments[_i];
1331
- }
1332
- var delegate = intervalProvider.delegate;
1333
- if (delegate === null || delegate === void 0 ? void 0 : delegate.setInterval) {
1334
- return delegate.setInterval.apply(delegate, __spreadArray([handler, timeout], __read(args)));
1335
- }
1336
- return setInterval.apply(void 0, __spreadArray([handler, timeout], __read(args)));
1337
- },
1338
- clearInterval: function (handle) {
1339
- var delegate = intervalProvider.delegate;
1340
- return ((delegate === null || delegate === void 0 ? void 0 : delegate.clearInterval) || clearInterval)(handle);
1341
- },
1342
- delegate: undefined,
1343
- };
1344
-
1345
- var AsyncAction = (function (_super) {
1346
- __extends(AsyncAction, _super);
1347
- function AsyncAction(scheduler, work) {
1348
- var _this = _super.call(this, scheduler, work) || this;
1349
- _this.scheduler = scheduler;
1350
- _this.work = work;
1351
- _this.pending = false;
1352
- return _this;
1353
- }
1354
- AsyncAction.prototype.schedule = function (state, delay) {
1355
- if (delay === void 0) { delay = 0; }
1356
- if (this.closed) {
1357
- return this;
1358
- }
1359
- this.state = state;
1360
- var id = this.id;
1361
- var scheduler = this.scheduler;
1362
- if (id != null) {
1363
- this.id = this.recycleAsyncId(scheduler, id, delay);
1364
- }
1365
- this.pending = true;
1366
- this.delay = delay;
1367
- this.id = this.id || this.requestAsyncId(scheduler, this.id, delay);
1368
- return this;
1369
- };
1370
- AsyncAction.prototype.requestAsyncId = function (scheduler, _id, delay) {
1371
- if (delay === void 0) { delay = 0; }
1372
- return intervalProvider.setInterval(scheduler.flush.bind(scheduler, this), delay);
1373
- };
1374
- AsyncAction.prototype.recycleAsyncId = function (_scheduler, id, delay) {
1375
- if (delay === void 0) { delay = 0; }
1376
- if (delay != null && this.delay === delay && this.pending === false) {
1377
- return id;
1378
- }
1379
- intervalProvider.clearInterval(id);
1380
- return undefined;
1381
- };
1382
- AsyncAction.prototype.execute = function (state, delay) {
1383
- if (this.closed) {
1384
- return new Error('executing a cancelled action');
1385
- }
1386
- this.pending = false;
1387
- var error = this._execute(state, delay);
1388
- if (error) {
1389
- return error;
1390
- }
1391
- else if (this.pending === false && this.id != null) {
1392
- this.id = this.recycleAsyncId(this.scheduler, this.id, null);
1393
- }
1394
- };
1395
- AsyncAction.prototype._execute = function (state, _delay) {
1396
- var errored = false;
1397
- var errorValue;
1398
- try {
1399
- this.work(state);
1400
- }
1401
- catch (e) {
1402
- errored = true;
1403
- errorValue = e ? e : new Error('Scheduled action threw falsy error');
1404
- }
1405
- if (errored) {
1406
- this.unsubscribe();
1407
- return errorValue;
1408
- }
1409
- };
1410
- AsyncAction.prototype.unsubscribe = function () {
1411
- if (!this.closed) {
1412
- var _a = this, id = _a.id, scheduler = _a.scheduler;
1413
- var actions = scheduler.actions;
1414
- this.work = this.state = this.scheduler = null;
1415
- this.pending = false;
1416
- arrRemove(actions, this);
1417
- if (id != null) {
1418
- this.id = this.recycleAsyncId(scheduler, id, null);
1419
- }
1420
- this.delay = null;
1421
- _super.prototype.unsubscribe.call(this);
1422
- }
1423
- };
1424
- return AsyncAction;
1425
- }(Action));
1426
-
1427
- var Scheduler = (function () {
1428
- function Scheduler(schedulerActionCtor, now) {
1429
- if (now === void 0) { now = Scheduler.now; }
1430
- this.schedulerActionCtor = schedulerActionCtor;
1431
- this.now = now;
1432
- }
1433
- Scheduler.prototype.schedule = function (work, delay, state) {
1434
- if (delay === void 0) { delay = 0; }
1435
- return new this.schedulerActionCtor(this, work).schedule(state, delay);
1436
- };
1437
- Scheduler.now = dateTimestampProvider.now;
1438
- return Scheduler;
1439
- }());
1440
-
1441
- var AsyncScheduler = (function (_super) {
1442
- __extends(AsyncScheduler, _super);
1443
- function AsyncScheduler(SchedulerAction, now) {
1444
- if (now === void 0) { now = Scheduler.now; }
1445
- var _this = _super.call(this, SchedulerAction, now) || this;
1446
- _this.actions = [];
1447
- _this._active = false;
1448
- _this._scheduled = undefined;
1449
- return _this;
1450
- }
1451
- AsyncScheduler.prototype.flush = function (action) {
1452
- var actions = this.actions;
1453
- if (this._active) {
1454
- actions.push(action);
1455
- return;
1456
- }
1457
- var error;
1458
- this._active = true;
1459
- do {
1460
- if ((error = action.execute(action.state, action.delay))) {
1461
- break;
1462
- }
1463
- } while ((action = actions.shift()));
1464
- this._active = false;
1465
- if (error) {
1466
- while ((action = actions.shift())) {
1467
- action.unsubscribe();
1468
- }
1469
- throw error;
1470
- }
1471
- };
1472
- return AsyncScheduler;
1473
- }(Scheduler));
1474
-
1475
- var asyncScheduler = new AsyncScheduler(AsyncAction);
1476
- var async = asyncScheduler;
1477
-
1478
- var EMPTY = new Observable(function (subscriber) { return subscriber.complete(); });
1479
-
1480
- function isScheduler(value) {
1481
- return value && isFunction(value.schedule);
1482
- }
1483
-
1484
- function last(arr) {
1485
- return arr[arr.length - 1];
1486
- }
1487
- function popResultSelector(args) {
1488
- return isFunction(last(args)) ? args.pop() : undefined;
1489
- }
1490
- function popScheduler(args) {
1491
- return isScheduler(last(args)) ? args.pop() : undefined;
1492
- }
1493
- function popNumber(args, defaultValue) {
1494
- return typeof last(args) === 'number' ? args.pop() : defaultValue;
1495
- }
1496
-
1497
- var isArrayLike = (function (x) { return x && typeof x.length === 'number' && typeof x !== 'function'; });
1498
-
1499
- function isPromise(value) {
1500
- return isFunction(value === null || value === void 0 ? void 0 : value.then);
1501
- }
1502
-
1503
- function isInteropObservable(input) {
1504
- return isFunction(input[observable]);
1505
- }
1506
-
1507
- function isAsyncIterable(obj) {
1508
- return Symbol.asyncIterator && isFunction(obj === null || obj === void 0 ? void 0 : obj[Symbol.asyncIterator]);
1509
- }
1510
-
1511
- function createInvalidObservableTypeError(input) {
1512
- return new TypeError("You provided " + (input !== null && typeof input === 'object' ? 'an invalid object' : "'" + input + "'") + " where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.");
1513
- }
1514
-
1515
- function getSymbolIterator() {
1516
- if (typeof Symbol !== 'function' || !Symbol.iterator) {
1517
- return '@@iterator';
1518
- }
1519
- return Symbol.iterator;
1520
- }
1521
- var iterator = getSymbolIterator();
1522
-
1523
- function isIterable(input) {
1524
- return isFunction(input === null || input === void 0 ? void 0 : input[iterator]);
1525
- }
1526
-
1527
- function readableStreamLikeToAsyncGenerator(readableStream) {
1528
- return __asyncGenerator(this, arguments, function readableStreamLikeToAsyncGenerator_1() {
1529
- var reader, _a, value, done;
1530
- return __generator(this, function (_b) {
1531
- switch (_b.label) {
1532
- case 0:
1533
- reader = readableStream.getReader();
1534
- _b.label = 1;
1535
- case 1:
1536
- _b.trys.push([1, , 9, 10]);
1537
- _b.label = 2;
1538
- case 2:
1539
- return [4, __await(reader.read())];
1540
- case 3:
1541
- _a = _b.sent(), value = _a.value, done = _a.done;
1542
- if (!done) return [3, 5];
1543
- return [4, __await(void 0)];
1544
- case 4: return [2, _b.sent()];
1545
- case 5: return [4, __await(value)];
1546
- case 6: return [4, _b.sent()];
1547
- case 7:
1548
- _b.sent();
1549
- return [3, 2];
1550
- case 8: return [3, 10];
1551
- case 9:
1552
- reader.releaseLock();
1553
- return [7];
1554
- case 10: return [2];
1555
- }
1556
- });
1557
- });
1558
- }
1559
- function isReadableStreamLike(obj) {
1560
- return isFunction(obj === null || obj === void 0 ? void 0 : obj.getReader);
1561
- }
1562
-
1563
- function innerFrom(input) {
1564
- if (input instanceof Observable) {
1565
- return input;
1566
- }
1567
- if (input != null) {
1568
- if (isInteropObservable(input)) {
1569
- return fromInteropObservable(input);
1570
- }
1571
- if (isArrayLike(input)) {
1572
- return fromArrayLike(input);
1573
- }
1574
- if (isPromise(input)) {
1575
- return fromPromise(input);
1576
- }
1577
- if (isAsyncIterable(input)) {
1578
- return fromAsyncIterable(input);
1579
- }
1580
- if (isIterable(input)) {
1581
- return fromIterable(input);
1582
- }
1583
- if (isReadableStreamLike(input)) {
1584
- return fromReadableStreamLike(input);
1585
- }
1586
- }
1587
- throw createInvalidObservableTypeError(input);
1588
- }
1589
- function fromInteropObservable(obj) {
1590
- return new Observable(function (subscriber) {
1591
- var obs = obj[observable]();
1592
- if (isFunction(obs.subscribe)) {
1593
- return obs.subscribe(subscriber);
1594
- }
1595
- throw new TypeError('Provided object does not correctly implement Symbol.observable');
1596
- });
1597
- }
1598
- function fromArrayLike(array) {
1599
- return new Observable(function (subscriber) {
1600
- for (var i = 0; i < array.length && !subscriber.closed; i++) {
1601
- subscriber.next(array[i]);
1602
- }
1603
- subscriber.complete();
1604
- });
1605
- }
1606
- function fromPromise(promise) {
1607
- return new Observable(function (subscriber) {
1608
- promise
1609
- .then(function (value) {
1610
- if (!subscriber.closed) {
1611
- subscriber.next(value);
1612
- subscriber.complete();
1613
- }
1614
- }, function (err) { return subscriber.error(err); })
1615
- .then(null, reportUnhandledError);
1616
- });
1617
- }
1618
- function fromIterable(iterable) {
1619
- return new Observable(function (subscriber) {
1620
- var e_1, _a;
1621
- try {
1622
- for (var iterable_1 = __values(iterable), iterable_1_1 = iterable_1.next(); !iterable_1_1.done; iterable_1_1 = iterable_1.next()) {
1623
- var value = iterable_1_1.value;
1624
- subscriber.next(value);
1625
- if (subscriber.closed) {
1626
- return;
1627
- }
1628
- }
1629
- }
1630
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
1631
- finally {
1632
- try {
1633
- if (iterable_1_1 && !iterable_1_1.done && (_a = iterable_1.return)) _a.call(iterable_1);
1634
- }
1635
- finally { if (e_1) throw e_1.error; }
1636
- }
1637
- subscriber.complete();
1638
- });
1639
- }
1640
- function fromAsyncIterable(asyncIterable) {
1641
- return new Observable(function (subscriber) {
1642
- process$1(asyncIterable, subscriber).catch(function (err) { return subscriber.error(err); });
1643
- });
1644
- }
1645
- function fromReadableStreamLike(readableStream) {
1646
- return fromAsyncIterable(readableStreamLikeToAsyncGenerator(readableStream));
1647
- }
1648
- function process$1(asyncIterable, subscriber) {
1649
- var asyncIterable_1, asyncIterable_1_1;
1650
- var e_2, _a;
1651
- return __awaiter(this, void 0, void 0, function () {
1652
- var value, e_2_1;
1653
- return __generator(this, function (_b) {
1654
- switch (_b.label) {
1655
- case 0:
1656
- _b.trys.push([0, 5, 6, 11]);
1657
- asyncIterable_1 = __asyncValues(asyncIterable);
1658
- _b.label = 1;
1659
- case 1: return [4, asyncIterable_1.next()];
1660
- case 2:
1661
- if (!(asyncIterable_1_1 = _b.sent(), !asyncIterable_1_1.done)) return [3, 4];
1662
- value = asyncIterable_1_1.value;
1663
- subscriber.next(value);
1664
- if (subscriber.closed) {
1665
- return [2];
1666
- }
1667
- _b.label = 3;
1668
- case 3: return [3, 1];
1669
- case 4: return [3, 11];
1670
- case 5:
1671
- e_2_1 = _b.sent();
1672
- e_2 = { error: e_2_1 };
1673
- return [3, 11];
1674
- case 6:
1675
- _b.trys.push([6, , 9, 10]);
1676
- if (!(asyncIterable_1_1 && !asyncIterable_1_1.done && (_a = asyncIterable_1.return))) return [3, 8];
1677
- return [4, _a.call(asyncIterable_1)];
1678
- case 7:
1679
- _b.sent();
1680
- _b.label = 8;
1681
- case 8: return [3, 10];
1682
- case 9:
1683
- if (e_2) throw e_2.error;
1684
- return [7];
1685
- case 10: return [7];
1686
- case 11:
1687
- subscriber.complete();
1688
- return [2];
1689
- }
1690
- });
1691
- });
1692
- }
1693
-
1694
- function executeSchedule(parentSubscription, scheduler, work, delay, repeat) {
1695
- if (delay === void 0) { delay = 0; }
1696
- if (repeat === void 0) { repeat = false; }
1697
- var scheduleSubscription = scheduler.schedule(function () {
1698
- work();
1699
- if (repeat) {
1700
- parentSubscription.add(this.schedule(null, delay));
1701
- }
1702
- else {
1703
- this.unsubscribe();
1704
- }
1705
- }, delay);
1706
- parentSubscription.add(scheduleSubscription);
1707
- if (!repeat) {
1708
- return scheduleSubscription;
1709
- }
1710
- }
1711
-
1712
- function observeOn(scheduler, delay) {
1713
- if (delay === void 0) { delay = 0; }
1714
- return operate(function (source, subscriber) {
1715
- source.subscribe(createOperatorSubscriber(subscriber, function (value) { return executeSchedule(subscriber, scheduler, function () { return subscriber.next(value); }, delay); }, function () { return executeSchedule(subscriber, scheduler, function () { return subscriber.complete(); }, delay); }, function (err) { return executeSchedule(subscriber, scheduler, function () { return subscriber.error(err); }, delay); }));
1716
- });
1717
- }
1718
-
1719
- function subscribeOn(scheduler, delay) {
1720
- if (delay === void 0) { delay = 0; }
1721
- return operate(function (source, subscriber) {
1722
- subscriber.add(scheduler.schedule(function () { return source.subscribe(subscriber); }, delay));
1723
- });
1724
- }
1725
-
1726
- function scheduleObservable(input, scheduler) {
1727
- return innerFrom(input).pipe(subscribeOn(scheduler), observeOn(scheduler));
1728
- }
1729
-
1730
- function schedulePromise(input, scheduler) {
1731
- return innerFrom(input).pipe(subscribeOn(scheduler), observeOn(scheduler));
1732
- }
1733
-
1734
- function scheduleArray(input, scheduler) {
1735
- return new Observable(function (subscriber) {
1736
- var i = 0;
1737
- return scheduler.schedule(function () {
1738
- if (i === input.length) {
1739
- subscriber.complete();
1740
- }
1741
- else {
1742
- subscriber.next(input[i++]);
1743
- if (!subscriber.closed) {
1744
- this.schedule();
1745
- }
1746
- }
1747
- });
1748
- });
1749
- }
1750
-
1751
- function scheduleIterable(input, scheduler) {
1752
- return new Observable(function (subscriber) {
1753
- var iterator$1;
1754
- executeSchedule(subscriber, scheduler, function () {
1755
- iterator$1 = input[iterator]();
1756
- executeSchedule(subscriber, scheduler, function () {
1757
- var _a;
1758
- var value;
1759
- var done;
1760
- try {
1761
- (_a = iterator$1.next(), value = _a.value, done = _a.done);
1762
- }
1763
- catch (err) {
1764
- subscriber.error(err);
1765
- return;
1766
- }
1767
- if (done) {
1768
- subscriber.complete();
1769
- }
1770
- else {
1771
- subscriber.next(value);
1772
- }
1773
- }, 0, true);
1774
- });
1775
- return function () { return isFunction(iterator$1 === null || iterator$1 === void 0 ? void 0 : iterator$1.return) && iterator$1.return(); };
1776
- });
1777
- }
1778
-
1779
- function scheduleAsyncIterable(input, scheduler) {
1780
- if (!input) {
1781
- throw new Error('Iterable cannot be null');
1782
- }
1783
- return new Observable(function (subscriber) {
1784
- executeSchedule(subscriber, scheduler, function () {
1785
- var iterator = input[Symbol.asyncIterator]();
1786
- executeSchedule(subscriber, scheduler, function () {
1787
- iterator.next().then(function (result) {
1788
- if (result.done) {
1789
- subscriber.complete();
1790
- }
1791
- else {
1792
- subscriber.next(result.value);
1793
- }
1794
- });
1795
- }, 0, true);
1796
- });
1797
- });
1798
- }
1799
-
1800
- function scheduleReadableStreamLike(input, scheduler) {
1801
- return scheduleAsyncIterable(readableStreamLikeToAsyncGenerator(input), scheduler);
1802
- }
1803
-
1804
- function scheduled(input, scheduler) {
1805
- if (input != null) {
1806
- if (isInteropObservable(input)) {
1807
- return scheduleObservable(input, scheduler);
1808
- }
1809
- if (isArrayLike(input)) {
1810
- return scheduleArray(input, scheduler);
1811
- }
1812
- if (isPromise(input)) {
1813
- return schedulePromise(input, scheduler);
1814
- }
1815
- if (isAsyncIterable(input)) {
1816
- return scheduleAsyncIterable(input, scheduler);
1817
- }
1818
- if (isIterable(input)) {
1819
- return scheduleIterable(input, scheduler);
1820
- }
1821
- if (isReadableStreamLike(input)) {
1822
- return scheduleReadableStreamLike(input, scheduler);
1823
- }
1824
- }
1825
- throw createInvalidObservableTypeError(input);
1826
- }
1827
-
1828
- function from(input, scheduler) {
1829
- return scheduler ? scheduled(input, scheduler) : innerFrom(input);
1830
- }
1831
-
1832
- var EmptyError = createErrorClass(function (_super) { return function EmptyErrorImpl() {
1833
- _super(this);
1834
- this.name = 'EmptyError';
1835
- this.message = 'no elements in sequence';
1836
- }; });
1837
-
1838
- function firstValueFrom(source, config) {
1839
- var hasConfig = typeof config === 'object';
1840
- return new Promise(function (resolve, reject) {
1841
- var subscriber = new SafeSubscriber({
1842
- next: function (value) {
1843
- resolve(value);
1844
- subscriber.unsubscribe();
1845
- },
1846
- error: reject,
1847
- complete: function () {
1848
- if (hasConfig) {
1849
- resolve(config.defaultValue);
1850
- }
1851
- else {
1852
- reject(new EmptyError());
1853
- }
1854
- },
1855
- });
1856
- source.subscribe(subscriber);
1857
- });
1858
- }
1859
-
1860
- function isValidDate(value) {
1861
- return value instanceof Date && !isNaN(value);
1862
- }
1863
-
1864
- function map(project, thisArg) {
1865
- return operate(function (source, subscriber) {
1866
- var index = 0;
1867
- source.subscribe(createOperatorSubscriber(subscriber, function (value) {
1868
- subscriber.next(project.call(thisArg, value, index++));
1869
- }));
1870
- });
1871
- }
1872
-
1873
- function mergeInternals(source, subscriber, project, concurrent, onBeforeNext, expand, innerSubScheduler, additionalFinalizer) {
1874
- var buffer = [];
1875
- var active = 0;
1876
- var index = 0;
1877
- var isComplete = false;
1878
- var checkComplete = function () {
1879
- if (isComplete && !buffer.length && !active) {
1880
- subscriber.complete();
1881
- }
1882
- };
1883
- var outerNext = function (value) { return (active < concurrent ? doInnerSub(value) : buffer.push(value)); };
1884
- var doInnerSub = function (value) {
1885
- expand && subscriber.next(value);
1886
- active++;
1887
- var innerComplete = false;
1888
- innerFrom(project(value, index++)).subscribe(createOperatorSubscriber(subscriber, function (innerValue) {
1889
- onBeforeNext === null || onBeforeNext === void 0 ? void 0 : onBeforeNext(innerValue);
1890
- if (expand) {
1891
- outerNext(innerValue);
1892
- }
1893
- else {
1894
- subscriber.next(innerValue);
1895
- }
1896
- }, function () {
1897
- innerComplete = true;
1898
- }, undefined, function () {
1899
- if (innerComplete) {
1900
- try {
1901
- active--;
1902
- var _loop_1 = function () {
1903
- var bufferedValue = buffer.shift();
1904
- if (innerSubScheduler) {
1905
- executeSchedule(subscriber, innerSubScheduler, function () { return doInnerSub(bufferedValue); });
1906
- }
1907
- else {
1908
- doInnerSub(bufferedValue);
1909
- }
1910
- };
1911
- while (buffer.length && active < concurrent) {
1912
- _loop_1();
1913
- }
1914
- checkComplete();
1915
- }
1916
- catch (err) {
1917
- subscriber.error(err);
1918
- }
1919
- }
1920
- }));
1921
- };
1922
- source.subscribe(createOperatorSubscriber(subscriber, outerNext, function () {
1923
- isComplete = true;
1924
- checkComplete();
1925
- }));
1926
- return function () {
1927
- additionalFinalizer === null || additionalFinalizer === void 0 ? void 0 : additionalFinalizer();
1928
- };
1929
- }
1930
-
1931
- function mergeMap(project, resultSelector, concurrent) {
1932
- if (concurrent === void 0) { concurrent = Infinity; }
1933
- if (isFunction(resultSelector)) {
1934
- return mergeMap(function (a, i) { return map(function (b, ii) { return resultSelector(a, b, i, ii); })(innerFrom(project(a, i))); }, concurrent);
1935
- }
1936
- else if (typeof resultSelector === 'number') {
1937
- concurrent = resultSelector;
1938
- }
1939
- return operate(function (source, subscriber) { return mergeInternals(source, subscriber, project, concurrent); });
1940
- }
1941
-
1942
- function mergeAll(concurrent) {
1943
- if (concurrent === void 0) { concurrent = Infinity; }
1944
- return mergeMap(identity, concurrent);
1945
- }
1946
-
1947
- function timer(dueTime, intervalOrScheduler, scheduler) {
1948
- if (dueTime === void 0) { dueTime = 0; }
1949
- if (scheduler === void 0) { scheduler = async; }
1950
- var intervalDuration = -1;
1951
- if (intervalOrScheduler != null) {
1952
- if (isScheduler(intervalOrScheduler)) {
1953
- scheduler = intervalOrScheduler;
1954
- }
1955
- else {
1956
- intervalDuration = intervalOrScheduler;
1957
- }
1958
- }
1959
- return new Observable(function (subscriber) {
1960
- var due = isValidDate(dueTime) ? +dueTime - scheduler.now() : dueTime;
1961
- if (due < 0) {
1962
- due = 0;
1963
- }
1964
- var n = 0;
1965
- return scheduler.schedule(function () {
1966
- if (!subscriber.closed) {
1967
- subscriber.next(n++);
1968
- if (0 <= intervalDuration) {
1969
- this.schedule(undefined, intervalDuration);
1970
- }
1971
- else {
1972
- subscriber.complete();
1973
- }
1974
- }
1975
- }, due);
1976
- });
1977
- }
1978
-
1979
- function merge() {
1980
- var args = [];
1981
- for (var _i = 0; _i < arguments.length; _i++) {
1982
- args[_i] = arguments[_i];
1983
- }
1984
- var scheduler = popScheduler(args);
1985
- var concurrent = popNumber(args, Infinity);
1986
- var sources = args;
1987
- return !sources.length
1988
- ?
1989
- EMPTY
1990
- : sources.length === 1
1991
- ?
1992
- innerFrom(sources[0])
1993
- :
1994
- mergeAll(concurrent)(from(sources, scheduler));
1995
- }
1996
-
1997
- function filter(predicate, thisArg) {
1998
- return operate(function (source, subscriber) {
1999
- var index = 0;
2000
- source.subscribe(createOperatorSubscriber(subscriber, function (value) { return predicate.call(thisArg, value, index++) && subscriber.next(value); }));
2001
- });
2002
- }
2003
-
2004
- function buffer(closingNotifier) {
2005
- return operate(function (source, subscriber) {
2006
- var currentBuffer = [];
2007
- source.subscribe(createOperatorSubscriber(subscriber, function (value) { return currentBuffer.push(value); }, function () {
2008
- subscriber.next(currentBuffer);
2009
- subscriber.complete();
2010
- }));
2011
- closingNotifier.subscribe(createOperatorSubscriber(subscriber, function () {
2012
- var b = currentBuffer;
2013
- currentBuffer = [];
2014
- subscriber.next(b);
2015
- }, noop));
2016
- return function () {
2017
- currentBuffer = null;
2018
- };
2019
- });
2020
- }
2021
-
2022
- function debounce(durationSelector) {
2023
- return operate(function (source, subscriber) {
2024
- var hasValue = false;
2025
- var lastValue = null;
2026
- var durationSubscriber = null;
2027
- var emit = function () {
2028
- durationSubscriber === null || durationSubscriber === void 0 ? void 0 : durationSubscriber.unsubscribe();
2029
- durationSubscriber = null;
2030
- if (hasValue) {
2031
- hasValue = false;
2032
- var value = lastValue;
2033
- lastValue = null;
2034
- subscriber.next(value);
2035
- }
2036
- };
2037
- source.subscribe(createOperatorSubscriber(subscriber, function (value) {
2038
- durationSubscriber === null || durationSubscriber === void 0 ? void 0 : durationSubscriber.unsubscribe();
2039
- hasValue = true;
2040
- lastValue = value;
2041
- durationSubscriber = createOperatorSubscriber(subscriber, emit, noop);
2042
- innerFrom(durationSelector(value)).subscribe(durationSubscriber);
2043
- }, function () {
2044
- emit();
2045
- subscriber.complete();
2046
- }, undefined, function () {
2047
- lastValue = durationSubscriber = null;
2048
- }));
2049
- });
2050
- }
2051
-
2052
- function defaultIfEmpty(defaultValue) {
2053
- return operate(function (source, subscriber) {
2054
- var hasValue = false;
2055
- source.subscribe(createOperatorSubscriber(subscriber, function (value) {
2056
- hasValue = true;
2057
- subscriber.next(value);
2058
- }, function () {
2059
- if (!hasValue) {
2060
- subscriber.next(defaultValue);
2061
- }
2062
- subscriber.complete();
2063
- }));
2064
- });
2065
- }
2066
-
2067
- function take(count) {
2068
- return count <= 0
2069
- ?
2070
- function () { return EMPTY; }
2071
- : operate(function (source, subscriber) {
2072
- var seen = 0;
2073
- source.subscribe(createOperatorSubscriber(subscriber, function (value) {
2074
- if (++seen <= count) {
2075
- subscriber.next(value);
2076
- if (count <= seen) {
2077
- subscriber.complete();
2078
- }
2079
- }
2080
- }));
2081
- });
2082
- }
2083
-
2084
- function throwIfEmpty(errorFactory) {
2085
- if (errorFactory === void 0) { errorFactory = defaultErrorFactory; }
2086
- return operate(function (source, subscriber) {
2087
- var hasValue = false;
2088
- source.subscribe(createOperatorSubscriber(subscriber, function (value) {
2089
- hasValue = true;
2090
- subscriber.next(value);
2091
- }, function () { return (hasValue ? subscriber.complete() : subscriber.error(errorFactory())); }));
2092
- });
394
+ function createDevLoader({
395
+ preamble,
396
+ client,
397
+ fileName
398
+ }) {
399
+ 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()));
400
+ }
401
+ function createProLoader({ fileName }) {
402
+ return contentProLoader.replace(/__SCRIPT__/g, JSON.stringify(fileName));
403
+ }
404
+
405
+ const serverEvent$ = new rxjs.ReplaySubject(1);
406
+ const close$ = serverEvent$.pipe(
407
+ rxjs.filter((e) => e.type === "close"),
408
+ rxjs.switchMap((e) => rxjs.of(e))
409
+ );
410
+ const start$ = serverEvent$.pipe(
411
+ rxjs.filter((e) => e.type === "start"),
412
+ rxjs.switchMap((e) => rxjs.of(e))
413
+ );
414
+ const fileWriterEvent$ = new rxjs.ReplaySubject(1);
415
+ const buildEnd$ = fileWriterEvent$.pipe(
416
+ rxjs.filter((e) => e.type === "build_end"),
417
+ rxjs.switchMap((e) => rxjs.of(e))
418
+ );
419
+ fileWriterEvent$.pipe(
420
+ rxjs.filter((e) => e.type === "build_start"),
421
+ rxjs.switchMap((e) => rxjs.of(e))
422
+ );
423
+ const allFilesReady$ = buildEnd$.pipe(
424
+ rxjs.switchMap(() => outputFiles.change$.pipe(rxjs.startWith({ type: "start" }))),
425
+ rxjs.map(() => [...outputFiles.values()]),
426
+ rxjs.switchMap((files) => Promise.allSettled(files.map(({ file }) => file)))
427
+ );
428
+ const isRejected = (x) => x?.status === "rejected";
429
+ const fileWriterError$ = allFilesReady$.pipe(
430
+ rxjs.mergeMap((results) => results.filter(isRejected)),
431
+ rxjs.map((rejected) => ({ err: rejected.reason, type: "error" }))
432
+ );
433
+ rxjs.firstValueFrom(
434
+ fileWriterError$.pipe(
435
+ rxjs.takeUntil(serverEvent$.pipe(rxjs.first(({ type }) => type === "close"))),
436
+ rxjs.toArray()
437
+ )
438
+ );
439
+ function prepFileData(fileId) {
440
+ const fileName = getFileName(fileId);
441
+ if (fileId.type === "asset") {
442
+ return prepAsset(fileName, fileId);
443
+ } else {
444
+ return prepScript(fileName, fileId);
445
+ }
2093
446
  }
2094
- function defaultErrorFactory() {
2095
- return new EmptyError();
447
+ function prepAsset(fileName, { id, source }) {
448
+ return ($) => $.pipe(
449
+ rxjs.mergeMap(async ({ server }) => {
450
+ const target = getOutputPath(server, fileName);
451
+ return {
452
+ target,
453
+ source: source ?? await promises.readFile(join(server.config.root, id)),
454
+ deps: []
455
+ };
456
+ })
457
+ );
458
+ }
459
+ function prepScript(fileName, script) {
460
+ return ($) => $.pipe(
461
+ rxjs.mergeMap(async ({ server }) => {
462
+ const target = getOutputPath(server, fileName);
463
+ const viteUrl = getViteUrl(script);
464
+ const transformResult = await server.transformRequest(viteUrl);
465
+ if (!transformResult)
466
+ throw new TypeError(`Unable to load "${script.id}" from server.`);
467
+ const { code, deps = [], dynamicDeps = [] } = transformResult;
468
+ return { target, code, deps: [...deps, ...dynamicDeps].flat(), server };
469
+ }),
470
+ rxjs.retry({ count: 10, delay: 100 }),
471
+ rxjs.mergeMap(async ({ target, server, ...rest }) => {
472
+ const plugins = server.config.plugins;
473
+ let { code, deps } = rest;
474
+ for (const plugin of plugins) {
475
+ const r = await plugin.renderCrxDevScript?.(code, script);
476
+ if (typeof r === "string")
477
+ code = r;
478
+ }
479
+ return { target, code, deps };
480
+ }),
481
+ rxjs.mergeMap(async ({ target, code, deps }) => {
482
+ await lexer__namespace.init;
483
+ const [imports] = lexer__namespace.parse(code, fileName);
484
+ const depSet = new Set(deps);
485
+ const magic = new MagicString__default["default"](code);
486
+ for (const i of imports)
487
+ if (i.n) {
488
+ depSet.add(i.n);
489
+ const fileName2 = getFileName({ type: "module", id: i.n });
490
+ magic.overwrite(i.s, i.e, `/${fileName2}`);
491
+ }
492
+ return { target, source: magic.toString(), deps: [...depSet] };
493
+ })
494
+ );
2096
495
  }
2097
-
2098
- function first(predicate, defaultValue) {
2099
- var hasDefaultValue = arguments.length >= 2;
2100
- return function (source) {
2101
- return source.pipe(predicate ? filter(function (v, i) { return predicate(v, i, source); }) : identity, take(1), hasDefaultValue ? defaultIfEmpty(defaultValue) : throwIfEmpty(function () { return new EmptyError(); }));
2102
- };
496
+ async function allFilesReady() {
497
+ await rxjs.firstValueFrom(allFilesReady$);
2103
498
  }
2104
499
 
2105
- function switchMap(project, resultSelector) {
2106
- return operate(function (source, subscriber) {
2107
- var innerSubscriber = null;
2108
- var index = 0;
2109
- var isComplete = false;
2110
- var checkComplete = function () { return isComplete && !innerSubscriber && subscriber.complete(); };
2111
- source.subscribe(createOperatorSubscriber(subscriber, function (value) {
2112
- innerSubscriber === null || innerSubscriber === void 0 ? void 0 : innerSubscriber.unsubscribe();
2113
- var innerIndex = 0;
2114
- var outerIndex = index++;
2115
- innerFrom(project(value, outerIndex)).subscribe((innerSubscriber = createOperatorSubscriber(subscriber, function (innerValue) { return subscriber.next(resultSelector ? resultSelector(value, innerValue, outerIndex, innerIndex++) : innerValue); }, function () {
2116
- innerSubscriber = null;
2117
- checkComplete();
2118
- })));
2119
- }, function () {
2120
- isComplete = true;
2121
- checkComplete();
2122
- }));
500
+ const { outputFile } = fsx__default["default"];
501
+ _debug("file-writer");
502
+ async function start({
503
+ server
504
+ }) {
505
+ serverEvent$.next({ type: "start", server });
506
+ const plugins = server.config.plugins.filter(
507
+ (p) => p.name?.startsWith("crx:")
508
+ );
509
+ const { rollupOptions, outDir } = server.config.build;
510
+ const inputOptions = {
511
+ input: "index.html",
512
+ ...rollupOptions,
513
+ plugins
514
+ };
515
+ const rollupOutputOptions = [rollupOptions.output].flat()[0];
516
+ const outputOptions = {
517
+ ...rollupOutputOptions,
518
+ dir: outDir,
519
+ format: "es"
520
+ };
521
+ fileWriterEvent$.next({ type: "build_start" });
522
+ const build = await rollup.rollup(inputOptions);
523
+ await build.write(outputOptions);
524
+ fileWriterEvent$.next({ type: "build_end" });
525
+ await allFilesReady();
526
+ }
527
+ async function close() {
528
+ serverEvent$.next({ type: "close" });
529
+ }
530
+ function add(script) {
531
+ const fileName = getFileName(script);
532
+ let file = outputFiles.get(fileName);
533
+ if (typeof file === "undefined") {
534
+ file = formatFileData({
535
+ ...script,
536
+ fileName,
537
+ file: write(script)
2123
538
  });
2124
- }
2125
-
2126
- function withLatestFrom() {
2127
- var inputs = [];
2128
- for (var _i = 0; _i < arguments.length; _i++) {
2129
- inputs[_i] = arguments[_i];
539
+ outputFiles.set(file.fileName, file);
540
+ }
541
+ return file;
542
+ }
543
+ function update(_id) {
544
+ const id = prefix$1("/", _id);
545
+ const types = ["iife", "module"];
546
+ const updatedFiles = [];
547
+ for (const type of types) {
548
+ const fileName = getFileName({ id, type });
549
+ const scriptFile = outputFiles.get(fileName);
550
+ if (scriptFile) {
551
+ scriptFile.file = write({ id, type });
552
+ updatedFiles.push(scriptFile);
553
+ outputFiles.set(fileName, scriptFile);
2130
554
  }
2131
- var project = popResultSelector(inputs);
2132
- return operate(function (source, subscriber) {
2133
- var len = inputs.length;
2134
- var otherValues = new Array(len);
2135
- var hasValue = inputs.map(function () { return false; });
2136
- var ready = false;
2137
- var _loop_1 = function (i) {
2138
- innerFrom(inputs[i]).subscribe(createOperatorSubscriber(subscriber, function (value) {
2139
- otherValues[i] = value;
2140
- if (!ready && !hasValue[i]) {
2141
- hasValue[i] = true;
2142
- (ready = hasValue.every(identity)) && (hasValue = null);
2143
- }
2144
- }, noop));
2145
- };
2146
- for (var i = 0; i < len; i++) {
2147
- _loop_1(i);
555
+ }
556
+ return updatedFiles;
557
+ }
558
+ async function write(fileId) {
559
+ const start2 = perf_hooks.performance.now();
560
+ const deps = await rxjs.firstValueFrom(
561
+ start$.pipe(
562
+ prepFileData(fileId),
563
+ rxjs.mergeMap(async ({ target, source, deps: deps2 }) => {
564
+ const files = deps2.map((id) => {
565
+ const r = [add({ id, type: "module" })];
566
+ if (id.includes("?import")) {
567
+ const [imported] = id.split("?import");
568
+ r.push(add({ id: imported, type: "asset" }));
569
+ }
570
+ return r;
571
+ }).flat();
572
+ if (source instanceof Uint8Array)
573
+ await outputFile(target, source);
574
+ else
575
+ await outputFile(target, source, { encoding: "utf8" });
576
+ return files;
577
+ }),
578
+ rxjs.takeUntil(close$),
579
+ rxjs.concatWith(rxjs.of([]))
580
+ )
581
+ );
582
+ const close2 = perf_hooks.performance.now();
583
+ return { start: start2, close: close2, deps };
584
+ }
585
+
586
+ const pluginContentScripts = () => {
587
+ let server;
588
+ let preambleCode;
589
+ let hmrTimeout;
590
+ let sub = new rxjs.Subscription();
591
+ return [
592
+ {
593
+ name: "crx:content-scripts",
594
+ apply: "serve",
595
+ config(config) {
596
+ const { contentScripts: contentScripts2 = {} } = getOptions(config);
597
+ hmrTimeout = contentScripts2.hmrTimeout ?? 5e3;
598
+ preambleCode = preambleCode ?? contentScripts2.preambleCode;
599
+ },
600
+ async configureServer(_server) {
601
+ server = _server;
602
+ if (typeof preambleCode === "undefined" && server.config.plugins.some(
603
+ ({ name = "none" }) => name.toLowerCase().includes("react")
604
+ )) {
605
+ try {
606
+ const react = await Promise.resolve().then(function () { return /*#__PURE__*/_interopNamespace(require('@vitejs/plugin-react')); });
607
+ preambleCode = react.default.preambleCode;
608
+ } catch (error) {
609
+ preambleCode = false;
610
+ }
2148
611
  }
2149
- source.subscribe(createOperatorSubscriber(subscriber, function (value) {
2150
- if (ready) {
2151
- var values = __spreadArray([value], __read(otherValues));
2152
- subscriber.next(project ? project.apply(void 0, __spreadArray([], __read(values))) : values);
612
+ sub.add(
613
+ contentScripts.change$.pipe(rxjs.filter(RxMap.isChangeType.set)).subscribe(({ value: script }) => {
614
+ const { type, id } = script;
615
+ if (type === "loader") {
616
+ let preamble = { fileName: "" };
617
+ if (preambleCode)
618
+ preamble = add({ type: "module", id: preambleId });
619
+ const client = add({ type: "module", id: viteClientId });
620
+ const file = add({ type: "module", id });
621
+ const loader = add({
622
+ type: "asset",
623
+ id: getFileName({ type: "loader", id }),
624
+ source: createDevLoader({
625
+ preamble: preamble.fileName,
626
+ client: client.fileName,
627
+ fileName: file.fileName
628
+ })
629
+ });
630
+ script.fileName = loader.fileName;
631
+ } else if (type === "iife") {
632
+ throw new Error("IIFE content scripts are not implemented");
633
+ } else {
634
+ const file = add({ type: "module", id });
635
+ script.fileName = file.fileName;
2153
636
  }
2154
- }));
2155
- });
2156
- }
2157
-
2158
- const { pathExistsSync, outputFile, statSync } = fsExtra__default["default"];
2159
- const debug$3 = _debug("file-writer").extend("events");
2160
- const writerEvent$ = new BehaviorSubject({
2161
- type: "init"
2162
- });
2163
- writerEvent$.subscribe((event) => {
2164
- debug$3("watcher event %O", event.type);
2165
- if (event.type === "error") {
2166
- debug$3("watcher error %O", event.error);
2167
- }
2168
- });
2169
- const filesError$ = writerEvent$.pipe(filter((x) => {
2170
- return x.type === "error";
2171
- }));
2172
- const filesStart$ = writerEvent$.pipe(filter((x) => {
2173
- return x.type === "buildStart";
2174
- }));
2175
- const filesStart = () => firstValueFrom(filesStart$);
2176
- const filesReady$ = writerEvent$.pipe(filter((x) => {
2177
- return x.type === "writeBundle";
2178
- }), switchMap((event) => timer(0, 100).pipe(map(() => event), first(({ bundle, options, timestamp }) => {
2179
- const result = Object.keys(bundle).every((p) => {
2180
- const stats = statSync(join(options.dir, p));
2181
- return stats.mtimeMs > timestamp;
2182
- });
2183
- return result;
2184
- }))));
2185
- const filesReady = () => firstValueFrom(filesReady$);
2186
- const server$ = new Subject();
2187
- const triggerName = firstValueFrom(server$.pipe(map(({ config: { cacheDir } }) => cacheDir), filter(isString), map((dir) => join(dir, ".crx-watch-trigger"))));
2188
- const rebuildFiles = async () => {
2189
- debug$3("rebuildFiles start");
2190
- await filesReady();
2191
- await Promise.all([
2192
- outputFile(await triggerName, Date.now().toString()),
2193
- filesStart()
2194
- ]);
2195
- await filesReady();
2196
- debug$3("rebuildFiles end");
2197
- };
2198
- function startLogger(server) {
2199
- const logger = vite.createLogger(server.config.logLevel, {
2200
- prefix: "[crx]"
2201
- });
2202
- const subs = [
2203
- filesStart$.subscribe(() => {
2204
- const message = colors__default["default"].green("files start");
2205
- const outDir = colors__default["default"].dim(relative(server.config.root, server.config.build.outDir));
2206
- logger.info(`${message} ${outDir}`, { timestamp: true });
2207
- }),
2208
- filesReady$.subscribe(({ duration: d }) => {
2209
- const message = colors__default["default"].green("files ready");
2210
- const duration = colors__default["default"].dim(`in ${colors__default["default"].bold(`${d}ms`)}`);
2211
- logger.info(`${message} ${duration}`, { timestamp: true });
2212
- }),
2213
- filesError$.subscribe(({ error }) => {
2214
- logger.error(colors__default["default"].dim("error from file writer:"), { timestamp: true });
2215
- if (error) {
2216
- const message = error?.stack ?? error.message;
2217
- logger.error(colors__default["default"].red(message));
637
+ })
638
+ );
639
+ },
640
+ resolveId(source) {
641
+ if (source === preambleId)
642
+ return preambleId;
643
+ if (source === contentHmrPortId)
644
+ return contentHmrPortId;
645
+ },
646
+ load(id) {
647
+ if (id === preambleId && typeof preambleCode === "string") {
648
+ const defined = preambleCode.replace(/__BASE__/g, server.config.base);
649
+ return defined;
650
+ }
651
+ if (id === contentHmrPortId) {
652
+ const defined = contentHmrPort.replace(
653
+ "__CRX_HMR_TIMEOUT__",
654
+ JSON.stringify(hmrTimeout)
655
+ );
656
+ return defined;
657
+ }
658
+ },
659
+ closeBundle() {
660
+ sub.unsubscribe();
661
+ sub = new rxjs.Subscription();
2218
662
  }
2219
- })
2220
- ];
2221
- return () => subs.forEach((sub) => sub.unsubscribe());
2222
- }
2223
- const pluginFileWriterEvents = () => {
2224
- let start = perf_hooks.performance.now();
2225
- let stopLogger;
2226
- return {
2227
- name: "crx:file-writer-events",
2228
- enforce: "post",
2229
- apply: "build",
2230
- fileWriterStart(server) {
2231
- debug$3("fileWriterStart");
2232
- stopLogger = startLogger(server);
2233
- },
2234
- closeWatcher() {
2235
- debug$3("closeWatcher");
2236
- stopLogger();
2237
663
  },
2238
- async buildStart(options) {
2239
- start = perf_hooks.performance.now();
2240
- const filename = await triggerName;
2241
- if (!pathExistsSync(filename)) {
2242
- await outputFile(filename, Date.now().toString());
664
+ {
665
+ name: "crx:content-scripts",
666
+ apply: "build",
667
+ enforce: "pre",
668
+ generateBundle() {
669
+ for (const [key, script] of contentScripts)
670
+ if (key === script.refId) {
671
+ if (script.type === "module") {
672
+ const fileName = this.getFileName(script.refId);
673
+ script.fileName = fileName;
674
+ } else if (script.type === "loader") {
675
+ const fileName = this.getFileName(script.refId);
676
+ script.fileName = fileName;
677
+ const refId = this.emitFile({
678
+ type: "asset",
679
+ name: getFileName({ type: "loader", id: basename(script.id) }),
680
+ source: createProLoader({ fileName })
681
+ });
682
+ script.loaderName = this.getFileName(refId);
683
+ } else if (script.type === "iife") {
684
+ throw new Error("IIFE content scripts are not implemented");
685
+ }
686
+ contentScripts.set(script.refId, formatFileData(script));
687
+ }
2243
688
  }
2244
- this.addWatchFile(filename);
2245
- writerEvent$.next({ type: "buildStart", options });
2246
- debug$3("buildStart");
2247
- },
2248
- writeBundle(options, bundle) {
2249
- const timestamp = perf_hooks.performance.now();
2250
- const duration = Math.round(timestamp - start);
2251
- writerEvent$.next({
2252
- type: "writeBundle",
2253
- options,
2254
- bundle,
2255
- duration,
2256
- timestamp
2257
- });
2258
- debug$3("writeBundle");
2259
- },
2260
- renderError(error) {
2261
- writerEvent$.next({ type: "error", error });
2262
- },
2263
- watchChange(id, { event }) {
2264
- writerEvent$.next({ type: "change", id, event });
2265
689
  }
2266
- };
690
+ ];
2267
691
  };
2268
692
 
2269
- var precontrollerScript = "const id = setInterval(() => location.reload(), 100);\nsetTimeout(() => clearInterval(id), 5e3);\n";
2270
-
2271
- 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";
2272
-
2273
- const pluginFileWriterHtml = () => {
2274
- let precontrollerName;
693
+ const pluginContentScriptsCss = () => {
694
+ let injectCss;
2275
695
  return {
2276
- name: "crx:file-writer-html",
2277
- apply: "build",
2278
- fileWriterStart(server) {
2279
- const plugins = server.config.plugins;
2280
- const i = plugins.findIndex(({ name }) => name === "alias");
2281
- plugins.splice(i, 0, {
2282
- name: "crx:load-precontroller",
2283
- apply: "serve",
2284
- load(id) {
2285
- if (id === `/${precontrollerName}`)
2286
- return "location.reload();";
2287
- }
2288
- });
696
+ name: "crx:content-scripts-css",
697
+ enforce: "post",
698
+ config(config) {
699
+ const { contentScripts: contentScripts2 = {} } = getOptions(config);
700
+ injectCss = contentScripts2.injectCss ?? true;
2289
701
  },
2290
702
  renderCrxManifest(manifest) {
2291
- if (this.meta.watchMode) {
2292
- const refId = this.emitFile({
2293
- type: "asset",
2294
- name: "precontroller.js",
2295
- source: precontrollerScript
2296
- });
2297
- precontrollerName = this.getFileName(refId);
2298
- for (const fileName of htmlFiles(manifest)) {
2299
- this.emitFile({
2300
- type: "asset",
2301
- fileName,
2302
- source: precontrollerHtml.replace("%PATH%", `/${precontrollerName}`)
2303
- });
703
+ if (injectCss) {
704
+ if (manifest.content_scripts) {
705
+ for (const script of manifest.content_scripts)
706
+ if (script.js)
707
+ for (const fileName of script.js)
708
+ if (contentScripts.has(fileName)) {
709
+ const { css } = contentScripts.get(fileName);
710
+ if (css?.length)
711
+ script.css = [script.css ?? [], css].flat();
712
+ } else {
713
+ throw new Error(
714
+ `Content script is undefined by fileName: ${fileName}`
715
+ );
716
+ }
2304
717
  }
2305
718
  }
2306
719
  return manifest;
@@ -2308,261 +721,342 @@ const pluginFileWriterHtml = () => {
2308
721
  };
2309
722
  };
2310
723
 
2311
- const { readFile: readFile$1 } = fs.promises;
2312
- const pluginFileWriterPublic = () => {
724
+ const pluginDeclaredContentScripts = () => {
725
+ return [];
726
+ };
727
+
728
+ const _dynamicScriptRegEx = /\b(import.meta).CRX_DYNAMIC_SCRIPT_(.+?);$/gm;
729
+ const dynamicScriptRegEx = () => {
730
+ _dynamicScriptRegEx.lastIndex = 0;
731
+ return _dynamicScriptRegEx;
732
+ };
733
+ const pluginDynamicContentScripts = () => {
2313
734
  let config;
2314
- return {
2315
- name: "crx:file-writer-public",
2316
- apply: "build",
2317
- configResolved(_config) {
2318
- config = _config;
2319
- },
2320
- async buildStart() {
2321
- if (this.meta.watchMode) {
2322
- this.addWatchFile(config.publicDir);
2323
- const publicFiles = await fg__default["default"](`${config.publicDir}/**/*`);
2324
- for (const file of publicFiles) {
2325
- const source = await readFile$1(file);
2326
- const fileName = relative(config.publicDir, file);
2327
- this.emitFile({ type: "asset", fileName, source });
735
+ return [
736
+ {
737
+ name: "crx:dynamic-content-scripts-loader",
738
+ enforce: "pre",
739
+ configResolved(_config) {
740
+ config = _config;
741
+ },
742
+ async resolveId(_source, importer) {
743
+ if (importer && _source.includes("?script")) {
744
+ const url = new URL(_source, "stub://stub");
745
+ if (url.searchParams.has("script")) {
746
+ const [source] = _source.split("?");
747
+ const resolved = await this.resolve(source, importer, {
748
+ skipSelf: true
749
+ });
750
+ if (!resolved)
751
+ throw new Error(
752
+ `Could not resolve dynamic script: "${_source}" from "${importer}"`
753
+ );
754
+ const { id } = resolved;
755
+ let type = "loader";
756
+ if (url.searchParams.has("module")) {
757
+ type = "module";
758
+ } else if (url.searchParams.has("iife")) {
759
+ type = "iife";
760
+ }
761
+ const scriptId = hashScriptId({ type, id });
762
+ const resolvedId = `${id}?scriptId=${scriptId}`;
763
+ let script = contentScripts.get(resolvedId);
764
+ if (typeof script === "undefined") {
765
+ let refId;
766
+ let fileName;
767
+ let loaderName;
768
+ if (config.command === "build") {
769
+ refId = this.emitFile({
770
+ type: "chunk",
771
+ id,
772
+ name: basename(id)
773
+ });
774
+ } else {
775
+ refId = scriptId;
776
+ const relId = relative(config.root, id);
777
+ fileName = getFileName({
778
+ type: type === "iife" ? "iife" : "module",
779
+ id: relId
780
+ });
781
+ if (type === "loader")
782
+ loaderName = getFileName({ type, id: relId });
783
+ }
784
+ script = formatFileData({
785
+ type,
786
+ id: relative(config.root, id),
787
+ isDynamicScript: true,
788
+ fileName,
789
+ loaderName,
790
+ refId,
791
+ scriptId,
792
+ matches: []
793
+ });
794
+ contentScripts.set(script.id, script);
795
+ }
796
+ return resolvedId;
797
+ } else if (url.searchParams.has("scriptId")) {
798
+ return _source;
799
+ }
800
+ }
801
+ },
802
+ async load(id) {
803
+ const index = id.indexOf("?scriptId=");
804
+ if (index > -1) {
805
+ const scriptId = id.slice(index + "?scriptId=".length);
806
+ const script = contentScripts.get(scriptId);
807
+ if (config.command === "build") {
808
+ return `export default import.meta.CRX_DYNAMIC_SCRIPT_${script.refId};`;
809
+ } else if (typeof script.fileName === "string") {
810
+ await fileReady(script);
811
+ return `export default ${JSON.stringify(script.fileName)};`;
812
+ } else {
813
+ throw new Error(
814
+ `Content script fileName is undefined: "${script.id}"`
815
+ );
816
+ }
2328
817
  }
2329
818
  }
819
+ },
820
+ {
821
+ name: "crx:dynamic-content-scripts-build",
822
+ apply: "build",
823
+ generateBundle(options, bundle) {
824
+ for (const chunk of Object.values(bundle))
825
+ if (chunk.type === "chunk") {
826
+ if (dynamicScriptRegEx().test(chunk.code)) {
827
+ const replaced = chunk.code.replace(
828
+ dynamicScriptRegEx(),
829
+ (match, p1, scriptKey) => {
830
+ const script = contentScripts.get(scriptKey);
831
+ if (typeof script === "undefined")
832
+ throw new Error(
833
+ `Content script refId is undefined: "${match}"`
834
+ );
835
+ if (typeof script.fileName === "undefined")
836
+ throw new Error(
837
+ `Content script fileName is undefined: "${script.id}"`
838
+ );
839
+ return `${JSON.stringify(
840
+ `/${script.loaderName ?? script.fileName}`
841
+ )};`;
842
+ }
843
+ );
844
+ chunk.code = replaced;
845
+ }
846
+ }
847
+ }
848
+ }
849
+ ];
850
+ };
851
+
852
+ const logger = vite.createLogger("error", { prefix: "crxjs" });
853
+ const pluginFileWriter = () => {
854
+ fileWriterError$.subscribe((error) => {
855
+ logger.error(error.err.message, { error: error.err });
856
+ });
857
+ return {
858
+ name: "crx:file-writer",
859
+ apply: "serve",
860
+ configureServer(server) {
861
+ server.httpServer?.on("listening", async () => {
862
+ try {
863
+ await start({ server });
864
+ } catch (error) {
865
+ console.error(error);
866
+ server.close();
867
+ }
868
+ });
869
+ server.httpServer?.on("close", () => close());
870
+ },
871
+ closeBundle() {
872
+ outputFiles.clear();
2330
873
  }
2331
874
  };
2332
875
  };
2333
876
 
2334
877
  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;
2335
- const customElementsPath = _require.resolve(customElementsId);
878
+ const customElementsPath = _require.resolve(customElementsId.slice(1));
2336
879
  const customElementsCode = fs.readFileSync(customElementsPath, "utf8");
2337
880
  const customElementsMap = fs.readFileSync(`${customElementsPath}.map`, "utf8");
2338
881
  const pluginFileWriterPolyfill = () => {
2339
882
  return {
2340
883
  name: "crx:file-writer-polyfill",
2341
- apply: "build",
884
+ apply: "serve",
2342
885
  enforce: "pre",
886
+ resolveId(source) {
887
+ if (source === customElementsId) {
888
+ return customElementsId;
889
+ }
890
+ },
2343
891
  load(id) {
2344
- if (id === idByUrl.get(customElementsId)) {
892
+ if (id === customElementsId) {
2345
893
  return { code: customElementsCode, map: customElementsMap };
2346
894
  }
2347
895
  },
2348
- transform(code, id) {
2349
- if (id === idByUrl.get(viteClientId)) {
896
+ renderCrxDevScript(code, { type, id }) {
897
+ if (type === "module" && id === viteClientId) {
2350
898
  const magic = new MagicString__default["default"](code);
2351
899
  magic.prepend(`import '${customElementsId}';`);
2352
900
  magic.prepend(`import { HMRPort } from '${contentHmrPortId}';`);
2353
901
  const ws = "new WebSocket";
2354
902
  const index = code.indexOf(ws);
2355
903
  magic.overwrite(index, index + ws.length, "new HMRPort");
2356
- return { code: magic.toString(), map: magic.generateMap() };
904
+ return magic.toString();
2357
905
  }
2358
906
  }
2359
907
  };
2360
908
  };
2361
909
 
2362
- function isUpdatePayload(p) {
2363
- return p.type === "update";
2364
- }
2365
- function isFullReloadPayload(p) {
2366
- return p.type === "full-reload";
910
+ async function manifestFiles(manifest, options = {}) {
911
+ let locales = [];
912
+ if (manifest.default_locale)
913
+ locales = await fg__default["default"]("_locales/**/messages.json", options);
914
+ const rulesets = manifest.declarative_net_request?.rule_resources.flatMap(
915
+ ({ path }) => path
916
+ ) ?? [];
917
+ const contentScripts = manifest.content_scripts?.flatMap(({ js }) => js) ?? [];
918
+ const contentStyles = manifest.content_scripts?.flatMap(({ css }) => css);
919
+ const serviceWorker = manifest.background?.service_worker;
920
+ const htmlPages = htmlFiles(manifest);
921
+ const icons = [
922
+ Object.values(
923
+ isString(manifest.icons) ? [manifest.icons] : manifest.icons ?? {}
924
+ ),
925
+ Object.values(
926
+ isString(manifest.action?.default_icon) ? [manifest.action?.default_icon] : manifest.action?.default_icon ?? {}
927
+ )
928
+ ].flat();
929
+ let webAccessibleResources = [];
930
+ if (manifest.web_accessible_resources) {
931
+ const resources = await Promise.all(
932
+ manifest.web_accessible_resources.flatMap(({ resources: resources2 }) => resources2).map(async (r) => {
933
+ if (["*", "**/*"].includes(r))
934
+ return void 0;
935
+ if (fg__default["default"].isDynamicPattern(r))
936
+ return fg__default["default"](r, options);
937
+ return r;
938
+ })
939
+ );
940
+ webAccessibleResources = resources.flat().filter(isString);
941
+ }
942
+ return {
943
+ contentScripts: [...new Set(contentScripts)].filter(isString),
944
+ contentStyles: [...new Set(contentStyles)].filter(isString),
945
+ html: htmlPages,
946
+ icons: [...new Set(icons)].filter(isString),
947
+ locales: [...new Set(locales)].filter(isString),
948
+ rulesets: [...new Set(rulesets)].filter(isString),
949
+ background: [serviceWorker].filter(isString),
950
+ webAccessibleResources
951
+ };
2367
952
  }
2368
- function isPrunePayload(p) {
2369
- return p.type === "prune";
953
+ async function dirFiles(dir) {
954
+ const files = await fg__default["default"](`${dir}/**/*`);
955
+ return files;
2370
956
  }
2371
- function isCrxHMRPayload(x) {
2372
- return x.type === "custom" && x.event.startsWith("crx:");
957
+ function htmlFiles(manifest) {
958
+ const files = [
959
+ manifest.action?.default_popup,
960
+ Object.values(manifest.chrome_url_overrides ?? {}),
961
+ manifest.devtools_page,
962
+ manifest.options_page,
963
+ manifest.options_ui?.page,
964
+ manifest.sandbox?.pages
965
+ ].flat().filter(isString).map((s) => s.split("#")[0]).sort();
966
+ return [...new Set(files)];
2373
967
  }
2374
- const hmrPayload$ = new Subject();
2375
- const hmrPrune$ = hmrPayload$.pipe(filter(isPrunePayload));
2376
- const hmrFullReload$ = hmrPayload$.pipe(filter(isFullReloadPayload));
2377
- const hmrUpdate$ = hmrPayload$.pipe(filter(isUpdatePayload));
2378
- const payload$ = merge(hmrFullReload$, hmrPrune$, hmrUpdate$);
2379
- const rebuildSignal$ = payload$.pipe(buffer(payload$.pipe(debounce(() => filesReady$))), map((payloads) => {
2380
- if (payloads.every(isUpdatePayload)) {
2381
- const owners = /* @__PURE__ */ new Set();
2382
- for (const { updates } of payloads)
2383
- for (const { path } of updates)
2384
- if (transformResultByOwner.has(path))
2385
- owners.add(path);
2386
- return { type: "partial", owners };
2387
- }
2388
- return { type: "full" };
2389
- }), filter((rebuild) => rebuild.type === "partial" ? rebuild.owners.size > 0 : true));
2390
- const crxHmrPayload$ = hmrPayload$.pipe(filter((p) => !isCrxHMRPayload(p)), buffer(filesReady$), mergeMap((pps) => {
2391
- let fullReload;
2392
- const payloads = [];
2393
- for (const p of pps.slice(-50))
2394
- if (p.type === "full-reload") {
2395
- fullReload = p;
2396
- } else {
2397
- payloads.push(p);
2398
- }
2399
- if (fullReload)
2400
- payloads.push(fullReload);
2401
- return payloads;
2402
- }), map((p) => {
2403
- switch (p.type) {
2404
- case "full-reload": {
2405
- const path = p.path && outputByOwner.get(p.path);
2406
- const fullReload = {
2407
- type: "full-reload",
2408
- path
2409
- };
2410
- return fullReload;
2411
- }
2412
- case "prune": {
2413
- const paths = [];
2414
- for (const owner of p.paths)
2415
- if (outputByOwner.has(owner))
2416
- paths.push(outputByOwner.get(owner));
2417
- return { type: "prune", paths };
2418
- }
2419
- case "update": {
2420
- const updates = [];
2421
- for (const { acceptedPath, path, ...rest } of p.updates)
2422
- if (outputByOwner.has(acceptedPath) && outputByOwner.has(path))
2423
- updates.push({
2424
- ...rest,
2425
- acceptedPath: outputByOwner.get(acceptedPath),
2426
- path: outputByOwner.get(path)
2427
- });
2428
- return { type: "update", updates };
2429
- }
2430
- default:
2431
- return p;
2432
- }
2433
- }), withLatestFrom(filesReady$), filter(([p, { bundle }]) => {
2434
- switch (p.type) {
2435
- case "full-reload":
2436
- return typeof p.path === "undefined" || p.path in bundle;
2437
- case "prune":
2438
- return p.paths.length > 0;
2439
- case "update":
2440
- return p.updates.length > 0;
2441
- default:
2442
- return true;
2443
- }
2444
- }), map(([p]) => ({
2445
- type: "custom",
2446
- event: "crx:content-script-payload",
2447
- data: p
2448
- })));
2449
968
 
2450
- function sortPlugins(plugins, command) {
2451
- const pre = [];
2452
- const mid = [];
2453
- const post = [];
2454
- for (const p of plugins) {
2455
- if (p.apply === command || !p.apply || !command) {
2456
- if (p.enforce === "pre")
2457
- pre.push(p);
2458
- else if (p.enforce === "post")
2459
- post.push(p);
2460
- else
2461
- mid.push(p);
2462
- }
2463
- }
2464
- return { pre, mid, post };
2465
- }
2466
- const pluginFileWriter = (crxPlugins) => (options) => {
2467
- const chunks = pluginFileWriterChunks();
2468
- const html = pluginFileWriterHtml();
2469
- const events = pluginFileWriterEvents();
2470
- const publicDir = pluginFileWriterPublic();
2471
- const polyfill = pluginFileWriterPolyfill();
2472
- const { pre, mid, post } = sortPlugins(crxPlugins, "build");
2473
- const plugins = [
2474
- ...pre,
2475
- ...mid,
2476
- polyfill,
2477
- chunks,
2478
- html,
2479
- publicDir,
2480
- ...post,
2481
- events
2482
- ].flat();
2483
- let watcher;
969
+ const pluginFileWriterPublic = () => {
970
+ let config;
2484
971
  return {
2485
- name: "crx:file-writer",
972
+ name: "crx:file-writer-public",
2486
973
  apply: "serve",
2487
- async config(_config, env) {
2488
- let config = _config;
2489
- for (const p of plugins) {
2490
- const r = await p.config?.(config, env);
2491
- config = r ?? config;
2492
- }
2493
- return config;
2494
- },
2495
- async configResolved(config) {
2496
- await Promise.all(plugins.map((p) => p.configResolved?.(config)));
2497
- },
2498
- configureServer(server) {
2499
- server.httpServer?.once("listening", async () => {
2500
- server$.next(server);
2501
- const optimizedDeps = server._optimizedDeps;
2502
- await optimizedDeps?.scanProcessing;
2503
- const { pre: pre2, mid: mid2, post: post2 } = sortPlugins([
2504
- ...server.config.plugins,
2505
- ...plugins
2506
- ]);
2507
- const allPlugins = [...pre2, ...mid2, ...post2];
2508
- await Promise.all(allPlugins.map(async (p) => {
2509
- try {
2510
- await p.fileWriterStart?.(server);
2511
- } catch (e) {
2512
- const hook = `[${p.name}].fileWriterStart`;
2513
- let error = new Error(`Error in plugin ${hook}`);
2514
- if (e instanceof Error) {
2515
- error = e;
2516
- error.message = `${hook} ${error.message}`;
2517
- } else if (typeof e === "string") {
2518
- error = new Error(`${hook} ${e}`);
2519
- }
2520
- writerEvent$.next({ type: "error", error });
2521
- }
2522
- }));
2523
- watcher = rollup.watch({
2524
- input: stubId,
2525
- context: "this",
2526
- output: {
2527
- dir: server.config.build.outDir,
2528
- format: "es"
2529
- },
2530
- plugins,
2531
- treeshake: false
2532
- });
2533
- watcher.on("event", (event) => {
2534
- if (event.code === "ERROR") {
2535
- const { message, parserError, stack, id, loc, code, frame } = event.error;
2536
- const error = parserError ?? new Error(message);
2537
- if (parserError && message.startsWith("Unexpected token")) {
2538
- const m = `Unexpected token in ${loc?.file ?? id}`;
2539
- error.message = [m, loc?.line, loc?.column].filter(isTruthy).join(":");
2540
- }
2541
- error.stack = (stack ?? error.stack)?.replace(/.+?\n/, `Error: ${error.message}
2542
- `);
2543
- writerEvent$.next({ type: "error", error, code, frame });
2544
- }
2545
- });
2546
- const rebuildSub = rebuildSignal$.subscribe((rebuild) => {
2547
- if (rebuild.type === "partial") {
2548
- for (const owner of rebuild.owners)
2549
- transformResultByOwner.delete(owner);
2550
- } else {
2551
- transformResultByOwner.clear();
2552
- }
2553
- rebuildFiles();
2554
- });
2555
- watcher.on("close", () => {
2556
- rebuildSub.unsubscribe();
2557
- });
2558
- });
974
+ configResolved(_config) {
975
+ config = _config;
2559
976
  },
2560
- closeBundle() {
2561
- watcher?.close();
977
+ async generateBundle() {
978
+ const publicDir = isAbsolute(config.publicDir) ? config.publicDir : resolve(config.root, config.publicDir);
979
+ const files = await dirFiles(publicDir);
980
+ for (const filepath of files) {
981
+ const source = await promises.readFile(filepath);
982
+ const fileName = relative(publicDir, filepath);
983
+ this.emitFile({ type: "asset", source, fileName });
984
+ }
2562
985
  }
2563
986
  };
2564
987
  };
2565
988
 
989
+ _debug("file-writer").extend("hmr");
990
+ const isCrxHMRPayload = (p) => p.type === "custom" && p.event.startsWith("crx:");
991
+ const hmrPayload$ = new rxjs.Subject();
992
+ const crxHMRPayload$ = hmrPayload$.pipe(
993
+ rxjs.filter((p) => !isCrxHMRPayload(p)),
994
+ rxjs.buffer(allFilesReady$),
995
+ rxjs.mergeMap((pps) => {
996
+ let fullReload;
997
+ const payloads = [];
998
+ for (const p of pps)
999
+ if (p.type === "full-reload") {
1000
+ fullReload = p;
1001
+ } else {
1002
+ payloads.push(p);
1003
+ }
1004
+ if (fullReload)
1005
+ payloads.push(fullReload);
1006
+ return payloads;
1007
+ }),
1008
+ rxjs.map((p) => {
1009
+ switch (p.type) {
1010
+ case "full-reload": {
1011
+ const fullReload = {
1012
+ type: "full-reload",
1013
+ path: p.path && getViteUrl({ id: p.path, type: "module" })
1014
+ };
1015
+ return fullReload;
1016
+ }
1017
+ case "prune": {
1018
+ const prune = {
1019
+ type: "prune",
1020
+ paths: p.paths.map((id) => getViteUrl({ id, type: "module" }))
1021
+ };
1022
+ return prune;
1023
+ }
1024
+ case "update": {
1025
+ const update = {
1026
+ type: "update",
1027
+ updates: p.updates.map(({ acceptedPath: ap, path: p2, ...rest }) => ({
1028
+ ...rest,
1029
+ acceptedPath: prefix$1("/", getFileName({ id: ap, type: "module" })),
1030
+ path: prefix$1("/", getFileName({ id: p2, type: "module" }))
1031
+ }))
1032
+ };
1033
+ return update;
1034
+ }
1035
+ default:
1036
+ return p;
1037
+ }
1038
+ }),
1039
+ rxjs.filter((p) => {
1040
+ switch (p.type) {
1041
+ case "full-reload":
1042
+ return typeof p.path === "undefined";
1043
+ case "prune":
1044
+ return p.paths.length > 0;
1045
+ case "update":
1046
+ return p.updates.length > 0;
1047
+ default:
1048
+ return true;
1049
+ }
1050
+ }),
1051
+ rxjs.map((data) => {
1052
+ return {
1053
+ type: "custom",
1054
+ event: "crx:content-script-payload",
1055
+ data
1056
+ };
1057
+ })
1058
+ );
1059
+
2566
1060
  function isImporter(file) {
2567
1061
  const seen = /* @__PURE__ */ new Set();
2568
1062
  const pred = (changedNode) => {
@@ -2579,68 +1073,112 @@ function isImporter(file) {
2579
1073
  return pred;
2580
1074
  }
2581
1075
 
2582
- const debug$2 = _debug("hmr");
1076
+ const debug$1 = _debug("hmr");
2583
1077
  const crxRuntimeReload = {
2584
1078
  type: "custom",
2585
1079
  event: "crx:runtime-reload"
2586
1080
  };
2587
1081
  const pluginHMR = () => {
2588
- let files;
1082
+ let inputManifestFiles;
2589
1083
  let decoratedSend;
1084
+ let config;
1085
+ let subs;
2590
1086
  return [
2591
- {
2592
- name: "crx:hmr",
2593
- apply: "build",
2594
- enforce: "post",
2595
- async renderCrxManifest(manifest) {
2596
- if (this.meta.watchMode) {
2597
- files = await manifestFiles(manifest);
2598
- }
2599
- return null;
2600
- }
2601
- },
2602
1087
  {
2603
1088
  name: "crx:hmr",
2604
1089
  apply: "serve",
2605
1090
  enforce: "pre",
2606
- config({ server = {}, ...config }) {
1091
+ async config({ server = {}, ...config2 }) {
2607
1092
  if (server.hmr === false)
2608
1093
  return;
2609
1094
  if (server.hmr === true)
2610
1095
  server.hmr = {};
2611
1096
  server.hmr = server.hmr ?? {};
2612
1097
  server.hmr.host = "localhost";
2613
- return { server, ...config };
1098
+ server.hmr.port = server.hmr.port ?? await getPort__default["default"]({ port: getPort.portNumbers(5200, 5300) });
1099
+ return { server, ...config2 };
2614
1100
  },
2615
- configResolved(config) {
1101
+ configResolved(_config) {
1102
+ config = _config;
2616
1103
  const { watch = {} } = config.server;
2617
1104
  config.server.watch = watch;
2618
1105
  watch.ignored = watch.ignored ? [...new Set([watch.ignored].flat())] : [];
2619
1106
  const outDir = isAbsolute(config.build.outDir) ? config.build.outDir : join(config.root, config.build.outDir, "**/*");
2620
- watch.ignored.push(outDir);
1107
+ if (!watch.ignored.includes(outDir))
1108
+ watch.ignored.push(outDir);
2621
1109
  },
2622
1110
  configureServer(server) {
2623
1111
  if (server.ws.send !== decoratedSend) {
2624
1112
  const { send } = server.ws;
2625
1113
  decoratedSend = (payload) => {
2626
- hmrPayload$.next(payload);
1114
+ if (payload.type === "error") {
1115
+ send({
1116
+ type: "custom",
1117
+ event: "crx:content-script-payload",
1118
+ data: payload
1119
+ });
1120
+ } else {
1121
+ hmrPayload$.next(payload);
1122
+ }
2627
1123
  send(payload);
2628
1124
  };
2629
1125
  server.ws.send = decoratedSend;
2630
- crxHmrPayload$.subscribe((payload) => {
2631
- send(payload);
2632
- });
1126
+ subs = new rxjs.Subscription(() => subs = new rxjs.Subscription());
1127
+ subs.add(fileWriterError$.subscribe(send));
1128
+ subs.add(
1129
+ crxHMRPayload$.subscribe((payload) => {
1130
+ send(payload);
1131
+ })
1132
+ );
2633
1133
  }
2634
1134
  },
2635
- handleHotUpdate({ file, modules, server }) {
2636
- const background = files.background[0] && join(server.config.root, files.background[0]);
2637
- if (background) {
2638
- if (file === background || modules.some(isImporter(background))) {
2639
- debug$2("sending runtime reload");
1135
+ closeBundle() {
1136
+ subs.unsubscribe();
1137
+ },
1138
+ handleHotUpdate({ modules, server }) {
1139
+ const { root } = server.config;
1140
+ const relFiles = /* @__PURE__ */ new Set();
1141
+ for (const m of modules)
1142
+ if (m.id?.startsWith(root)) {
1143
+ relFiles.add(m.id.slice(server.config.root.length));
1144
+ }
1145
+ if (inputManifestFiles.background.length) {
1146
+ const background = prefix$1("/", inputManifestFiles.background[0]);
1147
+ if (relFiles.has(background) || modules.some(isImporter(join(server.config.root, background)))) {
1148
+ debug$1("sending runtime reload");
2640
1149
  server.ws.send(crxRuntimeReload);
2641
1150
  return [];
2642
1151
  }
2643
1152
  }
1153
+ for (const [key, script] of contentScripts)
1154
+ if (key === script.id) {
1155
+ if (relFiles.has(script.id) || modules.some(isImporter(join(server.config.root, script.id)))) {
1156
+ relFiles.forEach((relFile) => update(relFile));
1157
+ }
1158
+ }
1159
+ }
1160
+ },
1161
+ {
1162
+ name: "crx:hmr",
1163
+ apply: "serve",
1164
+ enforce: "post",
1165
+ async transformCrxManifest(manifest) {
1166
+ inputManifestFiles = await manifestFiles(manifest, { cwd: config.root });
1167
+ return null;
1168
+ },
1169
+ renderCrxDevScript(code, { id: _id, type }) {
1170
+ if (type === "module" && _id !== "/@vite/client" && code.includes("createHotContext")) {
1171
+ const id = _id.replace(/t=\d+&/, "");
1172
+ const escaped = id.replace(/([?&.])/g, "\\$1");
1173
+ const regexp = new RegExp(
1174
+ `(?<=createHotContext\\(")${escaped}(?="\\))`
1175
+ );
1176
+ const fileUrl = prefix$1("/", getFileName({ id, type }));
1177
+ const replaced = code.replace(regexp, fileUrl);
1178
+ return replaced;
1179
+ } else {
1180
+ return code;
1181
+ }
2644
1182
  }
2645
1183
  }
2646
1184
  ];
@@ -2649,14 +1187,14 @@ const pluginHMR = () => {
2649
1187
  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";
2650
1188
 
2651
1189
  const pluginName = "crx:html-inline-scripts";
2652
- const debug$1 = _debug(pluginName);
1190
+ const debug = _debug(pluginName);
2653
1191
  const prefix = "@crx/inline-script";
2654
1192
  const isInlineTag = (t) => t.tag === "script" && !t.attrs?.src;
2655
1193
  const toKey = (ctx) => {
2656
1194
  const { dir, name } = parse(ctx.path);
2657
1195
  return join(prefix, dir, name);
2658
1196
  };
2659
- const pluginHtmlAuditor = () => {
1197
+ const pluginHtmlInlineScripts = () => {
2660
1198
  const pages = /* @__PURE__ */ new Map();
2661
1199
  const auditTransformIndexHtml = (p) => {
2662
1200
  let transform;
@@ -2719,10 +1257,12 @@ const pluginHtmlAuditor = () => {
2719
1257
  const p = pages.get(key);
2720
1258
  if (p?.scripts.some(isInlineTag)) {
2721
1259
  const $ = cheerio.load(html);
2722
- p.scripts.push(...$("script").toArray().map((el) => ({
2723
- tag: "script",
2724
- attrs: { src: $(el).attr("src"), type: "module" }
2725
- })));
1260
+ p.scripts.push(
1261
+ ...$("script").toArray().map((el) => ({
1262
+ tag: "script",
1263
+ attrs: { src: $(el).attr("src"), type: "module" }
1264
+ }))
1265
+ );
2726
1266
  $("script").remove();
2727
1267
  const loader2 = {
2728
1268
  tag: "script",
@@ -2770,15 +1310,19 @@ const pluginHtmlAuditor = () => {
2770
1310
  })}"`;
2771
1311
  return [inline, loader.replace("SCRIPTS", json)].join("\n");
2772
1312
  } else {
2773
- debug$1("page missing %s", id);
1313
+ debug("page missing %s", id);
2774
1314
  }
2775
1315
  }
2776
1316
  }
2777
1317
  };
2778
1318
  };
2779
1319
 
1320
+ var precontrollerJs = "const id = setInterval(() => location.reload(), 100);\nsetTimeout(() => clearInterval(id), 5e3);\n";
1321
+
1322
+ 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";
1323
+
2780
1324
  const { readFile } = fs.promises;
2781
- const pluginManifest = (_manifest) => () => {
1325
+ const pluginManifest = () => {
2782
1326
  let manifest;
2783
1327
  let plugins;
2784
1328
  let refId;
@@ -2788,15 +1332,18 @@ const pluginManifest = (_manifest) => () => {
2788
1332
  name: "crx:manifest-init",
2789
1333
  enforce: "pre",
2790
1334
  async config(config2, env) {
1335
+ const { manifest: _manifest } = await getOptions(config2);
2791
1336
  manifest = await (typeof _manifest === "function" ? _manifest(env) : _manifest);
2792
1337
  if (manifest.manifest_version !== 3)
2793
- throw new Error(`CRXJS does not support Manifest v${manifest.manifest_version}, please use Manifest v3`);
1338
+ throw new Error(
1339
+ `CRXJS does not support Manifest v${manifest.manifest_version}, please use Manifest v3`
1340
+ );
2794
1341
  if (env.command === "serve") {
2795
1342
  const {
2796
1343
  contentScripts: js,
2797
1344
  background: sw,
2798
1345
  html
2799
- } = await manifestFiles(manifest);
1346
+ } = await manifestFiles(manifest, { cwd: config2.root });
2800
1347
  const { entries = [] } = config2.optimizeDeps ?? {};
2801
1348
  let { input = [] } = config2.build?.rollupOptions ?? {};
2802
1349
  if (typeof input === "string")
@@ -2829,15 +1376,16 @@ const pluginManifest = (_manifest) => () => {
2829
1376
  },
2830
1377
  {
2831
1378
  name: "crx:manifest-loader",
2832
- apply: "build",
2833
1379
  enforce: "pre",
2834
- buildStart() {
2835
- refId = this.emitFile({
2836
- type: "chunk",
2837
- id: manifestId,
2838
- name: "crx-manifest.js",
2839
- preserveSignature: "strict"
2840
- });
1380
+ buildStart(options) {
1381
+ if (typeof options.input !== "undefined") {
1382
+ refId = this.emitFile({
1383
+ type: "chunk",
1384
+ id: manifestId,
1385
+ name: "crx-manifest.js",
1386
+ preserveSignature: "strict"
1387
+ });
1388
+ }
2841
1389
  },
2842
1390
  resolveId(source) {
2843
1391
  if (source === manifestId)
@@ -2852,13 +1400,22 @@ const pluginManifest = (_manifest) => () => {
2852
1400
  },
2853
1401
  {
2854
1402
  name: "crx:stub-input",
2855
- apply: "build",
2856
1403
  enforce: "pre",
2857
1404
  options({ input, ...options }) {
2858
- return {
2859
- input: isString(input) && input.endsWith("index.html") ? stubId : input,
2860
- ...options
2861
- };
1405
+ let finalInput = input;
1406
+ if (isString(input) && input.endsWith("index.html")) {
1407
+ finalInput = stubId;
1408
+ }
1409
+ if (config.command === "serve") {
1410
+ if (Array.isArray(input)) {
1411
+ finalInput = input.filter((x) => !x.endsWith(".html"));
1412
+ } else if (typeof input === "object") {
1413
+ for (const [key, value] of Object.entries(input))
1414
+ if (value.endsWith(".html"))
1415
+ delete input[key];
1416
+ }
1417
+ }
1418
+ return { input: finalInput, ...options };
2862
1419
  },
2863
1420
  resolveId(source) {
2864
1421
  if (source === stubId)
@@ -2881,12 +1438,13 @@ const pluginManifest = (_manifest) => () => {
2881
1438
  },
2882
1439
  {
2883
1440
  name: "crx:manifest-post",
2884
- apply: "build",
2885
1441
  enforce: "post",
2886
1442
  configResolved(_config) {
2887
1443
  config = _config;
2888
1444
  const plugins2 = config.plugins;
2889
- const crx = plugins2.findIndex(({ name }) => name === "crx:manifest-post");
1445
+ const crx = plugins2.findIndex(
1446
+ ({ name }) => name === "crx:manifest-post"
1447
+ );
2890
1448
  const [plugin] = plugins2.splice(crx, 1);
2891
1449
  plugins2.push(plugin);
2892
1450
  },
@@ -2905,30 +1463,56 @@ const pluginManifest = (_manifest) => () => {
2905
1463
  throw error;
2906
1464
  }
2907
1465
  }
2908
- if (manifest2.content_scripts?.length) {
2909
- manifest2.content_scripts = manifest2.content_scripts.map(({ js = [], ...rest }) => {
2910
- const refJS = js.map((file) => this.emitFile({
2911
- type: "chunk",
2912
- id: file,
2913
- name: basename(file)
2914
- }));
2915
- return { js: refJS, ...rest };
2916
- });
2917
- }
2918
- if (!this.meta.watchMode) {
1466
+ if (config.command === "serve") {
1467
+ if (manifest2.content_scripts)
1468
+ for (const { js = [], matches = [] } of manifest2.content_scripts)
1469
+ for (const id2 of js) {
1470
+ contentScripts.set(
1471
+ prefix$1("/", id2),
1472
+ formatFileData({
1473
+ type: "loader",
1474
+ id: id2,
1475
+ matches,
1476
+ refId: hashScriptId({ type: "loader", id: id2 }),
1477
+ fileName: getFileName({ type: "loader", id: id2 })
1478
+ })
1479
+ );
1480
+ }
1481
+ } else {
1482
+ if (manifest2.content_scripts)
1483
+ for (const { js = [], matches = [] } of manifest2.content_scripts)
1484
+ for (const file of js) {
1485
+ const id2 = join(config.root, file);
1486
+ const refId2 = this.emitFile({
1487
+ type: "chunk",
1488
+ id: id2,
1489
+ name: basename(file)
1490
+ });
1491
+ contentScripts.set(
1492
+ file,
1493
+ formatFileData({
1494
+ type: "loader",
1495
+ id: file,
1496
+ refId: refId2,
1497
+ matches
1498
+ })
1499
+ );
1500
+ }
2919
1501
  if (manifest2.background?.service_worker) {
2920
1502
  const file = manifest2.background.service_worker;
1503
+ const id2 = join(config.root, file);
2921
1504
  const refId2 = this.emitFile({
2922
1505
  type: "chunk",
2923
- id: file,
1506
+ id: id2,
2924
1507
  name: basename(file)
2925
1508
  });
2926
1509
  manifest2.background.service_worker = refId2;
2927
1510
  }
2928
1511
  for (const file of htmlFiles(manifest2)) {
1512
+ const id2 = join(config.root, file);
2929
1513
  this.emitFile({
2930
1514
  type: "chunk",
2931
- id: file,
1515
+ id: id2,
2932
1516
  name: basename(file)
2933
1517
  });
2934
1518
  }
@@ -2940,15 +1524,36 @@ const pluginManifest = (_manifest) => () => {
2940
1524
  const manifestName = this.getFileName(refId);
2941
1525
  const manifestJs = bundle[manifestName];
2942
1526
  let manifest2 = decodeManifest.call(this, manifestJs.code);
2943
- if (manifest2.background?.service_worker && !this.meta.watchMode) {
2944
- const ref = manifest2.background.service_worker;
2945
- const name = this.getFileName(ref);
2946
- manifest2.background.service_worker = name;
1527
+ if (config.command === "serve") {
1528
+ if (manifest2.content_scripts)
1529
+ for (const script of manifest2.content_scripts) {
1530
+ script.js = script.js?.map(
1531
+ (id) => getFileName({ id, type: "loader" })
1532
+ );
1533
+ }
1534
+ } else {
1535
+ if (manifest2.background?.service_worker) {
1536
+ const ref = manifest2.background.service_worker;
1537
+ const name = this.getFileName(ref);
1538
+ manifest2.background.service_worker = name;
1539
+ }
1540
+ manifest2.content_scripts = manifest2.content_scripts?.map(
1541
+ ({ js = [], ...rest }) => {
1542
+ return {
1543
+ js: js.map((id) => {
1544
+ const script = contentScripts.get(id);
1545
+ const fileName = script?.loaderName ?? script?.fileName;
1546
+ if (typeof fileName === "undefined")
1547
+ throw new Error(
1548
+ `Content script fileName is undefined: "${id}"`
1549
+ );
1550
+ return fileName;
1551
+ }),
1552
+ ...rest
1553
+ };
1554
+ }
1555
+ );
2947
1556
  }
2948
- manifest2.content_scripts = manifest2.content_scripts?.map(({ js = [], ...rest }) => {
2949
- const refJS = js.map((ref) => this.getFileName(ref));
2950
- return { js: refJS, ...rest };
2951
- });
2952
1557
  for (const plugin of plugins) {
2953
1558
  try {
2954
1559
  const m = structuredClone(manifest2);
@@ -2958,7 +1563,9 @@ const pluginManifest = (_manifest) => () => {
2958
1563
  const name = `[${plugin.name}]`;
2959
1564
  let message = error;
2960
1565
  if (error instanceof Error) {
2961
- message = colors__default["default"].red(`${name} ${error.stack ? error.stack : error.message}`);
1566
+ message = colors__default["default"].red(
1567
+ `${name} ${error.stack ? error.stack : error.message}`
1568
+ );
2962
1569
  } else if (typeof error === "string") {
2963
1570
  message = colors__default["default"].red(`${name} ${error}`);
2964
1571
  }
@@ -2972,24 +1579,46 @@ const pluginManifest = (_manifest) => () => {
2972
1579
  "rulesets",
2973
1580
  "webAccessibleResources"
2974
1581
  ];
2975
- const files = await manifestFiles(manifest2);
2976
- await Promise.all(assetTypes.map((k) => files[k]).flat().map(async (f) => {
2977
- if (typeof bundle[f] === "undefined") {
2978
- let filename = join(config.root, f);
2979
- if (!fs.existsSync(filename))
2980
- filename = join(config.publicDir, f);
2981
- if (!fs.existsSync(filename))
2982
- throw new Error(`ENOENT: Could not load manifest asset "${f}".
1582
+ const files = await manifestFiles(manifest2, { cwd: config.root });
1583
+ await Promise.all(
1584
+ assetTypes.map((k) => files[k]).flat().map(async (f) => {
1585
+ if (typeof bundle[f] === "undefined") {
1586
+ let filename = join(config.root, f);
1587
+ if (!fs.existsSync(filename))
1588
+ filename = join(config.publicDir, f);
1589
+ if (!fs.existsSync(filename))
1590
+ throw new Error(
1591
+ `ENOENT: Could not load manifest asset "${f}".
2983
1592
  Manifest assets must exist in one of these directories:
2984
1593
  Project root: "${config.root}"
2985
- Public dir: "${config.publicDir}"`);
2986
- this.emitFile({
1594
+ Public dir: "${config.publicDir}"`
1595
+ );
1596
+ this.emitFile({
1597
+ type: "asset",
1598
+ fileName: f,
1599
+ source: await readFile(filename)
1600
+ });
1601
+ }
1602
+ })
1603
+ );
1604
+ if (config.command === "serve" && files.html.length) {
1605
+ const refId2 = this.emitFile({
1606
+ type: "asset",
1607
+ name: "precontroller.js",
1608
+ source: precontrollerJs
1609
+ });
1610
+ const precontrollerJsName = this.getFileName(refId2);
1611
+ files.html.map(
1612
+ (f) => this.emitFile({
2987
1613
  type: "asset",
2988
1614
  fileName: f,
2989
- source: await readFile(filename)
2990
- });
2991
- }
2992
- }));
1615
+ source: precontrollerHtml.replace(
1616
+ "%SCRIPT%",
1617
+ `/${precontrollerJsName}`
1618
+ )
1619
+ })
1620
+ );
1621
+ }
2993
1622
  const manifestJson = bundle["manifest.json"];
2994
1623
  if (typeof manifestJson === "undefined") {
2995
1624
  this.emitFile({
@@ -3006,575 +1635,231 @@ Public dir: "${config.publicDir}"`);
3006
1635
  ];
3007
1636
  };
3008
1637
 
3009
- 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";
3010
-
3011
- 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";
3012
-
3013
- 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";
3014
-
3015
- function getScriptId({
3016
- format,
3017
- id
1638
+ function compileFileResources(fileName, {
1639
+ chunks,
1640
+ files,
1641
+ config
1642
+ }, resources = {
1643
+ assets: /* @__PURE__ */ new Set(),
1644
+ css: /* @__PURE__ */ new Set(),
1645
+ imports: /* @__PURE__ */ new Set()
3018
1646
  }) {
3019
- return crypto.createHash("sha1").update(format).update(id).digest("base64").replace(/[^A-Za-z0-9]/g, "").slice(0, 8);
3020
- }
3021
- const debug = _debug("content-scripts");
3022
- const dynamicResourcesName = "<dynamic_resource>";
3023
- const pluginResources = ({ contentScripts = {} }) => {
3024
- const { hmrTimeout = 5e3, injectCss = true } = contentScripts;
3025
- const dynamicScriptsById = /* @__PURE__ */ new Map();
3026
- const dynamicScriptsByLoaderRefId = /* @__PURE__ */ new Map();
3027
- const dynamicScriptsByRefId = /* @__PURE__ */ new Map();
3028
- const dynamicScriptsByScriptId = /* @__PURE__ */ new Map();
3029
- function emitDynamicScript(data) {
3030
- if (data.format === "iife") {
3031
- throw new Error(`Dynamic script format IIFE is unimplemented (imported in file: ${data.importer})`.trim());
3032
- } else {
3033
- data.refId = this.emitFile({ type: "chunk", id: data.id });
3034
- dynamicScriptsByRefId.set(data.refId, data);
3035
- }
3036
- if (data.format === "loader") {
3037
- data.loaderRefId = this.emitFile({
3038
- type: "asset",
3039
- name: `content-script-loader.${parse(data.id).name}.js`,
3040
- source: JSON.stringify(data)
3041
- });
3042
- dynamicScriptsByLoaderRefId.set(data.loaderRefId, data);
3043
- }
3044
- }
3045
- async function resolveDynamicScript(_source, importer) {
3046
- if (importer && _source.includes("?script")) {
3047
- const url = new URL(_source, "stub://stub");
3048
- if (url.searchParams.has("scriptId")) {
3049
- const scriptId = url.searchParams.get("scriptId");
3050
- const { finalId } = dynamicScriptsByScriptId.get(scriptId);
3051
- return finalId;
3052
- } else if (url.searchParams.has("script")) {
3053
- const [source] = _source.split("?");
3054
- const resolved = await this.resolve(source, importer, {
3055
- skipSelf: true
3056
- });
3057
- if (!resolved)
3058
- throw new Error(`Could not resolve dynamic script: "${_source}" from "${importer}"`);
3059
- const { id } = resolved;
3060
- let format = "loader";
3061
- if (url.searchParams.has("module")) {
3062
- format = "module";
3063
- } else if (url.searchParams.has("iife")) {
3064
- format = "iife";
3065
- }
3066
- const scriptId = getScriptId({ format, id });
3067
- const finalId = `${id}?scriptId=${scriptId}`;
3068
- const data = dynamicScriptsByScriptId.get(scriptId) ?? {
3069
- format,
3070
- id,
3071
- importer,
3072
- scriptId,
3073
- finalId
3074
- };
3075
- dynamicScriptsByScriptId.set(scriptId, data);
3076
- dynamicScriptsById.set(finalId, data);
3077
- return finalId;
1647
+ const chunk = chunks.get(fileName);
1648
+ if (chunk) {
1649
+ const { modules, facadeModuleId, imports, dynamicImports } = chunk;
1650
+ for (const x of imports)
1651
+ resources.imports.add(x);
1652
+ for (const x of dynamicImports)
1653
+ resources.imports.add(x);
1654
+ for (const x of [...imports, ...dynamicImports])
1655
+ compileFileResources(x, { chunks, files, config }, resources);
1656
+ for (const m of Object.keys(modules))
1657
+ if (m !== facadeModuleId) {
1658
+ const key = prefix$1("/", relative(config.root, m.split("?")[0]));
1659
+ const script = contentScripts.get(key);
1660
+ if (script)
1661
+ if (typeof script.fileName === "undefined") {
1662
+ throw new Error(`Content script fileName for ${m} is undefined`);
1663
+ } else {
1664
+ resources.imports.add(script.fileName);
1665
+ compileFileResources(
1666
+ script.fileName,
1667
+ { chunks, files, config },
1668
+ resources
1669
+ );
1670
+ }
3078
1671
  }
3079
- }
3080
1672
  }
3081
- function loadDynamicScript(id) {
3082
- const data = dynamicScriptsById.get(id);
3083
- if (data)
3084
- return `export default import.meta.CRX_DYNAMIC_SCRIPT_${data.scriptId};`;
1673
+ const file = files.get(fileName);
1674
+ if (file) {
1675
+ const { assets = [], css = [] } = file;
1676
+ for (const x of assets)
1677
+ resources.assets.add(x);
1678
+ for (const x of css)
1679
+ resources.css.add(x);
3085
1680
  }
3086
- let port;
3087
- let server;
3088
- let { preambleCode } = contentScripts;
3089
- let preambleRefId;
3090
- let contentClientRefId;
1681
+ return resources;
1682
+ }
1683
+
1684
+ const defineManifest = (manifest) => manifest;
1685
+ const defineDynamicResource = ({
1686
+ matches = ["http://*/*", "https://*/*"],
1687
+ use_dynamic_url = true
1688
+ }) => ({
1689
+ matches,
1690
+ resources: [DYNAMIC_RESOURCE],
1691
+ use_dynamic_url
1692
+ });
1693
+ const DYNAMIC_RESOURCE = "<dynamic_resource>";
1694
+
1695
+ _debug("web-acc-res");
1696
+ const pluginWebAccessibleResources = () => {
1697
+ let config;
1698
+ let injectCss;
3091
1699
  return [
3092
1700
  {
3093
- name: "crx:content-scripts-pre",
3094
- apply: "build",
3095
- enforce: "pre",
3096
- async fileWriterStart(_server) {
3097
- server = _server;
3098
- port = server.config.server.port.toString();
3099
- if (process.env.NODE_ENV !== "test" && typeof preambleCode === "undefined" && server.config.plugins.some(({ name }) => name.toLowerCase().includes("react"))) {
3100
- try {
3101
- const react = await Promise.resolve().then(function () { return /*#__PURE__*/_interopNamespace(require('@vitejs/plugin-react')); });
3102
- preambleCode = react.default.preambleCode;
3103
- } catch (error) {
3104
- preambleCode = false;
3105
- }
3106
- }
3107
- },
3108
- buildStart() {
3109
- if (this.meta.watchMode) {
3110
- if (preambleCode) {
3111
- preambleRefId = this.emitFile({
3112
- type: "chunk",
3113
- id: preambleId,
3114
- name: "content-script-preamble.js"
3115
- });
3116
- }
3117
- contentClientRefId = this.emitFile({
3118
- type: "chunk",
3119
- id: "/@vite/client",
3120
- name: "content-script-client.js"
3121
- });
3122
- }
3123
- },
3124
- resolveId(source) {
3125
- if (source === preambleId)
3126
- return preambleId;
3127
- if (source === contentHmrPortId)
3128
- return contentHmrPortId;
3129
- },
3130
- load(id) {
3131
- if (server && id === preambleId && typeof preambleCode === "string") {
3132
- const defined = preambleCode.replace(/__BASE__/g, server.config.base);
3133
- return defined;
3134
- }
3135
- if (id === contentHmrPortId) {
3136
- const defined = contentHmrPort.replace("__CRX_HMR_TIMEOUT__", JSON.stringify(hmrTimeout));
3137
- return defined;
3138
- }
3139
- }
3140
- },
3141
- {
3142
- name: "crx:dynamic-scripts-load",
1701
+ name: "crx:web-accessible-resources",
3143
1702
  apply: "serve",
3144
- enforce: "pre",
3145
- resolveId: resolveDynamicScript,
3146
- load: loadDynamicScript
3147
- },
3148
- {
3149
- name: "crx:dynamic-scripts-load",
3150
- apply: "build",
3151
- enforce: "pre",
3152
- resolveId(id, importer) {
3153
- if (!this.meta.watchMode)
3154
- return resolveDynamicScript.call(this, id, importer);
3155
- },
3156
- load(id) {
3157
- if (!this.meta.watchMode)
3158
- return loadDynamicScript.call(this, id);
1703
+ enforce: "post",
1704
+ renderCrxManifest(manifest) {
1705
+ manifest.web_accessible_resources = manifest.web_accessible_resources ?? [];
1706
+ manifest.web_accessible_resources = manifest.web_accessible_resources.map(({ resources, ...rest }) => ({
1707
+ resources: resources.filter((r) => r !== DYNAMIC_RESOURCE),
1708
+ ...rest
1709
+ })).filter(({ resources }) => resources.length);
1710
+ manifest.web_accessible_resources.push({
1711
+ use_dynamic_url: true,
1712
+ matches: ["<all_urls>"],
1713
+ resources: ["**/*", "*"]
1714
+ });
1715
+ return manifest;
3159
1716
  }
3160
1717
  },
3161
1718
  {
3162
- name: "crx:dynamic-scripts-build",
1719
+ name: "crx:web-accessible-resources",
3163
1720
  apply: "build",
3164
- buildStart() {
3165
- dynamicScriptsByLoaderRefId.clear();
3166
- dynamicScriptsByRefId.clear();
3167
- for (const [, data] of dynamicScriptsByScriptId) {
3168
- emitDynamicScript.call(this, data);
3169
- }
3170
- },
3171
- async transform(code) {
3172
- if (code.includes("import.meta.CRX_DYNAMIC_SCRIPT_")) {
3173
- const match = code.match(/import.meta.CRX_DYNAMIC_SCRIPT_(.+?);/);
3174
- const index = match.index;
3175
- const [statement, scriptId] = match;
3176
- const data = dynamicScriptsByScriptId.get(scriptId);
3177
- if (!data.refId)
3178
- emitDynamicScript.call(this, data);
3179
- const magic = new MagicString__default["default"](code);
3180
- magic.overwrite(index, index + statement.length, `import.meta.ROLLUP_FILE_URL_${data.loaderRefId ?? data.refId};`);
3181
- return { code: magic.toString(), map: magic.generateMap() };
3182
- }
3183
- },
3184
- resolveFileUrl({ referenceId, fileName, moduleId }) {
3185
- if (moduleId && referenceId) {
3186
- if (dynamicScriptsByRefId.has(referenceId) || dynamicScriptsByLoaderRefId.has(referenceId)) {
3187
- return `"/${fileName}"`;
3188
- }
3189
- }
1721
+ enforce: "post",
1722
+ async config({ build, ...config2 }, { command }) {
1723
+ const { contentScripts: contentScripts2 = {} } = await getOptions(config2);
1724
+ injectCss = contentScripts2.injectCss ?? true;
1725
+ return { ...config2, build: { ...build, manifest: command === "build" } };
3190
1726
  },
3191
- generateBundle(options, bundle) {
3192
- const preambleName = this.meta.watchMode && preambleRefId ? this.getFileName(preambleRefId) : "";
3193
- const contentClientName = this.meta.watchMode && contentClientRefId ? this.getFileName(contentClientRefId) : "";
3194
- for (const data of dynamicScriptsByScriptId.values()) {
3195
- if (data.refId && data.loaderRefId) {
3196
- const scriptName = this.getFileName(data.refId);
3197
- const loaderName = this.getFileName(data.loaderRefId);
3198
- 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));
3199
- const asset = bundle[loaderName];
3200
- if (asset?.type === "asset")
3201
- asset.source = source;
3202
- }
3203
- }
1727
+ configResolved(_config) {
1728
+ config = _config;
3204
1729
  },
3205
- writeBundle() {
3206
- for (const [, data] of dynamicScriptsByScriptId) {
3207
- if (data.refId) {
3208
- data.fileName = this.getFileName(data.refId);
3209
- delete data.refId;
3210
- }
3211
- if (data.loaderRefId) {
3212
- data.loaderName = this.getFileName(data.loaderRefId);
3213
- delete data.loaderRefId;
3214
- }
3215
- }
3216
- }
3217
- },
3218
- {
3219
- name: "crx:dynamic-scripts-serve",
3220
- apply: "serve",
3221
- configureServer(server2) {
3222
- server2.middlewares.use(injector__default["default"]((req) => {
3223
- return !!req.url?.includes("?scriptId");
3224
- }, async (content, req, res, callback) => {
3225
- const code = isString(content) ? content : content.toString();
3226
- if (code.includes("import.meta.CRX_DYNAMIC_SCRIPT_")) {
3227
- const matches = Array.from(code.matchAll(/import.meta.CRX_DYNAMIC_SCRIPT_(.+?);/g)).map((m) => ({
3228
- statement: m[0],
3229
- index: m.index,
3230
- data: dynamicScriptsByScriptId.get(m[1])
3231
- }));
3232
- if (matches.some(({ data }) => data.refId))
3233
- await filesReady();
3234
- if (matches.some(({ data }) => !(data.loaderName ?? data.fileName))) {
3235
- await rebuildFiles();
3236
- server2.ws.send(crxRuntimeReload);
3237
- }
3238
- const magic = new MagicString__default["default"](code);
3239
- for (const { index, statement, data } of matches)
3240
- if (typeof index === "number") {
3241
- magic.overwrite(index, index + statement.length, `"/${data.loaderName ?? data.fileName}"`);
3242
- }
3243
- callback(null, magic.toString());
3244
- } else {
3245
- callback(null, code);
1730
+ async renderCrxManifest(manifest, bundle) {
1731
+ const { web_accessible_resources: _war = [] } = manifest;
1732
+ const dynamicScriptMatches = /* @__PURE__ */ new Set();
1733
+ let dynamicScriptDynamicUrl = false;
1734
+ const web_accessible_resources = [];
1735
+ for (const r of _war) {
1736
+ const i = r.resources.indexOf(DYNAMIC_RESOURCE);
1737
+ if (i > -1 && isResourceByMatch(r)) {
1738
+ r.resources = [...r.resources];
1739
+ r.resources.splice(i, 1);
1740
+ for (const p of r.matches)
1741
+ dynamicScriptMatches.add(p);
1742
+ dynamicScriptDynamicUrl = r.use_dynamic_url ?? false;
3246
1743
  }
3247
- }));
3248
- }
3249
- },
3250
- {
3251
- name: "crx:content-script-resources",
3252
- apply: "build",
3253
- enforce: "post",
3254
- config({ build, ...config }, { command }) {
3255
- return { ...config, build: { ...build, manifest: command === "build" } };
3256
- },
3257
- renderCrxManifest(manifest, bundle) {
3258
- manifest.web_accessible_resources = manifest.web_accessible_resources ?? [];
3259
- if (manifest.content_scripts?.length || dynamicScriptsByRefId.size)
3260
- if (this.meta.watchMode) {
3261
- manifest.web_accessible_resources = manifest.web_accessible_resources.map(({ resources, ...rest }) => ({
3262
- resources: resources.filter((r) => r !== dynamicResourcesName),
3263
- ...rest
3264
- })).filter(({ resources }) => resources.length);
3265
- manifest.web_accessible_resources.push({
3266
- use_dynamic_url: true,
3267
- matches: ["<all_urls>"],
3268
- resources: ["**/*", "*"]
3269
- });
3270
- } else {
3271
- const vmAsset = bundle["manifest.json"];
3272
- if (!vmAsset)
3273
- throw new Error("vite manifest is missing");
3274
- const viteManifest = JSON.parse(vmAsset.source);
3275
- debug("vite manifest %O", viteManifest);
3276
- if (Object.keys(viteManifest).length === 0)
3277
- return;
3278
- const filesByName = /* @__PURE__ */ new Map();
3279
- for (const file of Object.values(viteManifest))
3280
- filesByName.set(file.file, file);
3281
- const chunksById = /* @__PURE__ */ new Map();
3282
- for (const [name, chunk] of Object.entries(bundle))
3283
- if (chunk.type === "chunk" && chunk.facadeModuleId)
3284
- chunksById.set(chunk.facadeModuleId, name);
3285
- const getChunkResources = (chunk) => {
3286
- const chunks = /* @__PURE__ */ new Set();
3287
- const assets = /* @__PURE__ */ new Set();
3288
- if (chunk.type === "asset")
3289
- return { chunks, assets };
3290
- const { dynamicImports, imports, modules } = chunk;
3291
- for (const i of dynamicImports)
3292
- chunks.add(i);
3293
- for (const i of imports)
3294
- chunks.add(i);
3295
- for (const id of Object.keys(modules))
3296
- if (dynamicScriptsById.has(id)) {
3297
- const data = dynamicScriptsById.get(id);
3298
- const fileName = this.getFileName(data.refId);
3299
- const chunk2 = bundle[fileName];
3300
- if (chunk2.type === "chunk")
3301
- chunks.add(fileName);
3302
- else
3303
- assets.add(fileName);
3304
- }
3305
- return { chunks, assets };
3306
- };
3307
- const getResources = (name, sets = {
3308
- assets: /* @__PURE__ */ new Set(),
3309
- css: /* @__PURE__ */ new Set(),
3310
- imports: /* @__PURE__ */ new Set()
3311
- }) => {
3312
- const {
3313
- assets = [],
3314
- css = [],
3315
- dynamicImports = [],
3316
- imports = [],
3317
- file
3318
- } = filesByName.get(name) ?? viteManifest[name] ?? {};
3319
- const chunk = bundle[file];
3320
- if (chunk?.type === "chunk") {
3321
- const r = getChunkResources(chunk);
3322
- assets.push(...r.assets);
3323
- for (const chunk2 of r.chunks) {
3324
- sets.imports.add(chunk2);
3325
- getResources(chunk2, sets);
3326
- }
3327
- }
3328
- for (const a of assets)
3329
- sets.assets.add(a);
3330
- for (const c of css)
3331
- sets.css.add(c);
3332
- for (const key of [...dynamicImports, ...imports]) {
3333
- const i = viteManifest[key].file;
3334
- sets.imports.add(i);
3335
- getResources(key, sets);
3336
- }
3337
- return sets;
3338
- };
3339
- for (const script of manifest.content_scripts ?? [])
3340
- if (script.js?.length) {
3341
- for (const name of script.js)
3342
- if (script.matches?.length) {
3343
- const { assets, css, imports } = getResources(name);
3344
- imports.add(name);
3345
- const resource = {
3346
- matches: script.matches,
3347
- resources: [...assets, ...imports],
3348
- use_dynamic_url: true
3349
- };
3350
- if (css.size)
3351
- if (injectCss) {
3352
- script.css = script.css ?? [];
3353
- script.css.push(...css);
3354
- } else {
3355
- resource.resources.push(...css);
3356
- }
3357
- if (resource.resources.length) {
3358
- resource.matches = resource.matches.map(stubMatchPattern);
3359
- manifest.web_accessible_resources.push(resource);
3360
- }
1744
+ if (r.resources.length > 0)
1745
+ web_accessible_resources.push(r);
1746
+ }
1747
+ if (dynamicScriptMatches.size === 0) {
1748
+ dynamicScriptMatches.add("http://*/*");
1749
+ dynamicScriptMatches.add("https://*/*");
1750
+ }
1751
+ if (contentScripts.size > 0) {
1752
+ const viteManifest = parseJsonAsset(
1753
+ bundle,
1754
+ "manifest.json"
1755
+ );
1756
+ const viteFiles = /* @__PURE__ */ new Map();
1757
+ for (const [, file] of Object.entries(viteManifest))
1758
+ viteFiles.set(file.file, file);
1759
+ if (viteFiles.size === 0)
1760
+ return null;
1761
+ const bundleChunks = /* @__PURE__ */ new Map();
1762
+ for (const chunk of Object.values(bundle))
1763
+ if (chunk.type === "chunk")
1764
+ bundleChunks.set(chunk.fileName, chunk);
1765
+ const moduleScriptResources = /* @__PURE__ */ new Map();
1766
+ for (const [
1767
+ key,
1768
+ { id, fileName, matches, type, isDynamicScript = false }
1769
+ ] of contentScripts)
1770
+ if (key === id) {
1771
+ if (isDynamicScript || matches.length)
1772
+ if (typeof fileName === "undefined") {
1773
+ throw new Error(
1774
+ `Content script filename is undefined for "${id}"`
1775
+ );
1776
+ } else {
1777
+ const { assets, css, imports } = compileFileResources(
1778
+ fileName,
1779
+ { chunks: bundleChunks, files: viteFiles, config }
1780
+ );
1781
+ contentScripts.get(key).css = [...css];
1782
+ if (type === "loader")
1783
+ imports.add(fileName);
1784
+ const resource = {
1785
+ matches: isDynamicScript ? [...dynamicScriptMatches] : matches,
1786
+ resources: [...assets, ...imports],
1787
+ use_dynamic_url: isDynamicScript ? dynamicScriptDynamicUrl : true
1788
+ };
1789
+ if (isDynamicScript || !injectCss) {
1790
+ resource.resources.push(...css);
3361
1791
  }
3362
- }
3363
- const dynamicResourceSet = /* @__PURE__ */ new Set();
3364
- for (const [refId, { format }] of dynamicScriptsByRefId)
3365
- if (format === "loader") {
3366
- const name = this.getFileName(refId);
3367
- const { assets, css, imports } = getResources(name);
3368
- dynamicResourceSet.add(name);
3369
- for (const a of assets)
3370
- dynamicResourceSet.add(a);
3371
- for (const c of css)
3372
- dynamicResourceSet.add(c);
3373
- for (const i of imports)
3374
- dynamicResourceSet.add(i);
3375
- }
3376
- if (dynamicResourceSet.size) {
3377
- let resource = manifest.web_accessible_resources.find(({ resources: [r] }) => r === dynamicResourcesName);
3378
- if (!resource) {
3379
- resource = {
3380
- resources: [dynamicResourcesName],
3381
- matches: ["http://*/*", "https://*/*"]
3382
- };
3383
- manifest.web_accessible_resources.push(resource);
3384
- }
3385
- resource.resources = [...dynamicResourceSet];
1792
+ if (resource.resources.length)
1793
+ if (type === "module") {
1794
+ moduleScriptResources.set(fileName, resource);
1795
+ } else {
1796
+ resource.matches = resource.matches.map(
1797
+ getMatchPatternOrigin
1798
+ );
1799
+ web_accessible_resources.push(resource);
1800
+ }
1801
+ }
3386
1802
  }
1803
+ for (const r of web_accessible_resources)
1804
+ if (isResourceByMatch(r))
1805
+ for (const res of r.resources)
1806
+ moduleScriptResources.delete(res);
1807
+ web_accessible_resources.push(...moduleScriptResources.values());
1808
+ }
1809
+ const hashedResources = /* @__PURE__ */ new Map();
1810
+ const combinedResources = [];
1811
+ for (const r of web_accessible_resources)
1812
+ if (isResourceByMatch(r)) {
1813
+ const { matches, resources, use_dynamic_url = false } = r;
1814
+ const key = JSON.stringify([use_dynamic_url, matches.sort()]);
1815
+ const combined = hashedResources.get(key) ?? /* @__PURE__ */ new Set();
1816
+ for (const res of resources)
1817
+ combined.add(res);
1818
+ hashedResources.set(key, combined);
1819
+ } else {
1820
+ combinedResources.push(r);
3387
1821
  }
3388
- if (manifest.web_accessible_resources?.length) {
3389
- const war = manifest.web_accessible_resources;
3390
- manifest.web_accessible_resources = [];
3391
- const map = /* @__PURE__ */ new Map();
3392
- for (const r of war)
3393
- if (isResourceByMatch(r)) {
3394
- const { matches, resources, use_dynamic_url = false } = r;
3395
- const key = [use_dynamic_url, matches.sort()].map((x) => JSON.stringify(x)).join("::");
3396
- const set = map.get(key) ?? /* @__PURE__ */ new Set();
3397
- resources.forEach((r2) => set.add(r2));
3398
- map.set(key, set);
3399
- } else {
3400
- manifest.web_accessible_resources.push(r);
3401
- }
3402
- for (const [key, set] of map) {
3403
- const [use_dynamic_url, matches] = key.split("::").map((x) => JSON.parse(x));
3404
- manifest.web_accessible_resources.push({
1822
+ for (const [key, resources] of hashedResources)
1823
+ if (resources.size > 0) {
1824
+ const [use_dynamic_url, matches] = JSON.parse(key);
1825
+ combinedResources.push({
3405
1826
  matches,
3406
- resources: [...set],
1827
+ resources: [...resources],
3407
1828
  use_dynamic_url
3408
1829
  });
3409
1830
  }
3410
- } else {
1831
+ if (combinedResources.length === 0)
3411
1832
  delete manifest.web_accessible_resources;
3412
- }
3413
- return manifest;
3414
- }
3415
- },
3416
- {
3417
- name: "crx:content-scripts-post",
3418
- apply: "build",
3419
- enforce: "post",
3420
- renderCrxManifest(manifest, bundle) {
3421
- if (this.meta.watchMode && typeof port === "undefined")
3422
- throw new Error("server port is undefined");
3423
- const preambleName = this.meta.watchMode && preambleRefId ? this.getFileName(preambleRefId) : "";
3424
- const contentClientName = this.meta.watchMode && contentClientRefId ? this.getFileName(contentClientRefId) : "";
3425
- if (!manifest.content_scripts?.length && !dynamicScriptsByRefId.size) {
3426
- delete bundle[contentClientName];
3427
- return manifest;
3428
- }
3429
- manifest.content_scripts = manifest.content_scripts?.map(({ js, ...rest }) => ({
3430
- js: js?.map((f) => {
3431
- const name = `content-script-loader.${parse(f).name}.js`;
3432
- 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));
3433
- const refId = this.emitFile({
3434
- type: "asset",
3435
- name,
3436
- source
3437
- });
3438
- return this.getFileName(refId);
3439
- }),
3440
- ...rest
3441
- }));
1833
+ else
1834
+ manifest.web_accessible_resources = combinedResources;
3442
1835
  return manifest;
3443
1836
  }
3444
1837
  }
3445
1838
  ];
3446
1839
  };
3447
1840
 
3448
- 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";
3449
-
3450
- function defineClientValues(code, config) {
3451
- let options = config.server.hmr;
3452
- options = options && typeof options !== "boolean" ? options : {};
3453
- const host = options.host || null;
3454
- const protocol = options.protocol || null;
3455
- const timeout = options.timeout || 3e4;
3456
- const overlay = options.overlay !== false;
3457
- let hmrPort;
3458
- if (isObject(config.server.hmr)) {
3459
- hmrPort = config.server.hmr.clientPort || config.server.hmr.port;
3460
- }
3461
- if (config.server.middlewareMode) {
3462
- hmrPort = String(hmrPort || 24678);
3463
- } else {
3464
- hmrPort = String(hmrPort || options.port || config.server.port);
3465
- }
3466
- let hmrBase = config.base;
3467
- if (options.path) {
3468
- hmrBase = join(hmrBase, options.path);
3469
- }
3470
- if (hmrBase !== "/") {
3471
- hmrPort = normalize(`${hmrPort}${hmrBase}`);
3472
- }
3473
- 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()));
3474
- function serializeDefine(define) {
3475
- let res = `{`;
3476
- for (const key in define) {
3477
- const val = define[key];
3478
- res += `${JSON.stringify(key)}: ${typeof val === "string" ? `(${val})` : JSON.stringify(val)}, `;
3479
- }
3480
- return res + `}`;
3481
- }
3482
- }
3483
-
3484
- const pluginBackground = () => {
3485
- let port;
3486
- let server;
1841
+ const crx = (options) => {
3487
1842
  return [
3488
- {
3489
- name: "crx:background-client",
3490
- apply: "serve",
3491
- configureServer(_server) {
3492
- server = _server;
3493
- },
3494
- resolveId(source) {
3495
- if (source === `/${workerClientId}`)
3496
- return workerClientId;
3497
- },
3498
- load(id) {
3499
- if (id === workerClientId) {
3500
- const base = `http://localhost:${server.config.server.port}/`;
3501
- return defineClientValues(workerHmrClient.replace("__BASE__", JSON.stringify(base)), server.config);
3502
- }
3503
- }
3504
- },
3505
- {
3506
- name: "crx:background-loader-file",
3507
- apply: "build",
3508
- enforce: "post",
3509
- fileWriterStart(server2) {
3510
- port = server2.config.server.port.toString();
3511
- },
3512
- renderCrxManifest(manifest) {
3513
- const worker = manifest.background?.service_worker;
3514
- let loader;
3515
- if (this.meta.watchMode) {
3516
- if (typeof port === "undefined")
3517
- throw new Error("server port is undefined in watch mode");
3518
- loader = `import 'http:/localhost:${port}/@vite/env';
3519
- `;
3520
- loader += `import 'http://localhost:${port}${workerClientId}';
3521
- `;
3522
- if (worker)
3523
- loader += `import 'http://localhost:${port}/${worker}';
3524
- `;
3525
- } else if (worker) {
3526
- loader = `import './${worker}';
3527
- `;
3528
- } else {
3529
- return null;
3530
- }
3531
- const refId = this.emitFile({
3532
- type: "asset",
3533
- fileName: "service-worker-loader.js",
3534
- source: loader
3535
- });
3536
- manifest.background = {
3537
- service_worker: this.getFileName(refId),
3538
- type: "module"
3539
- };
3540
- return manifest;
3541
- }
3542
- }
3543
- ];
3544
- };
3545
-
3546
- const defineManifest = (manifest) => manifest;
3547
- const defineDynamicResource = ({
3548
- matches = ["http://*/*", "https://*/*"],
3549
- use_dynamic_url = true
3550
- }) => ({
3551
- matches,
3552
- resources: [dynamicResourcesName],
3553
- use_dynamic_url
3554
- });
3555
-
3556
- function init(options, plugins) {
3557
- return plugins.map((p) => p?.(options)).flat().filter((p) => !!p && typeof p.name === "string");
3558
- }
3559
- const crx = ({
3560
- manifest,
3561
- ...options
3562
- }) => {
3563
- const plugins = init(options, [
3564
- pluginHMR,
3565
- pluginHtmlAuditor,
3566
- pluginResources,
3567
- pluginBackground,
3568
- pluginManifest(manifest)
3569
- ]);
3570
- plugins.unshift(...init(options, [pluginFileWriter(plugins)]));
3571
- return plugins;
1843
+ pluginOptionsProvider(options),
1844
+ pluginBackground(),
1845
+ pluginContentScripts(),
1846
+ pluginDeclaredContentScripts(),
1847
+ pluginDynamicContentScripts(),
1848
+ pluginFileWriter(),
1849
+ pluginFileWriterPublic(),
1850
+ pluginFileWriterPolyfill(),
1851
+ pluginHtmlInlineScripts(),
1852
+ pluginWebAccessibleResources(),
1853
+ pluginContentScriptsCss(),
1854
+ pluginHMR(),
1855
+ pluginManifest()
1856
+ ].flat();
3572
1857
  };
3573
1858
  const chromeExtension = crx;
3574
1859
 
1860
+ exports.allFilesReady = allFilesReady;
3575
1861
  exports.chromeExtension = chromeExtension;
3576
1862
  exports.crx = crx;
3577
1863
  exports.defineDynamicResource = defineDynamicResource;
3578
1864
  exports.defineManifest = defineManifest;
3579
- exports.filesReady = filesReady;
3580
- exports.rebuildFiles = rebuildFiles;
1865
+ exports.filesReady = fileReady;