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