ngx-extended-pdf-viewer
Version:
Embedding PDF files in your Angular application. Highly configurable viewer including the toolbar, sidebar, and all the features you're used to.
1,647 lines (1,614 loc) • 656 kB
JavaScript
/**
* @licstart The following is the entire license notice for the
* JavaScript code in this page
*
* Copyright 2023 Mozilla Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @licend The above is the entire license notice for the
* JavaScript code in this page
*/
/******/ var __webpack_modules__ = ({
/***/ 6873:
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
/* harmony export */ __webpack_require__.d(__webpack_exports__, {
/* harmony export */ "default": () => (/* binding */ canvasSize)
/* harmony export */ });
function _iterableToArrayLimit(arr, i) {
var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"];
if (null != _i) {
var _s,
_e,
_x,
_r,
_arr = [],
_n = !0,
_d = !1;
try {
if (_x = (_i = _i.call(arr)).next, 0 === i) {
if (Object(_i) !== _i) return;
_n = !1;
} else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = !0);
} catch (err) {
_d = !0, _e = err;
} finally {
try {
if (!_n && null != _i.return && (_r = _i.return(), Object(_r) !== _r)) return;
} finally {
if (_d) throw _e;
}
}
return _arr;
}
}
function ownKeys(object, enumerableOnly) {
var keys = Object.keys(object);
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(object);
enumerableOnly && (symbols = symbols.filter(function (sym) {
return Object.getOwnPropertyDescriptor(object, sym).enumerable;
})), keys.push.apply(keys, symbols);
}
return keys;
}
function _objectSpread2(target) {
for (var i = 1; i < arguments.length; i++) {
var source = null != arguments[i] ? arguments[i] : {};
i % 2 ? ownKeys(Object(source), !0).forEach(function (key) {
_defineProperty(target, key, source[key]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) {
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
});
}
return target;
}
function _defineProperty(obj, key, value) {
key = _toPropertyKey(key);
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function _objectWithoutPropertiesLoose(source, excluded) {
if (source == null) return {};
var target = {};
var sourceKeys = Object.keys(source);
var key, i;
for (i = 0; i < sourceKeys.length; i++) {
key = sourceKeys[i];
if (excluded.indexOf(key) >= 0) continue;
target[key] = source[key];
}
return target;
}
function _objectWithoutProperties(source, excluded) {
if (source == null) return {};
var target = _objectWithoutPropertiesLoose(source, excluded);
var key, i;
if (Object.getOwnPropertySymbols) {
var sourceSymbolKeys = Object.getOwnPropertySymbols(source);
for (i = 0; i < sourceSymbolKeys.length; i++) {
key = sourceSymbolKeys[i];
if (excluded.indexOf(key) >= 0) continue;
if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
target[key] = source[key];
}
}
return target;
}
function _slicedToArray(arr, i) {
return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest();
}
function _toConsumableArray(arr) {
return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
}
function _arrayWithoutHoles(arr) {
if (Array.isArray(arr)) return _arrayLikeToArray(arr);
}
function _arrayWithHoles(arr) {
if (Array.isArray(arr)) return arr;
}
function _iterableToArray(iter) {
if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
}
function _unsupportedIterableToArray(o, minLen) {
if (!o) return;
if (typeof o === "string") return _arrayLikeToArray(o, minLen);
var n = Object.prototype.toString.call(o).slice(8, -1);
if (n === "Object" && o.constructor) n = o.constructor.name;
if (n === "Map" || n === "Set") return Array.from(o);
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
}
function _arrayLikeToArray(arr, len) {
if (len == null || len > arr.length) len = arr.length;
for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
return arr2;
}
function _nonIterableSpread() {
throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _nonIterableRest() {
throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
}
function _toPrimitive(input, hint) {
if (typeof input !== "object" || input === null) return input;
var prim = input[Symbol.toPrimitive];
if (prim !== undefined) {
var res = prim.call(input, hint || "default");
if (typeof res !== "object") return res;
throw new TypeError("@@toPrimitive must return a primitive value.");
}
return (hint === "string" ? String : Number)(input);
}
function _toPropertyKey(arg) {
var key = _toPrimitive(arg, "string");
return typeof key === "symbol" ? key : String(key);
}
function canvasTest(settings) {
var size = settings.sizes.shift();
var width = Math.max(Math.ceil(size[0]), 1);
var height = Math.max(Math.ceil(size[1]), 1);
var fill = [width - 1, height - 1, 1, 1];
var job = Date.now();
var isWorker = typeof WorkerGlobalScope !== "undefined" && self instanceof WorkerGlobalScope;
var cropCvs, testCvs;
if (isWorker) {
cropCvs = new OffscreenCanvas(1, 1);
testCvs = new OffscreenCanvas(width, height);
} else {
cropCvs = document.createElement("canvas");
cropCvs.width = 1;
cropCvs.height = 1;
testCvs = document.createElement("canvas");
testCvs.width = width;
testCvs.height = height;
}
var cropCtx = cropCvs.getContext("2d");
var testCtx = testCvs.getContext("2d");
if (testCtx) {
testCtx.fillRect.apply(testCtx, fill);
cropCtx.drawImage(testCvs, width - 1, height - 1, 1, 1, 0, 0, 1, 1);
}
var isTestPass = cropCtx && cropCtx.getImageData(0, 0, 1, 1).data[3] !== 0;
var benchmark = Date.now() - job;
[cropCvs, testCvs].forEach(function (cvs) {
cvs.height = 0;
cvs.width = 0;
});
if (isWorker) {
postMessage({
width: width,
height: height,
benchmark: benchmark,
isTestPass: isTestPass
});
if (!isTestPass && settings.sizes.length) {
canvasTest(settings);
}
} else if (isTestPass) {
settings.onSuccess(width, height, benchmark);
} else {
settings.onError(width, height, benchmark);
if (settings.sizes.length) {
canvasTest(settings);
}
}
return isTestPass;
}
var testSizes = {
area: [16384, 14188, 11402, 11180, 10836, 8192, 4096, 1],
height: [8388607, 65535, 32767, 16384, 8192, 4096, 1],
width: [4194303, 65535, 32767, 16384, 8192, 4096, 1]
};
var _excluded = ["onError", "onSuccess"];
var defaults = {
max: null,
min: 1,
sizes: [],
step: 1024,
usePromise: false,
useWorker: false,
onError: Function.prototype,
onSuccess: Function.prototype
};
var workerJobs = {};
function createSizesArray(settings) {
var isArea = settings.width === settings.height;
var isWidth = settings.height === 1;
var isHeight = settings.width === 1;
var sizes = [];
if (!settings.width || !settings.height) {
settings.sizes.forEach(function (testSize) {
var width = isArea || isWidth ? testSize : 1;
var height = isArea || isHeight ? testSize : 1;
sizes.push([width, height]);
});
} else {
var testMin = settings.min || defaults.min;
var testStep = settings.step || defaults.step;
var testSize = Math.max(settings.width, settings.height);
while (testSize >= testMin) {
var width = isArea || isWidth ? testSize : 1;
var height = isArea || isHeight ? testSize : 1;
sizes.push([width, height]);
testSize -= testStep;
}
}
return sizes;
}
function handleMethod(settings) {
var hasCanvasSupport = window && "HTMLCanvasElement" in window;
var hasOffscreenCanvasSupport = window && "OffscreenCanvas" in window;
var jobID = Date.now();
var _onError = settings.onError,
_onSuccess = settings.onSuccess,
settingsWithoutCallbacks = _objectWithoutProperties(settings, _excluded);
var worker = null;
if (!hasCanvasSupport) {
return false;
}
if (settings.useWorker && hasOffscreenCanvasSupport) {
var js = "\n var canvasTest = ".concat(canvasTest.toString(), ";\n onmessage = function(e) {\n canvasTest(e.data);\n };\n ");
var blob = new Blob([js], {
type: "application/javascript"
});
var blobURL = URL.createObjectURL(blob);
worker = new Worker(blobURL);
URL.revokeObjectURL(blobURL);
worker.onmessage = function (e) {
var _e$data = e.data,
width = _e$data.width,
height = _e$data.height,
benchmark = _e$data.benchmark,
isTestPass = _e$data.isTestPass;
if (isTestPass) {
workerJobs[jobID].onSuccess(width, height, benchmark);
delete workerJobs[jobID];
} else {
workerJobs[jobID].onError(width, height, benchmark);
}
};
}
if (settings.usePromise) {
return new Promise(function (resolve, reject) {
var promiseSettings = _objectSpread2(_objectSpread2({}, settings), {}, {
onError: function onError(width, height, benchmark) {
var isLastTest;
if (settings.sizes.length === 0) {
isLastTest = true;
} else {
var _settings$sizes$slice = settings.sizes.slice(-1),
_settings$sizes$slice2 = _slicedToArray(_settings$sizes$slice, 1),
_settings$sizes$slice3 = _slicedToArray(_settings$sizes$slice2[0], 2),
lastWidth = _settings$sizes$slice3[0],
lastHeight = _settings$sizes$slice3[1];
isLastTest = width === lastWidth && height === lastHeight;
}
_onError(width, height, benchmark);
if (isLastTest) {
reject({
width: width,
height: height,
benchmark: benchmark
});
}
},
onSuccess: function onSuccess(width, height, benchmark) {
_onSuccess(width, height, benchmark);
resolve({
width: width,
height: height,
benchmark: benchmark
});
}
});
if (worker) {
var onError = promiseSettings.onError,
onSuccess = promiseSettings.onSuccess;
workerJobs[jobID] = {
onError: onError,
onSuccess: onSuccess
};
worker.postMessage(settingsWithoutCallbacks);
} else {
canvasTest(promiseSettings);
}
});
} else {
if (worker) {
workerJobs[jobID] = {
onError: _onError,
onSuccess: _onSuccess
};
worker.postMessage(settingsWithoutCallbacks);
} else {
return canvasTest(settings);
}
}
}
var canvasSize = {
maxArea: function maxArea() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var sizes = createSizesArray({
width: options.max,
height: options.max,
min: options.min,
step: options.step,
sizes: _toConsumableArray(testSizes.area)
});
var settings = _objectSpread2(_objectSpread2(_objectSpread2({}, defaults), options), {}, {
sizes: sizes
});
return handleMethod(settings);
},
maxHeight: function maxHeight() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var sizes = createSizesArray({
width: 1,
height: options.max,
min: options.min,
step: options.step,
sizes: _toConsumableArray(testSizes.height)
});
var settings = _objectSpread2(_objectSpread2(_objectSpread2({}, defaults), options), {}, {
sizes: sizes
});
return handleMethod(settings);
},
maxWidth: function maxWidth() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var sizes = createSizesArray({
width: options.max,
height: 1,
min: options.min,
step: options.step,
sizes: _toConsumableArray(testSizes.width)
});
var settings = _objectSpread2(_objectSpread2(_objectSpread2({}, defaults), options), {}, {
sizes: sizes
});
return handleMethod(settings);
},
test: function test() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var settings = _objectSpread2(_objectSpread2({}, defaults), options);
settings.sizes = _toConsumableArray(settings.sizes);
if (settings.width && settings.height) {
settings.sizes = [[settings.width, settings.height]];
}
return handleMethod(settings);
}
};
/***/ }),
/***/ 3695:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
FluentBundle: () => (/* reexport */ FluentBundle),
FluentResource: () => (/* reexport */ FluentResource)
});
// UNUSED EXPORTS: FluentDateTime, FluentNone, FluentNumber, FluentType
;// CONCATENATED MODULE: ./node_modules/@fluent/bundle/esm/types.js
class FluentType {
constructor(value) {
this.value = value;
}
valueOf() {
return this.value;
}
}
class FluentNone extends FluentType {
constructor(value = "???") {
super(value);
}
toString(scope) {
return `{${this.value}}`;
}
}
class FluentNumber extends FluentType {
constructor(value, opts = {}) {
super(value);
this.opts = opts;
}
toString(scope) {
try {
const nf = scope.memoizeIntlObject(Intl.NumberFormat, this.opts);
return nf.format(this.value);
} catch (err) {
scope.reportError(err);
return this.value.toString(10);
}
}
}
class FluentDateTime extends FluentType {
constructor(value, opts = {}) {
super(value);
this.opts = opts;
}
toString(scope) {
try {
const dtf = scope.memoizeIntlObject(Intl.DateTimeFormat, this.opts);
return dtf.format(this.value);
} catch (err) {
scope.reportError(err);
return new Date(this.value).toISOString();
}
}
}
;// CONCATENATED MODULE: ./node_modules/@fluent/bundle/esm/resolver.js
const MAX_PLACEABLES = 100;
const FSI = "\u2068";
const PDI = "\u2069";
function match(scope, selector, key) {
if (key === selector) {
return true;
}
if (key instanceof FluentNumber && selector instanceof FluentNumber && key.value === selector.value) {
return true;
}
if (selector instanceof FluentNumber && typeof key === "string") {
let category = scope.memoizeIntlObject(Intl.PluralRules, selector.opts).select(selector.value);
if (key === category) {
return true;
}
}
return false;
}
function getDefault(scope, variants, star) {
if (variants[star]) {
return resolvePattern(scope, variants[star].value);
}
scope.reportError(new RangeError("No default"));
return new FluentNone();
}
function getArguments(scope, args) {
const positional = [];
const named = Object.create(null);
for (const arg of args) {
if (arg.type === "narg") {
named[arg.name] = resolveExpression(scope, arg.value);
} else {
positional.push(resolveExpression(scope, arg));
}
}
return {
positional,
named
};
}
function resolveExpression(scope, expr) {
switch (expr.type) {
case "str":
return expr.value;
case "num":
return new FluentNumber(expr.value, {
minimumFractionDigits: expr.precision
});
case "var":
return resolveVariableReference(scope, expr);
case "mesg":
return resolveMessageReference(scope, expr);
case "term":
return resolveTermReference(scope, expr);
case "func":
return resolveFunctionReference(scope, expr);
case "select":
return resolveSelectExpression(scope, expr);
default:
return new FluentNone();
}
}
function resolveVariableReference(scope, {
name
}) {
let arg;
if (scope.params) {
if (Object.prototype.hasOwnProperty.call(scope.params, name)) {
arg = scope.params[name];
} else {
return new FluentNone(`$${name}`);
}
} else if (scope.args && Object.prototype.hasOwnProperty.call(scope.args, name)) {
arg = scope.args[name];
} else {
scope.reportError(new ReferenceError(`Unknown variable: $${name}`));
return new FluentNone(`$${name}`);
}
if (arg instanceof FluentType) {
return arg;
}
switch (typeof arg) {
case "string":
return arg;
case "number":
return new FluentNumber(arg);
case "object":
if (arg instanceof Date) {
return new FluentDateTime(arg.getTime());
}
default:
scope.reportError(new TypeError(`Variable type not supported: $${name}, ${typeof arg}`));
return new FluentNone(`$${name}`);
}
}
function resolveMessageReference(scope, {
name,
attr
}) {
const message = scope.bundle._messages.get(name);
if (!message) {
scope.reportError(new ReferenceError(`Unknown message: ${name}`));
return new FluentNone(name);
}
if (attr) {
const attribute = message.attributes[attr];
if (attribute) {
return resolvePattern(scope, attribute);
}
scope.reportError(new ReferenceError(`Unknown attribute: ${attr}`));
return new FluentNone(`${name}.${attr}`);
}
if (message.value) {
return resolvePattern(scope, message.value);
}
scope.reportError(new ReferenceError(`No value: ${name}`));
return new FluentNone(name);
}
function resolveTermReference(scope, {
name,
attr,
args
}) {
const id = `-${name}`;
const term = scope.bundle._terms.get(id);
if (!term) {
scope.reportError(new ReferenceError(`Unknown term: ${id}`));
return new FluentNone(id);
}
if (attr) {
const attribute = term.attributes[attr];
if (attribute) {
scope.params = getArguments(scope, args).named;
const resolved = resolvePattern(scope, attribute);
scope.params = null;
return resolved;
}
scope.reportError(new ReferenceError(`Unknown attribute: ${attr}`));
return new FluentNone(`${id}.${attr}`);
}
scope.params = getArguments(scope, args).named;
const resolved = resolvePattern(scope, term.value);
scope.params = null;
return resolved;
}
function resolveFunctionReference(scope, {
name,
args
}) {
let func = scope.bundle._functions[name];
if (!func) {
scope.reportError(new ReferenceError(`Unknown function: ${name}()`));
return new FluentNone(`${name}()`);
}
if (typeof func !== "function") {
scope.reportError(new TypeError(`Function ${name}() is not callable`));
return new FluentNone(`${name}()`);
}
try {
let resolved = getArguments(scope, args);
return func(resolved.positional, resolved.named);
} catch (err) {
scope.reportError(err);
return new FluentNone(`${name}()`);
}
}
function resolveSelectExpression(scope, {
selector,
variants,
star
}) {
let sel = resolveExpression(scope, selector);
if (sel instanceof FluentNone) {
return getDefault(scope, variants, star);
}
for (const variant of variants) {
const key = resolveExpression(scope, variant.key);
if (match(scope, sel, key)) {
return resolvePattern(scope, variant.value);
}
}
return getDefault(scope, variants, star);
}
function resolveComplexPattern(scope, ptn) {
if (scope.dirty.has(ptn)) {
scope.reportError(new RangeError("Cyclic reference"));
return new FluentNone();
}
scope.dirty.add(ptn);
const result = [];
const useIsolating = scope.bundle._useIsolating && ptn.length > 1;
for (const elem of ptn) {
if (typeof elem === "string") {
result.push(scope.bundle._transform(elem));
continue;
}
scope.placeables++;
if (scope.placeables > MAX_PLACEABLES) {
scope.dirty.delete(ptn);
throw new RangeError(`Too many placeables expanded: ${scope.placeables}, ` + `max allowed is ${MAX_PLACEABLES}`);
}
if (useIsolating) {
result.push(FSI);
}
result.push(resolveExpression(scope, elem).toString(scope));
if (useIsolating) {
result.push(PDI);
}
}
scope.dirty.delete(ptn);
return result.join("");
}
function resolvePattern(scope, value) {
if (typeof value === "string") {
return scope.bundle._transform(value);
}
return resolveComplexPattern(scope, value);
}
;// CONCATENATED MODULE: ./node_modules/@fluent/bundle/esm/scope.js
class Scope {
constructor(bundle, errors, args) {
this.dirty = new WeakSet();
this.params = null;
this.placeables = 0;
this.bundle = bundle;
this.errors = errors;
this.args = args;
}
reportError(error) {
if (!this.errors || !(error instanceof Error)) {
throw error;
}
this.errors.push(error);
}
memoizeIntlObject(ctor, opts) {
let cache = this.bundle._intls.get(ctor);
if (!cache) {
cache = {};
this.bundle._intls.set(ctor, cache);
}
let id = JSON.stringify(opts);
if (!cache[id]) {
cache[id] = new ctor(this.bundle.locales, opts);
}
return cache[id];
}
}
;// CONCATENATED MODULE: ./node_modules/@fluent/bundle/esm/builtins.js
function values(opts, allowed) {
const unwrapped = Object.create(null);
for (const [name, opt] of Object.entries(opts)) {
if (allowed.includes(name)) {
unwrapped[name] = opt.valueOf();
}
}
return unwrapped;
}
const NUMBER_ALLOWED = ["unitDisplay", "currencyDisplay", "useGrouping", "minimumIntegerDigits", "minimumFractionDigits", "maximumFractionDigits", "minimumSignificantDigits", "maximumSignificantDigits"];
function NUMBER(args, opts) {
let arg = args[0];
if (arg instanceof FluentNone) {
return new FluentNone(`NUMBER(${arg.valueOf()})`);
}
if (arg instanceof FluentNumber) {
return new FluentNumber(arg.valueOf(), {
...arg.opts,
...values(opts, NUMBER_ALLOWED)
});
}
if (arg instanceof FluentDateTime) {
return new FluentNumber(arg.valueOf(), {
...values(opts, NUMBER_ALLOWED)
});
}
throw new TypeError("Invalid argument to NUMBER");
}
const DATETIME_ALLOWED = ["dateStyle", "timeStyle", "fractionalSecondDigits", "dayPeriod", "hour12", "weekday", "era", "year", "month", "day", "hour", "minute", "second", "timeZoneName"];
function DATETIME(args, opts) {
let arg = args[0];
if (arg instanceof FluentNone) {
return new FluentNone(`DATETIME(${arg.valueOf()})`);
}
if (arg instanceof FluentDateTime) {
return new FluentDateTime(arg.valueOf(), {
...arg.opts,
...values(opts, DATETIME_ALLOWED)
});
}
if (arg instanceof FluentNumber) {
return new FluentDateTime(arg.valueOf(), {
...values(opts, DATETIME_ALLOWED)
});
}
throw new TypeError("Invalid argument to DATETIME");
}
;// CONCATENATED MODULE: ./node_modules/@fluent/bundle/esm/memoizer.js
const cache = new Map();
function getMemoizerForLocale(locales) {
const stringLocale = Array.isArray(locales) ? locales.join(" ") : locales;
let memoizer = cache.get(stringLocale);
if (memoizer === undefined) {
memoizer = new Map();
cache.set(stringLocale, memoizer);
}
return memoizer;
}
;// CONCATENATED MODULE: ./node_modules/@fluent/bundle/esm/bundle.js
class FluentBundle {
constructor(locales, {
functions,
useIsolating = true,
transform = v => v
} = {}) {
this._terms = new Map();
this._messages = new Map();
this.locales = Array.isArray(locales) ? locales : [locales];
this._functions = {
NUMBER: NUMBER,
DATETIME: DATETIME,
...functions
};
this._useIsolating = useIsolating;
this._transform = transform;
this._intls = getMemoizerForLocale(locales);
}
hasMessage(id) {
return this._messages.has(id);
}
getMessage(id) {
return this._messages.get(id);
}
addResource(res, {
allowOverrides = false
} = {}) {
const errors = [];
for (let i = 0; i < res.body.length; i++) {
let entry = res.body[i];
if (entry.id.startsWith("-")) {
if (allowOverrides === false && this._terms.has(entry.id)) {
errors.push(new Error(`Attempt to override an existing term: "${entry.id}"`));
continue;
}
this._terms.set(entry.id, entry);
} else {
if (allowOverrides === false && this._messages.has(entry.id)) {
errors.push(new Error(`Attempt to override an existing message: "${entry.id}"`));
continue;
}
this._messages.set(entry.id, entry);
}
}
return errors;
}
formatPattern(pattern, args = null, errors = null) {
if (typeof pattern === "string") {
return this._transform(pattern);
}
let scope = new Scope(this, errors, args);
try {
let value = resolveComplexPattern(scope, pattern);
return value.toString(scope);
} catch (err) {
if (scope.errors && err instanceof Error) {
scope.errors.push(err);
return new FluentNone().toString(scope);
}
throw err;
}
}
}
;// CONCATENATED MODULE: ./node_modules/@fluent/bundle/esm/resource.js
const RE_MESSAGE_START = /^(-?[a-zA-Z][\w-]*) *= */gm;
const RE_ATTRIBUTE_START = /\.([a-zA-Z][\w-]*) *= */y;
const RE_VARIANT_START = /\*?\[/y;
const RE_NUMBER_LITERAL = /(-?[0-9]+(?:\.([0-9]+))?)/y;
const RE_IDENTIFIER = /([a-zA-Z][\w-]*)/y;
const RE_REFERENCE = /([$-])?([a-zA-Z][\w-]*)(?:\.([a-zA-Z][\w-]*))?/y;
const RE_FUNCTION_NAME = /^[A-Z][A-Z0-9_-]*$/;
const RE_TEXT_RUN = /([^{}\n\r]+)/y;
const RE_STRING_RUN = /([^\\"\n\r]*)/y;
const RE_STRING_ESCAPE = /\\([\\"])/y;
const RE_UNICODE_ESCAPE = /\\u([a-fA-F0-9]{4})|\\U([a-fA-F0-9]{6})/y;
const RE_LEADING_NEWLINES = /^\n+/;
const RE_TRAILING_SPACES = / +$/;
const RE_BLANK_LINES = / *\r?\n/g;
const RE_INDENT = /( *)$/;
const TOKEN_BRACE_OPEN = /{\s*/y;
const TOKEN_BRACE_CLOSE = /\s*}/y;
const TOKEN_BRACKET_OPEN = /\[\s*/y;
const TOKEN_BRACKET_CLOSE = /\s*] */y;
const TOKEN_PAREN_OPEN = /\s*\(\s*/y;
const TOKEN_ARROW = /\s*->\s*/y;
const TOKEN_COLON = /\s*:\s*/y;
const TOKEN_COMMA = /\s*,?\s*/y;
const TOKEN_BLANK = /\s+/y;
class FluentResource {
constructor(source) {
this.body = [];
RE_MESSAGE_START.lastIndex = 0;
let cursor = 0;
while (true) {
let next = RE_MESSAGE_START.exec(source);
if (next === null) {
break;
}
cursor = RE_MESSAGE_START.lastIndex;
try {
this.body.push(parseMessage(next[1]));
} catch (err) {
if (err instanceof SyntaxError) {
continue;
}
throw err;
}
}
function test(re) {
re.lastIndex = cursor;
return re.test(source);
}
function consumeChar(char, errorClass) {
if (source[cursor] === char) {
cursor++;
return true;
}
if (errorClass) {
throw new errorClass(`Expected ${char}`);
}
return false;
}
function consumeToken(re, errorClass) {
if (test(re)) {
cursor = re.lastIndex;
return true;
}
if (errorClass) {
throw new errorClass(`Expected ${re.toString()}`);
}
return false;
}
function match(re) {
re.lastIndex = cursor;
let result = re.exec(source);
if (result === null) {
throw new SyntaxError(`Expected ${re.toString()}`);
}
cursor = re.lastIndex;
return result;
}
function match1(re) {
return match(re)[1];
}
function parseMessage(id) {
let value = parsePattern();
let attributes = parseAttributes();
if (value === null && Object.keys(attributes).length === 0) {
throw new SyntaxError("Expected message value or attributes");
}
return {
id,
value,
attributes
};
}
function parseAttributes() {
let attrs = Object.create(null);
while (test(RE_ATTRIBUTE_START)) {
let name = match1(RE_ATTRIBUTE_START);
let value = parsePattern();
if (value === null) {
throw new SyntaxError("Expected attribute value");
}
attrs[name] = value;
}
return attrs;
}
function parsePattern() {
let first;
if (test(RE_TEXT_RUN)) {
first = match1(RE_TEXT_RUN);
}
if (source[cursor] === "{" || source[cursor] === "}") {
return parsePatternElements(first ? [first] : [], Infinity);
}
let indent = parseIndent();
if (indent) {
if (first) {
return parsePatternElements([first, indent], indent.length);
}
indent.value = trim(indent.value, RE_LEADING_NEWLINES);
return parsePatternElements([indent], indent.length);
}
if (first) {
return trim(first, RE_TRAILING_SPACES);
}
return null;
}
function parsePatternElements(elements = [], commonIndent) {
while (true) {
if (test(RE_TEXT_RUN)) {
elements.push(match1(RE_TEXT_RUN));
continue;
}
if (source[cursor] === "{") {
elements.push(parsePlaceable());
continue;
}
if (source[cursor] === "}") {
throw new SyntaxError("Unbalanced closing brace");
}
let indent = parseIndent();
if (indent) {
elements.push(indent);
commonIndent = Math.min(commonIndent, indent.length);
continue;
}
break;
}
let lastIndex = elements.length - 1;
let lastElement = elements[lastIndex];
if (typeof lastElement === "string") {
elements[lastIndex] = trim(lastElement, RE_TRAILING_SPACES);
}
let baked = [];
for (let element of elements) {
if (element instanceof Indent) {
element = element.value.slice(0, element.value.length - commonIndent);
}
if (element) {
baked.push(element);
}
}
return baked;
}
function parsePlaceable() {
consumeToken(TOKEN_BRACE_OPEN, SyntaxError);
let selector = parseInlineExpression();
if (consumeToken(TOKEN_BRACE_CLOSE)) {
return selector;
}
if (consumeToken(TOKEN_ARROW)) {
let variants = parseVariants();
consumeToken(TOKEN_BRACE_CLOSE, SyntaxError);
return {
type: "select",
selector,
...variants
};
}
throw new SyntaxError("Unclosed placeable");
}
function parseInlineExpression() {
if (source[cursor] === "{") {
return parsePlaceable();
}
if (test(RE_REFERENCE)) {
let [, sigil, name, attr = null] = match(RE_REFERENCE);
if (sigil === "$") {
return {
type: "var",
name
};
}
if (consumeToken(TOKEN_PAREN_OPEN)) {
let args = parseArguments();
if (sigil === "-") {
return {
type: "term",
name,
attr,
args
};
}
if (RE_FUNCTION_NAME.test(name)) {
return {
type: "func",
name,
args
};
}
throw new SyntaxError("Function names must be all upper-case");
}
if (sigil === "-") {
return {
type: "term",
name,
attr,
args: []
};
}
return {
type: "mesg",
name,
attr
};
}
return parseLiteral();
}
function parseArguments() {
let args = [];
while (true) {
switch (source[cursor]) {
case ")":
cursor++;
return args;
case undefined:
throw new SyntaxError("Unclosed argument list");
}
args.push(parseArgument());
consumeToken(TOKEN_COMMA);
}
}
function parseArgument() {
let expr = parseInlineExpression();
if (expr.type !== "mesg") {
return expr;
}
if (consumeToken(TOKEN_COLON)) {
return {
type: "narg",
name: expr.name,
value: parseLiteral()
};
}
return expr;
}
function parseVariants() {
let variants = [];
let count = 0;
let star;
while (test(RE_VARIANT_START)) {
if (consumeChar("*")) {
star = count;
}
let key = parseVariantKey();
let value = parsePattern();
if (value === null) {
throw new SyntaxError("Expected variant value");
}
variants[count++] = {
key,
value
};
}
if (count === 0) {
return null;
}
if (star === undefined) {
throw new SyntaxError("Expected default variant");
}
return {
variants,
star
};
}
function parseVariantKey() {
consumeToken(TOKEN_BRACKET_OPEN, SyntaxError);
let key;
if (test(RE_NUMBER_LITERAL)) {
key = parseNumberLiteral();
} else {
key = {
type: "str",
value: match1(RE_IDENTIFIER)
};
}
consumeToken(TOKEN_BRACKET_CLOSE, SyntaxError);
return key;
}
function parseLiteral() {
if (test(RE_NUMBER_LITERAL)) {
return parseNumberLiteral();
}
if (source[cursor] === '"') {
return parseStringLiteral();
}
throw new SyntaxError("Invalid expression");
}
function parseNumberLiteral() {
let [, value, fraction = ""] = match(RE_NUMBER_LITERAL);
let precision = fraction.length;
return {
type: "num",
value: parseFloat(value),
precision
};
}
function parseStringLiteral() {
consumeChar('"', SyntaxError);
let value = "";
while (true) {
value += match1(RE_STRING_RUN);
if (source[cursor] === "\\") {
value += parseEscapeSequence();
continue;
}
if (consumeChar('"')) {
return {
type: "str",
value
};
}
throw new SyntaxError("Unclosed string literal");
}
}
function parseEscapeSequence() {
if (test(RE_STRING_ESCAPE)) {
return match1(RE_STRING_ESCAPE);
}
if (test(RE_UNICODE_ESCAPE)) {
let [, codepoint4, codepoint6] = match(RE_UNICODE_ESCAPE);
let codepoint = parseInt(codepoint4 || codepoint6, 16);
return codepoint <= 0xd7ff || 0xe000 <= codepoint ? String.fromCodePoint(codepoint) : "�";
}
throw new SyntaxError("Unknown escape sequence");
}
function parseIndent() {
let start = cursor;
consumeToken(TOKEN_BLANK);
switch (source[cursor]) {
case ".":
case "[":
case "*":
case "}":
case undefined:
return false;
case "{":
return makeIndent(source.slice(start, cursor));
}
if (source[cursor - 1] === " ") {
return makeIndent(source.slice(start, cursor));
}
return false;
}
function trim(text, re) {
return text.replace(re, "");
}
function makeIndent(blank) {
let value = blank.replace(RE_BLANK_LINES, "\n");
let length = RE_INDENT.exec(blank)[1].length;
return new Indent(value, length);
}
}
}
class Indent {
constructor(value, length) {
this.value = value;
this.length = length;
}
}
;// CONCATENATED MODULE: ./node_modules/@fluent/bundle/esm/index.js
/***/ }),
/***/ 8527:
/***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
// EXPORTS
__webpack_require__.d(__webpack_exports__, {
DOMLocalization: () => (/* reexport */ DOMLocalization)
});
// UNUSED EXPORTS: Localization
;// CONCATENATED MODULE: ./node_modules/@fluent/dom/esm/overlay.js
const reOverlay = /<|&#?\w+;/;
const TEXT_LEVEL_ELEMENTS = {
"http://www.w3.org/1999/xhtml": ["em", "strong", "small", "s", "cite", "q", "dfn", "abbr", "data", "time", "code", "var", "samp", "kbd", "sub", "sup", "i", "b", "u", "mark", "bdi", "bdo", "span", "br", "wbr"]
};
const LOCALIZABLE_ATTRIBUTES = {
"http://www.w3.org/1999/xhtml": {
global: ["title", "aria-label", "aria-valuetext"],
a: ["download"],
area: ["download", "alt"],
input: ["alt", "placeholder"],
menuitem: ["label"],
menu: ["label"],
optgroup: ["label"],
option: ["label"],
track: ["label"],
img: ["alt"],
textarea: ["placeholder"],
th: ["abbr"]
},
"http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul": {
global: ["accesskey", "aria-label", "aria-valuetext", "label", "title", "tooltiptext"],
description: ["value"],
key: ["key", "keycode"],
label: ["value"],
textbox: ["placeholder", "value"]
}
};
function translateElement(element, translation) {
const {
value
} = translation;
if (typeof value === "string") {
if (element.localName === "title" && element.namespaceURI === "http://www.w3.org/1999/xhtml") {
element.textContent = value;
} else if (!reOverlay.test(value)) {
element.textContent = value;
} else {
const templateElement = element.ownerDocument.createElementNS("http://www.w3.org/1999/xhtml", "template");
templateElement.innerHTML = value;
overlayChildNodes(templateElement.content, element);
}
}
overlayAttributes(translation, element);
}
function overlayChildNodes(fromFragment, toElement) {
for (const childNode of fromFragment.childNodes) {
if (childNode.nodeType === childNode.TEXT_NODE) {
continue;
}
if (childNode.hasAttribute("data-l10n-name")) {
const sanitized = getNodeForNamedElement(toElement, childNode);
fromFragment.replaceChild(sanitized, childNode);
continue;
}
if (isElementAllowed(childNode)) {
const sanitized = createSanitizedElement(childNode);
fromFragment.replaceChild(sanitized, childNode);
continue;
}
console.warn(`An element of forbidden type "${childNode.localName}" was found in ` + "the translation. Only safe text-level elements and elements with " + "data-l10n-name are allowed.");
fromFragment.replaceChild(createTextNodeFromTextContent(childNode), childNode);
}
toElement.textContent = "";
toElement.appendChild(fromFragment);
}
function hasAttribute(attributes, name) {
if (!attributes) {
return false;
}
for (let attr of attributes) {
if (attr.name === name) {
return true;
}
}
return false;
}
function overlayAttributes(fromElement, toElement) {
const explicitlyAllowed = toElement.hasAttribute("data-l10n-attrs") ? toElement.getAttribute("data-l10n-attrs").split(",").map(i => i.trim()) : null;
for (const attr of Array.from(toElement.attributes)) {
if (isAttrNameLocalizable(attr.name, toElement, explicitlyAllowed) && !hasAttribute(fromElement.attributes, attr.name)) {
toElement.removeAttribute(attr.name);
}
}
if (!fromElement.attributes) {
return;
}
for (const attr of Array.from(fromElement.attributes)) {
if (isAttrNameLocalizable(attr.name, toElement, explicitlyAllowed) && toElement.getAttribute(attr.name) !== attr.value) {
toElement.setAttribute(attr.name, attr.value);
}
}
}
function getNodeForNamedElement(sourceElement, translatedChild) {
const childName = translatedChild.getAttribute("data-l10n-name");
const sourceChild = sourceElement.querySelector(`[data-l10n-name="${childName}"]`);
if (!sourceChild) {
console.warn(`An element named "${childName}" wasn't found in the source.`);
return createTextNodeFromTextContent(translatedChild);
}
if (sourceChild.localName !== translatedChild.localName) {
console.warn(`An element named "${childName}" was found in the translation ` + `but its type ${translatedChild.localName} didn't match the ` + `element found in the source (${sourceChild.localName}).`);
return createTextNodeFromTextContent(translatedChild);
}
sourceElement.removeChild(sourceChild);
const clone = sourceChild.cloneNode(false);
return shallowPopulateUsing(translatedChild, clone);
}
function createSanitizedElement(element) {
const clone = element.ownerDocument.createElement(element.localName);
return shallowPopulateUsing(element, clone);
}
function createTextNodeFromTextContent(element) {
return element.ownerDocument.createTextNode(element.textContent);
}
function isElementAllowed(element) {
const allowed = TEXT_LEVEL_ELEMENTS[element.namespaceURI];
return allowed && allowed.includes(element.localName);
}
function isAttrNameLocalizable(name, element, explicitlyAllowed = null) {
if (explicitlyAllowed && explicitlyAllowed.includes(name)) {
return true;
}
const allowed = LOCALIZABLE_ATTRIBUTES[element.namespaceURI];
if (!allowed) {
return false;
}
const attrName = name.toLowerCase();
const elemName = element.localName;
if (allowed.global.includes(attrName)) {
return true;
}
if (!allowed[elemName]) {
return false;
}
if (allowed[elemName].includes(attrName)) {
return true;
}
if (element.namespaceURI === "http://www.w3.org/1999/xhtml" && elemName === "input" && attrName === "value") {
const type = element.type.toLowerCase();
if (type === "submit" || type === "button" || type === "reset") {
return true;
}
}
return false;
}
function shallowPopulateUsing(fromElement, toElement) {
toElement.textContent = fromElement.textContent;
overlayAttributes(fromElement, toElement);
return toElement;
}
;// CONCATENATED MODULE: ./node_modules/cached-iterable/src/cached_iterable.mjs
class CachedIterable extends Array {
static from(iterable) {
if (iterable instanceof this) {
return iterable;
}
return new this(iterable);
}
}
;// CONCATENATED MODULE: ./node_modules/cached-iterable/src/cached_sync_iterable.mjs
class CachedSyncIterable extends CachedIterable {
constructor(iterable) {
super();
if (Symbol.iterator in Object(iterable)) {
this.iterator = iterable[Symbol.iterator]();
} else {
throw new TypeError("Argument must implement the iteration protocol.");
}
}
[Symbol.iterator]() {
const cached = this;
let cur = 0;
return {
next() {
if (cached.length <= cur) {
cached.push(cached.iterator.next());
}
return cached[cur++];
}
};
}
touchNext(count = 1) {
let idx = 0;
while (idx++ < count) {
const last = this[this.length - 1];
if (last && last.done) {
break;
}
this.push(this.iterator.next());
}
return this[this.length - 1];
}
}
;// CONCATENATED MODULE: ./node_modules/cached-iterable/src/cached_async_iterable.mjs
class CachedAsyncIterable extends CachedIterable {
constructor(iterable) {
super();
if (Symbol.asyncIterator in Object(iterable)) {
this.iterator = iterable[Symbol.asyncIterator]();
} else if (Symbol.iterator in Object(iterable)) {
this.iterator = iterable[Symbol.iterator]();
} else {
throw new TypeError("Argument must implement the iteration protocol.");
}
}
[Symbol.asyncIterator]() {
const cached = this;
let cur = 0;
return {
async next() {
if (cached.length <= cur) {
cached.push(cached.iterator.next());
}
return cached[cur++];
}
};
}
async touchNext(count = 1) {
let idx = 0;
while (idx++ < count) {
const last = this[this.length - 1];
if (last && (await last).done) {
break;
}
this.push(this.iterator.next());
}
return this[this.length - 1];
}
}
;// CONCATENATED MODULE: ./node_modules/cached-iterable/src/index.mjs
;// CONCATENATED MODULE: ./node_modules/@fluent/dom/esm/localization.js
class Localization {
constructor(resourceIds = [], generateBundles) {
this.resourceIds = resourceIds;
this.generateBundles = generateBundles;
this.onChange(true);
}
addResourceIds(resourceIds, eager = false) {
this.resourceIds.push(...resourceIds);
this.onChange(eager);
return this.resourceIds.length;
}
removeResourceIds(resourceIds) {
this.resourceIds = this.resourceIds.filter(r => !resourceIds.includes(r));
this.onChange();
return this.resourceIds.length;
}
async formatWithFallback(keys, method) {
const translations = [];
let hasAtLeastOneBundle = false;
for await (const bundle of this.bundles) {
hasAtLeastOneBundle = true;
const missingIds = keysFromBundle(method, bundle, keys, translations);
if (missingIds.size === 0) {
break;
}
if (typeof console !== "undefined") {
const locale = bundle.locales[0];
const ids = Array.from(missingIds).join(", ");
console.warn(`[fluent] Missing translations in ${locale}: ${ids}`);
}
}
if (!hasAtLeastOneBundle && typeof console !== "undefined") {
console.warn(`[fluent] Request for keys failed because no resource bundles got generated.
keys: ${JSON.stringify(keys)}.
resourceIds: ${JSON.stringify(this.resourceIds)}.`);
}
return translations;
}
formatMessages(keys) {
return this.formatWithFallback(keys, messageFromBundle);
}
formatValues(keys) {
return this.formatWithFallback(keys, valueFromBundle);
}
async formatValue(id, args) {
const [val] = await this.formatValues([{
id,
args
}]);
return val;
}
handleEvent() {
this.onChange();
}
onChange(eager = false) {
this.bundles = CachedAsyncIterable.from(this.generateBundles(this.resourceIds));
if (eager) {
this.bundles.touchNext(2);
}
}
}
function valueFromBundle(bundle, errors, message, args) {
if (message.value) {
return bundle.formatPattern(message.value, args, errors);
}
return null;
}
function messageFromBundle(bundle, errors, message, args) {
const formatted = {
value: null,
attributes: null
};
if (message.value) {
formatted.value = bundle.formatPattern(message.value, args, errors);
}
let attrNames = Object.keys(message.attributes);
if (attrNames.length > 0) {
formatted.attributes = new Array(attrNames.length);
for (let [i, name] of attrNames.entries()) {
let value = bundle.formatPattern(message.attributes[name], args, errors);
formatted.attributes[i] = {
name,
value
};
}
}
return formatted;
}
function keysFromBundle(method, bundle, keys, translations) {
const messageErrors = [];
const missingIds = new Set();
keys.forEach(({
id,
args
}, i) => {
if (translations[i] !== undefined) {
return;
}
let message = bundle.getMessage(id);
if (message) {
messageErrors.length = 0;
translations[i] = method(bundle, messageErrors, message, args);
if (messageErrors.length > 0 && typeof console !== "undefined") {
const locale = bundle.locales[0];
const errors = messageErrors.join(", ");
console.warn(`[fluent][resolver] errors in ${locale}/${id}: ${errors}.`);
}
} else {
missingIds.add(id);
}
});
return missingIds;
}
;// CONCATENATED MODULE: ./node_modules/@fluent/dom/esm/dom_localization.js
const L10NID_ATTR_NAME = "data-l10n-id";
const L10NARGS_ATTR_NAME = "data-l10n-args";
const L10N_ELEMENT_QUERY = `[${L10NID_ATTR_NAME}]`;
class DOMLocalization extends Localization {
constructor(resourceIds, generateBundles) {
super(resourceIds, generateBundles);
this.roots = new Set();
this.pendingrAF = null;
this.pendingElements = new Set();
this.windowElement = null;
this.mutationObserver = null;
this.observerConfig = {
attributes: true,
characterData: false,
childList: true,
subtree: true,
attributeFilter: [L10NID_ATTR_NAME, L10NARGS_ATTR_NAME]
};
}
onChange(eager = false) {
super.onChange(eager);
if (this.roots) {
this.translateRoots();
}
}
setAttributes(element, id, args) {
element.setAttribute(L10NID_ATTR_NAME, id);
if (args) {
element.setAttribute(L10NARGS_ATTR_NAME, JSON.stringify(args));
} else {
element.removeAttribute(L10NARGS_ATTR_NAME);
}
return element;
}
getAttributes(element) {
return {
id: element.getAttribute(L10NID_ATTR_NAME),
args: JSON.parse(element.getAttribute(L10NARGS_ATTR_NAME) || null)
};
}
connectRoot(newRoot) {
for (const root of this.roots) {
if (root === newRoot || root.contains(newRoot) || newRoot.contains(root)) {
throw new Error("Cannot add a root that overlaps with existing root.");
}
}
if (this.windowElement) {
if (this.windowElement !== newRoot.ownerDocument.defaultView) {
throw new Error(`Cannot connect a root:
DOMLocalization already has a root from a different window.`);
}
} else {
this.windowElement = newRoot.ownerDocument.defaultView;
this.mutationObser