@crxjs/vite-plugin
Version:
Build Chrome Extensions with this Vite plugin.
1,382 lines (1,334 loc) • 132 kB
JavaScript
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var rollup = require('rollup');
var acornWalk = require('acorn-walk');
var crypto = require('crypto');
var debug$5 = require('debug');
var fg = require('fast-glob');
var v8 = require('v8');
var fs = require('fs');
var MagicString = require('magic-string');
var path = require('path');
var fsExtra = require('fs-extra');
var perf_hooks = require('perf_hooks');
var colors = require('picocolors');
var vite = require('vite');
var module$1 = require('module');
var cheerio = require('cheerio');
var jsesc = require('jsesc');
var injector = require('connect-injector');
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
function _interopNamespace(e) {
if (e && e.__esModule) return e;
var n = Object.create(null);
if (e) {
Object.keys(e).forEach(function (k) {
if (k !== 'default') {
var d = Object.getOwnPropertyDescriptor(e, k);
Object.defineProperty(n, k, d.get ? d : {
enumerable: true,
get: function () { return e[k]; }
});
}
});
}
n["default"] = e;
return Object.freeze(n);
}
var debug__default = /*#__PURE__*/_interopDefaultLegacy(debug$5);
var fg__default = /*#__PURE__*/_interopDefaultLegacy(fg);
var v8__default = /*#__PURE__*/_interopDefaultLegacy(v8);
var MagicString__default = /*#__PURE__*/_interopDefaultLegacy(MagicString);
var fsExtra__default = /*#__PURE__*/_interopDefaultLegacy(fsExtra);
var colors__default = /*#__PURE__*/_interopDefaultLegacy(colors);
var jsesc__default = /*#__PURE__*/_interopDefaultLegacy(jsesc);
var injector__default = /*#__PURE__*/_interopDefaultLegacy(injector);
const _debug = (id) => debug__default["default"]("crx").extend(id);
const structuredClone = (obj) => {
return v8__default["default"].deserialize(v8__default["default"].serialize(obj));
};
const createHash = (data, length = 5) => crypto.createHash("sha1").update(data).digest("base64").replace(/[^A-Za-z0-9]/g, "").slice(0, length);
const isString = (x) => typeof x === "string";
const isTruthy = (x) => !!x;
function isObject(value) {
return Object.prototype.toString.call(value) === "[object Object]";
}
const isResourceByMatch = (x) => "matches" in x;
async function manifestFiles(manifest, options = {}) {
let locales = [];
if (manifest.default_locale)
locales = await fg__default["default"]("_locales/**/messages.json", options);
const rulesets = manifest.declarative_net_request?.rule_resources.flatMap(({ path }) => path) ?? [];
const contentScripts = manifest.content_scripts?.flatMap(({ js }) => js) ?? [];
const contentStyles = manifest.content_scripts?.flatMap(({ css }) => css);
const serviceWorker = manifest.background?.service_worker;
const htmlPages = htmlFiles(manifest);
const icons = [
Object.values(isString(manifest.icons) ? [manifest.icons] : manifest.icons ?? {}),
Object.values(isString(manifest.action?.default_icon) ? [manifest.action?.default_icon] : manifest.action?.default_icon ?? {})
].flat();
let webAccessibleResources = [];
if (manifest.web_accessible_resources) {
const resources = await Promise.all(manifest.web_accessible_resources.flatMap(({ resources: resources2 }) => resources2).map(async (r) => {
if (["*", "**/*"].includes(r))
return void 0;
if (fg__default["default"].isDynamicPattern(r))
return fg__default["default"](r, options);
return r;
}));
webAccessibleResources = resources.flat().filter(isString);
}
return {
contentScripts: [...new Set(contentScripts)].filter(isString),
contentStyles: [...new Set(contentStyles)].filter(isString),
html: htmlPages,
icons: [...new Set(icons)].filter(isString),
locales: [...new Set(locales)].filter(isString),
rulesets: [...new Set(rulesets)].filter(isString),
background: [serviceWorker].filter(isString),
webAccessibleResources
};
}
function htmlFiles(manifest) {
const files = [
manifest.action?.default_popup,
Object.values(manifest.chrome_url_overrides ?? {}),
manifest.devtools_page,
manifest.options_page,
manifest.options_ui?.page,
manifest.sandbox?.pages
].flat().filter(isString).map((s) => s.split("#")[0]).sort();
return [...new Set(files)];
}
function decodeManifest(code) {
const tree = this.parse(code);
let literal;
let templateElement;
acornWalk.simple(tree, {
Literal(node) {
literal = node;
},
TemplateElement(node) {
templateElement = node;
}
});
let manifestJson = literal?.value;
if (!manifestJson)
manifestJson = templateElement?.value?.cooked;
if (!manifestJson)
throw new Error("unable to parse manifest code");
let result = JSON.parse(manifestJson);
if (typeof result === "string")
result = JSON.parse(result);
return result;
}
function encodeManifest(manifest) {
const json = JSON.stringify(JSON.stringify(manifest));
return `export default ${json}`;
}
const stubMatchPattern = (pattern) => {
if (pattern === "<all_urls>") {
return pattern;
}
const [schema, rest] = pattern.split("://");
const [origin, pathname] = rest.split("/");
const root = `${schema}://${origin}`;
return pathname ? `${root}/*` : root;
};
const idBySource = /* @__PURE__ */ new Map();
const idByUrl = /* @__PURE__ */ new Map();
const urlById = /* @__PURE__ */ new Map();
function setUrlMeta({
id,
source,
url
}) {
idBySource.set(source, id);
idByUrl.set(url, id);
urlById.set(id, url);
}
const fileById = /* @__PURE__ */ new Map();
const fileByUrl = /* @__PURE__ */ new Map();
const pathById = /* @__PURE__ */ new Map();
const pathByUrl = /* @__PURE__ */ new Map();
const setFileMeta = ({ file, id }) => {
const url = urlById.get(id);
if (!url)
return;
fileById.set(id, file);
fileByUrl.set(url, file);
const pathName = `/${file}`;
pathById.set(id, pathName);
pathByUrl.set(url, pathName);
};
const ownerById = /* @__PURE__ */ new Map();
const pathByOwner = /* @__PURE__ */ new Map();
const ownersByFile = /* @__PURE__ */ new Map();
const setOwnerMeta = ({ owner, id }) => {
const pathName = pathById.get(id);
if (!pathName)
return;
pathByOwner.set(owner, pathName);
ownerById.set(id, owner);
const fileName = fileById.get(id);
const owners = ownersByFile.get(fileName) ?? /* @__PURE__ */ new Set();
owners.add(owner);
ownersByFile.set(fileName, owners);
};
const outputById = /* @__PURE__ */ new Map();
const outputByOwner = /* @__PURE__ */ new Map();
const setOutputMeta = ({
output,
id
}) => {
const ownerName = ownerById.get(id);
if (!ownerName)
return;
outputByOwner.set(ownerName, output);
outputById.set(id, output);
};
const transformResultByOwner = /* @__PURE__ */ new Map();
const {
basename,
dirname,
extname,
delimiter,
format,
isAbsolute,
join,
normalize,
parse,
relative,
resolve,
toNamespacedPath,
sep
} = path.posix;
const viteClientId = "/@vite/client";
const customElementsId = "@webcomponents/custom-elements";
const reactRefreshId = "/@react-refresh";
const contentHmrPortId = "/crx-client-port";
const manifestId = "/crx-manifest";
const preambleId = "/crx-client-preamble";
const stubId = "/crx-stub";
const workerClientId = "/crx-client-worker";
const { readFile: readFile$2 } = fs.promises;
const debug$4 = _debug("file-writer").extend("chunks");
for (const source of [viteClientId, customElementsId]) {
setUrlMeta(sourceToUrlMeta(source));
}
setUrlMeta({
source: reactRefreshId,
id: "/react-refresh",
url: reactRefreshId
});
function sourceToUrlMeta(source) {
const [p, query = ""] = source.split("?");
const pathname = p.replace(/^\/@id\//, "").replace(/^\/@fs/, "");
const url = [pathname, query].filter(isTruthy).join("?");
const hash = createHash(url);
const base = p.split("/").slice(-4).filter(isTruthy).join("-");
const id = `/${base}-${hash}.js`.replace(/[@]/g, "");
return { id, url, source };
}
const pluginFileWriterChunks = () => {
let server;
return {
name: "crx:file-writer-chunks",
apply: "build",
fileWriterStart(_server) {
server = _server;
},
async resolveId(source, importer) {
if (this.meta.watchMode) {
if (idBySource.has(source)) {
const id = idBySource.get(source);
debug$4(`resolved cached ${source} -> ${id}`);
return id;
} else if (importer) {
const meta = sourceToUrlMeta(source);
setUrlMeta(meta);
const { id } = meta;
debug$4(`resolved ${source} -> ${id}`);
return id;
} else {
const [rawUrl] = await server.moduleGraph.resolveUrl(source);
const name = rawUrl.split("/").join("-").replace(/^-/, "");
const url = rawUrl.startsWith("/") ? rawUrl : `/${rawUrl}`;
const id = `/${name}-${createHash(url)}.js`;
setUrlMeta({ url, id, source });
debug$4(`resolved entry ${source} -> ${id}`);
return id;
}
}
},
async load(id) {
if (this.meta.watchMode && urlById.has(id)) {
const url = urlById.get(id);
let serverModule = await server.moduleGraph.getModuleByUrl(url);
let transformResult = null;
if (!serverModule) {
transformResult = await server.transformRequest(url);
serverModule = await server.moduleGraph.getModuleByUrl(url);
}
if (!serverModule)
throw new Error(`Unable to load "${url}" from server.`);
const { file, url: owner } = serverModule;
transformResult = transformResult ?? transformResultByOwner.get(owner) ?? serverModule.transformResult;
if (!transformResult)
transformResult = await server.transformRequest(url);
if (!transformResult)
throw new TypeError(`Unable to load "${url}" from server.`);
transformResultByOwner.set(owner, transformResult);
if (file) {
setFileMeta({ id, file });
this.addWatchFile(file);
if (urlById.get(id).includes("?import"))
this.emitFile({
type: "asset",
fileName: relative(server.config.root, file),
source: await readFile$2(file)
});
}
if (url)
setOwnerMeta({ id, owner });
return { code: transformResult.code, map: transformResult.map };
}
return null;
},
outputOptions(options) {
const cacheDir = relative(server.config.root, server.config.cacheDir);
const fileNameById = /* @__PURE__ */ new Map();
fileNameById.set("/react-refresh", "vendor/react-refresh.js");
function fileNames(info) {
const id = info.type === "chunk" ? info.facadeModuleId : info.name;
if (id && fileNameById.has(id))
return fileNameById.get(id);
let fileName = info.type === "chunk" ? "assets/[name].js" : "assets/[name].[ext]";
if (id && fileById.has(id)) {
fileName = fileById.get(id);
const url = new URL(urlById.get(id), "stub://stub");
if (url.searchParams.has("type"))
fileName += `.${url.searchParams.get("type")}`;
if (url.searchParams.has("index"))
fileName += `.${url.searchParams.get("index")}`;
}
if (id?.startsWith("/@crx/"))
fileName = `vendor/${id.slice("/@crx/".length).split("/").join("-")}`;
if (fileName.startsWith(server.config.root))
fileName = fileName.slice(server.config.root.length + 1);
if (fileName.startsWith(cacheDir))
fileName = `vendor/${fileName.slice(cacheDir.length + 1)}`;
if (fileName.includes("/node_modules/"))
fileName = `vendor/${fileName.split("/node_modules/").pop().split("/").join("-").replace("vite-dist-client", "vite")}`;
if (fileName.startsWith("/"))
fileName = fileName.slice(1);
if (!fileName.endsWith(".js"))
fileName += ".js";
if (id)
fileNameById.set(id, fileName);
fileName = fileName.replace(/:/g, "-").replace(/@/, "");
return fileName;
}
return {
...options,
preserveModules: true,
assetFileNames: fileNames,
entryFileNames: fileNames
};
},
generateBundle(options, bundle) {
for (const chunk of Object.values(bundle))
if (chunk.type === "chunk") {
const { facadeModuleId: id, modules, code, fileName } = chunk;
if (!id || Object.keys(modules).length !== 1)
continue;
const url = urlById.get(id);
if (url === viteClientId)
continue;
const ownerPath = ownerById.get(id);
if (!ownerPath)
continue;
const index = code.indexOf("createHotContext(");
if (index === -1)
continue;
const start = code.indexOf(ownerPath, index);
const end = start + ownerPath.length;
if (start > 0) {
const outputName = `/${fileName}`;
setOutputMeta({ id, output: outputName });
const magic = new MagicString__default["default"](code);
magic.overwrite(start, end, outputName);
chunk.code = magic.toString();
}
}
}
};
};
/******************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise */
var extendStatics = function(d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
function __extends(d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
function __awaiter(thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
function __generator(thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
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;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
}
function __values(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
function __read(o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
}
function __spreadArray(to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
}
function __await(v) {
return this instanceof __await ? (this.v = v, this) : new __await(v);
}
function __asyncGenerator(thisArg, _arguments, generator) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var g = generator.apply(thisArg, _arguments || []), i, q = [];
return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
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); }); }; }
function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
function fulfill(value) { resume("next", value); }
function reject(value) { resume("throw", value); }
function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
}
function __asyncValues(o) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var m = o[Symbol.asyncIterator], i;
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);
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); }); }; }
function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
}
function isFunction(value) {
return typeof value === 'function';
}
function createErrorClass(createImpl) {
var _super = function (instance) {
Error.call(instance);
instance.stack = new Error().stack;
};
var ctorFunc = createImpl(_super);
ctorFunc.prototype = Object.create(Error.prototype);
ctorFunc.prototype.constructor = ctorFunc;
return ctorFunc;
}
var UnsubscriptionError = createErrorClass(function (_super) {
return function UnsubscriptionErrorImpl(errors) {
_super(this);
this.message = errors
? errors.length + " errors occurred during unsubscription:\n" + errors.map(function (err, i) { return i + 1 + ") " + err.toString(); }).join('\n ')
: '';
this.name = 'UnsubscriptionError';
this.errors = errors;
};
});
function arrRemove(arr, item) {
if (arr) {
var index = arr.indexOf(item);
0 <= index && arr.splice(index, 1);
}
}
var Subscription = (function () {
function Subscription(initialTeardown) {
this.initialTeardown = initialTeardown;
this.closed = false;
this._parentage = null;
this._finalizers = null;
}
Subscription.prototype.unsubscribe = function () {
var e_1, _a, e_2, _b;
var errors;
if (!this.closed) {
this.closed = true;
var _parentage = this._parentage;
if (_parentage) {
this._parentage = null;
if (Array.isArray(_parentage)) {
try {
for (var _parentage_1 = __values(_parentage), _parentage_1_1 = _parentage_1.next(); !_parentage_1_1.done; _parentage_1_1 = _parentage_1.next()) {
var parent_1 = _parentage_1_1.value;
parent_1.remove(this);
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (_parentage_1_1 && !_parentage_1_1.done && (_a = _parentage_1.return)) _a.call(_parentage_1);
}
finally { if (e_1) throw e_1.error; }
}
}
else {
_parentage.remove(this);
}
}
var initialFinalizer = this.initialTeardown;
if (isFunction(initialFinalizer)) {
try {
initialFinalizer();
}
catch (e) {
errors = e instanceof UnsubscriptionError ? e.errors : [e];
}
}
var _finalizers = this._finalizers;
if (_finalizers) {
this._finalizers = null;
try {
for (var _finalizers_1 = __values(_finalizers), _finalizers_1_1 = _finalizers_1.next(); !_finalizers_1_1.done; _finalizers_1_1 = _finalizers_1.next()) {
var finalizer = _finalizers_1_1.value;
try {
execFinalizer(finalizer);
}
catch (err) {
errors = errors !== null && errors !== void 0 ? errors : [];
if (err instanceof UnsubscriptionError) {
errors = __spreadArray(__spreadArray([], __read(errors)), __read(err.errors));
}
else {
errors.push(err);
}
}
}
}
catch (e_2_1) { e_2 = { error: e_2_1 }; }
finally {
try {
if (_finalizers_1_1 && !_finalizers_1_1.done && (_b = _finalizers_1.return)) _b.call(_finalizers_1);
}
finally { if (e_2) throw e_2.error; }
}
}
if (errors) {
throw new UnsubscriptionError(errors);
}
}
};
Subscription.prototype.add = function (teardown) {
var _a;
if (teardown && teardown !== this) {
if (this.closed) {
execFinalizer(teardown);
}
else {
if (teardown instanceof Subscription) {
if (teardown.closed || teardown._hasParent(this)) {
return;
}
teardown._addParent(this);
}
(this._finalizers = (_a = this._finalizers) !== null && _a !== void 0 ? _a : []).push(teardown);
}
}
};
Subscription.prototype._hasParent = function (parent) {
var _parentage = this._parentage;
return _parentage === parent || (Array.isArray(_parentage) && _parentage.includes(parent));
};
Subscription.prototype._addParent = function (parent) {
var _parentage = this._parentage;
this._parentage = Array.isArray(_parentage) ? (_parentage.push(parent), _parentage) : _parentage ? [_parentage, parent] : parent;
};
Subscription.prototype._removeParent = function (parent) {
var _parentage = this._parentage;
if (_parentage === parent) {
this._parentage = null;
}
else if (Array.isArray(_parentage)) {
arrRemove(_parentage, parent);
}
};
Subscription.prototype.remove = function (teardown) {
var _finalizers = this._finalizers;
_finalizers && arrRemove(_finalizers, teardown);
if (teardown instanceof Subscription) {
teardown._removeParent(this);
}
};
Subscription.EMPTY = (function () {
var empty = new Subscription();
empty.closed = true;
return empty;
})();
return Subscription;
}());
var EMPTY_SUBSCRIPTION = Subscription.EMPTY;
function isSubscription(value) {
return (value instanceof Subscription ||
(value && 'closed' in value && isFunction(value.remove) && isFunction(value.add) && isFunction(value.unsubscribe)));
}
function execFinalizer(finalizer) {
if (isFunction(finalizer)) {
finalizer();
}
else {
finalizer.unsubscribe();
}
}
var config = {
onUnhandledError: null,
onStoppedNotification: null,
Promise: undefined,
useDeprecatedSynchronousErrorHandling: false,
useDeprecatedNextContext: false,
};
var timeoutProvider = {
setTimeout: function (handler, timeout) {
var args = [];
for (var _i = 2; _i < arguments.length; _i++) {
args[_i - 2] = arguments[_i];
}
var delegate = timeoutProvider.delegate;
if (delegate === null || delegate === void 0 ? void 0 : delegate.setTimeout) {
return delegate.setTimeout.apply(delegate, __spreadArray([handler, timeout], __read(args)));
}
return setTimeout.apply(void 0, __spreadArray([handler, timeout], __read(args)));
},
clearTimeout: function (handle) {
var delegate = timeoutProvider.delegate;
return ((delegate === null || delegate === void 0 ? void 0 : delegate.clearTimeout) || clearTimeout)(handle);
},
delegate: undefined,
};
function reportUnhandledError(err) {
timeoutProvider.setTimeout(function () {
{
throw err;
}
});
}
function noop() { }
var COMPLETE_NOTIFICATION = (function () { return createNotification('C', undefined, undefined); })();
function errorNotification(error) {
return createNotification('E', undefined, error);
}
function nextNotification(value) {
return createNotification('N', value, undefined);
}
function createNotification(kind, value, error) {
return {
kind: kind,
value: value,
error: error,
};
}
var context = null;
function errorContext(cb) {
if (config.useDeprecatedSynchronousErrorHandling) {
var isRoot = !context;
if (isRoot) {
context = { errorThrown: false, error: null };
}
cb();
if (isRoot) {
var _a = context, errorThrown = _a.errorThrown, error = _a.error;
context = null;
if (errorThrown) {
throw error;
}
}
}
else {
cb();
}
}
var Subscriber = (function (_super) {
__extends(Subscriber, _super);
function Subscriber(destination) {
var _this = _super.call(this) || this;
_this.isStopped = false;
if (destination) {
_this.destination = destination;
if (isSubscription(destination)) {
destination.add(_this);
}
}
else {
_this.destination = EMPTY_OBSERVER;
}
return _this;
}
Subscriber.create = function (next, error, complete) {
return new SafeSubscriber(next, error, complete);
};
Subscriber.prototype.next = function (value) {
if (this.isStopped) {
handleStoppedNotification(nextNotification(value), this);
}
else {
this._next(value);
}
};
Subscriber.prototype.error = function (err) {
if (this.isStopped) {
handleStoppedNotification(errorNotification(err), this);
}
else {
this.isStopped = true;
this._error(err);
}
};
Subscriber.prototype.complete = function () {
if (this.isStopped) {
handleStoppedNotification(COMPLETE_NOTIFICATION, this);
}
else {
this.isStopped = true;
this._complete();
}
};
Subscriber.prototype.unsubscribe = function () {
if (!this.closed) {
this.isStopped = true;
_super.prototype.unsubscribe.call(this);
this.destination = null;
}
};
Subscriber.prototype._next = function (value) {
this.destination.next(value);
};
Subscriber.prototype._error = function (err) {
try {
this.destination.error(err);
}
finally {
this.unsubscribe();
}
};
Subscriber.prototype._complete = function () {
try {
this.destination.complete();
}
finally {
this.unsubscribe();
}
};
return Subscriber;
}(Subscription));
var _bind = Function.prototype.bind;
function bind(fn, thisArg) {
return _bind.call(fn, thisArg);
}
var ConsumerObserver = (function () {
function ConsumerObserver(partialObserver) {
this.partialObserver = partialObserver;
}
ConsumerObserver.prototype.next = function (value) {
var partialObserver = this.partialObserver;
if (partialObserver.next) {
try {
partialObserver.next(value);
}
catch (error) {
handleUnhandledError(error);
}
}
};
ConsumerObserver.prototype.error = function (err) {
var partialObserver = this.partialObserver;
if (partialObserver.error) {
try {
partialObserver.error(err);
}
catch (error) {
handleUnhandledError(error);
}
}
else {
handleUnhandledError(err);
}
};
ConsumerObserver.prototype.complete = function () {
var partialObserver = this.partialObserver;
if (partialObserver.complete) {
try {
partialObserver.complete();
}
catch (error) {
handleUnhandledError(error);
}
}
};
return ConsumerObserver;
}());
var SafeSubscriber = (function (_super) {
__extends(SafeSubscriber, _super);
function SafeSubscriber(observerOrNext, error, complete) {
var _this = _super.call(this) || this;
var partialObserver;
if (isFunction(observerOrNext) || !observerOrNext) {
partialObserver = {
next: observerOrNext !== null && observerOrNext !== void 0 ? observerOrNext : undefined,
error: error !== null && error !== void 0 ? error : undefined,
complete: complete !== null && complete !== void 0 ? complete : undefined,
};
}
else {
var context_1;
if (_this && config.useDeprecatedNextContext) {
context_1 = Object.create(observerOrNext);
context_1.unsubscribe = function () { return _this.unsubscribe(); };
partialObserver = {
next: observerOrNext.next && bind(observerOrNext.next, context_1),
error: observerOrNext.error && bind(observerOrNext.error, context_1),
complete: observerOrNext.complete && bind(observerOrNext.complete, context_1),
};
}
else {
partialObserver = observerOrNext;
}
}
_this.destination = new ConsumerObserver(partialObserver);
return _this;
}
return SafeSubscriber;
}(Subscriber));
function handleUnhandledError(error) {
{
reportUnhandledError(error);
}
}
function defaultErrorHandler(err) {
throw err;
}
function handleStoppedNotification(notification, subscriber) {
var onStoppedNotification = config.onStoppedNotification;
onStoppedNotification && timeoutProvider.setTimeout(function () { return onStoppedNotification(notification, subscriber); });
}
var EMPTY_OBSERVER = {
closed: true,
next: noop,
error: defaultErrorHandler,
complete: noop,
};
var observable = (function () { return (typeof Symbol === 'function' && Symbol.observable) || '@@observable'; })();
function identity(x) {
return x;
}
function pipeFromArray(fns) {
if (fns.length === 0) {
return identity;
}
if (fns.length === 1) {
return fns[0];
}
return function piped(input) {
return fns.reduce(function (prev, fn) { return fn(prev); }, input);
};
}
var Observable = (function () {
function Observable(subscribe) {
if (subscribe) {
this._subscribe = subscribe;
}
}
Observable.prototype.lift = function (operator) {
var observable = new Observable();
observable.source = this;
observable.operator = operator;
return observable;
};
Observable.prototype.subscribe = function (observerOrNext, error, complete) {
var _this = this;
var subscriber = isSubscriber(observerOrNext) ? observerOrNext : new SafeSubscriber(observerOrNext, error, complete);
errorContext(function () {
var _a = _this, operator = _a.operator, source = _a.source;
subscriber.add(operator
?
operator.call(subscriber, source)
: source
?
_this._subscribe(subscriber)
:
_this._trySubscribe(subscriber));
});
return subscriber;
};
Observable.prototype._trySubscribe = function (sink) {
try {
return this._subscribe(sink);
}
catch (err) {
sink.error(err);
}
};
Observable.prototype.forEach = function (next, promiseCtor) {
var _this = this;
promiseCtor = getPromiseCtor(promiseCtor);
return new promiseCtor(function (resolve, reject) {
var subscriber = new SafeSubscriber({
next: function (value) {
try {
next(value);
}
catch (err) {
reject(err);
subscriber.unsubscribe();
}
},
error: reject,
complete: resolve,
});
_this.subscribe(subscriber);
});
};
Observable.prototype._subscribe = function (subscriber) {
var _a;
return (_a = this.source) === null || _a === void 0 ? void 0 : _a.subscribe(subscriber);
};
Observable.prototype[observable] = function () {
return this;
};
Observable.prototype.pipe = function () {
var operations = [];
for (var _i = 0; _i < arguments.length; _i++) {
operations[_i] = arguments[_i];
}
return pipeFromArray(operations)(this);
};
Observable.prototype.toPromise = function (promiseCtor) {
var _this = this;
promiseCtor = getPromiseCtor(promiseCtor);
return new promiseCtor(function (resolve, reject) {
var value;
_this.subscribe(function (x) { return (value = x); }, function (err) { return reject(err); }, function () { return resolve(value); });
});
};
Observable.create = function (subscribe) {
return new Observable(subscribe);
};
return Observable;
}());
function getPromiseCtor(promiseCtor) {
var _a;
return (_a = promiseCtor !== null && promiseCtor !== void 0 ? promiseCtor : config.Promise) !== null && _a !== void 0 ? _a : Promise;
}
function isObserver(value) {
return value && isFunction(value.next) && isFunction(value.error) && isFunction(value.complete);
}
function isSubscriber(value) {
return (value && value instanceof Subscriber) || (isObserver(value) && isSubscription(value));
}
function hasLift(source) {
return isFunction(source === null || source === void 0 ? void 0 : source.lift);
}
function operate(init) {
return function (source) {
if (hasLift(source)) {
return source.lift(function (liftedSource) {
try {
return init(liftedSource, this);
}
catch (err) {
this.error(err);
}
});
}
throw new TypeError('Unable to lift unknown Observable type');
};
}
function createOperatorSubscriber(destination, onNext, onComplete, onError, onFinalize) {
return new OperatorSubscriber(destination, onNext, onComplete, onError, onFinalize);
}
var OperatorSubscriber = (function (_super) {
__extends(OperatorSubscriber, _super);
function OperatorSubscriber(destination, onNext, onComplete, onError, onFinalize, shouldUnsubscribe) {
var _this = _super.call(this, destination) || this;
_this.onFinalize = onFinalize;
_this.shouldUnsubscribe = shouldUnsubscribe;
_this._next = onNext
? function (value) {
try {
onNext(value);
}
catch (err) {
destination.error(err);
}
}
: _super.prototype._next;
_this._error = onError
? function (err) {
try {
onError(err);
}
catch (err) {
destination.error(err);
}
finally {
this.unsubscribe();
}
}
: _super.prototype._error;
_this._complete = onComplete
? function () {
try {
onComplete();
}
catch (err) {
destination.error(err);
}
finally {
this.unsubscribe();
}
}
: _super.prototype._complete;
return _this;
}
OperatorSubscriber.prototype.unsubscribe = function () {
var _a;
if (!this.shouldUnsubscribe || this.shouldUnsubscribe()) {
var closed_1 = this.closed;
_super.prototype.unsubscribe.call(this);
!closed_1 && ((_a = this.onFinalize) === null || _a === void 0 ? void 0 : _a.call(this));
}
};
return OperatorSubscriber;
}(Subscriber));
var ObjectUnsubscribedError = createErrorClass(function (_super) {
return function ObjectUnsubscribedErrorImpl() {
_super(this);
this.name = 'ObjectUnsubscribedError';
this.message = 'object unsubscribed';
};
});
var Subject = (function (_super) {
__extends(Subject, _super);
function Subject() {
var _this = _super.call(this) || this;
_this.closed = false;
_this.currentObservers = null;
_this.observers = [];
_this.isStopped = false;
_this.hasError = false;
_this.thrownError = null;
return _this;
}
Subject.prototype.lift = function (operator) {
var subject = new AnonymousSubject(this, this);
subject.operator = operator;
return subject;
};
Subject.prototype._throwIfClosed = function () {
if (this.closed) {
throw new ObjectUnsubscribedError();
}
};
Subject.prototype.next = function (value) {
var _this = this;
errorContext(function () {
var e_1, _a;
_this._throwIfClosed();
if (!_this.isStopped) {
if (!_this.currentObservers) {
_this.currentObservers = Array.from(_this.observers);
}
try {
for (var _b = __values(_this.currentObservers), _c = _b.next(); !_c.done; _c = _b.next()) {
var observer = _c.value;
observer.next(value);
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
}
finally { if (e_1) throw e_1.error; }
}
}
});
};
Subject.prototype.error = function (err) {
var _this = this;
errorContext(function () {
_this._throwIfClosed();
if (!_this.isStopped) {
_this.hasError = _this.isStopped = true;
_this.thrownError = err;
var observers = _this.observers;
while (observers.length) {
observers.shift().error(err);
}
}
});
};
Subject.prototype.complete = function () {
var _this = this;
errorContext(function () {
_this._throwIfClosed();
if (!_this.isStopped) {
_this.isStopped = true;
var observers = _this.observers;
while (observers.length) {
observers.shift().complete();
}
}
});
};
Subject.prototype.unsubscribe = function () {
this.isStopped = this.closed = true;
this.observers = this.currentObservers = null;
};
Object.defineProperty(Subject.prototype, "observed", {
get: function () {
var _a;
return ((_a = this.observers) === null || _a === void 0 ? void 0 : _a.length) > 0;
},
enumerable: false,
configurable: true
});
Subject.prototype._trySubscribe = function (subscriber) {
this._throwIfClosed();
return _super.prototype._trySubscribe.call(this, subscriber);
};
Subject.prototype._subscribe = function (subscriber) {
this._throwIfClosed();
this._checkFinalizedStatuses(subscriber);
return this._innerSubscribe(subscriber);
};
Subject.prototype._innerSubscribe = function (subscriber) {
var _this = this;
var _a = this, hasError = _a.hasError, isStopped = _a.isStopped, observers = _a.observers;
if (hasError || isStopped) {
return EMPTY_SUBSCRIPTION;
}
this.currentObservers = null;
observers.push(subscriber);
return new Subscription(function () {
_this.currentObservers = null;
arrRemove(observers, subscriber);
});
};
Subject.prototype._checkFinalizedStatuses = function (subscriber) {
var _a = this, hasError = _a.hasError, thrownError = _a.thrownError, isStopped = _a.isStopped;
if (hasError) {
subscriber.error(thrownError);
}
else if (isStopped) {
subscriber.complete();
}
};
Subject.prototype.asObservable = function () {
var observable = new Observable();
observable.source = this;
return observable;
};
Subject.create = function (destination, source) {
return new AnonymousSubject(destination, source);
};
return Subject;
}(Observable));
var AnonymousSubject = (function (_super) {
__extends(AnonymousSubject, _super);
function AnonymousSubject(destination, source) {
var _this = _super.call(this) || this;
_this.destination = destination;
_this.source = source;
return _this;
}
AnonymousSubject.prototype.next = function (value) {
var _a, _b;
(_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.next) === null || _b === void 0 ? void 0 : _b.call(_a, value);
};
AnonymousSubject.prototype.error = function (err) {
var _a, _b;
(_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.error) === null || _b === void 0 ? void 0 : _b.call(_a, err);
};
AnonymousSubject.prototype.complete = function () {
var _a, _b;
(_b = (_a = this.destination) === null || _a === void 0 ? void 0 : _a.complete) === null || _b === void 0 ? void 0 : _b.call(_a);
};
AnonymousSubject.prototype._subscribe = function (subscriber) {
var _a, _b;
return (_b = (_a = this.source) === null || _a === void 0 ? void 0 : _a.subscribe(subscriber)) !== null && _b !== void 0 ? _b : EMPTY_SUBSCRIPTION;
};
return AnonymousSubject;
}(Subject));
var BehaviorSubject = (function (_super) {
__extends(BehaviorSubject, _super);
function BehaviorSubject(_value) {
var _this = _super.call(this) || this;
_this._value = _value;
return _this;
}
Object.defineProperty(BehaviorSubject.prototype, "value", {
get: function () {
return this.getValue();
},
enumerable: false,
configurable: true
});
BehaviorSubject.prototype._subscribe = function (subscriber) {
var subscription = _super.prototype._subscribe.call(this, subscriber);
!subscription.closed && subscriber.next(this._value);
return subscription;
};
BehaviorSubject.prototype.getValue = function () {
var _a = this, hasError = _a.hasError, thrownError = _a.thrownError, _value = _a._value;
if (hasError) {
throw thrownError;
}
this._throwIfClosed();
return _value;
};
BehaviorSubject.prototype.next = function (value) {
_super.prototype.next.call(this, (this._value = value));
};
return BehaviorSubject;
}(Subject));
var dateTimestampProvider = {
now: function () {
return (dateTimestampProvider.delegate || Date).now();
},
delegate: undefined,
};
var Action = (function (_super) {
__extends(Action, _super);
function Action(scheduler, work) {
return _super.call(this) || this;
}
Action.prototype.schedule = function (state, delay) {
return this;
};
return Action;
}(Subscription));
var intervalProvider = {
setInterval: function (handler, timeout) {
var args = [];
for (var _i = 2; _i < arguments.length; _i++) {
args[_i - 2] = arguments[_i];
}
var delegate = intervalProvider.delegate;
if (delegate === null || delegate === void 0 ? void 0 : delegate.setInterval) {
return delegate.setInterval.apply(delegate, __spreadArray([handler, timeout], __read(args)));
}
return setInterval.apply(void 0, __spreadArray([handler, timeout], __read(args)));
},
clearInterval: function (handle) {
var delegate = intervalProvider.delegate;
return ((delegate === null || delegate === void 0 ? void 0 : delegate.clearInterval) || clearInterval)(handle);
},
delegate: undefined,
};
var AsyncAction = (function (_super) {
__extends(AsyncAction, _super);
function AsyncAction(scheduler, work) {
var _this = _super.call(this, scheduler, work) || this;
_this.scheduler = scheduler;
_this.work = work;
_this.pending = false;
return _this;
}
AsyncAction.prototype.schedule = function (state, delay) {
if (delay === void 0) { delay = 0; }
if (this.closed) {
return this;
}
this.state = state;
var id = this.id;
var scheduler = this.scheduler;
if (id != null) {
this.id = this.recycleAsyncId(scheduler, id, delay);
}
this.pending = true;
this.delay = delay;
this.id = this.id || this.requestAsyncId(scheduler, this.id, delay);
return this;
};
AsyncAction.prototype.requestAsyncId = function (scheduler, _id, delay) {
if (delay === void 0) { delay = 0; }
return intervalProvider.setInterval(scheduler.flush.bind(scheduler, this), delay);
};
AsyncAction.prototype.recycleAsyncId = function (_scheduler, id, delay) {
if (delay === void 0) { delay = 0; }
if (delay != null && this.delay === delay && this.pending === false) {
return id;
}
intervalProvider.clearInterval(id);
return undefined;
};
AsyncAction.prototype.execute = function (state, d